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.

279705 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 < 1500
  132. #define JUCE_VC8_OR_EARLIER 1
  133. #if _MSC_VER < 1400
  134. #define JUCE_VC7_OR_EARLIER 1
  135. #if _MSC_VER < 1300
  136. #define JUCE_VC6 1
  137. #endif
  138. #endif
  139. #endif
  140. #if ! JUCE_VC7_OR_EARLIER
  141. #define JUCE_USE_INTRINSICS 1
  142. #endif
  143. #else
  144. #error unknown compiler
  145. #endif
  146. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  147. /*** End of inlined file: juce_TargetPlatform.h ***/
  148. // FORCE_AMALGAMATOR_INCLUDE
  149. /*** Start of inlined file: juce_Config.h ***/
  150. #ifndef __JUCE_CONFIG_JUCEHEADER__
  151. #define __JUCE_CONFIG_JUCEHEADER__
  152. /*
  153. This file contains macros that enable/disable various JUCE features.
  154. */
  155. /** The name of the namespace that all Juce classes and functions will be
  156. put inside. If this is not defined, no namespace will be used.
  157. */
  158. #ifndef JUCE_NAMESPACE
  159. #define JUCE_NAMESPACE juce
  160. #endif
  161. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  162. project settings, but if you define this value, you can override this to force
  163. it to be true or false.
  164. */
  165. #ifndef JUCE_FORCE_DEBUG
  166. //#define JUCE_FORCE_DEBUG 0
  167. #endif
  168. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  169. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  170. Enabling it will also leave this turned on in release builds. When it's disabled,
  171. however, the jassert and jassertfalse macros will not be compiled in a
  172. release build.
  173. @see jassert, jassertfalse, Logger
  174. */
  175. #ifndef JUCE_LOG_ASSERTIONS
  176. #define JUCE_LOG_ASSERTIONS 0
  177. #endif
  178. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  179. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  180. on your Windows build machine.
  181. See the comments in the ASIOAudioIODevice class's header file for more
  182. info about this.
  183. */
  184. #ifndef JUCE_ASIO
  185. #define JUCE_ASIO 0
  186. #endif
  187. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  188. */
  189. #ifndef JUCE_WASAPI
  190. #define JUCE_WASAPI 0
  191. #endif
  192. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  193. */
  194. #ifndef JUCE_DIRECTSOUND
  195. #define JUCE_DIRECTSOUND 1
  196. #endif
  197. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  198. #ifndef JUCE_ALSA
  199. #define JUCE_ALSA 1
  200. #endif
  201. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  202. #ifndef JUCE_JACK
  203. #define JUCE_JACK 0
  204. #endif
  205. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  206. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  207. installed, and its header files will need to be on your include path.
  208. */
  209. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  210. #define JUCE_QUICKTIME 0
  211. #endif
  212. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  213. #undef JUCE_QUICKTIME
  214. #endif
  215. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  216. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  217. */
  218. #ifndef JUCE_OPENGL
  219. #define JUCE_OPENGL 1
  220. #endif
  221. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  222. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  223. */
  224. #ifndef JUCE_DIRECT2D
  225. #define JUCE_DIRECT2D 0
  226. #endif
  227. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  228. If your app doesn't need to read FLAC files, you might want to disable this to
  229. reduce the size of your codebase and build time.
  230. */
  231. #ifndef JUCE_USE_FLAC
  232. #define JUCE_USE_FLAC 1
  233. #endif
  234. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  235. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  236. reduce the size of your codebase and build time.
  237. */
  238. #ifndef JUCE_USE_OGGVORBIS
  239. #define JUCE_USE_OGGVORBIS 1
  240. #endif
  241. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  242. Unless you're using CD-burning, you should probably turn this flag off to
  243. reduce code size.
  244. */
  245. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  246. #define JUCE_USE_CDBURNER 1
  247. #endif
  248. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  249. Unless you're using CD-reading, you should probably turn this flag off to
  250. reduce code size.
  251. */
  252. #ifndef JUCE_USE_CDREADER
  253. #define JUCE_USE_CDREADER 1
  254. #endif
  255. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  256. */
  257. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  258. #define JUCE_USE_CAMERA 0
  259. #endif
  260. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  261. gets repainted will flash in a random colour, so that you can check exactly how much and how
  262. often your components are being drawn.
  263. */
  264. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  265. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  266. #endif
  267. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  268. Unless you specifically want to disable this, it's best to leave this option turned on.
  269. */
  270. #ifndef JUCE_USE_XINERAMA
  271. #define JUCE_USE_XINERAMA 1
  272. #endif
  273. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  274. turned on unless you have a good reason to disable it.
  275. */
  276. #ifndef JUCE_USE_XSHM
  277. #define JUCE_USE_XSHM 1
  278. #endif
  279. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  280. */
  281. #ifndef JUCE_USE_XRENDER
  282. #define JUCE_USE_XRENDER 0
  283. #endif
  284. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  285. unless you have a good reason to disable it.
  286. */
  287. #ifndef JUCE_USE_XCURSOR
  288. #define JUCE_USE_XCURSOR 1
  289. #endif
  290. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  291. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  292. you're building a plugin hosting app.
  293. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  294. */
  295. #ifndef JUCE_PLUGINHOST_VST
  296. #define JUCE_PLUGINHOST_VST 0
  297. #endif
  298. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  299. of course, and should only be enabled if you're building a plugin hosting app.
  300. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  301. */
  302. #ifndef JUCE_PLUGINHOST_AU
  303. #define JUCE_PLUGINHOST_AU 0
  304. #endif
  305. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  306. This should be enabled if you're writing a console application.
  307. */
  308. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  309. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  310. #endif
  311. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  312. If you're not using any embedded web-pages, turning this off may reduce your code size.
  313. */
  314. #ifndef JUCE_WEB_BROWSER
  315. #define JUCE_WEB_BROWSER 1
  316. #endif
  317. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  318. Carbon isn't required for a normal app, but may be needed by specialised classes like
  319. plugin-hosts, which support older APIs.
  320. */
  321. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  322. #define JUCE_SUPPORT_CARBON 1
  323. #endif
  324. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  325. You might need to tweak this if you're linking to an external zlib library in your app,
  326. but for normal apps, this option should be left alone.
  327. */
  328. #ifndef JUCE_INCLUDE_ZLIB_CODE
  329. #define JUCE_INCLUDE_ZLIB_CODE 1
  330. #endif
  331. #ifndef JUCE_INCLUDE_FLAC_CODE
  332. #define JUCE_INCLUDE_FLAC_CODE 1
  333. #endif
  334. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  335. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  336. #endif
  337. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  338. #define JUCE_INCLUDE_PNGLIB_CODE 1
  339. #endif
  340. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  341. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  342. #endif
  343. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  344. (Currently, this only affects Windows builds in debug mode).
  345. */
  346. #ifndef JUCE_CHECK_MEMORY_LEAKS
  347. #define JUCE_CHECK_MEMORY_LEAKS 1
  348. #endif
  349. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  350. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  351. are passed to the JUCEApplication::unhandledException() callback for logging.
  352. */
  353. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  354. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  355. #endif
  356. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  357. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  358. #undef JUCE_QUICKTIME
  359. #define JUCE_QUICKTIME 0
  360. #undef JUCE_OPENGL
  361. #define JUCE_OPENGL 0
  362. #undef JUCE_USE_CDBURNER
  363. #define JUCE_USE_CDBURNER 0
  364. #undef JUCE_USE_CDREADER
  365. #define JUCE_USE_CDREADER 0
  366. #undef JUCE_WEB_BROWSER
  367. #define JUCE_WEB_BROWSER 0
  368. #undef JUCE_PLUGINHOST_AU
  369. #define JUCE_PLUGINHOST_AU 0
  370. #undef JUCE_PLUGINHOST_VST
  371. #define JUCE_PLUGINHOST_VST 0
  372. #endif
  373. #endif
  374. /*** End of inlined file: juce_Config.h ***/
  375. // FORCE_AMALGAMATOR_INCLUDE
  376. #ifndef JUCE_BUILD_CORE
  377. #define JUCE_BUILD_CORE 1
  378. #endif
  379. #ifndef JUCE_BUILD_MISC
  380. #define JUCE_BUILD_MISC 1
  381. #endif
  382. #ifndef JUCE_BUILD_GUI
  383. #define JUCE_BUILD_GUI 1
  384. #endif
  385. #ifndef JUCE_BUILD_NATIVE
  386. #define JUCE_BUILD_NATIVE 1
  387. #endif
  388. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  389. #undef JUCE_BUILD_MISC
  390. #undef JUCE_BUILD_GUI
  391. #endif
  392. //==============================================================================
  393. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  394. #if JUCE_WINDOWS
  395. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  396. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  397. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  398. #ifndef STRICT
  399. #define STRICT 1
  400. #endif
  401. #undef WIN32_LEAN_AND_MEAN
  402. #define WIN32_LEAN_AND_MEAN 1
  403. #if JUCE_MSVC
  404. #pragma warning (push)
  405. #pragma warning (disable : 4100 4201 4514 4312 4995)
  406. #endif
  407. #define _WIN32_WINNT 0x0500
  408. #define _UNICODE 1
  409. #define UNICODE 1
  410. #ifndef _WIN32_IE
  411. #define _WIN32_IE 0x0400
  412. #endif
  413. #include <windows.h>
  414. #include <windowsx.h>
  415. #include <commdlg.h>
  416. #include <shellapi.h>
  417. #include <mmsystem.h>
  418. #include <vfw.h>
  419. #include <tchar.h>
  420. #include <stddef.h>
  421. #include <ctime>
  422. #include <wininet.h>
  423. #include <nb30.h>
  424. #include <iphlpapi.h>
  425. #include <mapi.h>
  426. #include <float.h>
  427. #include <process.h>
  428. #include <Exdisp.h>
  429. #include <exdispid.h>
  430. #include <shlobj.h>
  431. #if ! JUCE_MINGW
  432. #include <crtdbg.h>
  433. #include <comutil.h>
  434. #endif
  435. #if JUCE_OPENGL
  436. #include <gl/gl.h>
  437. #endif
  438. #undef PACKED
  439. #if JUCE_ASIO
  440. /*
  441. This is very frustrating - we only need to use a handful of definitions from
  442. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  443. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  444. implementation...
  445. ..unfortunately that would break Steinberg's license agreement for use of
  446. their SDK, so I'm not allowed to do this.
  447. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  448. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  449. (see www.steinberg.net/Steinberg/Developers.asp).
  450. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  451. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  452. if you prefer). Make sure that your header search path will find the
  453. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  454. files are actually needed - so to simplify things, you could just copy
  455. these into your JUCE directory).
  456. If you're compiling and you get an error here because you don't have the
  457. ASIO SDK installed, you can disable ASIO support by commenting-out the
  458. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  459. */
  460. #include "iasiodrv.h"
  461. #endif
  462. #if JUCE_USE_CDBURNER
  463. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  464. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  465. flag in juce_Config.h to avoid these includes.
  466. */
  467. #include <imapi.h>
  468. #include <imapierror.h>
  469. #endif
  470. #if JUCE_USE_CAMERA
  471. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  472. These files are provided in the normal Windows SDK, but some Microsoft plonker
  473. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  474. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  475. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  476. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  477. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  478. The dummy file just needs to contain the following content:
  479. #define __IDxtCompositor_INTERFACE_DEFINED__
  480. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  481. #define __IDxtJpeg_INTERFACE_DEFINED__
  482. #define __IDxtKey_INTERFACE_DEFINED__
  483. ..and that should be enough to convince qedit.h that you have the SDK!
  484. */
  485. #include <dshow.h>
  486. #include <qedit.h>
  487. #include <dshowasf.h>
  488. #endif
  489. #if JUCE_WASAPI
  490. #include <MMReg.h>
  491. #include <mmdeviceapi.h>
  492. #include <Audioclient.h>
  493. #include <Avrt.h>
  494. #include <functiondiscoverykeys.h>
  495. #endif
  496. #if JUCE_QUICKTIME
  497. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  498. add its header directory to your include path.
  499. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  500. flag in juce_Config.h
  501. */
  502. #include <Movies.h>
  503. #include <QTML.h>
  504. #include <QuickTimeComponents.h>
  505. #include <MediaHandlers.h>
  506. #include <ImageCodec.h>
  507. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  508. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  509. your include search path to make these import statements work.
  510. */
  511. #import <QTOLibrary.dll>
  512. #import <QTOControl.dll>
  513. #endif
  514. #if JUCE_MSVC
  515. #pragma warning (pop)
  516. #endif
  517. #if JUCE_DIRECT2D
  518. #include <d2d1.h>
  519. #include <dwrite.h>
  520. #endif
  521. /** A simple COM smart pointer.
  522. Avoids having to include ATL just to get one of these.
  523. */
  524. template <class ComClass>
  525. class ComSmartPtr
  526. {
  527. public:
  528. ComSmartPtr() throw() : p (0) {}
  529. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  530. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  531. ~ComSmartPtr() { release(); }
  532. operator ComClass*() const throw() { return p; }
  533. ComClass& operator*() const throw() { return *p; }
  534. ComClass* operator->() const throw() { return p; }
  535. ComSmartPtr& operator= (ComClass* const newP)
  536. {
  537. if (newP != 0) newP->AddRef();
  538. release();
  539. p = newP;
  540. return *this;
  541. }
  542. ComSmartPtr& operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  543. // Releases and nullifies this pointer and returns its address
  544. ComClass** resetAndGetPointerAddress()
  545. {
  546. release();
  547. p = 0;
  548. return &p;
  549. }
  550. HRESULT CoCreateInstance (REFCLSID classUUID, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  551. {
  552. #ifndef __MINGW32__
  553. return ::CoCreateInstance (classUUID, 0, dwClsContext, __uuidof (ComClass), (void**) resetAndGetPointerAddress());
  554. #else
  555. return E_NOTIMPL;
  556. #endif
  557. }
  558. template <class OtherComClass>
  559. HRESULT QueryInterface (REFCLSID classUUID, ComSmartPtr<OtherComClass>& destObject) const
  560. {
  561. if (p == 0)
  562. return E_POINTER;
  563. return p->QueryInterface (classUUID, (void**) destObject.resetAndGetPointerAddress());
  564. }
  565. private:
  566. ComClass* p;
  567. void release() { if (p != 0) p->Release(); }
  568. ComClass** operator&() throw(); // private to avoid it being used accidentally
  569. };
  570. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  571. */
  572. template <class ComClass>
  573. class ComBaseClassHelper : public ComClass
  574. {
  575. public:
  576. ComBaseClassHelper() : refCount (1) {}
  577. virtual ~ComBaseClassHelper() {}
  578. HRESULT __stdcall QueryInterface (REFIID refId, void** result)
  579. {
  580. #ifndef __MINGW32__
  581. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  582. #endif
  583. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  584. *result = 0;
  585. return E_NOINTERFACE;
  586. }
  587. ULONG __stdcall AddRef() { return ++refCount; }
  588. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  589. protected:
  590. int refCount;
  591. };
  592. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  593. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  594. #elif JUCE_LINUX
  595. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  596. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  597. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  598. /*
  599. This file wraps together all the linux-specific headers, so
  600. that we can include them all just once, and compile all our
  601. platform-specific stuff in one big lump, keeping it out of the
  602. way of the rest of the codebase.
  603. */
  604. #include <sched.h>
  605. #include <pthread.h>
  606. #include <sys/time.h>
  607. #include <errno.h>
  608. #include <sys/stat.h>
  609. #include <sys/dir.h>
  610. #include <sys/ptrace.h>
  611. #include <sys/vfs.h>
  612. #include <sys/wait.h>
  613. #include <fnmatch.h>
  614. #include <utime.h>
  615. #include <pwd.h>
  616. #include <fcntl.h>
  617. #include <dlfcn.h>
  618. #include <netdb.h>
  619. #include <arpa/inet.h>
  620. #include <netinet/in.h>
  621. #include <sys/types.h>
  622. #include <sys/ioctl.h>
  623. #include <sys/socket.h>
  624. #include <net/if.h>
  625. #include <sys/sysinfo.h>
  626. #include <sys/file.h>
  627. #include <signal.h>
  628. /* Got a build error here? You'll need to install the freetype library...
  629. The name of the package to install is "libfreetype6-dev".
  630. */
  631. #include <ft2build.h>
  632. #include FT_FREETYPE_H
  633. #include <X11/Xlib.h>
  634. #include <X11/Xatom.h>
  635. #include <X11/Xresource.h>
  636. #include <X11/Xutil.h>
  637. #include <X11/Xmd.h>
  638. #include <X11/keysym.h>
  639. #include <X11/cursorfont.h>
  640. #if JUCE_USE_XINERAMA
  641. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  642. #include <X11/extensions/Xinerama.h>
  643. #endif
  644. #if JUCE_USE_XSHM
  645. #include <X11/extensions/XShm.h>
  646. #include <sys/shm.h>
  647. #include <sys/ipc.h>
  648. #endif
  649. #if JUCE_USE_XRENDER
  650. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  651. #include <X11/extensions/Xrender.h>
  652. #include <X11/extensions/Xcomposite.h>
  653. #endif
  654. #if JUCE_USE_XCURSOR
  655. // If you're missing this header, try installing the libxcursor-dev package
  656. #include <X11/Xcursor/Xcursor.h>
  657. #endif
  658. #if JUCE_OPENGL
  659. /* Got an include error here?
  660. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  661. and "freeglut3-dev".
  662. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  663. want to disable it.
  664. */
  665. #include <GL/glx.h>
  666. #endif
  667. #undef KeyPress
  668. #if JUCE_ALSA
  669. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  670. not got your paths set up correctly to find its header files.
  671. The package you need to install to get ASLA support is "libasound2-dev".
  672. If you don't have the ALSA library and don't want to build Juce with audio support,
  673. just disable the JUCE_ALSA flag in juce_Config.h
  674. */
  675. #include <alsa/asoundlib.h>
  676. #endif
  677. #if JUCE_JACK
  678. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  679. installed, or you've not got your paths set up correctly to find its header files.
  680. The package you need to install to get JACK support is "libjack-dev".
  681. If you don't have the jack-audio-connection-kit library and don't want to build
  682. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  683. */
  684. #include <jack/jack.h>
  685. //#include <jack/transport.h>
  686. #endif
  687. #undef SIZEOF
  688. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  689. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  690. #elif JUCE_MAC || JUCE_IPHONE
  691. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  692. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  693. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  694. /*
  695. This file wraps together all the mac-specific code, so that
  696. we can include all the native headers just once, and compile all our
  697. platform-specific stuff in one big lump, keeping it out of the way of
  698. the rest of the codebase.
  699. */
  700. #define USE_COREGRAPHICS_RENDERING 1
  701. #if JUCE_IOS
  702. #import <Foundation/Foundation.h>
  703. #import <UIKit/UIKit.h>
  704. #import <AudioToolbox/AudioToolbox.h>
  705. #import <AVFoundation/AVFoundation.h>
  706. #import <CoreData/CoreData.h>
  707. #import <MobileCoreServices/MobileCoreServices.h>
  708. #import <QuartzCore/QuartzCore.h>
  709. #include <sys/fcntl.h>
  710. #if JUCE_OPENGL
  711. #include <OpenGLES/ES1/gl.h>
  712. #include <OpenGLES/ES1/glext.h>
  713. #endif
  714. #else
  715. #import <Cocoa/Cocoa.h>
  716. #import <CoreAudio/HostTime.h>
  717. #import <CoreAudio/AudioHardware.h>
  718. #import <CoreMIDI/MIDIServices.h>
  719. #import <QTKit/QTKit.h>
  720. #import <WebKit/WebKit.h>
  721. #import <DiscRecording/DiscRecording.h>
  722. #import <IOKit/IOKitLib.h>
  723. #import <IOKit/IOCFPlugIn.h>
  724. #import <IOKit/hid/IOHIDLib.h>
  725. #import <IOKit/hid/IOHIDKeys.h>
  726. #import <IOKit/pwr_mgt/IOPMLib.h>
  727. #include <Carbon/Carbon.h>
  728. #include <sys/dir.h>
  729. #endif
  730. #include <sys/socket.h>
  731. #include <sys/sysctl.h>
  732. #include <sys/stat.h>
  733. #include <sys/param.h>
  734. #include <sys/mount.h>
  735. #include <fnmatch.h>
  736. #include <utime.h>
  737. #include <dlfcn.h>
  738. #include <ifaddrs.h>
  739. #include <net/if_dl.h>
  740. #include <mach/mach_time.h>
  741. #include <mach-o/dyld.h>
  742. #if MACOS_10_4_OR_EARLIER
  743. #include <GLUT/glut.h>
  744. #endif
  745. #if ! CGFLOAT_DEFINED
  746. #define CGFloat float
  747. #endif
  748. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  749. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  750. #else
  751. #error "Unknown platform!"
  752. #endif
  753. #endif
  754. //==============================================================================
  755. #define DONT_SET_USING_JUCE_NAMESPACE 1
  756. #undef max
  757. #undef min
  758. #define NO_DUMMY_DECL
  759. #if JUCE_BUILD_NATIVE
  760. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  761. #endif
  762. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  763. #pragma warning (disable: 4309 4305)
  764. #endif
  765. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  766. BEGIN_JUCE_NAMESPACE
  767. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  768. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  769. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  770. /**
  771. Creates a floating carbon window that can be used to hold a carbon UI.
  772. This is a handy class that's designed to be inlined where needed, e.g.
  773. in the audio plugin hosting code.
  774. */
  775. class CarbonViewWrapperComponent : public Component,
  776. public ComponentMovementWatcher,
  777. public Timer
  778. {
  779. public:
  780. CarbonViewWrapperComponent()
  781. : ComponentMovementWatcher (this),
  782. wrapperWindow (0),
  783. carbonWindow (0),
  784. embeddedView (0),
  785. recursiveResize (false)
  786. {
  787. }
  788. virtual ~CarbonViewWrapperComponent()
  789. {
  790. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  791. }
  792. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  793. virtual void removeView (HIViewRef embeddedView) = 0;
  794. virtual void mouseDown (int, int) {}
  795. virtual void paint() {}
  796. virtual bool getEmbeddedViewSize (int& w, int& h)
  797. {
  798. if (embeddedView == 0)
  799. return false;
  800. HIRect bounds;
  801. HIViewGetBounds (embeddedView, &bounds);
  802. w = jmax (1, roundToInt (bounds.size.width));
  803. h = jmax (1, roundToInt (bounds.size.height));
  804. return true;
  805. }
  806. void createWindow()
  807. {
  808. if (wrapperWindow == 0)
  809. {
  810. Rect r;
  811. r.left = getScreenX();
  812. r.top = getScreenY();
  813. r.right = r.left + getWidth();
  814. r.bottom = r.top + getHeight();
  815. CreateNewWindow (kDocumentWindowClass,
  816. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  817. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  818. &r, &wrapperWindow);
  819. jassert (wrapperWindow != 0);
  820. if (wrapperWindow == 0)
  821. return;
  822. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  823. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  824. [ownerWindow addChildWindow: carbonWindow
  825. ordered: NSWindowAbove];
  826. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  827. EventTypeSpec windowEventTypes[] =
  828. {
  829. { kEventClassWindow, kEventWindowGetClickActivation },
  830. { kEventClassWindow, kEventWindowHandleDeactivate },
  831. { kEventClassWindow, kEventWindowBoundsChanging },
  832. { kEventClassMouse, kEventMouseDown },
  833. { kEventClassMouse, kEventMouseMoved },
  834. { kEventClassMouse, kEventMouseDragged },
  835. { kEventClassMouse, kEventMouseUp},
  836. { kEventClassWindow, kEventWindowDrawContent },
  837. { kEventClassWindow, kEventWindowShown },
  838. { kEventClassWindow, kEventWindowHidden }
  839. };
  840. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  841. InstallWindowEventHandler (wrapperWindow, upp,
  842. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  843. windowEventTypes, this, &eventHandlerRef);
  844. setOurSizeToEmbeddedViewSize();
  845. setEmbeddedWindowToOurSize();
  846. creationTime = Time::getCurrentTime();
  847. }
  848. }
  849. void deleteWindow()
  850. {
  851. removeView (embeddedView);
  852. embeddedView = 0;
  853. if (wrapperWindow != 0)
  854. {
  855. RemoveEventHandler (eventHandlerRef);
  856. DisposeWindow (wrapperWindow);
  857. wrapperWindow = 0;
  858. }
  859. }
  860. void setOurSizeToEmbeddedViewSize()
  861. {
  862. int w, h;
  863. if (getEmbeddedViewSize (w, h))
  864. {
  865. if (w != getWidth() || h != getHeight())
  866. {
  867. startTimer (50);
  868. setSize (w, h);
  869. if (getParentComponent() != 0)
  870. getParentComponent()->setSize (w, h);
  871. }
  872. else
  873. {
  874. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  875. }
  876. }
  877. else
  878. {
  879. stopTimer();
  880. }
  881. }
  882. void setEmbeddedWindowToOurSize()
  883. {
  884. if (! recursiveResize)
  885. {
  886. recursiveResize = true;
  887. if (embeddedView != 0)
  888. {
  889. HIRect r;
  890. r.origin.x = 0;
  891. r.origin.y = 0;
  892. r.size.width = (float) getWidth();
  893. r.size.height = (float) getHeight();
  894. HIViewSetFrame (embeddedView, &r);
  895. }
  896. if (wrapperWindow != 0)
  897. {
  898. Rect wr;
  899. wr.left = getScreenX();
  900. wr.top = getScreenY();
  901. wr.right = wr.left + getWidth();
  902. wr.bottom = wr.top + getHeight();
  903. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  904. ShowWindow (wrapperWindow);
  905. }
  906. recursiveResize = false;
  907. }
  908. }
  909. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  910. {
  911. setEmbeddedWindowToOurSize();
  912. }
  913. void componentPeerChanged()
  914. {
  915. deleteWindow();
  916. createWindow();
  917. }
  918. void componentVisibilityChanged (Component&)
  919. {
  920. if (isShowing())
  921. createWindow();
  922. else
  923. deleteWindow();
  924. setEmbeddedWindowToOurSize();
  925. }
  926. static void recursiveHIViewRepaint (HIViewRef view)
  927. {
  928. HIViewSetNeedsDisplay (view, true);
  929. HIViewRef child = HIViewGetFirstSubview (view);
  930. while (child != 0)
  931. {
  932. recursiveHIViewRepaint (child);
  933. child = HIViewGetNextView (child);
  934. }
  935. }
  936. void timerCallback()
  937. {
  938. setOurSizeToEmbeddedViewSize();
  939. // To avoid strange overpainting problems when the UI is first opened, we'll
  940. // repaint it a few times during the first second that it's on-screen..
  941. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  942. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  943. }
  944. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  945. {
  946. switch (GetEventKind (event))
  947. {
  948. case kEventWindowHandleDeactivate:
  949. ActivateWindow (wrapperWindow, TRUE);
  950. return noErr;
  951. case kEventWindowGetClickActivation:
  952. {
  953. getTopLevelComponent()->toFront (false);
  954. [carbonWindow makeKeyAndOrderFront: nil];
  955. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  956. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  957. sizeof (ClickActivationResult), &howToHandleClick);
  958. HIViewSetNeedsDisplay (embeddedView, true);
  959. return noErr;
  960. }
  961. }
  962. return eventNotHandledErr;
  963. }
  964. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  965. {
  966. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  967. }
  968. protected:
  969. WindowRef wrapperWindow;
  970. NSWindow* carbonWindow;
  971. HIViewRef embeddedView;
  972. bool recursiveResize;
  973. Time creationTime;
  974. EventHandlerRef eventHandlerRef;
  975. };
  976. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  977. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  978. END_JUCE_NAMESPACE
  979. #endif
  980. #define JUCE_AMALGAMATED_TEMPLATE 1
  981. //==============================================================================
  982. #if JUCE_BUILD_CORE
  983. /*** Start of inlined file: juce_FileLogger.cpp ***/
  984. BEGIN_JUCE_NAMESPACE
  985. FileLogger::FileLogger (const File& logFile_,
  986. const String& welcomeMessage,
  987. const int maxInitialFileSizeBytes)
  988. : logFile (logFile_)
  989. {
  990. if (maxInitialFileSizeBytes >= 0)
  991. trimFileSize (maxInitialFileSizeBytes);
  992. if (! logFile_.exists())
  993. {
  994. // do this so that the parent directories get created..
  995. logFile_.create();
  996. }
  997. String welcome;
  998. welcome << "\r\n**********************************************************\r\n"
  999. << welcomeMessage
  1000. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  1001. << "\r\n";
  1002. logMessage (welcome);
  1003. }
  1004. FileLogger::~FileLogger()
  1005. {
  1006. }
  1007. void FileLogger::logMessage (const String& message)
  1008. {
  1009. DBG (message);
  1010. const ScopedLock sl (logLock);
  1011. FileOutputStream out (logFile, 256);
  1012. out << message << "\r\n";
  1013. }
  1014. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1015. {
  1016. if (maxFileSizeBytes <= 0)
  1017. {
  1018. logFile.deleteFile();
  1019. }
  1020. else
  1021. {
  1022. const int64 fileSize = logFile.getSize();
  1023. if (fileSize > maxFileSizeBytes)
  1024. {
  1025. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1026. jassert (in != 0);
  1027. if (in != 0)
  1028. {
  1029. in->setPosition (fileSize - maxFileSizeBytes);
  1030. String content;
  1031. {
  1032. MemoryBlock contentToSave;
  1033. contentToSave.setSize (maxFileSizeBytes + 4);
  1034. contentToSave.fillWith (0);
  1035. in->read (contentToSave.getData(), maxFileSizeBytes);
  1036. in = 0;
  1037. content = contentToSave.toString();
  1038. }
  1039. int newStart = 0;
  1040. while (newStart < fileSize
  1041. && content[newStart] != '\n'
  1042. && content[newStart] != '\r')
  1043. ++newStart;
  1044. logFile.deleteFile();
  1045. logFile.appendText (content.substring (newStart), false, false);
  1046. }
  1047. }
  1048. }
  1049. }
  1050. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1051. const String& logFileName,
  1052. const String& welcomeMessage,
  1053. const int maxInitialFileSizeBytes)
  1054. {
  1055. #if JUCE_MAC
  1056. File logFile ("~/Library/Logs");
  1057. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1058. .getChildFile (logFileName);
  1059. #else
  1060. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1061. if (logFile.isDirectory())
  1062. {
  1063. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1064. .getChildFile (logFileName);
  1065. }
  1066. #endif
  1067. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1068. }
  1069. END_JUCE_NAMESPACE
  1070. /*** End of inlined file: juce_FileLogger.cpp ***/
  1071. /*** Start of inlined file: juce_Logger.cpp ***/
  1072. BEGIN_JUCE_NAMESPACE
  1073. Logger::Logger()
  1074. {
  1075. }
  1076. Logger::~Logger()
  1077. {
  1078. }
  1079. Logger* Logger::currentLogger = 0;
  1080. void Logger::setCurrentLogger (Logger* const newLogger,
  1081. const bool deleteOldLogger)
  1082. {
  1083. Logger* const oldLogger = currentLogger;
  1084. currentLogger = newLogger;
  1085. if (deleteOldLogger)
  1086. delete oldLogger;
  1087. }
  1088. void Logger::writeToLog (const String& message)
  1089. {
  1090. if (currentLogger != 0)
  1091. currentLogger->logMessage (message);
  1092. else
  1093. outputDebugString (message);
  1094. }
  1095. #if JUCE_LOG_ASSERTIONS
  1096. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1097. {
  1098. String m ("JUCE Assertion failure in ");
  1099. m << filename << ", line " << lineNum;
  1100. Logger::writeToLog (m);
  1101. }
  1102. #endif
  1103. END_JUCE_NAMESPACE
  1104. /*** End of inlined file: juce_Logger.cpp ***/
  1105. /*** Start of inlined file: juce_Random.cpp ***/
  1106. BEGIN_JUCE_NAMESPACE
  1107. Random::Random (const int64 seedValue) throw()
  1108. : seed (seedValue)
  1109. {
  1110. }
  1111. Random::~Random() throw()
  1112. {
  1113. }
  1114. void Random::setSeed (const int64 newSeed) throw()
  1115. {
  1116. seed = newSeed;
  1117. }
  1118. void Random::combineSeed (const int64 seedValue) throw()
  1119. {
  1120. seed ^= nextInt64() ^ seedValue;
  1121. }
  1122. void Random::setSeedRandomly()
  1123. {
  1124. combineSeed ((int64) (pointer_sized_int) this);
  1125. combineSeed (Time::getMillisecondCounter());
  1126. combineSeed (Time::getHighResolutionTicks());
  1127. combineSeed (Time::getHighResolutionTicksPerSecond());
  1128. combineSeed (Time::currentTimeMillis());
  1129. }
  1130. int Random::nextInt() throw()
  1131. {
  1132. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1133. return (int) (seed >> 16);
  1134. }
  1135. int Random::nextInt (const int maxValue) throw()
  1136. {
  1137. jassert (maxValue > 0);
  1138. return (nextInt() & 0x7fffffff) % maxValue;
  1139. }
  1140. int64 Random::nextInt64() throw()
  1141. {
  1142. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1143. }
  1144. bool Random::nextBool() throw()
  1145. {
  1146. return (nextInt() & 0x80000000) != 0;
  1147. }
  1148. float Random::nextFloat() throw()
  1149. {
  1150. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1151. }
  1152. double Random::nextDouble() throw()
  1153. {
  1154. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1155. }
  1156. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1157. {
  1158. BigInteger n;
  1159. do
  1160. {
  1161. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1162. }
  1163. while (n >= maximumValue);
  1164. return n;
  1165. }
  1166. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1167. {
  1168. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1169. while ((startBit & 31) != 0 && numBits > 0)
  1170. {
  1171. arrayToChange.setBit (startBit++, nextBool());
  1172. --numBits;
  1173. }
  1174. while (numBits >= 32)
  1175. {
  1176. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1177. startBit += 32;
  1178. numBits -= 32;
  1179. }
  1180. while (--numBits >= 0)
  1181. arrayToChange.setBit (startBit + numBits, nextBool());
  1182. }
  1183. Random& Random::getSystemRandom() throw()
  1184. {
  1185. static Random sysRand (1);
  1186. return sysRand;
  1187. }
  1188. END_JUCE_NAMESPACE
  1189. /*** End of inlined file: juce_Random.cpp ***/
  1190. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1191. BEGIN_JUCE_NAMESPACE
  1192. RelativeTime::RelativeTime (const double seconds_) throw()
  1193. : seconds (seconds_)
  1194. {
  1195. }
  1196. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1197. : seconds (other.seconds)
  1198. {
  1199. }
  1200. RelativeTime::~RelativeTime() throw()
  1201. {
  1202. }
  1203. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1204. {
  1205. return RelativeTime (milliseconds * 0.001);
  1206. }
  1207. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1208. {
  1209. return RelativeTime (milliseconds * 0.001);
  1210. }
  1211. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1212. {
  1213. return RelativeTime (numberOfMinutes * 60.0);
  1214. }
  1215. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1216. {
  1217. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1218. }
  1219. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1220. {
  1221. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1222. }
  1223. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1224. {
  1225. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1226. }
  1227. int64 RelativeTime::inMilliseconds() const throw()
  1228. {
  1229. return (int64) (seconds * 1000.0);
  1230. }
  1231. double RelativeTime::inMinutes() const throw()
  1232. {
  1233. return seconds / 60.0;
  1234. }
  1235. double RelativeTime::inHours() const throw()
  1236. {
  1237. return seconds / (60.0 * 60.0);
  1238. }
  1239. double RelativeTime::inDays() const throw()
  1240. {
  1241. return seconds / (60.0 * 60.0 * 24.0);
  1242. }
  1243. double RelativeTime::inWeeks() const throw()
  1244. {
  1245. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1246. }
  1247. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1248. {
  1249. if (seconds < 0.001 && seconds > -0.001)
  1250. return returnValueForZeroTime;
  1251. String result;
  1252. if (seconds < 0)
  1253. result = "-";
  1254. int fieldsShown = 0;
  1255. int n = abs ((int) inWeeks());
  1256. if (n > 0)
  1257. {
  1258. result << n << ((n == 1) ? TRANS(" week ")
  1259. : TRANS(" weeks "));
  1260. ++fieldsShown;
  1261. }
  1262. n = abs ((int) inDays()) % 7;
  1263. if (n > 0)
  1264. {
  1265. result << n << ((n == 1) ? TRANS(" day ")
  1266. : TRANS(" days "));
  1267. ++fieldsShown;
  1268. }
  1269. if (fieldsShown < 2)
  1270. {
  1271. n = abs ((int) inHours()) % 24;
  1272. if (n > 0)
  1273. {
  1274. result << n << ((n == 1) ? TRANS(" hr ")
  1275. : TRANS(" hrs "));
  1276. ++fieldsShown;
  1277. }
  1278. if (fieldsShown < 2)
  1279. {
  1280. n = abs ((int) inMinutes()) % 60;
  1281. if (n > 0)
  1282. {
  1283. result << n << ((n == 1) ? TRANS(" min ")
  1284. : TRANS(" mins "));
  1285. ++fieldsShown;
  1286. }
  1287. if (fieldsShown < 2)
  1288. {
  1289. n = abs ((int) inSeconds()) % 60;
  1290. if (n > 0)
  1291. {
  1292. result << n << ((n == 1) ? TRANS(" sec ")
  1293. : TRANS(" secs "));
  1294. ++fieldsShown;
  1295. }
  1296. if (fieldsShown < 1)
  1297. {
  1298. n = abs ((int) inMilliseconds()) % 1000;
  1299. if (n > 0)
  1300. {
  1301. result << n << TRANS(" ms");
  1302. ++fieldsShown;
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. return result.trimEnd();
  1309. }
  1310. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1311. {
  1312. seconds = other.seconds;
  1313. return *this;
  1314. }
  1315. bool RelativeTime::operator== (const RelativeTime& other) const throw() { return seconds == other.seconds; }
  1316. bool RelativeTime::operator!= (const RelativeTime& other) const throw() { return seconds != other.seconds; }
  1317. bool RelativeTime::operator> (const RelativeTime& other) const throw() { return seconds > other.seconds; }
  1318. bool RelativeTime::operator< (const RelativeTime& other) const throw() { return seconds < other.seconds; }
  1319. bool RelativeTime::operator>= (const RelativeTime& other) const throw() { return seconds >= other.seconds; }
  1320. bool RelativeTime::operator<= (const RelativeTime& other) const throw() { return seconds <= other.seconds; }
  1321. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1322. {
  1323. return RelativeTime (seconds + timeToAdd.seconds);
  1324. }
  1325. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1326. {
  1327. return RelativeTime (seconds - timeToSubtract.seconds);
  1328. }
  1329. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1330. {
  1331. return RelativeTime (seconds + secondsToAdd);
  1332. }
  1333. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1334. {
  1335. return RelativeTime (seconds - secondsToSubtract);
  1336. }
  1337. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1338. {
  1339. seconds += timeToAdd.seconds;
  1340. return *this;
  1341. }
  1342. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1343. {
  1344. seconds -= timeToSubtract.seconds;
  1345. return *this;
  1346. }
  1347. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1348. {
  1349. seconds += secondsToAdd;
  1350. return *this;
  1351. }
  1352. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1353. {
  1354. seconds -= secondsToSubtract;
  1355. return *this;
  1356. }
  1357. END_JUCE_NAMESPACE
  1358. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1359. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1360. BEGIN_JUCE_NAMESPACE
  1361. SystemStats::CPUFlags SystemStats::cpuFlags;
  1362. const String SystemStats::getJUCEVersion()
  1363. {
  1364. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1365. + "." + String (JUCE_MINOR_VERSION)
  1366. + "." + String (JUCE_BUILDNUMBER);
  1367. }
  1368. #ifdef JUCE_DLL
  1369. void* juce_Malloc (const int size)
  1370. {
  1371. return malloc (size);
  1372. }
  1373. void* juce_Calloc (const int size)
  1374. {
  1375. return calloc (1, size);
  1376. }
  1377. void* juce_Realloc (void* const block, const int size)
  1378. {
  1379. return realloc (block, size);
  1380. }
  1381. void juce_Free (void* const block)
  1382. {
  1383. free (block);
  1384. }
  1385. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1386. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1387. {
  1388. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1389. }
  1390. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1391. {
  1392. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1393. }
  1394. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1395. {
  1396. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1397. }
  1398. void juce_DebugFree (void* const block)
  1399. {
  1400. _free_dbg (block, _NORMAL_BLOCK);
  1401. }
  1402. #endif
  1403. #endif
  1404. END_JUCE_NAMESPACE
  1405. /*** End of inlined file: juce_SystemStats.cpp ***/
  1406. /*** Start of inlined file: juce_Time.cpp ***/
  1407. #if JUCE_MSVC
  1408. #pragma warning (push)
  1409. #pragma warning (disable: 4514)
  1410. #endif
  1411. #ifndef JUCE_WINDOWS
  1412. #include <sys/time.h>
  1413. #else
  1414. #include <ctime>
  1415. #endif
  1416. #include <sys/timeb.h>
  1417. #if JUCE_MSVC
  1418. #pragma warning (pop)
  1419. #ifdef _INC_TIME_INL
  1420. #define USE_NEW_SECURE_TIME_FNS
  1421. #endif
  1422. #endif
  1423. BEGIN_JUCE_NAMESPACE
  1424. namespace TimeHelpers
  1425. {
  1426. static struct tm millisToLocal (const int64 millis) throw()
  1427. {
  1428. struct tm result;
  1429. const int64 seconds = millis / 1000;
  1430. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1431. {
  1432. // use extended maths for dates beyond 1970 to 2037..
  1433. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1434. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1435. const int days = (int) (jdm / literal64bit (86400));
  1436. const int a = 32044 + days;
  1437. const int b = (4 * a + 3) / 146097;
  1438. const int c = a - (b * 146097) / 4;
  1439. const int d = (4 * c + 3) / 1461;
  1440. const int e = c - (d * 1461) / 4;
  1441. const int m = (5 * e + 2) / 153;
  1442. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1443. result.tm_mon = m + 2 - 12 * (m / 10);
  1444. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1445. result.tm_wday = (days + 1) % 7;
  1446. result.tm_yday = -1;
  1447. int t = (int) (jdm % literal64bit (86400));
  1448. result.tm_hour = t / 3600;
  1449. t %= 3600;
  1450. result.tm_min = t / 60;
  1451. result.tm_sec = t % 60;
  1452. result.tm_isdst = -1;
  1453. }
  1454. else
  1455. {
  1456. time_t now = static_cast <time_t> (seconds);
  1457. #if JUCE_WINDOWS
  1458. #ifdef USE_NEW_SECURE_TIME_FNS
  1459. if (now >= 0 && now <= 0x793406fff)
  1460. localtime_s (&result, &now);
  1461. else
  1462. zeromem (&result, sizeof (result));
  1463. #else
  1464. result = *localtime (&now);
  1465. #endif
  1466. #else
  1467. // more thread-safe
  1468. localtime_r (&now, &result);
  1469. #endif
  1470. }
  1471. return result;
  1472. }
  1473. static int extendedModulo (const int64 value, const int modulo) throw()
  1474. {
  1475. return (int) (value >= 0 ? (value % modulo)
  1476. : (value - ((value / modulo) + 1) * modulo));
  1477. }
  1478. static uint32 lastMSCounterValue = 0;
  1479. }
  1480. Time::Time() throw()
  1481. : millisSinceEpoch (0)
  1482. {
  1483. }
  1484. Time::Time (const Time& other) throw()
  1485. : millisSinceEpoch (other.millisSinceEpoch)
  1486. {
  1487. }
  1488. Time::Time (const int64 ms) throw()
  1489. : millisSinceEpoch (ms)
  1490. {
  1491. }
  1492. Time::Time (const int year,
  1493. const int month,
  1494. const int day,
  1495. const int hours,
  1496. const int minutes,
  1497. const int seconds,
  1498. const int milliseconds,
  1499. const bool useLocalTime) throw()
  1500. {
  1501. jassert (year > 100); // year must be a 4-digit version
  1502. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1503. {
  1504. // use extended maths for dates beyond 1970 to 2037..
  1505. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1506. : 0;
  1507. const int a = (13 - month) / 12;
  1508. const int y = year + 4800 - a;
  1509. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1510. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1511. - 32045;
  1512. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1513. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1514. + milliseconds;
  1515. }
  1516. else
  1517. {
  1518. struct tm t;
  1519. t.tm_year = year - 1900;
  1520. t.tm_mon = month;
  1521. t.tm_mday = day;
  1522. t.tm_hour = hours;
  1523. t.tm_min = minutes;
  1524. t.tm_sec = seconds;
  1525. t.tm_isdst = -1;
  1526. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1527. if (millisSinceEpoch < 0)
  1528. millisSinceEpoch = 0;
  1529. else
  1530. millisSinceEpoch += milliseconds;
  1531. }
  1532. }
  1533. Time::~Time() throw()
  1534. {
  1535. }
  1536. Time& Time::operator= (const Time& other) throw()
  1537. {
  1538. millisSinceEpoch = other.millisSinceEpoch;
  1539. return *this;
  1540. }
  1541. int64 Time::currentTimeMillis() throw()
  1542. {
  1543. static uint32 lastCounterResult = 0xffffffff;
  1544. static int64 correction = 0;
  1545. const uint32 now = getMillisecondCounter();
  1546. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1547. if (now < lastCounterResult)
  1548. {
  1549. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1550. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1551. {
  1552. // get the time once using normal library calls, and store the difference needed to
  1553. // turn the millisecond counter into a real time.
  1554. #if JUCE_WINDOWS
  1555. struct _timeb t;
  1556. #ifdef USE_NEW_SECURE_TIME_FNS
  1557. _ftime_s (&t);
  1558. #else
  1559. _ftime (&t);
  1560. #endif
  1561. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1562. #else
  1563. struct timeval tv;
  1564. struct timezone tz;
  1565. gettimeofday (&tv, &tz);
  1566. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1567. #endif
  1568. }
  1569. }
  1570. lastCounterResult = now;
  1571. return correction + now;
  1572. }
  1573. uint32 juce_millisecondsSinceStartup() throw();
  1574. uint32 Time::getMillisecondCounter() throw()
  1575. {
  1576. const uint32 now = juce_millisecondsSinceStartup();
  1577. if (now < TimeHelpers::lastMSCounterValue)
  1578. {
  1579. // in multi-threaded apps this might be called concurrently, so
  1580. // make sure that our last counter value only increases and doesn't
  1581. // go backwards..
  1582. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1583. TimeHelpers::lastMSCounterValue = now;
  1584. }
  1585. else
  1586. {
  1587. TimeHelpers::lastMSCounterValue = now;
  1588. }
  1589. return now;
  1590. }
  1591. uint32 Time::getApproximateMillisecondCounter() throw()
  1592. {
  1593. jassert (TimeHelpers::lastMSCounterValue != 0);
  1594. return TimeHelpers::lastMSCounterValue;
  1595. }
  1596. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1597. {
  1598. for (;;)
  1599. {
  1600. const uint32 now = getMillisecondCounter();
  1601. if (now >= targetTime)
  1602. break;
  1603. const int toWait = targetTime - now;
  1604. if (toWait > 2)
  1605. {
  1606. Thread::sleep (jmin (20, toWait >> 1));
  1607. }
  1608. else
  1609. {
  1610. // xxx should consider using mutex_pause on the mac as it apparently
  1611. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1612. for (int i = 10; --i >= 0;)
  1613. Thread::yield();
  1614. }
  1615. }
  1616. }
  1617. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1618. {
  1619. return ticks / (double) getHighResolutionTicksPerSecond();
  1620. }
  1621. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1622. {
  1623. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1624. }
  1625. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1626. {
  1627. return Time (currentTimeMillis());
  1628. }
  1629. const String Time::toString (const bool includeDate,
  1630. const bool includeTime,
  1631. const bool includeSeconds,
  1632. const bool use24HourClock) const throw()
  1633. {
  1634. String result;
  1635. if (includeDate)
  1636. {
  1637. result << getDayOfMonth() << ' '
  1638. << getMonthName (true) << ' '
  1639. << getYear();
  1640. if (includeTime)
  1641. result << ' ';
  1642. }
  1643. if (includeTime)
  1644. {
  1645. const int mins = getMinutes();
  1646. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1647. << (mins < 10 ? ":0" : ":") << mins;
  1648. if (includeSeconds)
  1649. {
  1650. const int secs = getSeconds();
  1651. result << (secs < 10 ? ":0" : ":") << secs;
  1652. }
  1653. if (! use24HourClock)
  1654. result << (isAfternoon() ? "pm" : "am");
  1655. }
  1656. return result.trimEnd();
  1657. }
  1658. const String Time::formatted (const String& format) const
  1659. {
  1660. String buffer;
  1661. int bufferSize = 128;
  1662. buffer.preallocateStorage (bufferSize);
  1663. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1664. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1665. {
  1666. bufferSize += 128;
  1667. buffer.preallocateStorage (bufferSize);
  1668. }
  1669. return buffer;
  1670. }
  1671. int Time::getYear() const throw()
  1672. {
  1673. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1674. }
  1675. int Time::getMonth() const throw()
  1676. {
  1677. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1678. }
  1679. int Time::getDayOfMonth() const throw()
  1680. {
  1681. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1682. }
  1683. int Time::getDayOfWeek() const throw()
  1684. {
  1685. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1686. }
  1687. int Time::getHours() const throw()
  1688. {
  1689. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1690. }
  1691. int Time::getHoursInAmPmFormat() const throw()
  1692. {
  1693. const int hours = getHours();
  1694. if (hours == 0)
  1695. return 12;
  1696. else if (hours <= 12)
  1697. return hours;
  1698. else
  1699. return hours - 12;
  1700. }
  1701. bool Time::isAfternoon() const throw()
  1702. {
  1703. return getHours() >= 12;
  1704. }
  1705. int Time::getMinutes() const throw()
  1706. {
  1707. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1708. }
  1709. int Time::getSeconds() const throw()
  1710. {
  1711. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1712. }
  1713. int Time::getMilliseconds() const throw()
  1714. {
  1715. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1716. }
  1717. bool Time::isDaylightSavingTime() const throw()
  1718. {
  1719. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1720. }
  1721. const String Time::getTimeZone() const throw()
  1722. {
  1723. String zone[2];
  1724. #if JUCE_WINDOWS
  1725. _tzset();
  1726. #ifdef USE_NEW_SECURE_TIME_FNS
  1727. {
  1728. char name [128];
  1729. size_t length;
  1730. for (int i = 0; i < 2; ++i)
  1731. {
  1732. zeromem (name, sizeof (name));
  1733. _get_tzname (&length, name, 127, i);
  1734. zone[i] = name;
  1735. }
  1736. }
  1737. #else
  1738. const char** const zonePtr = (const char**) _tzname;
  1739. zone[0] = zonePtr[0];
  1740. zone[1] = zonePtr[1];
  1741. #endif
  1742. #else
  1743. tzset();
  1744. const char** const zonePtr = (const char**) tzname;
  1745. zone[0] = zonePtr[0];
  1746. zone[1] = zonePtr[1];
  1747. #endif
  1748. if (isDaylightSavingTime())
  1749. {
  1750. zone[0] = zone[1];
  1751. if (zone[0].length() > 3
  1752. && zone[0].containsIgnoreCase ("daylight")
  1753. && zone[0].contains ("GMT"))
  1754. zone[0] = "BST";
  1755. }
  1756. return zone[0].substring (0, 3);
  1757. }
  1758. const String Time::getMonthName (const bool threeLetterVersion) const
  1759. {
  1760. return getMonthName (getMonth(), threeLetterVersion);
  1761. }
  1762. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1763. {
  1764. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1765. }
  1766. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1767. {
  1768. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1769. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1770. monthNumber %= 12;
  1771. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1772. : longMonthNames [monthNumber]);
  1773. }
  1774. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1775. {
  1776. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1777. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1778. day %= 7;
  1779. return TRANS (threeLetterVersion ? shortDayNames [day]
  1780. : longDayNames [day]);
  1781. }
  1782. END_JUCE_NAMESPACE
  1783. /*** End of inlined file: juce_Time.cpp ***/
  1784. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1785. BEGIN_JUCE_NAMESPACE
  1786. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1787. #endif
  1788. #if JUCE_WINDOWS
  1789. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1790. #endif
  1791. #if JUCE_DEBUG
  1792. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1793. #endif
  1794. static bool juceInitialisedNonGUI = false;
  1795. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1796. {
  1797. if (! juceInitialisedNonGUI)
  1798. {
  1799. juceInitialisedNonGUI = true;
  1800. JUCE_AUTORELEASEPOOL
  1801. DBG (SystemStats::getJUCEVersion());
  1802. SystemStats::initialiseStats();
  1803. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1804. }
  1805. // Some basic tests, to keep an eye on things and make sure these types work ok
  1806. // on all platforms. Let me know if any of these assertions fail on your system!
  1807. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1808. static_jassert (sizeof (int8) == 1);
  1809. static_jassert (sizeof (uint8) == 1);
  1810. static_jassert (sizeof (int16) == 2);
  1811. static_jassert (sizeof (uint16) == 2);
  1812. static_jassert (sizeof (int32) == 4);
  1813. static_jassert (sizeof (uint32) == 4);
  1814. static_jassert (sizeof (int64) == 8);
  1815. static_jassert (sizeof (uint64) == 8);
  1816. }
  1817. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1818. {
  1819. if (juceInitialisedNonGUI)
  1820. {
  1821. juceInitialisedNonGUI = false;
  1822. JUCE_AUTORELEASEPOOL
  1823. LocalisedStrings::setCurrentMappings (0);
  1824. Thread::stopAllThreads (3000);
  1825. #if JUCE_WINDOWS
  1826. juce_shutdownWin32Sockets();
  1827. #endif
  1828. #if JUCE_DEBUG
  1829. juce_CheckForDanglingStreams();
  1830. #endif
  1831. }
  1832. }
  1833. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1834. void juce_setCurrentThreadName (const String& name);
  1835. static bool juceInitialisedGUI = false;
  1836. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1837. {
  1838. if (! juceInitialisedGUI)
  1839. {
  1840. juceInitialisedGUI = true;
  1841. JUCE_AUTORELEASEPOOL
  1842. initialiseJuce_NonGUI();
  1843. MessageManager::getInstance();
  1844. LookAndFeel::setDefaultLookAndFeel (0);
  1845. juce_setCurrentThreadName ("Juce Message Thread");
  1846. #if JUCE_DEBUG
  1847. // This section is just for catching people who mess up their project settings and
  1848. // turn RTTI off..
  1849. try
  1850. {
  1851. MemoryOutputStream mo;
  1852. OutputStream* o = &mo;
  1853. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1854. o = dynamic_cast <MemoryOutputStream*> (o);
  1855. jassert (o != 0);
  1856. }
  1857. catch (...)
  1858. {
  1859. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1860. jassertfalse;
  1861. }
  1862. #endif
  1863. }
  1864. }
  1865. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1866. {
  1867. if (juceInitialisedGUI)
  1868. {
  1869. juceInitialisedGUI = false;
  1870. JUCE_AUTORELEASEPOOL
  1871. DeletedAtShutdown::deleteAll();
  1872. LookAndFeel::clearDefaultLookAndFeel();
  1873. delete MessageManager::getInstance();
  1874. shutdownJuce_NonGUI();
  1875. }
  1876. }
  1877. #endif
  1878. #if JUCE_UNIT_TESTS
  1879. class AtomicTests : public UnitTest
  1880. {
  1881. public:
  1882. AtomicTests() : UnitTest ("Atomics") {}
  1883. void runTest()
  1884. {
  1885. beginTest ("Misc");
  1886. char a1[7];
  1887. expect (numElementsInArray(a1) == 7);
  1888. int a2[3];
  1889. expect (numElementsInArray(a2) == 3);
  1890. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1891. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1892. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1893. beginTest ("Atomic types");
  1894. AtomicTester <int>::testInteger (*this);
  1895. AtomicTester <unsigned int>::testInteger (*this);
  1896. AtomicTester <int32>::testInteger (*this);
  1897. AtomicTester <uint32>::testInteger (*this);
  1898. AtomicTester <long>::testInteger (*this);
  1899. AtomicTester <void*>::testInteger (*this);
  1900. AtomicTester <int*>::testInteger (*this);
  1901. AtomicTester <float>::testFloat (*this);
  1902. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1903. AtomicTester <int64>::testInteger (*this);
  1904. AtomicTester <uint64>::testInteger (*this);
  1905. AtomicTester <double>::testFloat (*this);
  1906. #endif
  1907. }
  1908. template <typename Type>
  1909. class AtomicTester
  1910. {
  1911. public:
  1912. AtomicTester() {}
  1913. static void testInteger (UnitTest& test)
  1914. {
  1915. Atomic<Type> a, b;
  1916. a.set ((Type) 10);
  1917. a += (Type) 15;
  1918. a.memoryBarrier();
  1919. a -= (Type) 5;
  1920. ++a; ++a; --a;
  1921. a.memoryBarrier();
  1922. testFloat (test);
  1923. }
  1924. static void testFloat (UnitTest& test)
  1925. {
  1926. Atomic<Type> a, b;
  1927. a = (Type) 21;
  1928. a.memoryBarrier();
  1929. /* These are some simple test cases to check the atomics - let me know
  1930. if any of these assertions fail on your system!
  1931. */
  1932. test.expect (a.get() == (Type) 21);
  1933. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1934. test.expect (a.get() == (Type) 21);
  1935. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1936. test.expect (a.get() == (Type) 101);
  1937. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1938. test.expect (a.get() == (Type) 101);
  1939. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1940. test.expect (a.get() == (Type) 200);
  1941. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1942. test.expect (a.get() == (Type) 300);
  1943. b = a;
  1944. test.expect (b.get() == a.get());
  1945. }
  1946. };
  1947. };
  1948. static AtomicTests atomicUnitTests;
  1949. #endif
  1950. END_JUCE_NAMESPACE
  1951. /*** End of inlined file: juce_Initialisation.cpp ***/
  1952. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1953. BEGIN_JUCE_NAMESPACE
  1954. AbstractFifo::AbstractFifo (const int capacity) throw()
  1955. : bufferSize (capacity)
  1956. {
  1957. jassert (bufferSize > 0);
  1958. }
  1959. AbstractFifo::~AbstractFifo() {}
  1960. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1961. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1962. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1963. void AbstractFifo::reset() throw()
  1964. {
  1965. validEnd = 0;
  1966. validStart = 0;
  1967. }
  1968. void AbstractFifo::setTotalSize (int newSize) throw()
  1969. {
  1970. jassert (newSize > 0);
  1971. reset();
  1972. bufferSize = newSize;
  1973. }
  1974. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1975. {
  1976. const int vs = validStart.get();
  1977. const int ve = validEnd.get();
  1978. const int freeSpace = bufferSize - (ve - vs);
  1979. numToWrite = jmin (numToWrite, freeSpace);
  1980. if (numToWrite <= 0)
  1981. {
  1982. startIndex1 = 0;
  1983. startIndex2 = 0;
  1984. blockSize1 = 0;
  1985. blockSize2 = 0;
  1986. }
  1987. else
  1988. {
  1989. startIndex1 = (int) (ve % bufferSize);
  1990. startIndex2 = 0;
  1991. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1992. numToWrite -= blockSize1;
  1993. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  1994. }
  1995. }
  1996. void AbstractFifo::finishedWrite (int numWritten) throw()
  1997. {
  1998. jassert (numWritten >= 0 && numWritten < bufferSize);
  1999. validEnd += numWritten;
  2000. }
  2001. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  2002. {
  2003. const int vs = validStart.get();
  2004. const int ve = validEnd.get();
  2005. const int numReady = ve - vs;
  2006. numWanted = jmin (numWanted, numReady);
  2007. if (numWanted <= 0)
  2008. {
  2009. startIndex1 = 0;
  2010. startIndex2 = 0;
  2011. blockSize1 = 0;
  2012. blockSize2 = 0;
  2013. }
  2014. else
  2015. {
  2016. startIndex1 = (int) (vs % bufferSize);
  2017. startIndex2 = 0;
  2018. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  2019. numWanted -= blockSize1;
  2020. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  2021. }
  2022. }
  2023. void AbstractFifo::finishedRead (int numRead) throw()
  2024. {
  2025. jassert (numRead >= 0 && numRead < bufferSize);
  2026. validStart += numRead;
  2027. }
  2028. END_JUCE_NAMESPACE
  2029. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2030. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2031. BEGIN_JUCE_NAMESPACE
  2032. BigInteger::BigInteger()
  2033. : numValues (4),
  2034. highestBit (-1),
  2035. negative (false)
  2036. {
  2037. values.calloc (numValues + 1);
  2038. }
  2039. BigInteger::BigInteger (const int32 value)
  2040. : numValues (4),
  2041. highestBit (31),
  2042. negative (value < 0)
  2043. {
  2044. values.calloc (numValues + 1);
  2045. values[0] = abs (value);
  2046. highestBit = getHighestBit();
  2047. }
  2048. BigInteger::BigInteger (const uint32 value)
  2049. : numValues (4),
  2050. highestBit (31),
  2051. negative (false)
  2052. {
  2053. values.calloc (numValues + 1);
  2054. values[0] = value;
  2055. highestBit = getHighestBit();
  2056. }
  2057. BigInteger::BigInteger (int64 value)
  2058. : numValues (4),
  2059. highestBit (63),
  2060. negative (value < 0)
  2061. {
  2062. values.calloc (numValues + 1);
  2063. if (value < 0)
  2064. value = -value;
  2065. values[0] = (uint32) value;
  2066. values[1] = (uint32) (value >> 32);
  2067. highestBit = getHighestBit();
  2068. }
  2069. BigInteger::BigInteger (const BigInteger& other)
  2070. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2071. highestBit (other.getHighestBit()),
  2072. negative (other.negative)
  2073. {
  2074. values.malloc (numValues + 1);
  2075. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2076. }
  2077. BigInteger::~BigInteger()
  2078. {
  2079. }
  2080. void BigInteger::swapWith (BigInteger& other) throw()
  2081. {
  2082. values.swapWith (other.values);
  2083. swapVariables (numValues, other.numValues);
  2084. swapVariables (highestBit, other.highestBit);
  2085. swapVariables (negative, other.negative);
  2086. }
  2087. BigInteger& BigInteger::operator= (const BigInteger& other)
  2088. {
  2089. if (this != &other)
  2090. {
  2091. highestBit = other.getHighestBit();
  2092. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2093. negative = other.negative;
  2094. values.malloc (numValues + 1);
  2095. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2096. }
  2097. return *this;
  2098. }
  2099. void BigInteger::ensureSize (const int numVals)
  2100. {
  2101. if (numVals + 2 >= numValues)
  2102. {
  2103. int oldSize = numValues;
  2104. numValues = ((numVals + 2) * 3) / 2;
  2105. values.realloc (numValues + 1);
  2106. while (oldSize < numValues)
  2107. values [oldSize++] = 0;
  2108. }
  2109. }
  2110. bool BigInteger::operator[] (const int bit) const throw()
  2111. {
  2112. return bit <= highestBit && bit >= 0
  2113. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2114. }
  2115. int BigInteger::toInteger() const throw()
  2116. {
  2117. const int n = (int) (values[0] & 0x7fffffff);
  2118. return negative ? -n : n;
  2119. }
  2120. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2121. {
  2122. BigInteger r;
  2123. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2124. r.ensureSize (bitToIndex (numBits));
  2125. r.highestBit = numBits;
  2126. int i = 0;
  2127. while (numBits > 0)
  2128. {
  2129. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2130. numBits -= 32;
  2131. startBit += 32;
  2132. }
  2133. r.highestBit = r.getHighestBit();
  2134. return r;
  2135. }
  2136. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2137. {
  2138. if (numBits > 32)
  2139. {
  2140. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2141. numBits = 32;
  2142. }
  2143. numBits = jmin (numBits, highestBit + 1 - startBit);
  2144. if (numBits <= 0)
  2145. return 0;
  2146. const int pos = bitToIndex (startBit);
  2147. const int offset = startBit & 31;
  2148. const int endSpace = 32 - numBits;
  2149. uint32 n = ((uint32) values [pos]) >> offset;
  2150. if (offset > endSpace)
  2151. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2152. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2153. }
  2154. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2155. {
  2156. if (numBits > 32)
  2157. {
  2158. jassertfalse;
  2159. numBits = 32;
  2160. }
  2161. for (int i = 0; i < numBits; ++i)
  2162. {
  2163. setBit (startBit + i, (valueToSet & 1) != 0);
  2164. valueToSet >>= 1;
  2165. }
  2166. }
  2167. void BigInteger::clear()
  2168. {
  2169. if (numValues > 16)
  2170. {
  2171. numValues = 4;
  2172. values.calloc (numValues + 1);
  2173. }
  2174. else
  2175. {
  2176. zeromem (values, sizeof (uint32) * (numValues + 1));
  2177. }
  2178. highestBit = -1;
  2179. negative = false;
  2180. }
  2181. void BigInteger::setBit (const int bit)
  2182. {
  2183. if (bit >= 0)
  2184. {
  2185. if (bit > highestBit)
  2186. {
  2187. ensureSize (bitToIndex (bit));
  2188. highestBit = bit;
  2189. }
  2190. values [bitToIndex (bit)] |= bitToMask (bit);
  2191. }
  2192. }
  2193. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2194. {
  2195. if (shouldBeSet)
  2196. setBit (bit);
  2197. else
  2198. clearBit (bit);
  2199. }
  2200. void BigInteger::clearBit (const int bit) throw()
  2201. {
  2202. if (bit >= 0 && bit <= highestBit)
  2203. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2204. }
  2205. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2206. {
  2207. while (--numBits >= 0)
  2208. setBit (startBit++, shouldBeSet);
  2209. }
  2210. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2211. {
  2212. if (bit >= 0)
  2213. shiftBits (1, bit);
  2214. setBit (bit, shouldBeSet);
  2215. }
  2216. bool BigInteger::isZero() const throw()
  2217. {
  2218. return getHighestBit() < 0;
  2219. }
  2220. bool BigInteger::isOne() const throw()
  2221. {
  2222. return getHighestBit() == 0 && ! negative;
  2223. }
  2224. bool BigInteger::isNegative() const throw()
  2225. {
  2226. return negative && ! isZero();
  2227. }
  2228. void BigInteger::setNegative (const bool neg) throw()
  2229. {
  2230. negative = neg;
  2231. }
  2232. void BigInteger::negate() throw()
  2233. {
  2234. negative = (! negative) && ! isZero();
  2235. }
  2236. #if JUCE_USE_INTRINSICS
  2237. #pragma intrinsic (_BitScanReverse)
  2238. #endif
  2239. namespace BitFunctions
  2240. {
  2241. inline int countBitsInInt32 (uint32 n) throw()
  2242. {
  2243. n -= ((n >> 1) & 0x55555555);
  2244. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2245. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2246. n += (n >> 8);
  2247. n += (n >> 16);
  2248. return n & 0x3f;
  2249. }
  2250. inline int highestBitInInt (uint32 n) throw()
  2251. {
  2252. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2253. #if JUCE_GCC
  2254. return 31 - __builtin_clz (n);
  2255. #elif JUCE_USE_INTRINSICS
  2256. unsigned long highest;
  2257. _BitScanReverse (&highest, n);
  2258. return (int) highest;
  2259. #else
  2260. n |= (n >> 1);
  2261. n |= (n >> 2);
  2262. n |= (n >> 4);
  2263. n |= (n >> 8);
  2264. n |= (n >> 16);
  2265. return countBitsInInt32 (n >> 1);
  2266. #endif
  2267. }
  2268. }
  2269. int BigInteger::countNumberOfSetBits() const throw()
  2270. {
  2271. int total = 0;
  2272. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2273. total += BitFunctions::countBitsInInt32 (values[i]);
  2274. return total;
  2275. }
  2276. int BigInteger::getHighestBit() const throw()
  2277. {
  2278. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2279. {
  2280. const uint32 n = values[i];
  2281. if (n != 0)
  2282. return BitFunctions::highestBitInInt (n) + (i << 5);
  2283. }
  2284. return -1;
  2285. }
  2286. int BigInteger::findNextSetBit (int i) const throw()
  2287. {
  2288. for (; i <= highestBit; ++i)
  2289. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2290. return i;
  2291. return -1;
  2292. }
  2293. int BigInteger::findNextClearBit (int i) const throw()
  2294. {
  2295. for (; i <= highestBit; ++i)
  2296. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2297. break;
  2298. return i;
  2299. }
  2300. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2301. {
  2302. if (other.isNegative())
  2303. return operator-= (-other);
  2304. if (isNegative())
  2305. {
  2306. if (compareAbsolute (other) < 0)
  2307. {
  2308. BigInteger temp (*this);
  2309. temp.negate();
  2310. *this = other;
  2311. operator-= (temp);
  2312. }
  2313. else
  2314. {
  2315. negate();
  2316. operator-= (other);
  2317. negate();
  2318. }
  2319. }
  2320. else
  2321. {
  2322. if (other.highestBit > highestBit)
  2323. highestBit = other.highestBit;
  2324. ++highestBit;
  2325. const int numInts = bitToIndex (highestBit) + 1;
  2326. ensureSize (numInts);
  2327. int64 remainder = 0;
  2328. for (int i = 0; i <= numInts; ++i)
  2329. {
  2330. if (i < numValues)
  2331. remainder += values[i];
  2332. if (i < other.numValues)
  2333. remainder += other.values[i];
  2334. values[i] = (uint32) remainder;
  2335. remainder >>= 32;
  2336. }
  2337. jassert (remainder == 0);
  2338. highestBit = getHighestBit();
  2339. }
  2340. return *this;
  2341. }
  2342. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2343. {
  2344. if (other.isNegative())
  2345. return operator+= (-other);
  2346. if (! isNegative())
  2347. {
  2348. if (compareAbsolute (other) < 0)
  2349. {
  2350. BigInteger temp (other);
  2351. swapWith (temp);
  2352. operator-= (temp);
  2353. negate();
  2354. return *this;
  2355. }
  2356. }
  2357. else
  2358. {
  2359. negate();
  2360. operator+= (other);
  2361. negate();
  2362. return *this;
  2363. }
  2364. const int numInts = bitToIndex (highestBit) + 1;
  2365. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2366. int64 amountToSubtract = 0;
  2367. for (int i = 0; i <= numInts; ++i)
  2368. {
  2369. if (i <= maxOtherInts)
  2370. amountToSubtract += (int64) other.values[i];
  2371. if (values[i] >= amountToSubtract)
  2372. {
  2373. values[i] = (uint32) (values[i] - amountToSubtract);
  2374. amountToSubtract = 0;
  2375. }
  2376. else
  2377. {
  2378. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2379. values[i] = (uint32) n;
  2380. amountToSubtract = 1;
  2381. }
  2382. }
  2383. return *this;
  2384. }
  2385. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2386. {
  2387. BigInteger total;
  2388. highestBit = getHighestBit();
  2389. const bool wasNegative = isNegative();
  2390. setNegative (false);
  2391. for (int i = 0; i <= highestBit; ++i)
  2392. {
  2393. if (operator[](i))
  2394. {
  2395. BigInteger n (other);
  2396. n.setNegative (false);
  2397. n <<= i;
  2398. total += n;
  2399. }
  2400. }
  2401. total.setNegative (wasNegative ^ other.isNegative());
  2402. swapWith (total);
  2403. return *this;
  2404. }
  2405. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2406. {
  2407. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2408. const int divHB = divisor.getHighestBit();
  2409. const int ourHB = getHighestBit();
  2410. if (divHB < 0 || ourHB < 0)
  2411. {
  2412. // division by zero
  2413. remainder.clear();
  2414. clear();
  2415. }
  2416. else
  2417. {
  2418. const bool wasNegative = isNegative();
  2419. swapWith (remainder);
  2420. remainder.setNegative (false);
  2421. clear();
  2422. BigInteger temp (divisor);
  2423. temp.setNegative (false);
  2424. int leftShift = ourHB - divHB;
  2425. temp <<= leftShift;
  2426. while (leftShift >= 0)
  2427. {
  2428. if (remainder.compareAbsolute (temp) >= 0)
  2429. {
  2430. remainder -= temp;
  2431. setBit (leftShift);
  2432. }
  2433. if (--leftShift >= 0)
  2434. temp >>= 1;
  2435. }
  2436. negative = wasNegative ^ divisor.isNegative();
  2437. remainder.setNegative (wasNegative);
  2438. }
  2439. }
  2440. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2441. {
  2442. BigInteger remainder;
  2443. divideBy (other, remainder);
  2444. return *this;
  2445. }
  2446. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2447. {
  2448. // this operation doesn't take into account negative values..
  2449. jassert (isNegative() == other.isNegative());
  2450. if (other.highestBit >= 0)
  2451. {
  2452. ensureSize (bitToIndex (other.highestBit));
  2453. int n = bitToIndex (other.highestBit) + 1;
  2454. while (--n >= 0)
  2455. values[n] |= other.values[n];
  2456. if (other.highestBit > highestBit)
  2457. highestBit = other.highestBit;
  2458. highestBit = getHighestBit();
  2459. }
  2460. return *this;
  2461. }
  2462. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2463. {
  2464. // this operation doesn't take into account negative values..
  2465. jassert (isNegative() == other.isNegative());
  2466. int n = numValues;
  2467. while (n > other.numValues)
  2468. values[--n] = 0;
  2469. while (--n >= 0)
  2470. values[n] &= other.values[n];
  2471. if (other.highestBit < highestBit)
  2472. highestBit = other.highestBit;
  2473. highestBit = getHighestBit();
  2474. return *this;
  2475. }
  2476. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2477. {
  2478. // this operation will only work with the absolute values
  2479. jassert (isNegative() == other.isNegative());
  2480. if (other.highestBit >= 0)
  2481. {
  2482. ensureSize (bitToIndex (other.highestBit));
  2483. int n = bitToIndex (other.highestBit) + 1;
  2484. while (--n >= 0)
  2485. values[n] ^= other.values[n];
  2486. if (other.highestBit > highestBit)
  2487. highestBit = other.highestBit;
  2488. highestBit = getHighestBit();
  2489. }
  2490. return *this;
  2491. }
  2492. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2493. {
  2494. BigInteger remainder;
  2495. divideBy (divisor, remainder);
  2496. swapWith (remainder);
  2497. return *this;
  2498. }
  2499. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2500. {
  2501. shiftBits (numBitsToShift, 0);
  2502. return *this;
  2503. }
  2504. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2505. {
  2506. return operator<<= (-numBitsToShift);
  2507. }
  2508. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2509. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2510. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2511. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2512. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2513. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2514. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2515. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2516. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2517. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2518. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2519. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2520. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2521. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2522. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2523. int BigInteger::compare (const BigInteger& other) const throw()
  2524. {
  2525. if (isNegative() == other.isNegative())
  2526. {
  2527. const int absComp = compareAbsolute (other);
  2528. return isNegative() ? -absComp : absComp;
  2529. }
  2530. else
  2531. {
  2532. return isNegative() ? -1 : 1;
  2533. }
  2534. }
  2535. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2536. {
  2537. const int h1 = getHighestBit();
  2538. const int h2 = other.getHighestBit();
  2539. if (h1 > h2)
  2540. return 1;
  2541. else if (h1 < h2)
  2542. return -1;
  2543. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2544. if (values[i] != other.values[i])
  2545. return (values[i] > other.values[i]) ? 1 : -1;
  2546. return 0;
  2547. }
  2548. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2549. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2550. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2551. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2552. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2553. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2554. void BigInteger::shiftBits (int bits, const int startBit)
  2555. {
  2556. if (highestBit < 0)
  2557. return;
  2558. if (startBit > 0)
  2559. {
  2560. if (bits < 0)
  2561. {
  2562. // right shift
  2563. for (int i = startBit; i <= highestBit; ++i)
  2564. setBit (i, operator[] (i - bits));
  2565. highestBit = getHighestBit();
  2566. }
  2567. else if (bits > 0)
  2568. {
  2569. // left shift
  2570. for (int i = highestBit + 1; --i >= startBit;)
  2571. setBit (i + bits, operator[] (i));
  2572. while (--bits >= 0)
  2573. clearBit (bits + startBit);
  2574. }
  2575. }
  2576. else
  2577. {
  2578. if (bits < 0)
  2579. {
  2580. // right shift
  2581. bits = -bits;
  2582. if (bits > highestBit)
  2583. {
  2584. clear();
  2585. }
  2586. else
  2587. {
  2588. const int wordsToMove = bitToIndex (bits);
  2589. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2590. highestBit -= bits;
  2591. if (wordsToMove > 0)
  2592. {
  2593. int i;
  2594. for (i = 0; i < top; ++i)
  2595. values [i] = values [i + wordsToMove];
  2596. for (i = 0; i < wordsToMove; ++i)
  2597. values [top + i] = 0;
  2598. bits &= 31;
  2599. }
  2600. if (bits != 0)
  2601. {
  2602. const int invBits = 32 - bits;
  2603. --top;
  2604. for (int i = 0; i < top; ++i)
  2605. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2606. values[top] = (values[top] >> bits);
  2607. }
  2608. highestBit = getHighestBit();
  2609. }
  2610. }
  2611. else if (bits > 0)
  2612. {
  2613. // left shift
  2614. ensureSize (bitToIndex (highestBit + bits) + 1);
  2615. const int wordsToMove = bitToIndex (bits);
  2616. int top = 1 + bitToIndex (highestBit);
  2617. highestBit += bits;
  2618. if (wordsToMove > 0)
  2619. {
  2620. int i;
  2621. for (i = top; --i >= 0;)
  2622. values [i + wordsToMove] = values [i];
  2623. for (i = 0; i < wordsToMove; ++i)
  2624. values [i] = 0;
  2625. bits &= 31;
  2626. }
  2627. if (bits != 0)
  2628. {
  2629. const int invBits = 32 - bits;
  2630. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2631. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2632. values [wordsToMove] = values [wordsToMove] << bits;
  2633. }
  2634. highestBit = getHighestBit();
  2635. }
  2636. }
  2637. }
  2638. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2639. {
  2640. while (! m->isZero())
  2641. {
  2642. if (n->compareAbsolute (*m) > 0)
  2643. swapVariables (m, n);
  2644. *m -= *n;
  2645. }
  2646. return *n;
  2647. }
  2648. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2649. {
  2650. BigInteger m (*this);
  2651. while (! n.isZero())
  2652. {
  2653. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2654. return simpleGCD (&m, &n);
  2655. BigInteger temp1 (m), temp2;
  2656. temp1.divideBy (n, temp2);
  2657. m = n;
  2658. n = temp2;
  2659. }
  2660. return m;
  2661. }
  2662. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2663. {
  2664. BigInteger exp (exponent);
  2665. exp %= modulus;
  2666. BigInteger value (1);
  2667. swapWith (value);
  2668. value %= modulus;
  2669. while (! exp.isZero())
  2670. {
  2671. if (exp [0])
  2672. {
  2673. operator*= (value);
  2674. operator%= (modulus);
  2675. }
  2676. value *= value;
  2677. value %= modulus;
  2678. exp >>= 1;
  2679. }
  2680. }
  2681. void BigInteger::inverseModulo (const BigInteger& modulus)
  2682. {
  2683. if (modulus.isOne() || modulus.isNegative())
  2684. {
  2685. clear();
  2686. return;
  2687. }
  2688. if (isNegative() || compareAbsolute (modulus) >= 0)
  2689. operator%= (modulus);
  2690. if (isOne())
  2691. return;
  2692. if (! (*this)[0])
  2693. {
  2694. // not invertible
  2695. clear();
  2696. return;
  2697. }
  2698. BigInteger a1 (modulus);
  2699. BigInteger a2 (*this);
  2700. BigInteger b1 (modulus);
  2701. BigInteger b2 (1);
  2702. while (! a2.isOne())
  2703. {
  2704. BigInteger temp1, temp2, multiplier (a1);
  2705. multiplier.divideBy (a2, temp1);
  2706. temp1 = a2;
  2707. temp1 *= multiplier;
  2708. temp2 = a1;
  2709. temp2 -= temp1;
  2710. a1 = a2;
  2711. a2 = temp2;
  2712. temp1 = b2;
  2713. temp1 *= multiplier;
  2714. temp2 = b1;
  2715. temp2 -= temp1;
  2716. b1 = b2;
  2717. b2 = temp2;
  2718. }
  2719. while (b2.isNegative())
  2720. b2 += modulus;
  2721. b2 %= modulus;
  2722. swapWith (b2);
  2723. }
  2724. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2725. {
  2726. return stream << value.toString (10);
  2727. }
  2728. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2729. {
  2730. String s;
  2731. BigInteger v (*this);
  2732. if (base == 2 || base == 8 || base == 16)
  2733. {
  2734. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2735. static const char* const hexDigits = "0123456789abcdef";
  2736. for (;;)
  2737. {
  2738. const int remainder = v.getBitRangeAsInt (0, bits);
  2739. v >>= bits;
  2740. if (remainder == 0 && v.isZero())
  2741. break;
  2742. s = String::charToString (hexDigits [remainder]) + s;
  2743. }
  2744. }
  2745. else if (base == 10)
  2746. {
  2747. const BigInteger ten (10);
  2748. BigInteger remainder;
  2749. for (;;)
  2750. {
  2751. v.divideBy (ten, remainder);
  2752. if (remainder.isZero() && v.isZero())
  2753. break;
  2754. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2755. }
  2756. }
  2757. else
  2758. {
  2759. jassertfalse; // can't do the specified base!
  2760. return String::empty;
  2761. }
  2762. s = s.paddedLeft ('0', minimumNumCharacters);
  2763. return isNegative() ? "-" + s : s;
  2764. }
  2765. void BigInteger::parseString (const String& text, const int base)
  2766. {
  2767. clear();
  2768. const juce_wchar* t = text;
  2769. if (base == 2 || base == 8 || base == 16)
  2770. {
  2771. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2772. for (;;)
  2773. {
  2774. const juce_wchar c = *t++;
  2775. const int digit = CharacterFunctions::getHexDigitValue (c);
  2776. if (((uint32) digit) < (uint32) base)
  2777. {
  2778. operator<<= (bits);
  2779. operator+= (digit);
  2780. }
  2781. else if (c == 0)
  2782. {
  2783. break;
  2784. }
  2785. }
  2786. }
  2787. else if (base == 10)
  2788. {
  2789. const BigInteger ten ((uint32) 10);
  2790. for (;;)
  2791. {
  2792. const juce_wchar c = *t++;
  2793. if (c >= '0' && c <= '9')
  2794. {
  2795. operator*= (ten);
  2796. operator+= ((int) (c - '0'));
  2797. }
  2798. else if (c == 0)
  2799. {
  2800. break;
  2801. }
  2802. }
  2803. }
  2804. setNegative (text.trimStart().startsWithChar ('-'));
  2805. }
  2806. const MemoryBlock BigInteger::toMemoryBlock() const
  2807. {
  2808. const int numBytes = (getHighestBit() + 8) >> 3;
  2809. MemoryBlock mb ((size_t) numBytes);
  2810. for (int i = 0; i < numBytes; ++i)
  2811. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2812. return mb;
  2813. }
  2814. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2815. {
  2816. clear();
  2817. for (int i = (int) data.getSize(); --i >= 0;)
  2818. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2819. }
  2820. END_JUCE_NAMESPACE
  2821. /*** End of inlined file: juce_BigInteger.cpp ***/
  2822. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2823. BEGIN_JUCE_NAMESPACE
  2824. MemoryBlock::MemoryBlock() throw()
  2825. : size (0)
  2826. {
  2827. }
  2828. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2829. {
  2830. if (initialSize > 0)
  2831. {
  2832. size = initialSize;
  2833. data.allocate (initialSize, initialiseToZero);
  2834. }
  2835. else
  2836. {
  2837. size = 0;
  2838. }
  2839. }
  2840. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2841. : size (other.size)
  2842. {
  2843. if (size > 0)
  2844. {
  2845. jassert (other.data != 0);
  2846. data.malloc (size);
  2847. memcpy (data, other.data, size);
  2848. }
  2849. }
  2850. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2851. : size (jmax ((size_t) 0, sizeInBytes))
  2852. {
  2853. jassert (sizeInBytes >= 0);
  2854. if (size > 0)
  2855. {
  2856. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2857. data.malloc (size);
  2858. if (dataToInitialiseFrom != 0)
  2859. memcpy (data, dataToInitialiseFrom, size);
  2860. }
  2861. }
  2862. MemoryBlock::~MemoryBlock() throw()
  2863. {
  2864. jassert (size >= 0); // should never happen
  2865. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2866. }
  2867. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2868. {
  2869. if (this != &other)
  2870. {
  2871. setSize (other.size, false);
  2872. memcpy (data, other.data, size);
  2873. }
  2874. return *this;
  2875. }
  2876. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2877. {
  2878. return matches (other.data, other.size);
  2879. }
  2880. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2881. {
  2882. return ! operator== (other);
  2883. }
  2884. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2885. {
  2886. return size == dataSize
  2887. && memcmp (data, dataToCompare, size) == 0;
  2888. }
  2889. // this will resize the block to this size
  2890. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2891. {
  2892. if (size != newSize)
  2893. {
  2894. if (newSize <= 0)
  2895. {
  2896. data.free();
  2897. size = 0;
  2898. }
  2899. else
  2900. {
  2901. if (data != 0)
  2902. {
  2903. data.realloc (newSize);
  2904. if (initialiseToZero && (newSize > size))
  2905. zeromem (data + size, newSize - size);
  2906. }
  2907. else
  2908. {
  2909. data.allocate (newSize, initialiseToZero);
  2910. }
  2911. size = newSize;
  2912. }
  2913. }
  2914. }
  2915. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2916. {
  2917. if (size < minimumSize)
  2918. setSize (minimumSize, initialiseToZero);
  2919. }
  2920. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2921. {
  2922. swapVariables (size, other.size);
  2923. data.swapWith (other.data);
  2924. }
  2925. void MemoryBlock::fillWith (const uint8 value) throw()
  2926. {
  2927. memset (data, (int) value, size);
  2928. }
  2929. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2930. {
  2931. if (numBytes > 0)
  2932. {
  2933. const size_t oldSize = size;
  2934. setSize (size + numBytes);
  2935. memcpy (data + oldSize, srcData, numBytes);
  2936. }
  2937. }
  2938. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2939. {
  2940. const char* d = static_cast<const char*> (src);
  2941. if (offset < 0)
  2942. {
  2943. d -= offset;
  2944. num -= offset;
  2945. offset = 0;
  2946. }
  2947. if (offset + num > size)
  2948. num = size - offset;
  2949. if (num > 0)
  2950. memcpy (data + offset, d, num);
  2951. }
  2952. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2953. {
  2954. char* d = static_cast<char*> (dst);
  2955. if (offset < 0)
  2956. {
  2957. zeromem (d, -offset);
  2958. d -= offset;
  2959. num += offset;
  2960. offset = 0;
  2961. }
  2962. if (offset + num > size)
  2963. {
  2964. const size_t newNum = size - offset;
  2965. zeromem (d + newNum, num - newNum);
  2966. num = newNum;
  2967. }
  2968. if (num > 0)
  2969. memcpy (d, data + offset, num);
  2970. }
  2971. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2972. {
  2973. if (startByte < 0)
  2974. {
  2975. numBytesToRemove += startByte;
  2976. startByte = 0;
  2977. }
  2978. if (startByte + numBytesToRemove >= size)
  2979. {
  2980. setSize (startByte);
  2981. }
  2982. else if (numBytesToRemove > 0)
  2983. {
  2984. memmove (data + startByte,
  2985. data + startByte + numBytesToRemove,
  2986. size - (startByte + numBytesToRemove));
  2987. setSize (size - numBytesToRemove);
  2988. }
  2989. }
  2990. const String MemoryBlock::toString() const
  2991. {
  2992. return String (static_cast <const char*> (getData()), size);
  2993. }
  2994. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2995. {
  2996. int res = 0;
  2997. size_t byte = bitRangeStart >> 3;
  2998. int offsetInByte = (int) bitRangeStart & 7;
  2999. size_t bitsSoFar = 0;
  3000. while (numBits > 0 && (size_t) byte < size)
  3001. {
  3002. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3003. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  3004. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  3005. bitsSoFar += bitsThisTime;
  3006. numBits -= bitsThisTime;
  3007. ++byte;
  3008. offsetInByte = 0;
  3009. }
  3010. return res;
  3011. }
  3012. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  3013. {
  3014. size_t byte = bitRangeStart >> 3;
  3015. int offsetInByte = (int) bitRangeStart & 7;
  3016. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3017. while (numBits > 0 && (size_t) byte < size)
  3018. {
  3019. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3020. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3021. const unsigned int tempBits = bitsToSet << offsetInByte;
  3022. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3023. ++byte;
  3024. numBits -= bitsThisTime;
  3025. bitsToSet >>= bitsThisTime;
  3026. mask >>= bitsThisTime;
  3027. offsetInByte = 0;
  3028. }
  3029. }
  3030. void MemoryBlock::loadFromHexString (const String& hex)
  3031. {
  3032. ensureSize (hex.length() >> 1);
  3033. char* dest = data;
  3034. int i = 0;
  3035. for (;;)
  3036. {
  3037. int byte = 0;
  3038. for (int loop = 2; --loop >= 0;)
  3039. {
  3040. byte <<= 4;
  3041. for (;;)
  3042. {
  3043. const juce_wchar c = hex [i++];
  3044. if (c >= '0' && c <= '9')
  3045. {
  3046. byte |= c - '0';
  3047. break;
  3048. }
  3049. else if (c >= 'a' && c <= 'z')
  3050. {
  3051. byte |= c - ('a' - 10);
  3052. break;
  3053. }
  3054. else if (c >= 'A' && c <= 'Z')
  3055. {
  3056. byte |= c - ('A' - 10);
  3057. break;
  3058. }
  3059. else if (c == 0)
  3060. {
  3061. setSize (static_cast <size_t> (dest - data));
  3062. return;
  3063. }
  3064. }
  3065. }
  3066. *dest++ = (char) byte;
  3067. }
  3068. }
  3069. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3070. const String MemoryBlock::toBase64Encoding() const
  3071. {
  3072. const size_t numChars = ((size << 3) + 5) / 6;
  3073. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3074. const int initialLen = destString.length();
  3075. destString.preallocateStorage (initialLen + 2 + numChars);
  3076. juce_wchar* d = destString;
  3077. d += initialLen;
  3078. *d++ = '.';
  3079. for (size_t i = 0; i < numChars; ++i)
  3080. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3081. *d++ = 0;
  3082. return destString;
  3083. }
  3084. bool MemoryBlock::fromBase64Encoding (const String& s)
  3085. {
  3086. const int startPos = s.indexOfChar ('.') + 1;
  3087. if (startPos <= 0)
  3088. return false;
  3089. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3090. setSize (numBytesNeeded, true);
  3091. const int numChars = s.length() - startPos;
  3092. const juce_wchar* srcChars = s;
  3093. srcChars += startPos;
  3094. int pos = 0;
  3095. for (int i = 0; i < numChars; ++i)
  3096. {
  3097. const char c = (char) srcChars[i];
  3098. for (int j = 0; j < 64; ++j)
  3099. {
  3100. if (encodingTable[j] == c)
  3101. {
  3102. setBitRange (pos, 6, j);
  3103. pos += 6;
  3104. break;
  3105. }
  3106. }
  3107. }
  3108. return true;
  3109. }
  3110. END_JUCE_NAMESPACE
  3111. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3112. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3113. BEGIN_JUCE_NAMESPACE
  3114. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3115. : properties (ignoreCaseOfKeyNames),
  3116. fallbackProperties (0),
  3117. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3118. {
  3119. }
  3120. PropertySet::PropertySet (const PropertySet& other)
  3121. : properties (other.properties),
  3122. fallbackProperties (other.fallbackProperties),
  3123. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3124. {
  3125. }
  3126. PropertySet& PropertySet::operator= (const PropertySet& other)
  3127. {
  3128. properties = other.properties;
  3129. fallbackProperties = other.fallbackProperties;
  3130. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3131. propertyChanged();
  3132. return *this;
  3133. }
  3134. PropertySet::~PropertySet()
  3135. {
  3136. }
  3137. void PropertySet::clear()
  3138. {
  3139. const ScopedLock sl (lock);
  3140. if (properties.size() > 0)
  3141. {
  3142. properties.clear();
  3143. propertyChanged();
  3144. }
  3145. }
  3146. const String PropertySet::getValue (const String& keyName,
  3147. const String& defaultValue) const throw()
  3148. {
  3149. const ScopedLock sl (lock);
  3150. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3151. if (index >= 0)
  3152. return properties.getAllValues() [index];
  3153. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3154. : defaultValue;
  3155. }
  3156. int PropertySet::getIntValue (const String& keyName,
  3157. const int defaultValue) const throw()
  3158. {
  3159. const ScopedLock sl (lock);
  3160. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3161. if (index >= 0)
  3162. return properties.getAllValues() [index].getIntValue();
  3163. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3164. : defaultValue;
  3165. }
  3166. double PropertySet::getDoubleValue (const String& keyName,
  3167. const double defaultValue) const throw()
  3168. {
  3169. const ScopedLock sl (lock);
  3170. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3171. if (index >= 0)
  3172. return properties.getAllValues()[index].getDoubleValue();
  3173. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3174. : defaultValue;
  3175. }
  3176. bool PropertySet::getBoolValue (const String& keyName,
  3177. const bool defaultValue) const throw()
  3178. {
  3179. const ScopedLock sl (lock);
  3180. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3181. if (index >= 0)
  3182. return properties.getAllValues() [index].getIntValue() != 0;
  3183. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3184. : defaultValue;
  3185. }
  3186. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3187. {
  3188. return XmlDocument::parse (getValue (keyName));
  3189. }
  3190. void PropertySet::setValue (const String& keyName, const var& v)
  3191. {
  3192. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3193. if (keyName.isNotEmpty())
  3194. {
  3195. const String value (v.toString());
  3196. const ScopedLock sl (lock);
  3197. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3198. if (index < 0 || properties.getAllValues() [index] != value)
  3199. {
  3200. properties.set (keyName, value);
  3201. propertyChanged();
  3202. }
  3203. }
  3204. }
  3205. void PropertySet::removeValue (const String& keyName)
  3206. {
  3207. if (keyName.isNotEmpty())
  3208. {
  3209. const ScopedLock sl (lock);
  3210. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3211. if (index >= 0)
  3212. {
  3213. properties.remove (keyName);
  3214. propertyChanged();
  3215. }
  3216. }
  3217. }
  3218. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3219. {
  3220. setValue (keyName, xml == 0 ? var::null
  3221. : var (xml->createDocument (String::empty, true)));
  3222. }
  3223. bool PropertySet::containsKey (const String& keyName) const throw()
  3224. {
  3225. const ScopedLock sl (lock);
  3226. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3227. }
  3228. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3229. {
  3230. const ScopedLock sl (lock);
  3231. fallbackProperties = fallbackProperties_;
  3232. }
  3233. XmlElement* PropertySet::createXml (const String& nodeName) const
  3234. {
  3235. const ScopedLock sl (lock);
  3236. XmlElement* const xml = new XmlElement (nodeName);
  3237. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3238. {
  3239. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3240. e->setAttribute ("name", properties.getAllKeys()[i]);
  3241. e->setAttribute ("val", properties.getAllValues()[i]);
  3242. }
  3243. return xml;
  3244. }
  3245. void PropertySet::restoreFromXml (const XmlElement& xml)
  3246. {
  3247. const ScopedLock sl (lock);
  3248. clear();
  3249. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3250. {
  3251. if (e->hasAttribute ("name")
  3252. && e->hasAttribute ("val"))
  3253. {
  3254. properties.set (e->getStringAttribute ("name"),
  3255. e->getStringAttribute ("val"));
  3256. }
  3257. }
  3258. if (properties.size() > 0)
  3259. propertyChanged();
  3260. }
  3261. void PropertySet::propertyChanged()
  3262. {
  3263. }
  3264. END_JUCE_NAMESPACE
  3265. /*** End of inlined file: juce_PropertySet.cpp ***/
  3266. /*** Start of inlined file: juce_Identifier.cpp ***/
  3267. BEGIN_JUCE_NAMESPACE
  3268. StringPool& Identifier::getPool()
  3269. {
  3270. static StringPool pool;
  3271. return pool;
  3272. }
  3273. Identifier::Identifier() throw()
  3274. : name (0)
  3275. {
  3276. }
  3277. Identifier::Identifier (const Identifier& other) throw()
  3278. : name (other.name)
  3279. {
  3280. }
  3281. Identifier& Identifier::operator= (const Identifier& other) throw()
  3282. {
  3283. name = other.name;
  3284. return *this;
  3285. }
  3286. Identifier::Identifier (const String& name_)
  3287. : name (Identifier::getPool().getPooledString (name_))
  3288. {
  3289. /* An Identifier string must be suitable for use as a script variable or XML
  3290. attribute, so it can only contain this limited set of characters.. */
  3291. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3292. }
  3293. Identifier::Identifier (const char* const name_)
  3294. : name (Identifier::getPool().getPooledString (name_))
  3295. {
  3296. /* An Identifier string must be suitable for use as a script variable or XML
  3297. attribute, so it can only contain this limited set of characters.. */
  3298. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3299. }
  3300. Identifier::~Identifier()
  3301. {
  3302. }
  3303. END_JUCE_NAMESPACE
  3304. /*** End of inlined file: juce_Identifier.cpp ***/
  3305. /*** Start of inlined file: juce_Variant.cpp ***/
  3306. BEGIN_JUCE_NAMESPACE
  3307. class var::VariantType
  3308. {
  3309. public:
  3310. VariantType() {}
  3311. virtual ~VariantType() {}
  3312. virtual int toInt (const ValueUnion&) const { return 0; }
  3313. virtual double toDouble (const ValueUnion&) const { return 0; }
  3314. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3315. virtual bool toBool (const ValueUnion&) const { return false; }
  3316. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3317. virtual bool isVoid() const throw() { return false; }
  3318. virtual bool isInt() const throw() { return false; }
  3319. virtual bool isBool() const throw() { return false; }
  3320. virtual bool isDouble() const throw() { return false; }
  3321. virtual bool isString() const throw() { return false; }
  3322. virtual bool isObject() const throw() { return false; }
  3323. virtual bool isMethod() const throw() { return false; }
  3324. virtual void cleanUp (ValueUnion&) const throw() {}
  3325. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3326. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3327. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3328. };
  3329. class var::VariantType_Void : public var::VariantType
  3330. {
  3331. public:
  3332. VariantType_Void() {}
  3333. static const VariantType_Void instance;
  3334. bool isVoid() const throw() { return true; }
  3335. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3336. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3337. };
  3338. class var::VariantType_Int : public var::VariantType
  3339. {
  3340. public:
  3341. VariantType_Int() {}
  3342. static const VariantType_Int instance;
  3343. int toInt (const ValueUnion& data) const { return data.intValue; };
  3344. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3345. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3346. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3347. bool isInt() const throw() { return true; }
  3348. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3349. {
  3350. return otherType.toInt (otherData) == data.intValue;
  3351. }
  3352. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3353. {
  3354. output.writeCompressedInt (5);
  3355. output.writeByte (1);
  3356. output.writeInt (data.intValue);
  3357. }
  3358. };
  3359. class var::VariantType_Double : public var::VariantType
  3360. {
  3361. public:
  3362. VariantType_Double() {}
  3363. static const VariantType_Double instance;
  3364. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3365. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3366. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3367. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3368. bool isDouble() const throw() { return true; }
  3369. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3370. {
  3371. return otherType.toDouble (otherData) == data.doubleValue;
  3372. }
  3373. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3374. {
  3375. output.writeCompressedInt (9);
  3376. output.writeByte (4);
  3377. output.writeDouble (data.doubleValue);
  3378. }
  3379. };
  3380. class var::VariantType_Bool : public var::VariantType
  3381. {
  3382. public:
  3383. VariantType_Bool() {}
  3384. static const VariantType_Bool instance;
  3385. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3386. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3387. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3388. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3389. bool isBool() const throw() { return true; }
  3390. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3391. {
  3392. return otherType.toBool (otherData) == data.boolValue;
  3393. }
  3394. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3395. {
  3396. output.writeCompressedInt (1);
  3397. output.writeByte (data.boolValue ? 2 : 3);
  3398. }
  3399. };
  3400. class var::VariantType_String : public var::VariantType
  3401. {
  3402. public:
  3403. VariantType_String() {}
  3404. static const VariantType_String instance;
  3405. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3406. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3407. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3408. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3409. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3410. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3411. || data.stringValue->trim().equalsIgnoreCase ("true")
  3412. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3413. bool isString() const throw() { return true; }
  3414. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3415. {
  3416. return otherType.toString (otherData) == *data.stringValue;
  3417. }
  3418. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3419. {
  3420. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3421. output.writeCompressedInt (len + 1);
  3422. output.writeByte (5);
  3423. HeapBlock<char> temp (len);
  3424. data.stringValue->copyToUTF8 (temp, len);
  3425. output.write (temp, len);
  3426. }
  3427. };
  3428. class var::VariantType_Object : public var::VariantType
  3429. {
  3430. public:
  3431. VariantType_Object() {}
  3432. static const VariantType_Object instance;
  3433. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3434. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3435. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3436. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3437. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3438. bool isObject() const throw() { return true; }
  3439. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3440. {
  3441. return otherType.toObject (otherData) == data.objectValue;
  3442. }
  3443. void writeToStream (const ValueUnion&, OutputStream& output) const
  3444. {
  3445. jassertfalse; // Can't write an object to a stream!
  3446. output.writeCompressedInt (0);
  3447. }
  3448. };
  3449. class var::VariantType_Method : public var::VariantType
  3450. {
  3451. public:
  3452. VariantType_Method() {}
  3453. static const VariantType_Method instance;
  3454. const String toString (const ValueUnion&) const { return "Method"; }
  3455. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3456. bool isMethod() const throw() { return true; }
  3457. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3458. {
  3459. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3460. }
  3461. void writeToStream (const ValueUnion&, OutputStream& output) const
  3462. {
  3463. jassertfalse; // Can't write a method to a stream!
  3464. output.writeCompressedInt (0);
  3465. }
  3466. };
  3467. const var::VariantType_Void var::VariantType_Void::instance;
  3468. const var::VariantType_Int var::VariantType_Int::instance;
  3469. const var::VariantType_Bool var::VariantType_Bool::instance;
  3470. const var::VariantType_Double var::VariantType_Double::instance;
  3471. const var::VariantType_String var::VariantType_String::instance;
  3472. const var::VariantType_Object var::VariantType_Object::instance;
  3473. const var::VariantType_Method var::VariantType_Method::instance;
  3474. var::var() throw() : type (&VariantType_Void::instance)
  3475. {
  3476. }
  3477. var::~var() throw()
  3478. {
  3479. type->cleanUp (value);
  3480. }
  3481. const var var::null;
  3482. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3483. {
  3484. type->createCopy (value, valueToCopy.value);
  3485. }
  3486. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3487. {
  3488. value.intValue = value_;
  3489. }
  3490. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3491. {
  3492. value.boolValue = value_;
  3493. }
  3494. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3495. {
  3496. value.doubleValue = value_;
  3497. }
  3498. var::var (const String& value_) : type (&VariantType_String::instance)
  3499. {
  3500. value.stringValue = new String (value_);
  3501. }
  3502. var::var (const char* const value_) : type (&VariantType_String::instance)
  3503. {
  3504. value.stringValue = new String (value_);
  3505. }
  3506. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3507. {
  3508. value.stringValue = new String (value_);
  3509. }
  3510. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3511. {
  3512. value.objectValue = object;
  3513. if (object != 0)
  3514. object->incReferenceCount();
  3515. }
  3516. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3517. {
  3518. value.methodValue = method_;
  3519. }
  3520. bool var::isVoid() const throw() { return type->isVoid(); }
  3521. bool var::isInt() const throw() { return type->isInt(); }
  3522. bool var::isBool() const throw() { return type->isBool(); }
  3523. bool var::isDouble() const throw() { return type->isDouble(); }
  3524. bool var::isString() const throw() { return type->isString(); }
  3525. bool var::isObject() const throw() { return type->isObject(); }
  3526. bool var::isMethod() const throw() { return type->isMethod(); }
  3527. var::operator int() const { return type->toInt (value); }
  3528. var::operator bool() const { return type->toBool (value); }
  3529. var::operator float() const { return (float) type->toDouble (value); }
  3530. var::operator double() const { return type->toDouble (value); }
  3531. const String var::toString() const { return type->toString (value); }
  3532. var::operator const String() const { return type->toString (value); }
  3533. DynamicObject* var::getObject() const { return type->toObject (value); }
  3534. void var::swapWith (var& other) throw()
  3535. {
  3536. swapVariables (type, other.type);
  3537. swapVariables (value, other.value);
  3538. }
  3539. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3540. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3541. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3542. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3543. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3544. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3545. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3546. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3547. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3548. bool var::equals (const var& other) const throw()
  3549. {
  3550. return type->equals (value, other.value, *other.type);
  3551. }
  3552. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3553. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3554. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3555. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3556. void var::writeToStream (OutputStream& output) const
  3557. {
  3558. type->writeToStream (value, output);
  3559. }
  3560. const var var::readFromStream (InputStream& input)
  3561. {
  3562. const int numBytes = input.readCompressedInt();
  3563. if (numBytes > 0)
  3564. {
  3565. switch (input.readByte())
  3566. {
  3567. case 1: return var (input.readInt());
  3568. case 2: return var (true);
  3569. case 3: return var (false);
  3570. case 4: return var (input.readDouble());
  3571. case 5:
  3572. {
  3573. MemoryOutputStream mo;
  3574. mo.writeFromInputStream (input, numBytes - 1);
  3575. return var (mo.toUTF8());
  3576. }
  3577. default: input.skipNextBytes (numBytes - 1); break;
  3578. }
  3579. }
  3580. return var::null;
  3581. }
  3582. const var var::operator[] (const Identifier& propertyName) const
  3583. {
  3584. DynamicObject* const o = getObject();
  3585. return o != 0 ? o->getProperty (propertyName) : var::null;
  3586. }
  3587. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3588. {
  3589. DynamicObject* const o = getObject();
  3590. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3591. }
  3592. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3593. {
  3594. if (isMethod())
  3595. {
  3596. DynamicObject* const target = targetObject.getObject();
  3597. if (target != 0)
  3598. return (target->*(value.methodValue)) (arguments, numArguments);
  3599. }
  3600. return var::null;
  3601. }
  3602. const var var::call (const Identifier& method) const
  3603. {
  3604. return invoke (method, 0, 0);
  3605. }
  3606. const var var::call (const Identifier& method, const var& arg1) const
  3607. {
  3608. return invoke (method, &arg1, 1);
  3609. }
  3610. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3611. {
  3612. var args[] = { arg1, arg2 };
  3613. return invoke (method, args, 2);
  3614. }
  3615. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3616. {
  3617. var args[] = { arg1, arg2, arg3 };
  3618. return invoke (method, args, 3);
  3619. }
  3620. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3621. {
  3622. var args[] = { arg1, arg2, arg3, arg4 };
  3623. return invoke (method, args, 4);
  3624. }
  3625. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3626. {
  3627. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3628. return invoke (method, args, 5);
  3629. }
  3630. END_JUCE_NAMESPACE
  3631. /*** End of inlined file: juce_Variant.cpp ***/
  3632. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3633. BEGIN_JUCE_NAMESPACE
  3634. NamedValueSet::NamedValue::NamedValue() throw()
  3635. {
  3636. }
  3637. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3638. : name (name_), value (value_)
  3639. {
  3640. }
  3641. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3642. {
  3643. return name == other.name && value == other.value;
  3644. }
  3645. NamedValueSet::NamedValueSet() throw()
  3646. {
  3647. }
  3648. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3649. : values (other.values)
  3650. {
  3651. }
  3652. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3653. {
  3654. values = other.values;
  3655. return *this;
  3656. }
  3657. NamedValueSet::~NamedValueSet()
  3658. {
  3659. }
  3660. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3661. {
  3662. return values == other.values;
  3663. }
  3664. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3665. {
  3666. return ! operator== (other);
  3667. }
  3668. int NamedValueSet::size() const throw()
  3669. {
  3670. return values.size();
  3671. }
  3672. const var& NamedValueSet::operator[] (const Identifier& name) const
  3673. {
  3674. for (int i = values.size(); --i >= 0;)
  3675. {
  3676. const NamedValue& v = values.getReference(i);
  3677. if (v.name == name)
  3678. return v.value;
  3679. }
  3680. return var::null;
  3681. }
  3682. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3683. {
  3684. const var* v = getVarPointer (name);
  3685. return v != 0 ? *v : defaultReturnValue;
  3686. }
  3687. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3688. {
  3689. for (int i = values.size(); --i >= 0;)
  3690. {
  3691. NamedValue& v = values.getReference(i);
  3692. if (v.name == name)
  3693. return &(v.value);
  3694. }
  3695. return 0;
  3696. }
  3697. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3698. {
  3699. for (int i = values.size(); --i >= 0;)
  3700. {
  3701. NamedValue& v = values.getReference(i);
  3702. if (v.name == name)
  3703. {
  3704. if (v.value == newValue)
  3705. return false;
  3706. v.value = newValue;
  3707. return true;
  3708. }
  3709. }
  3710. values.add (NamedValue (name, newValue));
  3711. return true;
  3712. }
  3713. bool NamedValueSet::contains (const Identifier& name) const
  3714. {
  3715. return getVarPointer (name) != 0;
  3716. }
  3717. bool NamedValueSet::remove (const Identifier& name)
  3718. {
  3719. for (int i = values.size(); --i >= 0;)
  3720. {
  3721. if (values.getReference(i).name == name)
  3722. {
  3723. values.remove (i);
  3724. return true;
  3725. }
  3726. }
  3727. return false;
  3728. }
  3729. const Identifier NamedValueSet::getName (const int index) const
  3730. {
  3731. jassert (((unsigned int) index) < (unsigned int) values.size());
  3732. return values [index].name;
  3733. }
  3734. const var NamedValueSet::getValueAt (const int index) const
  3735. {
  3736. jassert (((unsigned int) index) < (unsigned int) values.size());
  3737. return values [index].value;
  3738. }
  3739. void NamedValueSet::clear()
  3740. {
  3741. values.clear();
  3742. }
  3743. END_JUCE_NAMESPACE
  3744. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3745. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3746. BEGIN_JUCE_NAMESPACE
  3747. DynamicObject::DynamicObject()
  3748. {
  3749. }
  3750. DynamicObject::~DynamicObject()
  3751. {
  3752. }
  3753. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3754. {
  3755. var* const v = properties.getVarPointer (propertyName);
  3756. return v != 0 && ! v->isMethod();
  3757. }
  3758. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3759. {
  3760. return properties [propertyName];
  3761. }
  3762. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3763. {
  3764. properties.set (propertyName, newValue);
  3765. }
  3766. void DynamicObject::removeProperty (const Identifier& propertyName)
  3767. {
  3768. properties.remove (propertyName);
  3769. }
  3770. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3771. {
  3772. return getProperty (methodName).isMethod();
  3773. }
  3774. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3775. const var* parameters,
  3776. int numParameters)
  3777. {
  3778. return properties [methodName].invoke (var (this), parameters, numParameters);
  3779. }
  3780. void DynamicObject::setMethod (const Identifier& name,
  3781. var::MethodFunction methodFunction)
  3782. {
  3783. properties.set (name, var (methodFunction));
  3784. }
  3785. void DynamicObject::clear()
  3786. {
  3787. properties.clear();
  3788. }
  3789. END_JUCE_NAMESPACE
  3790. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3791. /*** Start of inlined file: juce_Expression.cpp ***/
  3792. BEGIN_JUCE_NAMESPACE
  3793. class Expression::Helpers
  3794. {
  3795. public:
  3796. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3797. // This helper function is needed to work around VC6 scoping bugs
  3798. static const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  3799. friend class Expression::Term; // (also only needed as a VC6 workaround)
  3800. class Constant : public Term
  3801. {
  3802. public:
  3803. Constant (const double value_, bool isResolutionTarget_)
  3804. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3805. Type getType() const throw() { return constantType; }
  3806. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3807. double evaluate (const EvaluationContext&, int) const { return value; }
  3808. int getNumInputs() const { return 0; }
  3809. Term* getInput (int) const { return 0; }
  3810. const TermPtr negated()
  3811. {
  3812. return new Constant (-value, isResolutionTarget);
  3813. }
  3814. const String toString() const
  3815. {
  3816. if (isResolutionTarget)
  3817. return "@" + String (value);
  3818. return String (value);
  3819. }
  3820. double value;
  3821. bool isResolutionTarget;
  3822. };
  3823. class Symbol : public Term
  3824. {
  3825. public:
  3826. explicit Symbol (const String& symbol_)
  3827. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3828. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3829. {}
  3830. Symbol (const String& symbol_, const String& member_)
  3831. : mainSymbol (symbol_),
  3832. member (member_)
  3833. {}
  3834. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3835. {
  3836. if (++recursionDepth > 256)
  3837. throw EvaluationError ("Recursive symbol references");
  3838. try
  3839. {
  3840. return getTermFor (c.getSymbolValue (mainSymbol, member))->evaluate (c, recursionDepth);
  3841. }
  3842. catch (...)
  3843. {}
  3844. return 0;
  3845. }
  3846. Type getType() const throw() { return symbolType; }
  3847. Term* clone() const { return new Symbol (mainSymbol, member); }
  3848. int getNumInputs() const { return 0; }
  3849. Term* getInput (int) const { return 0; }
  3850. const String getSymbolName() const { return toString(); }
  3851. const String toString() const
  3852. {
  3853. return member.isEmpty() ? mainSymbol
  3854. : mainSymbol + "." + member;
  3855. }
  3856. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3857. {
  3858. if (s == mainSymbol)
  3859. return true;
  3860. if (++recursionDepth > 256)
  3861. throw EvaluationError ("Recursive symbol references");
  3862. try
  3863. {
  3864. return c != 0 && getTermFor (c->getSymbolValue (mainSymbol, member))->referencesSymbol (s, c, recursionDepth);
  3865. }
  3866. catch (EvaluationError&)
  3867. {
  3868. return false;
  3869. }
  3870. }
  3871. String mainSymbol, member;
  3872. };
  3873. class Function : public Term
  3874. {
  3875. public:
  3876. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3877. : functionName (functionName_), parameters (parameters_)
  3878. {}
  3879. Term* clone() const { return new Function (functionName, parameters); }
  3880. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3881. {
  3882. HeapBlock <double> params (parameters.size());
  3883. for (int i = 0; i < parameters.size(); ++i)
  3884. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3885. return c.evaluateFunction (functionName, params, parameters.size());
  3886. }
  3887. Type getType() const throw() { return functionType; }
  3888. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3889. int getNumInputs() const { return parameters.size(); }
  3890. Term* getInput (int i) const { return parameters [i]; }
  3891. const String getFunctionName() const { return functionName; }
  3892. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3893. {
  3894. for (int i = 0; i < parameters.size(); ++i)
  3895. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3896. return true;
  3897. return false;
  3898. }
  3899. const String toString() const
  3900. {
  3901. if (parameters.size() == 0)
  3902. return functionName + "()";
  3903. String s (functionName + " (");
  3904. for (int i = 0; i < parameters.size(); ++i)
  3905. {
  3906. s << parameters.getUnchecked(i)->toString();
  3907. if (i < parameters.size() - 1)
  3908. s << ", ";
  3909. }
  3910. s << ')';
  3911. return s;
  3912. }
  3913. const String functionName;
  3914. ReferenceCountedArray<Term> parameters;
  3915. };
  3916. class Negate : public Term
  3917. {
  3918. public:
  3919. Negate (const TermPtr& input_) : input (input_)
  3920. {
  3921. jassert (input_ != 0);
  3922. }
  3923. Type getType() const throw() { return operatorType; }
  3924. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3925. int getNumInputs() const { return 1; }
  3926. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3927. Term* clone() const { return new Negate (input->clone()); }
  3928. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3929. const String getFunctionName() const { return "-"; }
  3930. const TermPtr negated()
  3931. {
  3932. return input;
  3933. }
  3934. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3935. {
  3936. (void) input_;
  3937. jassert (input_ == input);
  3938. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3939. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3940. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3941. }
  3942. const String toString() const
  3943. {
  3944. if (input->getOperatorPrecedence() > 0)
  3945. return "-(" + input->toString() + ")";
  3946. else
  3947. return "-" + input->toString();
  3948. }
  3949. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3950. {
  3951. return input->referencesSymbol (s, c, recursionDepth);
  3952. }
  3953. private:
  3954. const TermPtr input;
  3955. };
  3956. class BinaryTerm : public Term
  3957. {
  3958. public:
  3959. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3960. {
  3961. jassert (left_ != 0 && right_ != 0);
  3962. }
  3963. int getInputIndexFor (const Term* possibleInput) const
  3964. {
  3965. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3966. }
  3967. Type getType() const throw() { return operatorType; }
  3968. int getNumInputs() const { return 2; }
  3969. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3970. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3971. {
  3972. return left->referencesSymbol (s, c, recursionDepth)
  3973. || right->referencesSymbol (s, c, recursionDepth);
  3974. }
  3975. const String toString() const
  3976. {
  3977. String s;
  3978. const int ourPrecendence = getOperatorPrecedence();
  3979. if (left->getOperatorPrecedence() > ourPrecendence)
  3980. s << '(' << left->toString() << ')';
  3981. else
  3982. s = left->toString();
  3983. s << ' ' << getFunctionName() << ' ';
  3984. if (right->getOperatorPrecedence() >= ourPrecendence)
  3985. s << '(' << right->toString() << ')';
  3986. else
  3987. s << right->toString();
  3988. return s;
  3989. }
  3990. protected:
  3991. const TermPtr left, right;
  3992. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3993. {
  3994. jassert (input == left || input == right);
  3995. if (input != left && input != right)
  3996. return 0;
  3997. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3998. if (dest == 0)
  3999. return new Constant (overallTarget, false);
  4000. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  4001. }
  4002. };
  4003. class Add : public BinaryTerm
  4004. {
  4005. public:
  4006. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4007. Term* clone() const { return new Add (left->clone(), right->clone()); }
  4008. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  4009. int getOperatorPrecedence() const { return 2; }
  4010. const String getFunctionName() const { return "+"; }
  4011. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4012. {
  4013. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4014. if (newDest == 0)
  4015. return 0;
  4016. return new Subtract (newDest, (input == left ? right : left)->clone());
  4017. }
  4018. private:
  4019. Add (const Add&);
  4020. Add& operator= (const Add&);
  4021. };
  4022. class Subtract : public BinaryTerm
  4023. {
  4024. public:
  4025. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4026. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4027. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  4028. int getOperatorPrecedence() const { return 2; }
  4029. const String getFunctionName() const { return "-"; }
  4030. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4031. {
  4032. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4033. if (newDest == 0)
  4034. return 0;
  4035. if (input == left)
  4036. return new Add (newDest, right->clone());
  4037. else
  4038. return new Subtract (left->clone(), newDest);
  4039. }
  4040. private:
  4041. Subtract (const Subtract&);
  4042. Subtract& operator= (const Subtract&);
  4043. };
  4044. class Multiply : public BinaryTerm
  4045. {
  4046. public:
  4047. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4048. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4049. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4050. const String getFunctionName() const { return "*"; }
  4051. int getOperatorPrecedence() const { return 1; }
  4052. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4053. {
  4054. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4055. if (newDest == 0)
  4056. return 0;
  4057. return new Divide (newDest, (input == left ? right : left)->clone());
  4058. }
  4059. private:
  4060. Multiply (const Multiply&);
  4061. Multiply& operator= (const Multiply&);
  4062. };
  4063. class Divide : public BinaryTerm
  4064. {
  4065. public:
  4066. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4067. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4068. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4069. const String getFunctionName() const { return "/"; }
  4070. int getOperatorPrecedence() const { return 1; }
  4071. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4072. {
  4073. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4074. if (newDest == 0)
  4075. return 0;
  4076. if (input == left)
  4077. return new Multiply (newDest, right->clone());
  4078. else
  4079. return new Divide (left->clone(), newDest);
  4080. }
  4081. private:
  4082. Divide (const Divide&);
  4083. Divide& operator= (const Divide&);
  4084. };
  4085. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4086. {
  4087. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4088. if (inputIndex >= 0)
  4089. return topLevel;
  4090. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4091. {
  4092. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4093. if (t != 0)
  4094. return t;
  4095. }
  4096. return 0;
  4097. }
  4098. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4099. {
  4100. Constant* c = dynamic_cast<Constant*> (term);
  4101. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4102. return c;
  4103. if (dynamic_cast<Function*> (term) != 0)
  4104. return 0;
  4105. int i;
  4106. const int numIns = term->getNumInputs();
  4107. for (i = 0; i < numIns; ++i)
  4108. {
  4109. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4110. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4111. return c;
  4112. }
  4113. for (i = 0; i < numIns; ++i)
  4114. {
  4115. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4116. if (c != 0)
  4117. return c;
  4118. }
  4119. return 0;
  4120. }
  4121. static bool containsAnySymbols (const Term* const t)
  4122. {
  4123. if (dynamic_cast <const Symbol*> (t) != 0)
  4124. return true;
  4125. for (int i = t->getNumInputs(); --i >= 0;)
  4126. if (containsAnySymbols (t->getInput (i)))
  4127. return true;
  4128. return false;
  4129. }
  4130. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4131. {
  4132. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4133. if (sym != 0 && sym->mainSymbol == oldName)
  4134. {
  4135. sym->mainSymbol = newName;
  4136. return true;
  4137. }
  4138. bool anyChanged = false;
  4139. for (int i = t->getNumInputs(); --i >= 0;)
  4140. if (renameSymbol (t->getInput (i), oldName, newName))
  4141. anyChanged = true;
  4142. return anyChanged;
  4143. }
  4144. class Parser
  4145. {
  4146. public:
  4147. Parser (const String& stringToParse, int& textIndex_)
  4148. : textString (stringToParse), textIndex (textIndex_)
  4149. {
  4150. text = textString;
  4151. }
  4152. const TermPtr readExpression()
  4153. {
  4154. TermPtr lhs (readMultiplyOrDivideExpression());
  4155. char opType;
  4156. while (lhs != 0 && readOperator ("+-", &opType))
  4157. {
  4158. TermPtr rhs (readMultiplyOrDivideExpression());
  4159. if (rhs == 0)
  4160. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4161. if (opType == '+')
  4162. lhs = new Add (lhs, rhs);
  4163. else
  4164. lhs = new Subtract (lhs, rhs);
  4165. }
  4166. return lhs;
  4167. }
  4168. private:
  4169. const String textString;
  4170. const juce_wchar* text;
  4171. int& textIndex;
  4172. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4173. {
  4174. return c >= '0' && c <= '9';
  4175. }
  4176. void skipWhitespace (int& i)
  4177. {
  4178. while (CharacterFunctions::isWhitespace (text [i]))
  4179. ++i;
  4180. }
  4181. bool readChar (const juce_wchar required)
  4182. {
  4183. if (text[textIndex] == required)
  4184. {
  4185. ++textIndex;
  4186. return true;
  4187. }
  4188. return false;
  4189. }
  4190. bool readOperator (const char* ops, char* const opType = 0)
  4191. {
  4192. skipWhitespace (textIndex);
  4193. while (*ops != 0)
  4194. {
  4195. if (readChar (*ops))
  4196. {
  4197. if (opType != 0)
  4198. *opType = *ops;
  4199. return true;
  4200. }
  4201. ++ops;
  4202. }
  4203. return false;
  4204. }
  4205. bool readIdentifier (String& identifier)
  4206. {
  4207. skipWhitespace (textIndex);
  4208. int i = textIndex;
  4209. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4210. {
  4211. ++i;
  4212. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4213. ++i;
  4214. }
  4215. if (i > textIndex)
  4216. {
  4217. identifier = String (text + textIndex, i - textIndex);
  4218. textIndex = i;
  4219. return true;
  4220. }
  4221. return false;
  4222. }
  4223. Term* readNumber()
  4224. {
  4225. skipWhitespace (textIndex);
  4226. int i = textIndex;
  4227. const bool isResolutionTarget = (text[i] == '@');
  4228. if (isResolutionTarget)
  4229. {
  4230. ++i;
  4231. skipWhitespace (i);
  4232. textIndex = i;
  4233. }
  4234. if (text[i] == '-')
  4235. {
  4236. ++i;
  4237. skipWhitespace (i);
  4238. }
  4239. int numDigits = 0;
  4240. while (isDecimalDigit (text[i]))
  4241. {
  4242. ++i;
  4243. ++numDigits;
  4244. }
  4245. const bool hasPoint = (text[i] == '.');
  4246. if (hasPoint)
  4247. {
  4248. ++i;
  4249. while (isDecimalDigit (text[i]))
  4250. {
  4251. ++i;
  4252. ++numDigits;
  4253. }
  4254. }
  4255. if (numDigits == 0)
  4256. return 0;
  4257. juce_wchar c = text[i];
  4258. const bool hasExponent = (c == 'e' || c == 'E');
  4259. if (hasExponent)
  4260. {
  4261. ++i;
  4262. c = text[i];
  4263. if (c == '+' || c == '-')
  4264. ++i;
  4265. int numExpDigits = 0;
  4266. while (isDecimalDigit (text[i]))
  4267. {
  4268. ++i;
  4269. ++numExpDigits;
  4270. }
  4271. if (numExpDigits == 0)
  4272. return 0;
  4273. }
  4274. const int start = textIndex;
  4275. textIndex = i;
  4276. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4277. }
  4278. const TermPtr readMultiplyOrDivideExpression()
  4279. {
  4280. TermPtr lhs (readUnaryExpression());
  4281. char opType;
  4282. while (lhs != 0 && readOperator ("*/", &opType))
  4283. {
  4284. TermPtr rhs (readUnaryExpression());
  4285. if (rhs == 0)
  4286. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4287. if (opType == '*')
  4288. lhs = new Multiply (lhs, rhs);
  4289. else
  4290. lhs = new Divide (lhs, rhs);
  4291. }
  4292. return lhs;
  4293. }
  4294. const TermPtr readUnaryExpression()
  4295. {
  4296. char opType;
  4297. if (readOperator ("+-", &opType))
  4298. {
  4299. TermPtr term (readUnaryExpression());
  4300. if (term == 0)
  4301. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4302. if (opType == '-')
  4303. term = term->negated();
  4304. return term;
  4305. }
  4306. return readPrimaryExpression();
  4307. }
  4308. const TermPtr readPrimaryExpression()
  4309. {
  4310. TermPtr e (readParenthesisedExpression());
  4311. if (e != 0)
  4312. return e;
  4313. e = readNumber();
  4314. if (e != 0)
  4315. return e;
  4316. String identifier;
  4317. if (readIdentifier (identifier))
  4318. {
  4319. if (readOperator ("(")) // method call...
  4320. {
  4321. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4322. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4323. TermPtr param (readExpression());
  4324. if (param == 0)
  4325. {
  4326. if (readOperator (")"))
  4327. return func.release();
  4328. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4329. }
  4330. f->parameters.add (param);
  4331. while (readOperator (","))
  4332. {
  4333. param = readExpression();
  4334. if (param == 0)
  4335. throw ParseError ("Expected expression after \",\"");
  4336. f->parameters.add (param);
  4337. }
  4338. if (readOperator (")"))
  4339. return func.release();
  4340. throw ParseError ("Expected \")\"");
  4341. }
  4342. else // just a symbol..
  4343. {
  4344. return new Symbol (identifier);
  4345. }
  4346. }
  4347. return 0;
  4348. }
  4349. const TermPtr readParenthesisedExpression()
  4350. {
  4351. if (! readOperator ("("))
  4352. return 0;
  4353. const TermPtr e (readExpression());
  4354. if (e == 0 || ! readOperator (")"))
  4355. return 0;
  4356. return e;
  4357. }
  4358. Parser (const Parser&);
  4359. Parser& operator= (const Parser&);
  4360. };
  4361. };
  4362. Expression::Expression()
  4363. : term (new Expression::Helpers::Constant (0, false))
  4364. {
  4365. }
  4366. Expression::~Expression()
  4367. {
  4368. }
  4369. Expression::Expression (Term* const term_)
  4370. : term (term_)
  4371. {
  4372. jassert (term != 0);
  4373. }
  4374. Expression::Expression (const double constant)
  4375. : term (new Expression::Helpers::Constant (constant, false))
  4376. {
  4377. }
  4378. Expression::Expression (const Expression& other)
  4379. : term (other.term)
  4380. {
  4381. }
  4382. Expression& Expression::operator= (const Expression& other)
  4383. {
  4384. term = other.term;
  4385. return *this;
  4386. }
  4387. Expression::Expression (const String& stringToParse)
  4388. {
  4389. int i = 0;
  4390. Helpers::Parser parser (stringToParse, i);
  4391. term = parser.readExpression();
  4392. if (term == 0)
  4393. term = new Helpers::Constant (0, false);
  4394. }
  4395. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4396. {
  4397. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4398. const Helpers::TermPtr term (parser.readExpression());
  4399. if (term != 0)
  4400. return Expression (term);
  4401. return Expression();
  4402. }
  4403. double Expression::evaluate() const
  4404. {
  4405. return evaluate (Expression::EvaluationContext());
  4406. }
  4407. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4408. {
  4409. return term->evaluate (context, 0);
  4410. }
  4411. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4412. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4413. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4414. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4415. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4416. const String Expression::toString() const
  4417. {
  4418. return term->toString();
  4419. }
  4420. const Expression Expression::symbol (const String& symbol)
  4421. {
  4422. return Expression (new Helpers::Symbol (symbol));
  4423. }
  4424. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4425. {
  4426. ReferenceCountedArray<Term> params;
  4427. for (int i = 0; i < parameters.size(); ++i)
  4428. params.add (parameters.getReference(i).term);
  4429. return Expression (new Helpers::Function (functionName, params));
  4430. }
  4431. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4432. const Expression::EvaluationContext& context) const
  4433. {
  4434. ScopedPointer<Term> newTerm (term->clone());
  4435. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4436. if (termToAdjust == 0)
  4437. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4438. if (termToAdjust == 0)
  4439. {
  4440. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4441. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4442. }
  4443. jassert (termToAdjust != 0);
  4444. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4445. if (parent == 0)
  4446. {
  4447. termToAdjust->value = targetValue;
  4448. }
  4449. else
  4450. {
  4451. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4452. if (reverseTerm == 0)
  4453. return Expression (targetValue);
  4454. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4455. }
  4456. return Expression (newTerm.release());
  4457. }
  4458. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4459. {
  4460. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4461. Expression newExpression (term->clone());
  4462. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4463. return newExpression;
  4464. }
  4465. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4466. {
  4467. return term->referencesSymbol (symbol, context, 0);
  4468. }
  4469. bool Expression::usesAnySymbols() const
  4470. {
  4471. return Helpers::containsAnySymbols (term);
  4472. }
  4473. Expression::Type Expression::getType() const throw()
  4474. {
  4475. return term->getType();
  4476. }
  4477. const String Expression::getSymbol() const
  4478. {
  4479. return term->getSymbolName();
  4480. }
  4481. const String Expression::getFunction() const
  4482. {
  4483. return term->getFunctionName();
  4484. }
  4485. const String Expression::getOperator() const
  4486. {
  4487. return term->getFunctionName();
  4488. }
  4489. int Expression::getNumInputs() const
  4490. {
  4491. return term->getNumInputs();
  4492. }
  4493. const Expression Expression::getInput (int index) const
  4494. {
  4495. return Expression (term->getInput (index));
  4496. }
  4497. int Expression::Term::getOperatorPrecedence() const
  4498. {
  4499. return 0;
  4500. }
  4501. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4502. {
  4503. return false;
  4504. }
  4505. int Expression::Term::getInputIndexFor (const Term*) const
  4506. {
  4507. return -1;
  4508. }
  4509. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4510. {
  4511. jassertfalse;
  4512. return 0;
  4513. }
  4514. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4515. {
  4516. return new Helpers::Negate (this);
  4517. }
  4518. const String Expression::Term::getSymbolName() const
  4519. {
  4520. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4521. return String::empty;
  4522. }
  4523. const String Expression::Term::getFunctionName() const
  4524. {
  4525. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4526. return String::empty;
  4527. }
  4528. Expression::ParseError::ParseError (const String& message)
  4529. : description (message)
  4530. {
  4531. DBG ("Expression::ParseError: " + message);
  4532. }
  4533. Expression::EvaluationError::EvaluationError (const String& message)
  4534. : description (message)
  4535. {
  4536. DBG ("Expression::EvaluationError: " + description);
  4537. }
  4538. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4539. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4540. {
  4541. DBG ("Expression::EvaluationError: " + description);
  4542. }
  4543. Expression::EvaluationContext::EvaluationContext() {}
  4544. Expression::EvaluationContext::~EvaluationContext() {}
  4545. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4546. {
  4547. throw EvaluationError (symbol, member);
  4548. }
  4549. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4550. {
  4551. if (numParams > 0)
  4552. {
  4553. if (functionName == "min")
  4554. {
  4555. double v = parameters[0];
  4556. for (int i = 1; i < numParams; ++i)
  4557. v = jmin (v, parameters[i]);
  4558. return v;
  4559. }
  4560. else if (functionName == "max")
  4561. {
  4562. double v = parameters[0];
  4563. for (int i = 1; i < numParams; ++i)
  4564. v = jmax (v, parameters[i]);
  4565. return v;
  4566. }
  4567. else if (numParams == 1)
  4568. {
  4569. if (functionName == "sin") return sin (parameters[0]);
  4570. else if (functionName == "cos") return cos (parameters[0]);
  4571. else if (functionName == "tan") return tan (parameters[0]);
  4572. else if (functionName == "abs") return std::abs (parameters[0]);
  4573. }
  4574. }
  4575. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4576. }
  4577. END_JUCE_NAMESPACE
  4578. /*** End of inlined file: juce_Expression.cpp ***/
  4579. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4580. BEGIN_JUCE_NAMESPACE
  4581. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4582. {
  4583. jassert (keyData != 0);
  4584. jassert (keyBytes > 0);
  4585. static const uint32 initialPValues [18] =
  4586. {
  4587. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4588. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4589. 0x9216d5d9, 0x8979fb1b
  4590. };
  4591. static const uint32 initialSValues [4 * 256] =
  4592. {
  4593. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4594. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4595. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4596. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4597. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4598. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4599. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4600. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4601. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4602. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4603. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4604. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4605. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4606. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4607. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4608. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4609. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4610. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4611. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4612. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4613. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4614. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4615. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4616. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4617. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4618. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4619. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4620. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4621. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4622. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4623. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4624. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4625. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4626. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4627. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4628. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4629. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4630. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4631. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4632. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4633. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4634. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4635. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4636. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4637. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4638. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4639. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4640. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4641. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4642. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4643. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4644. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4645. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4646. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4647. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4648. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4649. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4650. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4651. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4652. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4653. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4654. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4655. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4656. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4657. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4658. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4659. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4660. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4661. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4662. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4663. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4664. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4665. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4666. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4667. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4668. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4669. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4670. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4671. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4672. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4673. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4674. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4675. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4676. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4677. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4678. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4679. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4680. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4681. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4682. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4683. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4684. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4685. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4686. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4687. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4688. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4689. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4690. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4691. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4692. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4693. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4694. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4695. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4696. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4697. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4698. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4699. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4700. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4701. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4702. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4703. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4704. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4705. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4706. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4707. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4708. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4709. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4710. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4711. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4712. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4713. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4714. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4715. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4716. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4717. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4718. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4719. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4720. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4721. };
  4722. memcpy (p, initialPValues, sizeof (p));
  4723. int i, j = 0;
  4724. for (i = 4; --i >= 0;)
  4725. {
  4726. s[i].malloc (256);
  4727. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4728. }
  4729. for (i = 0; i < 18; ++i)
  4730. {
  4731. uint32 d = 0;
  4732. for (int k = 0; k < 4; ++k)
  4733. {
  4734. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4735. if (++j >= keyBytes)
  4736. j = 0;
  4737. }
  4738. p[i] = initialPValues[i] ^ d;
  4739. }
  4740. uint32 l = 0, r = 0;
  4741. for (i = 0; i < 18; i += 2)
  4742. {
  4743. encrypt (l, r);
  4744. p[i] = l;
  4745. p[i + 1] = r;
  4746. }
  4747. for (i = 0; i < 4; ++i)
  4748. {
  4749. for (j = 0; j < 256; j += 2)
  4750. {
  4751. encrypt (l, r);
  4752. s[i][j] = l;
  4753. s[i][j + 1] = r;
  4754. }
  4755. }
  4756. }
  4757. BlowFish::BlowFish (const BlowFish& other)
  4758. {
  4759. for (int i = 4; --i >= 0;)
  4760. s[i].malloc (256);
  4761. operator= (other);
  4762. }
  4763. BlowFish& BlowFish::operator= (const BlowFish& other)
  4764. {
  4765. memcpy (p, other.p, sizeof (p));
  4766. for (int i = 4; --i >= 0;)
  4767. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4768. return *this;
  4769. }
  4770. BlowFish::~BlowFish()
  4771. {
  4772. }
  4773. uint32 BlowFish::F (const uint32 x) const throw()
  4774. {
  4775. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4776. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4777. }
  4778. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4779. {
  4780. uint32 l = data1;
  4781. uint32 r = data2;
  4782. for (int i = 0; i < 16; ++i)
  4783. {
  4784. l ^= p[i];
  4785. r ^= F(l);
  4786. swapVariables (l, r);
  4787. }
  4788. data1 = r ^ p[17];
  4789. data2 = l ^ p[16];
  4790. }
  4791. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4792. {
  4793. uint32 l = data1;
  4794. uint32 r = data2;
  4795. for (int i = 17; i > 1; --i)
  4796. {
  4797. l ^= p[i];
  4798. r ^= F(l);
  4799. swapVariables (l, r);
  4800. }
  4801. data1 = r ^ p[0];
  4802. data2 = l ^ p[1];
  4803. }
  4804. END_JUCE_NAMESPACE
  4805. /*** End of inlined file: juce_BlowFish.cpp ***/
  4806. /*** Start of inlined file: juce_MD5.cpp ***/
  4807. BEGIN_JUCE_NAMESPACE
  4808. MD5::MD5()
  4809. {
  4810. zerostruct (result);
  4811. }
  4812. MD5::MD5 (const MD5& other)
  4813. {
  4814. memcpy (result, other.result, sizeof (result));
  4815. }
  4816. MD5& MD5::operator= (const MD5& other)
  4817. {
  4818. memcpy (result, other.result, sizeof (result));
  4819. return *this;
  4820. }
  4821. MD5::MD5 (const MemoryBlock& data)
  4822. {
  4823. ProcessContext context;
  4824. context.processBlock (data.getData(), data.getSize());
  4825. context.finish (result);
  4826. }
  4827. MD5::MD5 (const void* data, const size_t numBytes)
  4828. {
  4829. ProcessContext context;
  4830. context.processBlock (data, numBytes);
  4831. context.finish (result);
  4832. }
  4833. MD5::MD5 (const String& text)
  4834. {
  4835. ProcessContext context;
  4836. const int len = text.length();
  4837. const juce_wchar* const t = text;
  4838. for (int i = 0; i < len; ++i)
  4839. {
  4840. // force the string into integer-sized unicode characters, to try to make it
  4841. // get the same results on all platforms + compilers.
  4842. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4843. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4844. }
  4845. context.finish (result);
  4846. }
  4847. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4848. {
  4849. ProcessContext context;
  4850. if (numBytesToRead < 0)
  4851. numBytesToRead = std::numeric_limits<int64>::max();
  4852. while (numBytesToRead > 0)
  4853. {
  4854. uint8 tempBuffer [512];
  4855. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4856. if (bytesRead <= 0)
  4857. break;
  4858. numBytesToRead -= bytesRead;
  4859. context.processBlock (tempBuffer, bytesRead);
  4860. }
  4861. context.finish (result);
  4862. }
  4863. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4864. {
  4865. processStream (input, numBytesToRead);
  4866. }
  4867. MD5::MD5 (const File& file)
  4868. {
  4869. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4870. if (fin != 0)
  4871. processStream (*fin, -1);
  4872. else
  4873. zerostruct (result);
  4874. }
  4875. MD5::~MD5()
  4876. {
  4877. }
  4878. namespace MD5Functions
  4879. {
  4880. void encode (void* const output, const void* const input, const int numBytes) throw()
  4881. {
  4882. for (int i = 0; i < (numBytes >> 2); ++i)
  4883. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4884. }
  4885. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4886. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4887. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4888. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4889. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4890. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4891. {
  4892. a += F (b, c, d) + x + ac;
  4893. a = rotateLeft (a, s) + b;
  4894. }
  4895. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4896. {
  4897. a += G (b, c, d) + x + ac;
  4898. a = rotateLeft (a, s) + b;
  4899. }
  4900. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4901. {
  4902. a += H (b, c, d) + x + ac;
  4903. a = rotateLeft (a, s) + b;
  4904. }
  4905. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4906. {
  4907. a += I (b, c, d) + x + ac;
  4908. a = rotateLeft (a, s) + b;
  4909. }
  4910. }
  4911. MD5::ProcessContext::ProcessContext()
  4912. {
  4913. state[0] = 0x67452301;
  4914. state[1] = 0xefcdab89;
  4915. state[2] = 0x98badcfe;
  4916. state[3] = 0x10325476;
  4917. count[0] = 0;
  4918. count[1] = 0;
  4919. }
  4920. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4921. {
  4922. int bufferPos = ((count[0] >> 3) & 0x3F);
  4923. count[0] += (uint32) (dataSize << 3);
  4924. if (count[0] < ((uint32) dataSize << 3))
  4925. count[1]++;
  4926. count[1] += (uint32) (dataSize >> 29);
  4927. const size_t spaceLeft = 64 - bufferPos;
  4928. size_t i = 0;
  4929. if (dataSize >= spaceLeft)
  4930. {
  4931. memcpy (buffer + bufferPos, data, spaceLeft);
  4932. transform (buffer);
  4933. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4934. transform (static_cast <const char*> (data) + i);
  4935. bufferPos = 0;
  4936. }
  4937. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4938. }
  4939. void MD5::ProcessContext::finish (void* const result)
  4940. {
  4941. unsigned char encodedLength[8];
  4942. MD5Functions::encode (encodedLength, count, 8);
  4943. // Pad out to 56 mod 64.
  4944. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4945. const int paddingLength = (index < 56) ? (56 - index)
  4946. : (120 - index);
  4947. uint8 paddingBuffer [64];
  4948. zeromem (paddingBuffer, paddingLength);
  4949. paddingBuffer [0] = 0x80;
  4950. processBlock (paddingBuffer, paddingLength);
  4951. processBlock (encodedLength, 8);
  4952. MD5Functions::encode (result, state, 16);
  4953. zerostruct (buffer);
  4954. }
  4955. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4956. {
  4957. using namespace MD5Functions;
  4958. uint32 a = state[0];
  4959. uint32 b = state[1];
  4960. uint32 c = state[2];
  4961. uint32 d = state[3];
  4962. uint32 x[16];
  4963. encode (x, bufferToTransform, 64);
  4964. enum Constants
  4965. {
  4966. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4967. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4968. };
  4969. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4970. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4971. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4972. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4973. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4974. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4975. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4976. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4977. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4978. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4979. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4980. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4981. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4982. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4983. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4984. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4985. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4986. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4987. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4988. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4989. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4990. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4991. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4992. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4993. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4994. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4995. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4996. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4997. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4998. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4999. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  5000. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  5001. state[0] += a;
  5002. state[1] += b;
  5003. state[2] += c;
  5004. state[3] += d;
  5005. zerostruct (x);
  5006. }
  5007. const MemoryBlock MD5::getRawChecksumData() const
  5008. {
  5009. return MemoryBlock (result, sizeof (result));
  5010. }
  5011. const String MD5::toHexString() const
  5012. {
  5013. return String::toHexString (result, sizeof (result), 0);
  5014. }
  5015. bool MD5::operator== (const MD5& other) const
  5016. {
  5017. return memcmp (result, other.result, sizeof (result)) == 0;
  5018. }
  5019. bool MD5::operator!= (const MD5& other) const
  5020. {
  5021. return ! operator== (other);
  5022. }
  5023. END_JUCE_NAMESPACE
  5024. /*** End of inlined file: juce_MD5.cpp ***/
  5025. /*** Start of inlined file: juce_Primes.cpp ***/
  5026. BEGIN_JUCE_NAMESPACE
  5027. namespace PrimesHelpers
  5028. {
  5029. void createSmallSieve (const int numBits, BigInteger& result)
  5030. {
  5031. result.setBit (numBits);
  5032. result.clearBit (numBits); // to enlarge the array
  5033. result.setBit (0);
  5034. int n = 2;
  5035. do
  5036. {
  5037. for (int i = n + n; i < numBits; i += n)
  5038. result.setBit (i);
  5039. n = result.findNextClearBit (n + 1);
  5040. }
  5041. while (n <= (numBits >> 1));
  5042. }
  5043. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5044. const BigInteger& smallSieve, const int smallSieveSize)
  5045. {
  5046. jassert (! base[0]); // must be even!
  5047. result.setBit (numBits);
  5048. result.clearBit (numBits); // to enlarge the array
  5049. int index = smallSieve.findNextClearBit (0);
  5050. do
  5051. {
  5052. const int prime = (index << 1) + 1;
  5053. BigInteger r (base), remainder;
  5054. r.divideBy (prime, remainder);
  5055. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5056. if (r.isZero())
  5057. i += prime;
  5058. if ((i & 1) == 0)
  5059. i += prime;
  5060. i = (i - 1) >> 1;
  5061. while (i < numBits)
  5062. {
  5063. result.setBit (i);
  5064. i += prime;
  5065. }
  5066. index = smallSieve.findNextClearBit (index + 1);
  5067. }
  5068. while (index < smallSieveSize);
  5069. }
  5070. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5071. const int numBits, BigInteger& result, const int certainty)
  5072. {
  5073. for (int i = 0; i < numBits; ++i)
  5074. {
  5075. if (! sieve[i])
  5076. {
  5077. result = base + (unsigned int) ((i << 1) + 1);
  5078. if (Primes::isProbablyPrime (result, certainty))
  5079. return true;
  5080. }
  5081. }
  5082. return false;
  5083. }
  5084. bool passesMillerRabin (const BigInteger& n, int iterations)
  5085. {
  5086. const BigInteger one (1), two (2);
  5087. const BigInteger nMinusOne (n - one);
  5088. BigInteger d (nMinusOne);
  5089. const int s = d.findNextSetBit (0);
  5090. d >>= s;
  5091. BigInteger smallPrimes;
  5092. int numBitsInSmallPrimes = 0;
  5093. for (;;)
  5094. {
  5095. numBitsInSmallPrimes += 256;
  5096. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5097. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5098. if (numPrimesFound > iterations + 1)
  5099. break;
  5100. }
  5101. int smallPrime = 2;
  5102. while (--iterations >= 0)
  5103. {
  5104. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5105. BigInteger r (smallPrime);
  5106. r.exponentModulo (d, n);
  5107. if (r != one && r != nMinusOne)
  5108. {
  5109. for (int j = 0; j < s; ++j)
  5110. {
  5111. r.exponentModulo (two, n);
  5112. if (r == nMinusOne)
  5113. break;
  5114. }
  5115. if (r != nMinusOne)
  5116. return false;
  5117. }
  5118. }
  5119. return true;
  5120. }
  5121. }
  5122. const BigInteger Primes::createProbablePrime (const int bitLength,
  5123. const int certainty,
  5124. const int* randomSeeds,
  5125. int numRandomSeeds)
  5126. {
  5127. using namespace PrimesHelpers;
  5128. int defaultSeeds [16];
  5129. if (numRandomSeeds <= 0)
  5130. {
  5131. randomSeeds = defaultSeeds;
  5132. numRandomSeeds = numElementsInArray (defaultSeeds);
  5133. Random r (0);
  5134. for (int j = 10; --j >= 0;)
  5135. {
  5136. r.setSeedRandomly();
  5137. for (int i = numRandomSeeds; --i >= 0;)
  5138. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5139. }
  5140. }
  5141. BigInteger smallSieve;
  5142. const int smallSieveSize = 15000;
  5143. createSmallSieve (smallSieveSize, smallSieve);
  5144. BigInteger p;
  5145. for (int i = numRandomSeeds; --i >= 0;)
  5146. {
  5147. BigInteger p2;
  5148. Random r (randomSeeds[i]);
  5149. r.fillBitsRandomly (p2, 0, bitLength);
  5150. p ^= p2;
  5151. }
  5152. p.setBit (bitLength - 1);
  5153. p.clearBit (0);
  5154. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5155. while (p.getHighestBit() < bitLength)
  5156. {
  5157. p += 2 * searchLen;
  5158. BigInteger sieve;
  5159. bigSieve (p, searchLen, sieve,
  5160. smallSieve, smallSieveSize);
  5161. BigInteger candidate;
  5162. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5163. return candidate;
  5164. }
  5165. jassertfalse;
  5166. return BigInteger();
  5167. }
  5168. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5169. {
  5170. using namespace PrimesHelpers;
  5171. if (! number[0])
  5172. return false;
  5173. if (number.getHighestBit() <= 10)
  5174. {
  5175. const int num = number.getBitRangeAsInt (0, 10);
  5176. for (int i = num / 2; --i > 1;)
  5177. if (num % i == 0)
  5178. return false;
  5179. return true;
  5180. }
  5181. else
  5182. {
  5183. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5184. return false;
  5185. return passesMillerRabin (number, certainty);
  5186. }
  5187. }
  5188. END_JUCE_NAMESPACE
  5189. /*** End of inlined file: juce_Primes.cpp ***/
  5190. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5191. BEGIN_JUCE_NAMESPACE
  5192. RSAKey::RSAKey()
  5193. {
  5194. }
  5195. RSAKey::RSAKey (const String& s)
  5196. {
  5197. if (s.containsChar (','))
  5198. {
  5199. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5200. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5201. }
  5202. else
  5203. {
  5204. // the string needs to be two hex numbers, comma-separated..
  5205. jassertfalse;
  5206. }
  5207. }
  5208. RSAKey::~RSAKey()
  5209. {
  5210. }
  5211. bool RSAKey::operator== (const RSAKey& other) const throw()
  5212. {
  5213. return part1 == other.part1 && part2 == other.part2;
  5214. }
  5215. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5216. {
  5217. return ! operator== (other);
  5218. }
  5219. const String RSAKey::toString() const
  5220. {
  5221. return part1.toString (16) + "," + part2.toString (16);
  5222. }
  5223. bool RSAKey::applyToValue (BigInteger& value) const
  5224. {
  5225. if (part1.isZero() || part2.isZero() || value <= 0)
  5226. {
  5227. jassertfalse; // using an uninitialised key
  5228. value.clear();
  5229. return false;
  5230. }
  5231. BigInteger result;
  5232. while (! value.isZero())
  5233. {
  5234. result *= part2;
  5235. BigInteger remainder;
  5236. value.divideBy (part2, remainder);
  5237. remainder.exponentModulo (part1, part2);
  5238. result += remainder;
  5239. }
  5240. value.swapWith (result);
  5241. return true;
  5242. }
  5243. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5244. {
  5245. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5246. // are fast to divide + multiply
  5247. for (int i = 2; i <= 65536; i *= 2)
  5248. {
  5249. const BigInteger e (1 + i);
  5250. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5251. return e;
  5252. }
  5253. BigInteger e (4);
  5254. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5255. ++e;
  5256. return e;
  5257. }
  5258. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5259. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5260. {
  5261. jassert (numBits > 16); // not much point using less than this..
  5262. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5263. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5264. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5265. const BigInteger n (p * q);
  5266. const BigInteger m (--p * --q);
  5267. const BigInteger e (findBestCommonDivisor (p, q));
  5268. BigInteger d (e);
  5269. d.inverseModulo (m);
  5270. publicKey.part1 = e;
  5271. publicKey.part2 = n;
  5272. privateKey.part1 = d;
  5273. privateKey.part2 = n;
  5274. }
  5275. END_JUCE_NAMESPACE
  5276. /*** End of inlined file: juce_RSAKey.cpp ***/
  5277. /*** Start of inlined file: juce_InputStream.cpp ***/
  5278. BEGIN_JUCE_NAMESPACE
  5279. char InputStream::readByte()
  5280. {
  5281. char temp = 0;
  5282. read (&temp, 1);
  5283. return temp;
  5284. }
  5285. bool InputStream::readBool()
  5286. {
  5287. return readByte() != 0;
  5288. }
  5289. short InputStream::readShort()
  5290. {
  5291. char temp[2];
  5292. if (read (temp, 2) == 2)
  5293. return (short) ByteOrder::littleEndianShort (temp);
  5294. return 0;
  5295. }
  5296. short InputStream::readShortBigEndian()
  5297. {
  5298. char temp[2];
  5299. if (read (temp, 2) == 2)
  5300. return (short) ByteOrder::bigEndianShort (temp);
  5301. return 0;
  5302. }
  5303. int InputStream::readInt()
  5304. {
  5305. char temp[4];
  5306. if (read (temp, 4) == 4)
  5307. return (int) ByteOrder::littleEndianInt (temp);
  5308. return 0;
  5309. }
  5310. int InputStream::readIntBigEndian()
  5311. {
  5312. char temp[4];
  5313. if (read (temp, 4) == 4)
  5314. return (int) ByteOrder::bigEndianInt (temp);
  5315. return 0;
  5316. }
  5317. int InputStream::readCompressedInt()
  5318. {
  5319. const unsigned char sizeByte = readByte();
  5320. if (sizeByte == 0)
  5321. return 0;
  5322. const int numBytes = (sizeByte & 0x7f);
  5323. if (numBytes > 4)
  5324. {
  5325. jassertfalse; // trying to read corrupt data - this method must only be used
  5326. // to read data that was written by OutputStream::writeCompressedInt()
  5327. return 0;
  5328. }
  5329. char bytes[4] = { 0, 0, 0, 0 };
  5330. if (read (bytes, numBytes) != numBytes)
  5331. return 0;
  5332. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5333. return (sizeByte >> 7) ? -num : num;
  5334. }
  5335. int64 InputStream::readInt64()
  5336. {
  5337. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5338. if (read (n.asBytes, 8) == 8)
  5339. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5340. return 0;
  5341. }
  5342. int64 InputStream::readInt64BigEndian()
  5343. {
  5344. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5345. if (read (n.asBytes, 8) == 8)
  5346. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5347. return 0;
  5348. }
  5349. float InputStream::readFloat()
  5350. {
  5351. // the union below relies on these types being the same size...
  5352. static_jassert (sizeof (int32) == sizeof (float));
  5353. union { int32 asInt; float asFloat; } n;
  5354. n.asInt = (int32) readInt();
  5355. return n.asFloat;
  5356. }
  5357. float InputStream::readFloatBigEndian()
  5358. {
  5359. union { int32 asInt; float asFloat; } n;
  5360. n.asInt = (int32) readIntBigEndian();
  5361. return n.asFloat;
  5362. }
  5363. double InputStream::readDouble()
  5364. {
  5365. union { int64 asInt; double asDouble; } n;
  5366. n.asInt = readInt64();
  5367. return n.asDouble;
  5368. }
  5369. double InputStream::readDoubleBigEndian()
  5370. {
  5371. union { int64 asInt; double asDouble; } n;
  5372. n.asInt = readInt64BigEndian();
  5373. return n.asDouble;
  5374. }
  5375. const String InputStream::readString()
  5376. {
  5377. MemoryBlock buffer (256);
  5378. char* data = static_cast<char*> (buffer.getData());
  5379. size_t i = 0;
  5380. while ((data[i] = readByte()) != 0)
  5381. {
  5382. if (++i >= buffer.getSize())
  5383. {
  5384. buffer.setSize (buffer.getSize() + 512);
  5385. data = static_cast<char*> (buffer.getData());
  5386. }
  5387. }
  5388. return String::fromUTF8 (data, (int) i);
  5389. }
  5390. const String InputStream::readNextLine()
  5391. {
  5392. MemoryBlock buffer (256);
  5393. char* data = static_cast<char*> (buffer.getData());
  5394. size_t i = 0;
  5395. while ((data[i] = readByte()) != 0)
  5396. {
  5397. if (data[i] == '\n')
  5398. break;
  5399. if (data[i] == '\r')
  5400. {
  5401. const int64 lastPos = getPosition();
  5402. if (readByte() != '\n')
  5403. setPosition (lastPos);
  5404. break;
  5405. }
  5406. if (++i >= buffer.getSize())
  5407. {
  5408. buffer.setSize (buffer.getSize() + 512);
  5409. data = static_cast<char*> (buffer.getData());
  5410. }
  5411. }
  5412. return String::fromUTF8 (data, (int) i);
  5413. }
  5414. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5415. {
  5416. MemoryOutputStream mo (block, true);
  5417. return mo.writeFromInputStream (*this, numBytes);
  5418. }
  5419. const String InputStream::readEntireStreamAsString()
  5420. {
  5421. MemoryOutputStream mo;
  5422. mo.writeFromInputStream (*this, -1);
  5423. return mo.toString();
  5424. }
  5425. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5426. {
  5427. if (numBytesToSkip > 0)
  5428. {
  5429. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5430. HeapBlock<char> temp (skipBufferSize);
  5431. while (numBytesToSkip > 0 && ! isExhausted())
  5432. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5433. }
  5434. }
  5435. END_JUCE_NAMESPACE
  5436. /*** End of inlined file: juce_InputStream.cpp ***/
  5437. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5438. BEGIN_JUCE_NAMESPACE
  5439. #if JUCE_DEBUG
  5440. static Array<void*, CriticalSection> activeStreams;
  5441. void juce_CheckForDanglingStreams()
  5442. {
  5443. /*
  5444. It's always a bad idea to leak any object, but if you're leaking output
  5445. streams, then there's a good chance that you're failing to flush a file
  5446. to disk properly, which could result in corrupted data and other similar
  5447. nastiness..
  5448. */
  5449. jassert (activeStreams.size() == 0);
  5450. };
  5451. #endif
  5452. OutputStream::OutputStream()
  5453. {
  5454. #if JUCE_DEBUG
  5455. activeStreams.add (this);
  5456. #endif
  5457. }
  5458. OutputStream::~OutputStream()
  5459. {
  5460. #if JUCE_DEBUG
  5461. activeStreams.removeValue (this);
  5462. #endif
  5463. }
  5464. void OutputStream::writeBool (const bool b)
  5465. {
  5466. writeByte (b ? (char) 1
  5467. : (char) 0);
  5468. }
  5469. void OutputStream::writeByte (char byte)
  5470. {
  5471. write (&byte, 1);
  5472. }
  5473. void OutputStream::writeShort (short value)
  5474. {
  5475. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5476. write (&v, 2);
  5477. }
  5478. void OutputStream::writeShortBigEndian (short value)
  5479. {
  5480. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5481. write (&v, 2);
  5482. }
  5483. void OutputStream::writeInt (int value)
  5484. {
  5485. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5486. write (&v, 4);
  5487. }
  5488. void OutputStream::writeIntBigEndian (int value)
  5489. {
  5490. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5491. write (&v, 4);
  5492. }
  5493. void OutputStream::writeCompressedInt (int value)
  5494. {
  5495. unsigned int un = (value < 0) ? (unsigned int) -value
  5496. : (unsigned int) value;
  5497. uint8 data[5];
  5498. int num = 0;
  5499. while (un > 0)
  5500. {
  5501. data[++num] = (uint8) un;
  5502. un >>= 8;
  5503. }
  5504. data[0] = (uint8) num;
  5505. if (value < 0)
  5506. data[0] |= 0x80;
  5507. write (data, num + 1);
  5508. }
  5509. void OutputStream::writeInt64 (int64 value)
  5510. {
  5511. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5512. write (&v, 8);
  5513. }
  5514. void OutputStream::writeInt64BigEndian (int64 value)
  5515. {
  5516. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5517. write (&v, 8);
  5518. }
  5519. void OutputStream::writeFloat (float value)
  5520. {
  5521. union { int asInt; float asFloat; } n;
  5522. n.asFloat = value;
  5523. writeInt (n.asInt);
  5524. }
  5525. void OutputStream::writeFloatBigEndian (float value)
  5526. {
  5527. union { int asInt; float asFloat; } n;
  5528. n.asFloat = value;
  5529. writeIntBigEndian (n.asInt);
  5530. }
  5531. void OutputStream::writeDouble (double value)
  5532. {
  5533. union { int64 asInt; double asDouble; } n;
  5534. n.asDouble = value;
  5535. writeInt64 (n.asInt);
  5536. }
  5537. void OutputStream::writeDoubleBigEndian (double value)
  5538. {
  5539. union { int64 asInt; double asDouble; } n;
  5540. n.asDouble = value;
  5541. writeInt64BigEndian (n.asInt);
  5542. }
  5543. void OutputStream::writeString (const String& text)
  5544. {
  5545. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5546. // if lots of large, persistent strings were to be written to streams).
  5547. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5548. HeapBlock<char> temp (numBytes);
  5549. text.copyToUTF8 (temp, numBytes);
  5550. write (temp, numBytes);
  5551. }
  5552. void OutputStream::writeText (const String& text, const bool asUnicode,
  5553. const bool writeUnicodeHeaderBytes)
  5554. {
  5555. if (asUnicode)
  5556. {
  5557. if (writeUnicodeHeaderBytes)
  5558. write ("\x0ff\x0fe", 2);
  5559. const juce_wchar* src = text;
  5560. bool lastCharWasReturn = false;
  5561. while (*src != 0)
  5562. {
  5563. if (*src == L'\n' && ! lastCharWasReturn)
  5564. writeShort ((short) L'\r');
  5565. lastCharWasReturn = (*src == L'\r');
  5566. writeShort ((short) *src++);
  5567. }
  5568. }
  5569. else
  5570. {
  5571. const char* src = text.toUTF8();
  5572. const char* t = src;
  5573. for (;;)
  5574. {
  5575. if (*t == '\n')
  5576. {
  5577. if (t > src)
  5578. write (src, (int) (t - src));
  5579. write ("\r\n", 2);
  5580. src = t + 1;
  5581. }
  5582. else if (*t == '\r')
  5583. {
  5584. if (t[1] == '\n')
  5585. ++t;
  5586. }
  5587. else if (*t == 0)
  5588. {
  5589. if (t > src)
  5590. write (src, (int) (t - src));
  5591. break;
  5592. }
  5593. ++t;
  5594. }
  5595. }
  5596. }
  5597. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5598. {
  5599. if (numBytesToWrite < 0)
  5600. numBytesToWrite = std::numeric_limits<int64>::max();
  5601. int numWritten = 0;
  5602. while (numBytesToWrite > 0 && ! source.isExhausted())
  5603. {
  5604. char buffer [8192];
  5605. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5606. if (num <= 0)
  5607. break;
  5608. write (buffer, num);
  5609. numBytesToWrite -= num;
  5610. numWritten += num;
  5611. }
  5612. return numWritten;
  5613. }
  5614. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5615. {
  5616. return stream << String (number);
  5617. }
  5618. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5619. {
  5620. return stream << String (number);
  5621. }
  5622. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5623. {
  5624. stream.writeByte (character);
  5625. return stream;
  5626. }
  5627. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5628. {
  5629. stream.write (text, (int) strlen (text));
  5630. return stream;
  5631. }
  5632. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5633. {
  5634. stream.write (data.getData(), (int) data.getSize());
  5635. return stream;
  5636. }
  5637. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5638. {
  5639. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5640. if (in != 0)
  5641. stream.writeFromInputStream (*in, -1);
  5642. return stream;
  5643. }
  5644. END_JUCE_NAMESPACE
  5645. /*** End of inlined file: juce_OutputStream.cpp ***/
  5646. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5647. BEGIN_JUCE_NAMESPACE
  5648. DirectoryIterator::DirectoryIterator (const File& directory,
  5649. bool isRecursive_,
  5650. const String& wildCard_,
  5651. const int whatToLookFor_)
  5652. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5653. wildCard (wildCard_),
  5654. path (File::addTrailingSeparator (directory.getFullPathName())),
  5655. index (-1),
  5656. totalNumFiles (-1),
  5657. whatToLookFor (whatToLookFor_),
  5658. isRecursive (isRecursive_),
  5659. hasBeenAdvanced (false)
  5660. {
  5661. // you have to specify the type of files you're looking for!
  5662. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5663. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5664. }
  5665. DirectoryIterator::~DirectoryIterator()
  5666. {
  5667. }
  5668. bool DirectoryIterator::next()
  5669. {
  5670. return next (0, 0, 0, 0, 0, 0);
  5671. }
  5672. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5673. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5674. {
  5675. hasBeenAdvanced = true;
  5676. if (subIterator != 0)
  5677. {
  5678. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5679. return true;
  5680. subIterator = 0;
  5681. }
  5682. String filename;
  5683. bool isDirectory, isHidden;
  5684. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5685. {
  5686. ++index;
  5687. if (! filename.containsOnly ("."))
  5688. {
  5689. const File fileFound (path + filename, 0);
  5690. bool matches = false;
  5691. if (isDirectory)
  5692. {
  5693. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5694. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5695. matches = (whatToLookFor & File::findDirectories) != 0;
  5696. }
  5697. else
  5698. {
  5699. matches = (whatToLookFor & File::findFiles) != 0;
  5700. }
  5701. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5702. if (matches && isRecursive)
  5703. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5704. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5705. matches = ! isHidden;
  5706. if (matches)
  5707. {
  5708. currentFile = fileFound;
  5709. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5710. if (isDirResult != 0) *isDirResult = isDirectory;
  5711. return true;
  5712. }
  5713. else if (subIterator != 0)
  5714. {
  5715. return next();
  5716. }
  5717. }
  5718. }
  5719. return false;
  5720. }
  5721. const File DirectoryIterator::getFile() const
  5722. {
  5723. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5724. return subIterator->getFile();
  5725. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5726. jassert (hasBeenAdvanced);
  5727. return currentFile;
  5728. }
  5729. float DirectoryIterator::getEstimatedProgress() const
  5730. {
  5731. if (totalNumFiles < 0)
  5732. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5733. if (totalNumFiles <= 0)
  5734. return 0.0f;
  5735. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5736. : (float) index;
  5737. return detailedIndex / totalNumFiles;
  5738. }
  5739. END_JUCE_NAMESPACE
  5740. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5741. /*** Start of inlined file: juce_File.cpp ***/
  5742. #if ! JUCE_WINDOWS
  5743. #include <pwd.h>
  5744. #endif
  5745. BEGIN_JUCE_NAMESPACE
  5746. File::File (const String& fullPathName)
  5747. : fullPath (parseAbsolutePath (fullPathName))
  5748. {
  5749. }
  5750. File::File (const String& path, int)
  5751. : fullPath (path)
  5752. {
  5753. }
  5754. const File File::createFileWithoutCheckingPath (const String& path)
  5755. {
  5756. return File (path, 0);
  5757. }
  5758. File::File (const File& other)
  5759. : fullPath (other.fullPath)
  5760. {
  5761. }
  5762. File& File::operator= (const String& newPath)
  5763. {
  5764. fullPath = parseAbsolutePath (newPath);
  5765. return *this;
  5766. }
  5767. File& File::operator= (const File& other)
  5768. {
  5769. fullPath = other.fullPath;
  5770. return *this;
  5771. }
  5772. const File File::nonexistent;
  5773. const String File::parseAbsolutePath (const String& p)
  5774. {
  5775. if (p.isEmpty())
  5776. return String::empty;
  5777. #if JUCE_WINDOWS
  5778. // Windows..
  5779. String path (p.replaceCharacter ('/', '\\'));
  5780. if (path.startsWithChar (File::separator))
  5781. {
  5782. if (path[1] != File::separator)
  5783. {
  5784. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5785. If you're trying to parse a string that may be either a relative path or an absolute path,
  5786. you MUST provide a context against which the partial path can be evaluated - you can do
  5787. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5788. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5789. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5790. */
  5791. jassertfalse;
  5792. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5793. }
  5794. }
  5795. else if (! path.containsChar (':'))
  5796. {
  5797. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5798. If you're trying to parse a string that may be either a relative path or an absolute path,
  5799. you MUST provide a context against which the partial path can be evaluated - you can do
  5800. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5801. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5802. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5803. */
  5804. jassertfalse;
  5805. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5806. }
  5807. #else
  5808. // Mac or Linux..
  5809. String path (p.replaceCharacter ('\\', '/'));
  5810. if (path.startsWithChar ('~'))
  5811. {
  5812. if (path[1] == File::separator || path[1] == 0)
  5813. {
  5814. // expand a name of the form "~/abc"
  5815. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5816. + path.substring (1);
  5817. }
  5818. else
  5819. {
  5820. // expand a name of type "~dave/abc"
  5821. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5822. struct passwd* const pw = getpwnam (userName.toUTF8());
  5823. if (pw != 0)
  5824. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5825. }
  5826. }
  5827. else if (! path.startsWithChar (File::separator))
  5828. {
  5829. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5830. If you're trying to parse a string that may be either a relative path or an absolute path,
  5831. you MUST provide a context against which the partial path can be evaluated - you can do
  5832. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5833. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5834. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5835. */
  5836. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5837. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5838. }
  5839. #endif
  5840. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5841. path = path.dropLastCharacters (1);
  5842. return path;
  5843. }
  5844. const String File::addTrailingSeparator (const String& path)
  5845. {
  5846. return path.endsWithChar (File::separator) ? path
  5847. : path + File::separator;
  5848. }
  5849. #if JUCE_LINUX
  5850. #define NAMES_ARE_CASE_SENSITIVE 1
  5851. #endif
  5852. bool File::areFileNamesCaseSensitive()
  5853. {
  5854. #if NAMES_ARE_CASE_SENSITIVE
  5855. return true;
  5856. #else
  5857. return false;
  5858. #endif
  5859. }
  5860. bool File::operator== (const File& other) const
  5861. {
  5862. #if NAMES_ARE_CASE_SENSITIVE
  5863. return fullPath == other.fullPath;
  5864. #else
  5865. return fullPath.equalsIgnoreCase (other.fullPath);
  5866. #endif
  5867. }
  5868. bool File::operator!= (const File& other) const
  5869. {
  5870. return ! operator== (other);
  5871. }
  5872. bool File::operator< (const File& other) const
  5873. {
  5874. #if NAMES_ARE_CASE_SENSITIVE
  5875. return fullPath < other.fullPath;
  5876. #else
  5877. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5878. #endif
  5879. }
  5880. bool File::operator> (const File& other) const
  5881. {
  5882. #if NAMES_ARE_CASE_SENSITIVE
  5883. return fullPath > other.fullPath;
  5884. #else
  5885. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5886. #endif
  5887. }
  5888. bool File::setReadOnly (const bool shouldBeReadOnly,
  5889. const bool applyRecursively) const
  5890. {
  5891. bool worked = true;
  5892. if (applyRecursively && isDirectory())
  5893. {
  5894. Array <File> subFiles;
  5895. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5896. for (int i = subFiles.size(); --i >= 0;)
  5897. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5898. }
  5899. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5900. }
  5901. bool File::deleteRecursively() const
  5902. {
  5903. bool worked = true;
  5904. if (isDirectory())
  5905. {
  5906. Array<File> subFiles;
  5907. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5908. for (int i = subFiles.size(); --i >= 0;)
  5909. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5910. }
  5911. return deleteFile() && worked;
  5912. }
  5913. bool File::moveFileTo (const File& newFile) const
  5914. {
  5915. if (newFile.fullPath == fullPath)
  5916. return true;
  5917. #if ! NAMES_ARE_CASE_SENSITIVE
  5918. if (*this != newFile)
  5919. #endif
  5920. if (! newFile.deleteFile())
  5921. return false;
  5922. return moveInternal (newFile);
  5923. }
  5924. bool File::copyFileTo (const File& newFile) const
  5925. {
  5926. return (*this == newFile)
  5927. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5928. }
  5929. bool File::copyDirectoryTo (const File& newDirectory) const
  5930. {
  5931. if (isDirectory() && newDirectory.createDirectory())
  5932. {
  5933. Array<File> subFiles;
  5934. findChildFiles (subFiles, File::findFiles, false);
  5935. int i;
  5936. for (i = 0; i < subFiles.size(); ++i)
  5937. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5938. return false;
  5939. subFiles.clear();
  5940. findChildFiles (subFiles, File::findDirectories, false);
  5941. for (i = 0; i < subFiles.size(); ++i)
  5942. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5943. return false;
  5944. return true;
  5945. }
  5946. return false;
  5947. }
  5948. const String File::getPathUpToLastSlash() const
  5949. {
  5950. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5951. if (lastSlash > 0)
  5952. return fullPath.substring (0, lastSlash);
  5953. else if (lastSlash == 0)
  5954. return separatorString;
  5955. else
  5956. return fullPath;
  5957. }
  5958. const File File::getParentDirectory() const
  5959. {
  5960. return File (getPathUpToLastSlash(), (int) 0);
  5961. }
  5962. const String File::getFileName() const
  5963. {
  5964. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5965. }
  5966. int File::hashCode() const
  5967. {
  5968. return fullPath.hashCode();
  5969. }
  5970. int64 File::hashCode64() const
  5971. {
  5972. return fullPath.hashCode64();
  5973. }
  5974. const String File::getFileNameWithoutExtension() const
  5975. {
  5976. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5977. const int lastDot = fullPath.lastIndexOfChar ('.');
  5978. if (lastDot > lastSlash)
  5979. return fullPath.substring (lastSlash, lastDot);
  5980. else
  5981. return fullPath.substring (lastSlash);
  5982. }
  5983. bool File::isAChildOf (const File& potentialParent) const
  5984. {
  5985. if (potentialParent == File::nonexistent)
  5986. return false;
  5987. const String ourPath (getPathUpToLastSlash());
  5988. #if NAMES_ARE_CASE_SENSITIVE
  5989. if (potentialParent.fullPath == ourPath)
  5990. #else
  5991. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5992. #endif
  5993. {
  5994. return true;
  5995. }
  5996. else if (potentialParent.fullPath.length() >= ourPath.length())
  5997. {
  5998. return false;
  5999. }
  6000. else
  6001. {
  6002. return getParentDirectory().isAChildOf (potentialParent);
  6003. }
  6004. }
  6005. bool File::isAbsolutePath (const String& path)
  6006. {
  6007. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  6008. #if JUCE_WINDOWS
  6009. || (path.isNotEmpty() && path[1] == ':');
  6010. #else
  6011. || path.startsWithChar ('~');
  6012. #endif
  6013. }
  6014. const File File::getChildFile (String relativePath) const
  6015. {
  6016. if (isAbsolutePath (relativePath))
  6017. {
  6018. // the path is really absolute..
  6019. return File (relativePath);
  6020. }
  6021. else
  6022. {
  6023. // it's relative, so remove any ../ or ./ bits at the start.
  6024. String path (fullPath);
  6025. if (relativePath[0] == '.')
  6026. {
  6027. #if JUCE_WINDOWS
  6028. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6029. #else
  6030. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6031. #endif
  6032. while (relativePath[0] == '.')
  6033. {
  6034. if (relativePath[1] == '.')
  6035. {
  6036. if (relativePath [2] == 0 || relativePath[2] == separator)
  6037. {
  6038. const int lastSlash = path.lastIndexOfChar (separator);
  6039. if (lastSlash >= 0)
  6040. path = path.substring (0, lastSlash);
  6041. relativePath = relativePath.substring (3);
  6042. }
  6043. else
  6044. {
  6045. break;
  6046. }
  6047. }
  6048. else if (relativePath[1] == separator)
  6049. {
  6050. relativePath = relativePath.substring (2);
  6051. }
  6052. else
  6053. {
  6054. break;
  6055. }
  6056. }
  6057. }
  6058. return File (addTrailingSeparator (path) + relativePath);
  6059. }
  6060. }
  6061. const File File::getSiblingFile (const String& fileName) const
  6062. {
  6063. return getParentDirectory().getChildFile (fileName);
  6064. }
  6065. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6066. {
  6067. if (bytes == 1)
  6068. {
  6069. return "1 byte";
  6070. }
  6071. else if (bytes < 1024)
  6072. {
  6073. return String ((int) bytes) + " bytes";
  6074. }
  6075. else if (bytes < 1024 * 1024)
  6076. {
  6077. return String (bytes / 1024.0, 1) + " KB";
  6078. }
  6079. else if (bytes < 1024 * 1024 * 1024)
  6080. {
  6081. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6082. }
  6083. else
  6084. {
  6085. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6086. }
  6087. }
  6088. bool File::create() const
  6089. {
  6090. if (exists())
  6091. return true;
  6092. {
  6093. const File parentDir (getParentDirectory());
  6094. if (parentDir == *this || ! parentDir.createDirectory())
  6095. return false;
  6096. FileOutputStream fo (*this, 8);
  6097. }
  6098. return exists();
  6099. }
  6100. bool File::createDirectory() const
  6101. {
  6102. if (! isDirectory())
  6103. {
  6104. const File parentDir (getParentDirectory());
  6105. if (parentDir == *this || ! parentDir.createDirectory())
  6106. return false;
  6107. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6108. return isDirectory();
  6109. }
  6110. return true;
  6111. }
  6112. const Time File::getCreationTime() const
  6113. {
  6114. int64 m, a, c;
  6115. getFileTimesInternal (m, a, c);
  6116. return Time (c);
  6117. }
  6118. const Time File::getLastModificationTime() const
  6119. {
  6120. int64 m, a, c;
  6121. getFileTimesInternal (m, a, c);
  6122. return Time (m);
  6123. }
  6124. const Time File::getLastAccessTime() const
  6125. {
  6126. int64 m, a, c;
  6127. getFileTimesInternal (m, a, c);
  6128. return Time (a);
  6129. }
  6130. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6131. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6132. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6133. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6134. {
  6135. if (! existsAsFile())
  6136. return false;
  6137. FileInputStream in (*this);
  6138. return getSize() == in.readIntoMemoryBlock (destBlock);
  6139. }
  6140. const String File::loadFileAsString() const
  6141. {
  6142. if (! existsAsFile())
  6143. return String::empty;
  6144. FileInputStream in (*this);
  6145. return in.readEntireStreamAsString();
  6146. }
  6147. int File::findChildFiles (Array<File>& results,
  6148. const int whatToLookFor,
  6149. const bool searchRecursively,
  6150. const String& wildCardPattern) const
  6151. {
  6152. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6153. int total = 0;
  6154. while (di.next())
  6155. {
  6156. results.add (di.getFile());
  6157. ++total;
  6158. }
  6159. return total;
  6160. }
  6161. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6162. {
  6163. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6164. int total = 0;
  6165. while (di.next())
  6166. ++total;
  6167. return total;
  6168. }
  6169. bool File::containsSubDirectories() const
  6170. {
  6171. if (isDirectory())
  6172. {
  6173. DirectoryIterator di (*this, false, "*", findDirectories);
  6174. return di.next();
  6175. }
  6176. return false;
  6177. }
  6178. const File File::getNonexistentChildFile (const String& prefix_,
  6179. const String& suffix,
  6180. bool putNumbersInBrackets) const
  6181. {
  6182. File f (getChildFile (prefix_ + suffix));
  6183. if (f.exists())
  6184. {
  6185. int num = 2;
  6186. String prefix (prefix_);
  6187. // remove any bracketed numbers that may already be on the end..
  6188. if (prefix.trim().endsWithChar (')'))
  6189. {
  6190. putNumbersInBrackets = true;
  6191. const int openBracks = prefix.lastIndexOfChar ('(');
  6192. const int closeBracks = prefix.lastIndexOfChar (')');
  6193. if (openBracks > 0
  6194. && closeBracks > openBracks
  6195. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6196. {
  6197. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6198. prefix = prefix.substring (0, openBracks);
  6199. }
  6200. }
  6201. // also use brackets if it ends in a digit.
  6202. putNumbersInBrackets = putNumbersInBrackets
  6203. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6204. do
  6205. {
  6206. if (putNumbersInBrackets)
  6207. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6208. else
  6209. f = getChildFile (prefix + String (num++) + suffix);
  6210. } while (f.exists());
  6211. }
  6212. return f;
  6213. }
  6214. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6215. {
  6216. if (exists())
  6217. {
  6218. return getParentDirectory()
  6219. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6220. getFileExtension(),
  6221. putNumbersInBrackets);
  6222. }
  6223. else
  6224. {
  6225. return *this;
  6226. }
  6227. }
  6228. const String File::getFileExtension() const
  6229. {
  6230. String ext;
  6231. if (! isDirectory())
  6232. {
  6233. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6234. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6235. ext = fullPath.substring (indexOfDot);
  6236. }
  6237. return ext;
  6238. }
  6239. bool File::hasFileExtension (const String& possibleSuffix) const
  6240. {
  6241. if (possibleSuffix.isEmpty())
  6242. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6243. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6244. if (semicolon >= 0)
  6245. {
  6246. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6247. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6248. }
  6249. else
  6250. {
  6251. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6252. {
  6253. if (possibleSuffix.startsWithChar ('.'))
  6254. return true;
  6255. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6256. if (dotPos >= 0)
  6257. return fullPath [dotPos] == '.';
  6258. }
  6259. }
  6260. return false;
  6261. }
  6262. const File File::withFileExtension (const String& newExtension) const
  6263. {
  6264. if (fullPath.isEmpty())
  6265. return File::nonexistent;
  6266. String filePart (getFileName());
  6267. int i = filePart.lastIndexOfChar ('.');
  6268. if (i >= 0)
  6269. filePart = filePart.substring (0, i);
  6270. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6271. filePart << '.';
  6272. return getSiblingFile (filePart + newExtension);
  6273. }
  6274. bool File::startAsProcess (const String& parameters) const
  6275. {
  6276. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6277. }
  6278. FileInputStream* File::createInputStream() const
  6279. {
  6280. if (existsAsFile())
  6281. return new FileInputStream (*this);
  6282. return 0;
  6283. }
  6284. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6285. {
  6286. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6287. if (out->failedToOpen())
  6288. return 0;
  6289. return out.release();
  6290. }
  6291. bool File::appendData (const void* const dataToAppend,
  6292. const int numberOfBytes) const
  6293. {
  6294. if (numberOfBytes > 0)
  6295. {
  6296. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6297. if (out == 0)
  6298. return false;
  6299. out->write (dataToAppend, numberOfBytes);
  6300. }
  6301. return true;
  6302. }
  6303. bool File::replaceWithData (const void* const dataToWrite,
  6304. const int numberOfBytes) const
  6305. {
  6306. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6307. if (numberOfBytes <= 0)
  6308. return deleteFile();
  6309. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6310. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6311. return tempFile.overwriteTargetFileWithTemporary();
  6312. }
  6313. bool File::appendText (const String& text,
  6314. const bool asUnicode,
  6315. const bool writeUnicodeHeaderBytes) const
  6316. {
  6317. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6318. if (out != 0)
  6319. {
  6320. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6321. return true;
  6322. }
  6323. return false;
  6324. }
  6325. bool File::replaceWithText (const String& textToWrite,
  6326. const bool asUnicode,
  6327. const bool writeUnicodeHeaderBytes) const
  6328. {
  6329. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6330. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6331. return tempFile.overwriteTargetFileWithTemporary();
  6332. }
  6333. bool File::hasIdenticalContentTo (const File& other) const
  6334. {
  6335. if (other == *this)
  6336. return true;
  6337. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6338. {
  6339. FileInputStream in1 (*this), in2 (other);
  6340. const int bufferSize = 4096;
  6341. HeapBlock <char> buffer1, buffer2;
  6342. buffer1.malloc (bufferSize);
  6343. buffer2.malloc (bufferSize);
  6344. for (;;)
  6345. {
  6346. const int num1 = in1.read (buffer1, bufferSize);
  6347. const int num2 = in2.read (buffer2, bufferSize);
  6348. if (num1 != num2)
  6349. break;
  6350. if (num1 <= 0)
  6351. return true;
  6352. if (memcmp (buffer1, buffer2, num1) != 0)
  6353. break;
  6354. }
  6355. }
  6356. return false;
  6357. }
  6358. const String File::createLegalPathName (const String& original)
  6359. {
  6360. String s (original);
  6361. String start;
  6362. if (s[1] == ':')
  6363. {
  6364. start = s.substring (0, 2);
  6365. s = s.substring (2);
  6366. }
  6367. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6368. .substring (0, 1024);
  6369. }
  6370. const String File::createLegalFileName (const String& original)
  6371. {
  6372. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6373. const int maxLength = 128; // only the length of the filename, not the whole path
  6374. const int len = s.length();
  6375. if (len > maxLength)
  6376. {
  6377. const int lastDot = s.lastIndexOfChar ('.');
  6378. if (lastDot > jmax (0, len - 12))
  6379. {
  6380. s = s.substring (0, maxLength - (len - lastDot))
  6381. + s.substring (lastDot);
  6382. }
  6383. else
  6384. {
  6385. s = s.substring (0, maxLength);
  6386. }
  6387. }
  6388. return s;
  6389. }
  6390. const String File::getRelativePathFrom (const File& dir) const
  6391. {
  6392. String thisPath (fullPath);
  6393. {
  6394. int len = thisPath.length();
  6395. while (--len >= 0 && thisPath [len] == File::separator)
  6396. thisPath [len] = 0;
  6397. }
  6398. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6399. : dir.fullPath));
  6400. const int len = jmin (thisPath.length(), dirPath.length());
  6401. int commonBitLength = 0;
  6402. for (int i = 0; i < len; ++i)
  6403. {
  6404. #if NAMES_ARE_CASE_SENSITIVE
  6405. if (thisPath[i] != dirPath[i])
  6406. #else
  6407. if (CharacterFunctions::toLowerCase (thisPath[i])
  6408. != CharacterFunctions::toLowerCase (dirPath[i]))
  6409. #endif
  6410. {
  6411. break;
  6412. }
  6413. ++commonBitLength;
  6414. }
  6415. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6416. --commonBitLength;
  6417. // if the only common bit is the root, then just return the full path..
  6418. if (commonBitLength <= 0
  6419. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6420. return fullPath;
  6421. thisPath = thisPath.substring (commonBitLength);
  6422. dirPath = dirPath.substring (commonBitLength);
  6423. while (dirPath.isNotEmpty())
  6424. {
  6425. #if JUCE_WINDOWS
  6426. thisPath = "..\\" + thisPath;
  6427. #else
  6428. thisPath = "../" + thisPath;
  6429. #endif
  6430. const int sep = dirPath.indexOfChar (separator);
  6431. if (sep >= 0)
  6432. dirPath = dirPath.substring (sep + 1);
  6433. else
  6434. dirPath = String::empty;
  6435. }
  6436. return thisPath;
  6437. }
  6438. const File File::createTempFile (const String& fileNameEnding)
  6439. {
  6440. const File tempFile (getSpecialLocation (tempDirectory)
  6441. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6442. .withFileExtension (fileNameEnding));
  6443. if (tempFile.exists())
  6444. return createTempFile (fileNameEnding);
  6445. else
  6446. return tempFile;
  6447. }
  6448. #if JUCE_UNIT_TESTS
  6449. class FileTests : public UnitTest
  6450. {
  6451. public:
  6452. FileTests() : UnitTest ("Files") {}
  6453. void runTest()
  6454. {
  6455. beginTest ("Reading");
  6456. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6457. const File temp (File::getSpecialLocation (File::tempDirectory));
  6458. expect (! File::nonexistent.exists());
  6459. expect (home.isDirectory());
  6460. expect (home.exists());
  6461. expect (! home.existsAsFile());
  6462. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6463. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6464. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6465. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6466. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6467. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6468. expect (home.getBytesFreeOnVolume() > 0);
  6469. expect (! home.isHidden());
  6470. expect (home.isOnHardDisk());
  6471. expect (! home.isOnCDRomDrive());
  6472. expect (File::getCurrentWorkingDirectory().exists());
  6473. expect (home.setAsCurrentWorkingDirectory());
  6474. expect (File::getCurrentWorkingDirectory() == home);
  6475. {
  6476. Array<File> roots;
  6477. File::findFileSystemRoots (roots);
  6478. expect (roots.size() > 0);
  6479. int numRootsExisting = 0;
  6480. for (int i = 0; i < roots.size(); ++i)
  6481. if (roots[i].exists())
  6482. ++numRootsExisting;
  6483. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6484. expect (numRootsExisting > 0);
  6485. }
  6486. beginTest ("Writing");
  6487. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6488. expect (demoFolder.deleteRecursively());
  6489. expect (demoFolder.createDirectory());
  6490. expect (demoFolder.isDirectory());
  6491. expect (demoFolder.getParentDirectory() == temp);
  6492. expect (temp.isDirectory());
  6493. {
  6494. Array<File> files;
  6495. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6496. expect (files.contains (demoFolder));
  6497. }
  6498. {
  6499. Array<File> files;
  6500. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6501. expect (files.contains (demoFolder));
  6502. }
  6503. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6504. expect (tempFile.getFileExtension() == ".txt");
  6505. expect (tempFile.hasFileExtension (".txt"));
  6506. expect (tempFile.hasFileExtension ("txt"));
  6507. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6508. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6509. expect (tempFile.hasWriteAccess());
  6510. {
  6511. FileOutputStream fo (tempFile);
  6512. fo.write ("0123456789", 10);
  6513. }
  6514. expect (tempFile.exists());
  6515. expect (tempFile.getSize() == 10);
  6516. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6517. expect (tempFile.loadFileAsString() == "0123456789");
  6518. expect (! demoFolder.containsSubDirectories());
  6519. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6520. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6521. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6522. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6523. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6524. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6525. expect (demoFolder.containsSubDirectories());
  6526. expect (tempFile.hasWriteAccess());
  6527. tempFile.setReadOnly (true);
  6528. expect (! tempFile.hasWriteAccess());
  6529. tempFile.setReadOnly (false);
  6530. expect (tempFile.hasWriteAccess());
  6531. Time t (Time::getCurrentTime());
  6532. tempFile.setLastModificationTime (t);
  6533. Time t2 = tempFile.getLastModificationTime();
  6534. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6535. {
  6536. MemoryBlock mb;
  6537. tempFile.loadFileAsData (mb);
  6538. expect (mb.getSize() == 10);
  6539. expect (mb[0] == '0');
  6540. }
  6541. expect (tempFile.appendData ("abcdefghij", 10));
  6542. expect (tempFile.getSize() == 20);
  6543. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6544. expect (tempFile.getSize() == 10);
  6545. File tempFile2 (tempFile.getNonexistentSibling (false));
  6546. expect (tempFile.copyFileTo (tempFile2));
  6547. expect (tempFile2.exists());
  6548. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6549. expect (tempFile.deleteFile());
  6550. expect (! tempFile.exists());
  6551. expect (tempFile2.moveFileTo (tempFile));
  6552. expect (tempFile.exists());
  6553. expect (! tempFile2.exists());
  6554. expect (demoFolder.deleteRecursively());
  6555. expect (! demoFolder.exists());
  6556. }
  6557. };
  6558. static FileTests fileUnitTests;
  6559. #endif
  6560. END_JUCE_NAMESPACE
  6561. /*** End of inlined file: juce_File.cpp ***/
  6562. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6563. BEGIN_JUCE_NAMESPACE
  6564. int64 juce_fileSetPosition (void* handle, int64 pos);
  6565. FileInputStream::FileInputStream (const File& f)
  6566. : file (f),
  6567. fileHandle (0),
  6568. currentPosition (0),
  6569. totalSize (0),
  6570. needToSeek (true)
  6571. {
  6572. openHandle();
  6573. }
  6574. FileInputStream::~FileInputStream()
  6575. {
  6576. closeHandle();
  6577. }
  6578. int64 FileInputStream::getTotalLength()
  6579. {
  6580. return totalSize;
  6581. }
  6582. int FileInputStream::read (void* buffer, int bytesToRead)
  6583. {
  6584. int num = 0;
  6585. if (needToSeek)
  6586. {
  6587. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6588. return 0;
  6589. needToSeek = false;
  6590. }
  6591. num = readInternal (buffer, bytesToRead);
  6592. currentPosition += num;
  6593. return num;
  6594. }
  6595. bool FileInputStream::isExhausted()
  6596. {
  6597. return currentPosition >= totalSize;
  6598. }
  6599. int64 FileInputStream::getPosition()
  6600. {
  6601. return currentPosition;
  6602. }
  6603. bool FileInputStream::setPosition (int64 pos)
  6604. {
  6605. pos = jlimit ((int64) 0, totalSize, pos);
  6606. needToSeek |= (currentPosition != pos);
  6607. currentPosition = pos;
  6608. return true;
  6609. }
  6610. END_JUCE_NAMESPACE
  6611. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6612. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6613. BEGIN_JUCE_NAMESPACE
  6614. int64 juce_fileSetPosition (void* handle, int64 pos);
  6615. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6616. : file (f),
  6617. fileHandle (0),
  6618. currentPosition (0),
  6619. bufferSize (bufferSize_),
  6620. bytesInBuffer (0),
  6621. buffer (jmax (bufferSize_, 16))
  6622. {
  6623. openHandle();
  6624. }
  6625. FileOutputStream::~FileOutputStream()
  6626. {
  6627. flush();
  6628. closeHandle();
  6629. }
  6630. int64 FileOutputStream::getPosition()
  6631. {
  6632. return currentPosition;
  6633. }
  6634. bool FileOutputStream::setPosition (int64 newPosition)
  6635. {
  6636. if (newPosition != currentPosition)
  6637. {
  6638. flush();
  6639. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6640. }
  6641. return newPosition == currentPosition;
  6642. }
  6643. void FileOutputStream::flush()
  6644. {
  6645. if (bytesInBuffer > 0)
  6646. {
  6647. writeInternal (buffer, bytesInBuffer);
  6648. bytesInBuffer = 0;
  6649. }
  6650. flushInternal();
  6651. }
  6652. bool FileOutputStream::write (const void* const src, const int numBytes)
  6653. {
  6654. if (bytesInBuffer + numBytes < bufferSize)
  6655. {
  6656. memcpy (buffer + bytesInBuffer, src, numBytes);
  6657. bytesInBuffer += numBytes;
  6658. currentPosition += numBytes;
  6659. }
  6660. else
  6661. {
  6662. if (bytesInBuffer > 0)
  6663. {
  6664. // flush the reservoir
  6665. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6666. bytesInBuffer = 0;
  6667. if (! wroteOk)
  6668. return false;
  6669. }
  6670. if (numBytes < bufferSize)
  6671. {
  6672. memcpy (buffer + bytesInBuffer, src, numBytes);
  6673. bytesInBuffer += numBytes;
  6674. currentPosition += numBytes;
  6675. }
  6676. else
  6677. {
  6678. const int bytesWritten = writeInternal (src, numBytes);
  6679. if (bytesWritten < 0)
  6680. return false;
  6681. currentPosition += bytesWritten;
  6682. return bytesWritten == numBytes;
  6683. }
  6684. }
  6685. return true;
  6686. }
  6687. END_JUCE_NAMESPACE
  6688. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6689. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6690. BEGIN_JUCE_NAMESPACE
  6691. FileSearchPath::FileSearchPath()
  6692. {
  6693. }
  6694. FileSearchPath::FileSearchPath (const String& path)
  6695. {
  6696. init (path);
  6697. }
  6698. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6699. : directories (other.directories)
  6700. {
  6701. }
  6702. FileSearchPath::~FileSearchPath()
  6703. {
  6704. }
  6705. FileSearchPath& FileSearchPath::operator= (const String& path)
  6706. {
  6707. init (path);
  6708. return *this;
  6709. }
  6710. void FileSearchPath::init (const String& path)
  6711. {
  6712. directories.clear();
  6713. directories.addTokens (path, ";", "\"");
  6714. directories.trim();
  6715. directories.removeEmptyStrings();
  6716. for (int i = directories.size(); --i >= 0;)
  6717. directories.set (i, directories[i].unquoted());
  6718. }
  6719. int FileSearchPath::getNumPaths() const
  6720. {
  6721. return directories.size();
  6722. }
  6723. const File FileSearchPath::operator[] (const int index) const
  6724. {
  6725. return File (directories [index]);
  6726. }
  6727. const String FileSearchPath::toString() const
  6728. {
  6729. StringArray directories2 (directories);
  6730. for (int i = directories2.size(); --i >= 0;)
  6731. if (directories2[i].containsChar (';'))
  6732. directories2.set (i, directories2[i].quoted());
  6733. return directories2.joinIntoString (";");
  6734. }
  6735. void FileSearchPath::add (const File& dir, const int insertIndex)
  6736. {
  6737. directories.insert (insertIndex, dir.getFullPathName());
  6738. }
  6739. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6740. {
  6741. for (int i = 0; i < directories.size(); ++i)
  6742. if (File (directories[i]) == dir)
  6743. return;
  6744. add (dir);
  6745. }
  6746. void FileSearchPath::remove (const int index)
  6747. {
  6748. directories.remove (index);
  6749. }
  6750. void FileSearchPath::addPath (const FileSearchPath& other)
  6751. {
  6752. for (int i = 0; i < other.getNumPaths(); ++i)
  6753. addIfNotAlreadyThere (other[i]);
  6754. }
  6755. void FileSearchPath::removeRedundantPaths()
  6756. {
  6757. for (int i = directories.size(); --i >= 0;)
  6758. {
  6759. const File d1 (directories[i]);
  6760. for (int j = directories.size(); --j >= 0;)
  6761. {
  6762. const File d2 (directories[j]);
  6763. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6764. {
  6765. directories.remove (i);
  6766. break;
  6767. }
  6768. }
  6769. }
  6770. }
  6771. void FileSearchPath::removeNonExistentPaths()
  6772. {
  6773. for (int i = directories.size(); --i >= 0;)
  6774. if (! File (directories[i]).isDirectory())
  6775. directories.remove (i);
  6776. }
  6777. int FileSearchPath::findChildFiles (Array<File>& results,
  6778. const int whatToLookFor,
  6779. const bool searchRecursively,
  6780. const String& wildCardPattern) const
  6781. {
  6782. int total = 0;
  6783. for (int i = 0; i < directories.size(); ++i)
  6784. total += operator[] (i).findChildFiles (results,
  6785. whatToLookFor,
  6786. searchRecursively,
  6787. wildCardPattern);
  6788. return total;
  6789. }
  6790. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6791. const bool checkRecursively) const
  6792. {
  6793. for (int i = directories.size(); --i >= 0;)
  6794. {
  6795. const File d (directories[i]);
  6796. if (checkRecursively)
  6797. {
  6798. if (fileToCheck.isAChildOf (d))
  6799. return true;
  6800. }
  6801. else
  6802. {
  6803. if (fileToCheck.getParentDirectory() == d)
  6804. return true;
  6805. }
  6806. }
  6807. return false;
  6808. }
  6809. END_JUCE_NAMESPACE
  6810. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6811. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6812. BEGIN_JUCE_NAMESPACE
  6813. NamedPipe::NamedPipe()
  6814. : internal (0)
  6815. {
  6816. }
  6817. NamedPipe::~NamedPipe()
  6818. {
  6819. close();
  6820. }
  6821. bool NamedPipe::openExisting (const String& pipeName)
  6822. {
  6823. currentPipeName = pipeName;
  6824. return openInternal (pipeName, false);
  6825. }
  6826. bool NamedPipe::createNewPipe (const String& pipeName)
  6827. {
  6828. currentPipeName = pipeName;
  6829. return openInternal (pipeName, true);
  6830. }
  6831. bool NamedPipe::isOpen() const
  6832. {
  6833. return internal != 0;
  6834. }
  6835. const String NamedPipe::getName() const
  6836. {
  6837. return currentPipeName;
  6838. }
  6839. // other methods for this class are implemented in the platform-specific files
  6840. END_JUCE_NAMESPACE
  6841. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6842. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6843. BEGIN_JUCE_NAMESPACE
  6844. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6845. {
  6846. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6847. "temp_" + String (Random::getSystemRandom().nextInt()),
  6848. suffix,
  6849. optionFlags);
  6850. }
  6851. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6852. : targetFile (targetFile_)
  6853. {
  6854. // If you use this constructor, you need to give it a valid target file!
  6855. jassert (targetFile != File::nonexistent);
  6856. createTempFile (targetFile.getParentDirectory(),
  6857. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6858. targetFile.getFileExtension(),
  6859. optionFlags);
  6860. }
  6861. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6862. const String& suffix, const int optionFlags)
  6863. {
  6864. if ((optionFlags & useHiddenFile) != 0)
  6865. name = "." + name;
  6866. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6867. }
  6868. TemporaryFile::~TemporaryFile()
  6869. {
  6870. if (! deleteTemporaryFile())
  6871. {
  6872. /* Failed to delete our temporary file! The most likely reason for this would be
  6873. that you've not closed an output stream that was being used to write to file.
  6874. If you find that something beyond your control is changing permissions on
  6875. your temporary files and preventing them from being deleted, you may want to
  6876. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6877. handle them appropriately.
  6878. */
  6879. jassertfalse;
  6880. }
  6881. }
  6882. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6883. {
  6884. // This method only works if you created this object with the constructor
  6885. // that takes a target file!
  6886. jassert (targetFile != File::nonexistent);
  6887. if (temporaryFile.exists())
  6888. {
  6889. // Have a few attempts at overwriting the file before giving up..
  6890. for (int i = 5; --i >= 0;)
  6891. {
  6892. if (temporaryFile.moveFileTo (targetFile))
  6893. return true;
  6894. Thread::sleep (100);
  6895. }
  6896. }
  6897. else
  6898. {
  6899. // There's no temporary file to use. If your write failed, you should
  6900. // probably check, and not bother calling this method.
  6901. jassertfalse;
  6902. }
  6903. return false;
  6904. }
  6905. bool TemporaryFile::deleteTemporaryFile() const
  6906. {
  6907. // Have a few attempts at deleting the file before giving up..
  6908. for (int i = 5; --i >= 0;)
  6909. {
  6910. if (temporaryFile.deleteFile())
  6911. return true;
  6912. Thread::sleep (50);
  6913. }
  6914. return false;
  6915. }
  6916. END_JUCE_NAMESPACE
  6917. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6918. /*** Start of inlined file: juce_Socket.cpp ***/
  6919. #if JUCE_WINDOWS
  6920. #include <winsock2.h>
  6921. #if JUCE_MSVC
  6922. #pragma warning (push)
  6923. #pragma warning (disable : 4127 4389 4018)
  6924. #endif
  6925. #else
  6926. #if JUCE_LINUX
  6927. #include <sys/types.h>
  6928. #include <sys/socket.h>
  6929. #include <sys/errno.h>
  6930. #include <unistd.h>
  6931. #include <netinet/in.h>
  6932. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6933. #include <CoreServices/CoreServices.h>
  6934. #endif
  6935. #include <fcntl.h>
  6936. #include <netdb.h>
  6937. #include <arpa/inet.h>
  6938. #include <netinet/tcp.h>
  6939. #endif
  6940. BEGIN_JUCE_NAMESPACE
  6941. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6942. typedef socklen_t juce_socklen_t;
  6943. #else
  6944. typedef int juce_socklen_t;
  6945. #endif
  6946. #if JUCE_WINDOWS
  6947. namespace SocketHelpers
  6948. {
  6949. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6950. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6951. void initWin32Sockets()
  6952. {
  6953. static CriticalSection lock;
  6954. const ScopedLock sl (lock);
  6955. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6956. {
  6957. WSADATA wsaData;
  6958. const WORD wVersionRequested = MAKEWORD (1, 1);
  6959. WSAStartup (wVersionRequested, &wsaData);
  6960. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6961. }
  6962. }
  6963. }
  6964. void juce_shutdownWin32Sockets()
  6965. {
  6966. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6967. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6968. }
  6969. #endif
  6970. namespace SocketHelpers
  6971. {
  6972. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6973. {
  6974. const int sndBufSize = 65536;
  6975. const int rcvBufSize = 65536;
  6976. const int one = 1;
  6977. return handle > 0
  6978. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6979. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6980. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6981. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6982. }
  6983. bool bindSocketToPort (const int handle, const int port) throw()
  6984. {
  6985. if (handle <= 0 || port <= 0)
  6986. return false;
  6987. struct sockaddr_in servTmpAddr;
  6988. zerostruct (servTmpAddr);
  6989. servTmpAddr.sin_family = PF_INET;
  6990. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6991. servTmpAddr.sin_port = htons ((uint16) port);
  6992. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6993. }
  6994. int readSocket (const int handle,
  6995. void* const destBuffer, const int maxBytesToRead,
  6996. bool volatile& connected,
  6997. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6998. {
  6999. int bytesRead = 0;
  7000. while (bytesRead < maxBytesToRead)
  7001. {
  7002. int bytesThisTime;
  7003. #if JUCE_WINDOWS
  7004. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  7005. #else
  7006. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  7007. && errno == EINTR
  7008. && connected)
  7009. {
  7010. }
  7011. #endif
  7012. if (bytesThisTime <= 0 || ! connected)
  7013. {
  7014. if (bytesRead == 0)
  7015. bytesRead = -1;
  7016. break;
  7017. }
  7018. bytesRead += bytesThisTime;
  7019. if (! blockUntilSpecifiedAmountHasArrived)
  7020. break;
  7021. }
  7022. return bytesRead;
  7023. }
  7024. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  7025. {
  7026. struct timeval timeout;
  7027. struct timeval* timeoutp;
  7028. if (timeoutMsecs >= 0)
  7029. {
  7030. timeout.tv_sec = timeoutMsecs / 1000;
  7031. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7032. timeoutp = &timeout;
  7033. }
  7034. else
  7035. {
  7036. timeoutp = 0;
  7037. }
  7038. fd_set rset, wset;
  7039. FD_ZERO (&rset);
  7040. FD_SET (handle, &rset);
  7041. FD_ZERO (&wset);
  7042. FD_SET (handle, &wset);
  7043. fd_set* const prset = forReading ? &rset : 0;
  7044. fd_set* const pwset = forReading ? 0 : &wset;
  7045. #if JUCE_WINDOWS
  7046. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7047. return -1;
  7048. #else
  7049. {
  7050. int result;
  7051. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7052. && errno == EINTR)
  7053. {
  7054. }
  7055. if (result < 0)
  7056. return -1;
  7057. }
  7058. #endif
  7059. {
  7060. int opt;
  7061. juce_socklen_t len = sizeof (opt);
  7062. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7063. || opt != 0)
  7064. return -1;
  7065. }
  7066. if ((forReading && FD_ISSET (handle, &rset))
  7067. || ((! forReading) && FD_ISSET (handle, &wset)))
  7068. return 1;
  7069. return 0;
  7070. }
  7071. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7072. {
  7073. #if JUCE_WINDOWS
  7074. u_long nonBlocking = shouldBlock ? 0 : 1;
  7075. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7076. return false;
  7077. #else
  7078. int socketFlags = fcntl (handle, F_GETFL, 0);
  7079. if (socketFlags == -1)
  7080. return false;
  7081. if (shouldBlock)
  7082. socketFlags &= ~O_NONBLOCK;
  7083. else
  7084. socketFlags |= O_NONBLOCK;
  7085. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7086. return false;
  7087. #endif
  7088. return true;
  7089. }
  7090. bool connectSocket (int volatile& handle,
  7091. const bool isDatagram,
  7092. void** serverAddress,
  7093. const String& hostName,
  7094. const int portNumber,
  7095. const int timeOutMillisecs) throw()
  7096. {
  7097. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7098. if (hostEnt == 0)
  7099. return false;
  7100. struct in_addr targetAddress;
  7101. memcpy (&targetAddress.s_addr,
  7102. *(hostEnt->h_addr_list),
  7103. sizeof (targetAddress.s_addr));
  7104. struct sockaddr_in servTmpAddr;
  7105. zerostruct (servTmpAddr);
  7106. servTmpAddr.sin_family = PF_INET;
  7107. servTmpAddr.sin_addr = targetAddress;
  7108. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7109. if (handle < 0)
  7110. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7111. if (handle < 0)
  7112. return false;
  7113. if (isDatagram)
  7114. {
  7115. *serverAddress = new struct sockaddr_in();
  7116. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7117. return true;
  7118. }
  7119. setSocketBlockingState (handle, false);
  7120. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7121. if (result < 0)
  7122. {
  7123. #if JUCE_WINDOWS
  7124. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7125. #else
  7126. if (errno == EINPROGRESS)
  7127. #endif
  7128. {
  7129. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7130. {
  7131. setSocketBlockingState (handle, true);
  7132. return false;
  7133. }
  7134. }
  7135. }
  7136. setSocketBlockingState (handle, true);
  7137. resetSocketOptions (handle, false, false);
  7138. return true;
  7139. }
  7140. }
  7141. StreamingSocket::StreamingSocket()
  7142. : portNumber (0),
  7143. handle (-1),
  7144. connected (false),
  7145. isListener (false)
  7146. {
  7147. #if JUCE_WINDOWS
  7148. SocketHelpers::initWin32Sockets();
  7149. #endif
  7150. }
  7151. StreamingSocket::StreamingSocket (const String& hostName_,
  7152. const int portNumber_,
  7153. const int handle_)
  7154. : hostName (hostName_),
  7155. portNumber (portNumber_),
  7156. handle (handle_),
  7157. connected (true),
  7158. isListener (false)
  7159. {
  7160. #if JUCE_WINDOWS
  7161. SocketHelpers::initWin32Sockets();
  7162. #endif
  7163. SocketHelpers::resetSocketOptions (handle_, false, false);
  7164. }
  7165. StreamingSocket::~StreamingSocket()
  7166. {
  7167. close();
  7168. }
  7169. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7170. {
  7171. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7172. : -1;
  7173. }
  7174. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7175. {
  7176. if (isListener || ! connected)
  7177. return -1;
  7178. #if JUCE_WINDOWS
  7179. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7180. #else
  7181. int result;
  7182. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7183. && errno == EINTR)
  7184. {
  7185. }
  7186. return result;
  7187. #endif
  7188. }
  7189. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7190. const int timeoutMsecs) const
  7191. {
  7192. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7193. : -1;
  7194. }
  7195. bool StreamingSocket::bindToPort (const int port)
  7196. {
  7197. return SocketHelpers::bindSocketToPort (handle, port);
  7198. }
  7199. bool StreamingSocket::connect (const String& remoteHostName,
  7200. const int remotePortNumber,
  7201. const int timeOutMillisecs)
  7202. {
  7203. if (isListener)
  7204. {
  7205. jassertfalse; // a listener socket can't connect to another one!
  7206. return false;
  7207. }
  7208. if (connected)
  7209. close();
  7210. hostName = remoteHostName;
  7211. portNumber = remotePortNumber;
  7212. isListener = false;
  7213. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7214. remotePortNumber, timeOutMillisecs);
  7215. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7216. {
  7217. close();
  7218. return false;
  7219. }
  7220. return true;
  7221. }
  7222. void StreamingSocket::close()
  7223. {
  7224. #if JUCE_WINDOWS
  7225. if (handle != SOCKET_ERROR || connected)
  7226. closesocket (handle);
  7227. connected = false;
  7228. #else
  7229. if (connected)
  7230. {
  7231. connected = false;
  7232. if (isListener)
  7233. {
  7234. // need to do this to interrupt the accept() function..
  7235. StreamingSocket temp;
  7236. temp.connect ("localhost", portNumber, 1000);
  7237. }
  7238. }
  7239. if (handle != -1)
  7240. ::close (handle);
  7241. #endif
  7242. hostName = String::empty;
  7243. portNumber = 0;
  7244. handle = -1;
  7245. isListener = false;
  7246. }
  7247. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7248. {
  7249. if (connected)
  7250. close();
  7251. hostName = "listener";
  7252. portNumber = newPortNumber;
  7253. isListener = true;
  7254. struct sockaddr_in servTmpAddr;
  7255. zerostruct (servTmpAddr);
  7256. servTmpAddr.sin_family = PF_INET;
  7257. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7258. if (localHostName.isNotEmpty())
  7259. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7260. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7261. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7262. if (handle < 0)
  7263. return false;
  7264. const int reuse = 1;
  7265. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7266. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7267. || listen (handle, SOMAXCONN) < 0)
  7268. {
  7269. close();
  7270. return false;
  7271. }
  7272. connected = true;
  7273. return true;
  7274. }
  7275. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7276. {
  7277. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7278. // prepare this socket as a listener.
  7279. if (connected && isListener)
  7280. {
  7281. struct sockaddr address;
  7282. juce_socklen_t len = sizeof (sockaddr);
  7283. const int newSocket = (int) accept (handle, &address, &len);
  7284. if (newSocket >= 0 && connected)
  7285. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7286. portNumber, newSocket);
  7287. }
  7288. return 0;
  7289. }
  7290. bool StreamingSocket::isLocal() const throw()
  7291. {
  7292. return hostName == "127.0.0.1";
  7293. }
  7294. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7295. : portNumber (0),
  7296. handle (-1),
  7297. connected (true),
  7298. allowBroadcast (allowBroadcast_),
  7299. serverAddress (0)
  7300. {
  7301. #if JUCE_WINDOWS
  7302. SocketHelpers::initWin32Sockets();
  7303. #endif
  7304. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7305. bindToPort (localPortNumber);
  7306. }
  7307. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7308. const int handle_, const int localPortNumber)
  7309. : hostName (hostName_),
  7310. portNumber (portNumber_),
  7311. handle (handle_),
  7312. connected (true),
  7313. allowBroadcast (false),
  7314. serverAddress (0)
  7315. {
  7316. #if JUCE_WINDOWS
  7317. SocketHelpers::initWin32Sockets();
  7318. #endif
  7319. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7320. bindToPort (localPortNumber);
  7321. }
  7322. DatagramSocket::~DatagramSocket()
  7323. {
  7324. close();
  7325. delete static_cast <struct sockaddr_in*> (serverAddress);
  7326. serverAddress = 0;
  7327. }
  7328. void DatagramSocket::close()
  7329. {
  7330. #if JUCE_WINDOWS
  7331. closesocket (handle);
  7332. connected = false;
  7333. #else
  7334. connected = false;
  7335. ::close (handle);
  7336. #endif
  7337. hostName = String::empty;
  7338. portNumber = 0;
  7339. handle = -1;
  7340. }
  7341. bool DatagramSocket::bindToPort (const int port)
  7342. {
  7343. return SocketHelpers::bindSocketToPort (handle, port);
  7344. }
  7345. bool DatagramSocket::connect (const String& remoteHostName,
  7346. const int remotePortNumber,
  7347. const int timeOutMillisecs)
  7348. {
  7349. if (connected)
  7350. close();
  7351. hostName = remoteHostName;
  7352. portNumber = remotePortNumber;
  7353. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7354. remoteHostName, remotePortNumber,
  7355. timeOutMillisecs);
  7356. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7357. {
  7358. close();
  7359. return false;
  7360. }
  7361. return true;
  7362. }
  7363. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7364. {
  7365. struct sockaddr address;
  7366. juce_socklen_t len = sizeof (sockaddr);
  7367. while (waitUntilReady (true, -1) == 1)
  7368. {
  7369. char buf[1];
  7370. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7371. {
  7372. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7373. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7374. -1, -1);
  7375. }
  7376. }
  7377. return 0;
  7378. }
  7379. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7380. const int timeoutMsecs) const
  7381. {
  7382. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7383. : -1;
  7384. }
  7385. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7386. {
  7387. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7388. : -1;
  7389. }
  7390. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7391. {
  7392. // You need to call connect() first to set the server address..
  7393. jassert (serverAddress != 0 && connected);
  7394. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7395. numBytesToWrite, 0,
  7396. (const struct sockaddr*) serverAddress,
  7397. sizeof (struct sockaddr_in))
  7398. : -1;
  7399. }
  7400. bool DatagramSocket::isLocal() const throw()
  7401. {
  7402. return hostName == "127.0.0.1";
  7403. }
  7404. #if JUCE_MSVC
  7405. #pragma warning (pop)
  7406. #endif
  7407. END_JUCE_NAMESPACE
  7408. /*** End of inlined file: juce_Socket.cpp ***/
  7409. /*** Start of inlined file: juce_URL.cpp ***/
  7410. BEGIN_JUCE_NAMESPACE
  7411. URL::URL()
  7412. {
  7413. }
  7414. URL::URL (const String& url_)
  7415. : url (url_)
  7416. {
  7417. int i = url.indexOfChar ('?');
  7418. if (i >= 0)
  7419. {
  7420. do
  7421. {
  7422. const int nextAmp = url.indexOfChar (i + 1, '&');
  7423. const int equalsPos = url.indexOfChar (i + 1, '=');
  7424. if (equalsPos > i + 1)
  7425. {
  7426. if (nextAmp < 0)
  7427. {
  7428. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7429. removeEscapeChars (url.substring (equalsPos + 1)));
  7430. }
  7431. else if (nextAmp > 0 && equalsPos < nextAmp)
  7432. {
  7433. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7434. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7435. }
  7436. }
  7437. i = nextAmp;
  7438. }
  7439. while (i >= 0);
  7440. url = url.upToFirstOccurrenceOf ("?", false, false);
  7441. }
  7442. }
  7443. URL::URL (const URL& other)
  7444. : url (other.url),
  7445. postData (other.postData),
  7446. parameters (other.parameters),
  7447. filesToUpload (other.filesToUpload),
  7448. mimeTypes (other.mimeTypes)
  7449. {
  7450. }
  7451. URL& URL::operator= (const URL& other)
  7452. {
  7453. url = other.url;
  7454. postData = other.postData;
  7455. parameters = other.parameters;
  7456. filesToUpload = other.filesToUpload;
  7457. mimeTypes = other.mimeTypes;
  7458. return *this;
  7459. }
  7460. URL::~URL()
  7461. {
  7462. }
  7463. namespace URLHelpers
  7464. {
  7465. const String getMangledParameters (const StringPairArray& parameters)
  7466. {
  7467. String p;
  7468. for (int i = 0; i < parameters.size(); ++i)
  7469. {
  7470. if (i > 0)
  7471. p << '&';
  7472. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7473. << '='
  7474. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7475. }
  7476. return p;
  7477. }
  7478. int findStartOfDomain (const String& url)
  7479. {
  7480. int i = 0;
  7481. while (CharacterFunctions::isLetterOrDigit (url[i])
  7482. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7483. ++i;
  7484. return url[i] == ':' ? i + 1 : 0;
  7485. }
  7486. }
  7487. const String URL::toString (const bool includeGetParameters) const
  7488. {
  7489. if (includeGetParameters && parameters.size() > 0)
  7490. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7491. else
  7492. return url;
  7493. }
  7494. bool URL::isWellFormed() const
  7495. {
  7496. //xxx TODO
  7497. return url.isNotEmpty();
  7498. }
  7499. const String URL::getDomain() const
  7500. {
  7501. int start = URLHelpers::findStartOfDomain (url);
  7502. while (url[start] == '/')
  7503. ++start;
  7504. const int end1 = url.indexOfChar (start, '/');
  7505. const int end2 = url.indexOfChar (start, ':');
  7506. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7507. : jmin (end1, end2);
  7508. return url.substring (start, end);
  7509. }
  7510. const String URL::getSubPath() const
  7511. {
  7512. int start = URLHelpers::findStartOfDomain (url);
  7513. while (url[start] == '/')
  7514. ++start;
  7515. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7516. return startOfPath <= 0 ? String::empty
  7517. : url.substring (startOfPath);
  7518. }
  7519. const String URL::getScheme() const
  7520. {
  7521. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7522. }
  7523. const URL URL::withNewSubPath (const String& newPath) const
  7524. {
  7525. int start = URLHelpers::findStartOfDomain (url);
  7526. while (url[start] == '/')
  7527. ++start;
  7528. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7529. URL u (*this);
  7530. if (startOfPath > 0)
  7531. u.url = url.substring (0, startOfPath);
  7532. if (! u.url.endsWithChar ('/'))
  7533. u.url << '/';
  7534. if (newPath.startsWithChar ('/'))
  7535. u.url << newPath.substring (1);
  7536. else
  7537. u.url << newPath;
  7538. return u;
  7539. }
  7540. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7541. {
  7542. if (possibleURL.startsWithIgnoreCase ("http:")
  7543. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7544. return true;
  7545. if (possibleURL.startsWithIgnoreCase ("file:")
  7546. || possibleURL.containsChar ('@')
  7547. || possibleURL.endsWithChar ('.')
  7548. || (! possibleURL.containsChar ('.')))
  7549. return false;
  7550. if (possibleURL.startsWithIgnoreCase ("www.")
  7551. && possibleURL.substring (5).containsChar ('.'))
  7552. return true;
  7553. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7554. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7555. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7556. return true;
  7557. return false;
  7558. }
  7559. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7560. {
  7561. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7562. return atSign > 0
  7563. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7564. && (! possibleEmailAddress.endsWithChar ('.'));
  7565. }
  7566. void* juce_openInternetFile (const String& url,
  7567. const String& headers,
  7568. const MemoryBlock& optionalPostData,
  7569. const bool isPost,
  7570. URL::OpenStreamProgressCallback* callback,
  7571. void* callbackContext,
  7572. int timeOutMs);
  7573. void juce_closeInternetFile (void* handle);
  7574. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7575. int juce_seekInInternetFile (void* handle, int newPosition);
  7576. int64 juce_getInternetFileContentLength (void* handle);
  7577. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7578. class WebInputStream : public InputStream
  7579. {
  7580. public:
  7581. WebInputStream (const URL& url,
  7582. const bool isPost_,
  7583. URL::OpenStreamProgressCallback* const progressCallback_,
  7584. void* const progressCallbackContext_,
  7585. const String& extraHeaders,
  7586. const int timeOutMs_,
  7587. StringPairArray* const responseHeaders)
  7588. : position (0),
  7589. finished (false),
  7590. isPost (isPost_),
  7591. progressCallback (progressCallback_),
  7592. progressCallbackContext (progressCallbackContext_),
  7593. timeOutMs (timeOutMs_)
  7594. {
  7595. server = url.toString (! isPost);
  7596. if (isPost_)
  7597. createHeadersAndPostData (url);
  7598. headers += extraHeaders;
  7599. if (! headers.endsWithChar ('\n'))
  7600. headers << "\r\n";
  7601. handle = juce_openInternetFile (server, headers, postData, isPost,
  7602. progressCallback_, progressCallbackContext_,
  7603. timeOutMs);
  7604. if (responseHeaders != 0)
  7605. juce_getInternetFileHeaders (handle, *responseHeaders);
  7606. }
  7607. ~WebInputStream()
  7608. {
  7609. juce_closeInternetFile (handle);
  7610. }
  7611. bool isError() const { return handle == 0; }
  7612. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7613. bool isExhausted() { return finished; }
  7614. int64 getPosition() { return position; }
  7615. int read (void* dest, int bytes)
  7616. {
  7617. if (finished || isError())
  7618. {
  7619. return 0;
  7620. }
  7621. else
  7622. {
  7623. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7624. position += bytesRead;
  7625. if (bytesRead == 0)
  7626. finished = true;
  7627. return bytesRead;
  7628. }
  7629. }
  7630. bool setPosition (int64 wantedPos)
  7631. {
  7632. if (wantedPos != position)
  7633. {
  7634. finished = false;
  7635. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7636. if (actualPos == wantedPos)
  7637. {
  7638. position = wantedPos;
  7639. }
  7640. else
  7641. {
  7642. if (wantedPos < position)
  7643. {
  7644. juce_closeInternetFile (handle);
  7645. position = 0;
  7646. finished = false;
  7647. handle = juce_openInternetFile (server, headers, postData, isPost,
  7648. progressCallback, progressCallbackContext,
  7649. timeOutMs);
  7650. }
  7651. skipNextBytes (wantedPos - position);
  7652. }
  7653. }
  7654. return true;
  7655. }
  7656. juce_UseDebuggingNewOperator
  7657. private:
  7658. String server, headers;
  7659. MemoryBlock postData;
  7660. int64 position;
  7661. bool finished;
  7662. const bool isPost;
  7663. void* handle;
  7664. URL::OpenStreamProgressCallback* const progressCallback;
  7665. void* const progressCallbackContext;
  7666. const int timeOutMs;
  7667. void createHeadersAndPostData (const URL& url)
  7668. {
  7669. MemoryOutputStream data (postData, false);
  7670. if (url.getFilesToUpload().size() > 0)
  7671. {
  7672. // need to upload some files, so do it as multi-part...
  7673. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7674. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7675. data << "--" << boundary;
  7676. int i;
  7677. for (i = 0; i < url.getParameters().size(); ++i)
  7678. {
  7679. data << "\r\nContent-Disposition: form-data; name=\""
  7680. << url.getParameters().getAllKeys() [i]
  7681. << "\"\r\n\r\n"
  7682. << url.getParameters().getAllValues() [i]
  7683. << "\r\n--"
  7684. << boundary;
  7685. }
  7686. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7687. {
  7688. const File file (url.getFilesToUpload().getAllValues() [i]);
  7689. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7690. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7691. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7692. const String mimeType (url.getMimeTypesOfUploadFiles()
  7693. .getValue (paramName, String::empty));
  7694. if (mimeType.isNotEmpty())
  7695. data << "Content-Type: " << mimeType << "\r\n";
  7696. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7697. << file << "\r\n--" << boundary;
  7698. }
  7699. data << "--\r\n";
  7700. data.flush();
  7701. }
  7702. else
  7703. {
  7704. data << URLHelpers::getMangledParameters (url.getParameters())
  7705. << url.getPostData();
  7706. data.flush();
  7707. // just a short text attachment, so use simple url encoding..
  7708. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7709. + String ((unsigned int) postData.getSize())
  7710. + "\r\n";
  7711. }
  7712. }
  7713. WebInputStream (const WebInputStream&);
  7714. WebInputStream& operator= (const WebInputStream&);
  7715. };
  7716. InputStream* URL::createInputStream (const bool usePostCommand,
  7717. OpenStreamProgressCallback* const progressCallback,
  7718. void* const progressCallbackContext,
  7719. const String& extraHeaders,
  7720. const int timeOutMs,
  7721. StringPairArray* const responseHeaders) const
  7722. {
  7723. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7724. progressCallback, progressCallbackContext,
  7725. extraHeaders, timeOutMs, responseHeaders));
  7726. return wi->isError() ? 0 : wi.release();
  7727. }
  7728. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7729. const bool usePostCommand) const
  7730. {
  7731. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7732. if (in != 0)
  7733. {
  7734. in->readIntoMemoryBlock (destData);
  7735. return true;
  7736. }
  7737. return false;
  7738. }
  7739. const String URL::readEntireTextStream (const bool usePostCommand) const
  7740. {
  7741. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7742. if (in != 0)
  7743. return in->readEntireStreamAsString();
  7744. return String::empty;
  7745. }
  7746. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7747. {
  7748. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7749. }
  7750. const URL URL::withParameter (const String& parameterName,
  7751. const String& parameterValue) const
  7752. {
  7753. URL u (*this);
  7754. u.parameters.set (parameterName, parameterValue);
  7755. return u;
  7756. }
  7757. const URL URL::withFileToUpload (const String& parameterName,
  7758. const File& fileToUpload,
  7759. const String& mimeType) const
  7760. {
  7761. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7762. URL u (*this);
  7763. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7764. u.mimeTypes.set (parameterName, mimeType);
  7765. return u;
  7766. }
  7767. const URL URL::withPOSTData (const String& postData_) const
  7768. {
  7769. URL u (*this);
  7770. u.postData = postData_;
  7771. return u;
  7772. }
  7773. const StringPairArray& URL::getParameters() const
  7774. {
  7775. return parameters;
  7776. }
  7777. const StringPairArray& URL::getFilesToUpload() const
  7778. {
  7779. return filesToUpload;
  7780. }
  7781. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7782. {
  7783. return mimeTypes;
  7784. }
  7785. const String URL::removeEscapeChars (const String& s)
  7786. {
  7787. String result (s.replaceCharacter ('+', ' '));
  7788. if (! result.containsChar ('%'))
  7789. return result;
  7790. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7791. // after all the replacements have been made, so that multi-byte chars are handled.
  7792. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7793. for (int i = 0; i < utf8.size(); ++i)
  7794. {
  7795. if (utf8.getUnchecked(i) == '%')
  7796. {
  7797. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7798. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7799. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7800. {
  7801. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7802. utf8.removeRange (i + 1, 2);
  7803. }
  7804. }
  7805. }
  7806. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7807. }
  7808. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7809. {
  7810. const char* const legalChars = isParameter ? "_-.*!'()"
  7811. : ",$_-.*!'()";
  7812. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7813. for (int i = 0; i < utf8.size(); ++i)
  7814. {
  7815. const char c = utf8.getUnchecked(i);
  7816. if (! (CharacterFunctions::isLetterOrDigit (c)
  7817. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7818. {
  7819. if (c == ' ')
  7820. {
  7821. utf8.set (i, '+');
  7822. }
  7823. else
  7824. {
  7825. static const char* const hexDigits = "0123456789abcdef";
  7826. utf8.set (i, '%');
  7827. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7828. utf8.insert (++i, hexDigits [c & 15]);
  7829. }
  7830. }
  7831. }
  7832. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7833. }
  7834. bool URL::launchInDefaultBrowser() const
  7835. {
  7836. String u (toString (true));
  7837. if (u.containsChar ('@') && ! u.containsChar (':'))
  7838. u = "mailto:" + u;
  7839. return PlatformUtilities::openDocument (u, String::empty);
  7840. }
  7841. END_JUCE_NAMESPACE
  7842. /*** End of inlined file: juce_URL.cpp ***/
  7843. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7844. BEGIN_JUCE_NAMESPACE
  7845. MACAddress::MACAddress()
  7846. : asInt64 (0)
  7847. {
  7848. }
  7849. MACAddress::MACAddress (const MACAddress& other)
  7850. : asInt64 (other.asInt64)
  7851. {
  7852. }
  7853. MACAddress& MACAddress::operator= (const MACAddress& other)
  7854. {
  7855. asInt64 = other.asInt64;
  7856. return *this;
  7857. }
  7858. MACAddress::MACAddress (const uint8 bytes[6])
  7859. : asInt64 (0)
  7860. {
  7861. memcpy (asBytes, bytes, sizeof (asBytes));
  7862. }
  7863. const String MACAddress::toString() const
  7864. {
  7865. String s;
  7866. s.preallocateStorage (18);
  7867. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7868. {
  7869. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  7870. if (i < numElementsInArray (asBytes) - 1)
  7871. s << '-';
  7872. }
  7873. return s;
  7874. }
  7875. int64 MACAddress::toInt64() const throw()
  7876. {
  7877. int64 n = 0;
  7878. for (int i = numElementsInArray (asBytes); --i >= 0;)
  7879. n = (n << 8) | asBytes[i];
  7880. return n;
  7881. }
  7882. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  7883. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  7884. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  7885. END_JUCE_NAMESPACE
  7886. /*** End of inlined file: juce_MACAddress.cpp ***/
  7887. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7888. BEGIN_JUCE_NAMESPACE
  7889. namespace
  7890. {
  7891. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7892. {
  7893. // You need to supply a real stream when creating a BufferedInputStream
  7894. jassert (source != 0);
  7895. requestedSize = jmax (256, requestedSize);
  7896. const int64 sourceSize = source->getTotalLength();
  7897. if (sourceSize >= 0 && sourceSize < requestedSize)
  7898. requestedSize = jmax (32, (int) sourceSize);
  7899. return requestedSize;
  7900. }
  7901. }
  7902. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  7903. const bool deleteSourceWhenDestroyed)
  7904. : source (sourceStream),
  7905. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  7906. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  7907. position (sourceStream->getPosition()),
  7908. lastReadPos (0),
  7909. bufferStart (position),
  7910. bufferOverlap (128)
  7911. {
  7912. buffer.malloc (bufferSize);
  7913. }
  7914. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  7915. : source (&sourceStream),
  7916. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  7917. position (sourceStream.getPosition()),
  7918. lastReadPos (0),
  7919. bufferStart (position),
  7920. bufferOverlap (128)
  7921. {
  7922. buffer.malloc (bufferSize);
  7923. }
  7924. BufferedInputStream::~BufferedInputStream()
  7925. {
  7926. }
  7927. int64 BufferedInputStream::getTotalLength()
  7928. {
  7929. return source->getTotalLength();
  7930. }
  7931. int64 BufferedInputStream::getPosition()
  7932. {
  7933. return position;
  7934. }
  7935. bool BufferedInputStream::setPosition (int64 newPosition)
  7936. {
  7937. position = jmax ((int64) 0, newPosition);
  7938. return true;
  7939. }
  7940. bool BufferedInputStream::isExhausted()
  7941. {
  7942. return (position >= lastReadPos)
  7943. && source->isExhausted();
  7944. }
  7945. void BufferedInputStream::ensureBuffered()
  7946. {
  7947. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7948. if (position < bufferStart || position >= bufferEndOverlap)
  7949. {
  7950. int bytesRead;
  7951. if (position < lastReadPos
  7952. && position >= bufferEndOverlap
  7953. && position >= bufferStart)
  7954. {
  7955. const int bytesToKeep = (int) (lastReadPos - position);
  7956. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7957. bufferStart = position;
  7958. bytesRead = source->read (buffer + bytesToKeep,
  7959. bufferSize - bytesToKeep);
  7960. lastReadPos += bytesRead;
  7961. bytesRead += bytesToKeep;
  7962. }
  7963. else
  7964. {
  7965. bufferStart = position;
  7966. source->setPosition (bufferStart);
  7967. bytesRead = source->read (buffer, bufferSize);
  7968. lastReadPos = bufferStart + bytesRead;
  7969. }
  7970. while (bytesRead < bufferSize)
  7971. buffer [bytesRead++] = 0;
  7972. }
  7973. }
  7974. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7975. {
  7976. if (position >= bufferStart
  7977. && position + maxBytesToRead <= lastReadPos)
  7978. {
  7979. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7980. position += maxBytesToRead;
  7981. return maxBytesToRead;
  7982. }
  7983. else
  7984. {
  7985. if (position < bufferStart || position >= lastReadPos)
  7986. ensureBuffered();
  7987. int bytesRead = 0;
  7988. while (maxBytesToRead > 0)
  7989. {
  7990. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7991. if (bytesAvailable > 0)
  7992. {
  7993. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7994. maxBytesToRead -= bytesAvailable;
  7995. bytesRead += bytesAvailable;
  7996. position += bytesAvailable;
  7997. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7998. }
  7999. const int64 oldLastReadPos = lastReadPos;
  8000. ensureBuffered();
  8001. if (oldLastReadPos == lastReadPos)
  8002. break; // if ensureBuffered() failed to read any more data, bail out
  8003. if (isExhausted())
  8004. break;
  8005. }
  8006. return bytesRead;
  8007. }
  8008. }
  8009. const String BufferedInputStream::readString()
  8010. {
  8011. if (position >= bufferStart
  8012. && position < lastReadPos)
  8013. {
  8014. const int maxChars = (int) (lastReadPos - position);
  8015. const char* const src = buffer + (int) (position - bufferStart);
  8016. for (int i = 0; i < maxChars; ++i)
  8017. {
  8018. if (src[i] == 0)
  8019. {
  8020. position += i + 1;
  8021. return String::fromUTF8 (src, i);
  8022. }
  8023. }
  8024. }
  8025. return InputStream::readString();
  8026. }
  8027. END_JUCE_NAMESPACE
  8028. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  8029. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  8030. BEGIN_JUCE_NAMESPACE
  8031. FileInputSource::FileInputSource (const File& file_)
  8032. : file (file_)
  8033. {
  8034. }
  8035. FileInputSource::~FileInputSource()
  8036. {
  8037. }
  8038. InputStream* FileInputSource::createInputStream()
  8039. {
  8040. return file.createInputStream();
  8041. }
  8042. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  8043. {
  8044. return file.getSiblingFile (relatedItemPath).createInputStream();
  8045. }
  8046. int64 FileInputSource::hashCode() const
  8047. {
  8048. return file.hashCode();
  8049. }
  8050. END_JUCE_NAMESPACE
  8051. /*** End of inlined file: juce_FileInputSource.cpp ***/
  8052. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  8053. BEGIN_JUCE_NAMESPACE
  8054. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  8055. const size_t sourceDataSize,
  8056. const bool keepInternalCopy)
  8057. : data (static_cast <const char*> (sourceData)),
  8058. dataSize (sourceDataSize),
  8059. position (0)
  8060. {
  8061. if (keepInternalCopy)
  8062. {
  8063. internalCopy.append (data, sourceDataSize);
  8064. data = static_cast <const char*> (internalCopy.getData());
  8065. }
  8066. }
  8067. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  8068. const bool keepInternalCopy)
  8069. : data (static_cast <const char*> (sourceData.getData())),
  8070. dataSize (sourceData.getSize()),
  8071. position (0)
  8072. {
  8073. if (keepInternalCopy)
  8074. {
  8075. internalCopy = sourceData;
  8076. data = static_cast <const char*> (internalCopy.getData());
  8077. }
  8078. }
  8079. MemoryInputStream::~MemoryInputStream()
  8080. {
  8081. }
  8082. int64 MemoryInputStream::getTotalLength()
  8083. {
  8084. return dataSize;
  8085. }
  8086. int MemoryInputStream::read (void* const buffer, const int howMany)
  8087. {
  8088. jassert (howMany >= 0);
  8089. const int num = jmin (howMany, (int) (dataSize - position));
  8090. memcpy (buffer, data + position, num);
  8091. position += num;
  8092. return (int) num;
  8093. }
  8094. bool MemoryInputStream::isExhausted()
  8095. {
  8096. return (position >= dataSize);
  8097. }
  8098. bool MemoryInputStream::setPosition (const int64 pos)
  8099. {
  8100. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8101. return true;
  8102. }
  8103. int64 MemoryInputStream::getPosition()
  8104. {
  8105. return position;
  8106. }
  8107. #if JUCE_UNIT_TESTS
  8108. class MemoryStreamTests : public UnitTest
  8109. {
  8110. public:
  8111. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8112. void runTest()
  8113. {
  8114. beginTest ("Basics");
  8115. int randomInt = Random::getSystemRandom().nextInt();
  8116. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8117. double randomDouble = Random::getSystemRandom().nextDouble();
  8118. String randomString;
  8119. for (int i = 50; --i >= 0;)
  8120. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8121. MemoryOutputStream mo;
  8122. mo.writeInt (randomInt);
  8123. mo.writeIntBigEndian (randomInt);
  8124. mo.writeCompressedInt (randomInt);
  8125. mo.writeString (randomString);
  8126. mo.writeInt64 (randomInt64);
  8127. mo.writeInt64BigEndian (randomInt64);
  8128. mo.writeDouble (randomDouble);
  8129. mo.writeDoubleBigEndian (randomDouble);
  8130. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8131. expect (mi.readInt() == randomInt);
  8132. expect (mi.readIntBigEndian() == randomInt);
  8133. expect (mi.readCompressedInt() == randomInt);
  8134. expect (mi.readString() == randomString);
  8135. expect (mi.readInt64() == randomInt64);
  8136. expect (mi.readInt64BigEndian() == randomInt64);
  8137. expect (mi.readDouble() == randomDouble);
  8138. expect (mi.readDoubleBigEndian() == randomDouble);
  8139. }
  8140. };
  8141. static MemoryStreamTests memoryInputStreamUnitTests;
  8142. #endif
  8143. END_JUCE_NAMESPACE
  8144. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8145. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8146. BEGIN_JUCE_NAMESPACE
  8147. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8148. : data (internalBlock),
  8149. position (0),
  8150. size (0)
  8151. {
  8152. internalBlock.setSize (initialSize, false);
  8153. }
  8154. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8155. const bool appendToExistingBlockContent)
  8156. : data (memoryBlockToWriteTo),
  8157. position (0),
  8158. size (0)
  8159. {
  8160. if (appendToExistingBlockContent)
  8161. position = size = memoryBlockToWriteTo.getSize();
  8162. }
  8163. MemoryOutputStream::~MemoryOutputStream()
  8164. {
  8165. flush();
  8166. }
  8167. void MemoryOutputStream::flush()
  8168. {
  8169. if (&data != &internalBlock)
  8170. data.setSize (size, false);
  8171. }
  8172. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8173. {
  8174. data.ensureSize (bytesToPreallocate + 1);
  8175. }
  8176. void MemoryOutputStream::reset() throw()
  8177. {
  8178. position = 0;
  8179. size = 0;
  8180. }
  8181. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8182. {
  8183. if (howMany > 0)
  8184. {
  8185. const size_t storageNeeded = position + howMany;
  8186. if (storageNeeded >= data.getSize())
  8187. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  8188. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8189. position += howMany;
  8190. size = jmax (size, position);
  8191. }
  8192. return true;
  8193. }
  8194. const void* MemoryOutputStream::getData() const throw()
  8195. {
  8196. void* const d = data.getData();
  8197. if (data.getSize() > size)
  8198. static_cast <char*> (d) [size] = 0;
  8199. return d;
  8200. }
  8201. bool MemoryOutputStream::setPosition (int64 newPosition)
  8202. {
  8203. if (newPosition <= (int64) size)
  8204. {
  8205. // ok to seek backwards
  8206. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8207. return true;
  8208. }
  8209. else
  8210. {
  8211. // trying to make it bigger isn't a good thing to do..
  8212. return false;
  8213. }
  8214. }
  8215. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8216. {
  8217. // before writing from an input, see if we can preallocate to make it more efficient..
  8218. int64 availableData = source.getTotalLength() - source.getPosition();
  8219. if (availableData > 0)
  8220. {
  8221. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8222. availableData = maxNumBytesToWrite;
  8223. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8224. }
  8225. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8226. }
  8227. const String MemoryOutputStream::toUTF8() const
  8228. {
  8229. return String (static_cast <const char*> (getData()), getDataSize());
  8230. }
  8231. const String MemoryOutputStream::toString() const
  8232. {
  8233. return String::createStringFromData (getData(), getDataSize());
  8234. }
  8235. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8236. {
  8237. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8238. return stream;
  8239. }
  8240. END_JUCE_NAMESPACE
  8241. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8242. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8243. BEGIN_JUCE_NAMESPACE
  8244. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8245. const int64 startPositionInSourceStream_,
  8246. const int64 lengthOfSourceStream_,
  8247. const bool deleteSourceWhenDestroyed)
  8248. : source (sourceStream),
  8249. startPositionInSourceStream (startPositionInSourceStream_),
  8250. lengthOfSourceStream (lengthOfSourceStream_)
  8251. {
  8252. if (deleteSourceWhenDestroyed)
  8253. sourceToDelete = source;
  8254. setPosition (0);
  8255. }
  8256. SubregionStream::~SubregionStream()
  8257. {
  8258. }
  8259. int64 SubregionStream::getTotalLength()
  8260. {
  8261. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8262. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8263. : srcLen;
  8264. }
  8265. int64 SubregionStream::getPosition()
  8266. {
  8267. return source->getPosition() - startPositionInSourceStream;
  8268. }
  8269. bool SubregionStream::setPosition (int64 newPosition)
  8270. {
  8271. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8272. }
  8273. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8274. {
  8275. if (lengthOfSourceStream < 0)
  8276. {
  8277. return source->read (destBuffer, maxBytesToRead);
  8278. }
  8279. else
  8280. {
  8281. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8282. if (maxBytesToRead <= 0)
  8283. return 0;
  8284. return source->read (destBuffer, maxBytesToRead);
  8285. }
  8286. }
  8287. bool SubregionStream::isExhausted()
  8288. {
  8289. if (lengthOfSourceStream >= 0)
  8290. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8291. else
  8292. return source->isExhausted();
  8293. }
  8294. END_JUCE_NAMESPACE
  8295. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8296. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8297. BEGIN_JUCE_NAMESPACE
  8298. PerformanceCounter::PerformanceCounter (const String& name_,
  8299. int runsPerPrintout,
  8300. const File& loggingFile)
  8301. : name (name_),
  8302. numRuns (0),
  8303. runsPerPrint (runsPerPrintout),
  8304. totalTime (0),
  8305. outputFile (loggingFile)
  8306. {
  8307. if (outputFile != File::nonexistent)
  8308. {
  8309. String s ("**** Counter for \"");
  8310. s << name_ << "\" started at: "
  8311. << Time::getCurrentTime().toString (true, true)
  8312. << "\r\n";
  8313. outputFile.appendText (s, false, false);
  8314. }
  8315. }
  8316. PerformanceCounter::~PerformanceCounter()
  8317. {
  8318. printStatistics();
  8319. }
  8320. void PerformanceCounter::start()
  8321. {
  8322. started = Time::getHighResolutionTicks();
  8323. }
  8324. void PerformanceCounter::stop()
  8325. {
  8326. const int64 now = Time::getHighResolutionTicks();
  8327. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8328. if (++numRuns == runsPerPrint)
  8329. printStatistics();
  8330. }
  8331. void PerformanceCounter::printStatistics()
  8332. {
  8333. if (numRuns > 0)
  8334. {
  8335. String s ("Performance count for \"");
  8336. s << name << "\" - average over " << numRuns << " run(s) = ";
  8337. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8338. if (micros > 10000)
  8339. s << (micros/1000) << " millisecs";
  8340. else
  8341. s << micros << " microsecs";
  8342. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8343. Logger::outputDebugString (s);
  8344. s << "\r\n";
  8345. if (outputFile != File::nonexistent)
  8346. outputFile.appendText (s, false, false);
  8347. numRuns = 0;
  8348. totalTime = 0;
  8349. }
  8350. }
  8351. END_JUCE_NAMESPACE
  8352. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8353. /*** Start of inlined file: juce_Uuid.cpp ***/
  8354. BEGIN_JUCE_NAMESPACE
  8355. Uuid::Uuid()
  8356. {
  8357. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8358. // to make it very very unlikely that two UUIDs will ever be the same..
  8359. static int64 macAddresses[2];
  8360. static bool hasCheckedMacAddresses = false;
  8361. if (! hasCheckedMacAddresses)
  8362. {
  8363. hasCheckedMacAddresses = true;
  8364. Array<MACAddress> result;
  8365. MACAddress::findAllAddresses (result);
  8366. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8367. macAddresses[i] = result[i].toInt64();
  8368. }
  8369. value.asInt64[0] = macAddresses[0];
  8370. value.asInt64[1] = macAddresses[1];
  8371. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8372. // whose seed will carry over between calls to this method.
  8373. Random r (macAddresses[0] ^ macAddresses[1]
  8374. ^ Random::getSystemRandom().nextInt64());
  8375. for (int i = 4; --i >= 0;)
  8376. {
  8377. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8378. value.asInt[i] ^= r.nextInt();
  8379. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8380. }
  8381. }
  8382. Uuid::~Uuid() throw()
  8383. {
  8384. }
  8385. Uuid::Uuid (const Uuid& other)
  8386. : value (other.value)
  8387. {
  8388. }
  8389. Uuid& Uuid::operator= (const Uuid& other)
  8390. {
  8391. value = other.value;
  8392. return *this;
  8393. }
  8394. bool Uuid::operator== (const Uuid& other) const
  8395. {
  8396. return value.asInt64[0] == other.value.asInt64[0]
  8397. && value.asInt64[1] == other.value.asInt64[1];
  8398. }
  8399. bool Uuid::operator!= (const Uuid& other) const
  8400. {
  8401. return ! operator== (other);
  8402. }
  8403. bool Uuid::isNull() const throw()
  8404. {
  8405. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8406. }
  8407. const String Uuid::toString() const
  8408. {
  8409. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8410. }
  8411. Uuid::Uuid (const String& uuidString)
  8412. {
  8413. operator= (uuidString);
  8414. }
  8415. Uuid& Uuid::operator= (const String& uuidString)
  8416. {
  8417. MemoryBlock mb;
  8418. mb.loadFromHexString (uuidString);
  8419. mb.ensureSize (sizeof (value.asBytes), true);
  8420. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8421. return *this;
  8422. }
  8423. Uuid::Uuid (const uint8* const rawData)
  8424. {
  8425. operator= (rawData);
  8426. }
  8427. Uuid& Uuid::operator= (const uint8* const rawData)
  8428. {
  8429. if (rawData != 0)
  8430. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8431. else
  8432. zeromem (value.asBytes, sizeof (value.asBytes));
  8433. return *this;
  8434. }
  8435. END_JUCE_NAMESPACE
  8436. /*** End of inlined file: juce_Uuid.cpp ***/
  8437. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8438. BEGIN_JUCE_NAMESPACE
  8439. class ZipFile::ZipEntryInfo
  8440. {
  8441. public:
  8442. ZipFile::ZipEntry entry;
  8443. int streamOffset;
  8444. int compressedSize;
  8445. bool compressed;
  8446. };
  8447. class ZipFile::ZipInputStream : public InputStream
  8448. {
  8449. public:
  8450. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8451. : file (file_),
  8452. zipEntryInfo (zei),
  8453. pos (0),
  8454. headerSize (0),
  8455. inputStream (0)
  8456. {
  8457. inputStream = file_.inputStream;
  8458. if (file_.inputSource != 0)
  8459. {
  8460. inputStream = streamToDelete = file.inputSource->createInputStream();
  8461. }
  8462. else
  8463. {
  8464. #if JUCE_DEBUG
  8465. file_.numOpenStreams++;
  8466. #endif
  8467. }
  8468. char buffer [30];
  8469. if (inputStream != 0
  8470. && inputStream->setPosition (zei.streamOffset)
  8471. && inputStream->read (buffer, 30) == 30
  8472. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8473. {
  8474. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8475. + ByteOrder::littleEndianShort (buffer + 28);
  8476. }
  8477. }
  8478. ~ZipInputStream()
  8479. {
  8480. #if JUCE_DEBUG
  8481. if (inputStream != 0 && inputStream == file.inputStream)
  8482. file.numOpenStreams--;
  8483. #endif
  8484. }
  8485. int64 getTotalLength()
  8486. {
  8487. return zipEntryInfo.compressedSize;
  8488. }
  8489. int read (void* buffer, int howMany)
  8490. {
  8491. if (headerSize <= 0)
  8492. return 0;
  8493. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8494. if (inputStream == 0)
  8495. return 0;
  8496. int num;
  8497. if (inputStream == file.inputStream)
  8498. {
  8499. const ScopedLock sl (file.lock);
  8500. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8501. num = inputStream->read (buffer, howMany);
  8502. }
  8503. else
  8504. {
  8505. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8506. num = inputStream->read (buffer, howMany);
  8507. }
  8508. pos += num;
  8509. return num;
  8510. }
  8511. bool isExhausted()
  8512. {
  8513. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8514. }
  8515. int64 getPosition()
  8516. {
  8517. return pos;
  8518. }
  8519. bool setPosition (int64 newPos)
  8520. {
  8521. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8522. return true;
  8523. }
  8524. private:
  8525. ZipFile& file;
  8526. ZipEntryInfo zipEntryInfo;
  8527. int64 pos;
  8528. int headerSize;
  8529. InputStream* inputStream;
  8530. ScopedPointer<InputStream> streamToDelete;
  8531. ZipInputStream (const ZipInputStream&);
  8532. ZipInputStream& operator= (const ZipInputStream&);
  8533. };
  8534. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8535. : inputStream (source_)
  8536. #if JUCE_DEBUG
  8537. , numOpenStreams (0)
  8538. #endif
  8539. {
  8540. if (deleteStreamWhenDestroyed)
  8541. streamToDelete = inputStream;
  8542. init();
  8543. }
  8544. ZipFile::ZipFile (const File& file)
  8545. : inputStream (0)
  8546. #if JUCE_DEBUG
  8547. , numOpenStreams (0)
  8548. #endif
  8549. {
  8550. inputSource = new FileInputSource (file);
  8551. init();
  8552. }
  8553. ZipFile::ZipFile (InputSource* const inputSource_)
  8554. : inputStream (0),
  8555. inputSource (inputSource_)
  8556. #if JUCE_DEBUG
  8557. , numOpenStreams (0)
  8558. #endif
  8559. {
  8560. init();
  8561. }
  8562. ZipFile::~ZipFile()
  8563. {
  8564. #if JUCE_DEBUG
  8565. entries.clear();
  8566. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8567. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8568. Streams can't be kept open after the file is deleted because they need to share the input
  8569. stream that the file uses to read itself.
  8570. */
  8571. jassert (numOpenStreams == 0);
  8572. #endif
  8573. }
  8574. int ZipFile::getNumEntries() const throw()
  8575. {
  8576. return entries.size();
  8577. }
  8578. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8579. {
  8580. ZipEntryInfo* const zei = entries [index];
  8581. return zei != 0 ? &(zei->entry) : 0;
  8582. }
  8583. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8584. {
  8585. for (int i = 0; i < entries.size(); ++i)
  8586. if (entries.getUnchecked (i)->entry.filename == fileName)
  8587. return i;
  8588. return -1;
  8589. }
  8590. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8591. {
  8592. return getEntry (getIndexOfFileName (fileName));
  8593. }
  8594. InputStream* ZipFile::createStreamForEntry (const int index)
  8595. {
  8596. ZipEntryInfo* const zei = entries[index];
  8597. InputStream* stream = 0;
  8598. if (zei != 0)
  8599. {
  8600. stream = new ZipInputStream (*this, *zei);
  8601. if (zei->compressed)
  8602. {
  8603. stream = new GZIPDecompressorInputStream (stream, true, true,
  8604. zei->entry.uncompressedSize);
  8605. // (much faster to unzip in big blocks using a buffer..)
  8606. stream = new BufferedInputStream (stream, 32768, true);
  8607. }
  8608. }
  8609. return stream;
  8610. }
  8611. class ZipFile::ZipFilenameComparator
  8612. {
  8613. public:
  8614. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8615. {
  8616. return first->entry.filename.compare (second->entry.filename);
  8617. }
  8618. };
  8619. void ZipFile::sortEntriesByFilename()
  8620. {
  8621. ZipFilenameComparator sorter;
  8622. entries.sort (sorter);
  8623. }
  8624. void ZipFile::init()
  8625. {
  8626. ScopedPointer <InputStream> toDelete;
  8627. InputStream* in = inputStream;
  8628. if (inputSource != 0)
  8629. {
  8630. in = inputSource->createInputStream();
  8631. toDelete = in;
  8632. }
  8633. if (in != 0)
  8634. {
  8635. int numEntries = 0;
  8636. int pos = findEndOfZipEntryTable (*in, numEntries);
  8637. if (pos >= 0 && pos < in->getTotalLength())
  8638. {
  8639. const int size = (int) (in->getTotalLength() - pos);
  8640. in->setPosition (pos);
  8641. MemoryBlock headerData;
  8642. if (in->readIntoMemoryBlock (headerData, size) == size)
  8643. {
  8644. pos = 0;
  8645. for (int i = 0; i < numEntries; ++i)
  8646. {
  8647. if (pos + 46 > size)
  8648. break;
  8649. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8650. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8651. if (pos + 46 + fileNameLen > size)
  8652. break;
  8653. ZipEntryInfo* const zei = new ZipEntryInfo();
  8654. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8655. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8656. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8657. const int year = 1980 + (date >> 9);
  8658. const int month = ((date >> 5) & 15) - 1;
  8659. const int day = date & 31;
  8660. const int hours = time >> 11;
  8661. const int minutes = (time >> 5) & 63;
  8662. const int seconds = (time & 31) << 1;
  8663. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8664. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8665. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8666. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8667. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8668. entries.add (zei);
  8669. pos += 46 + fileNameLen
  8670. + ByteOrder::littleEndianShort (buffer + 30)
  8671. + ByteOrder::littleEndianShort (buffer + 32);
  8672. }
  8673. }
  8674. }
  8675. }
  8676. }
  8677. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8678. {
  8679. BufferedInputStream in (input, 8192);
  8680. in.setPosition (in.getTotalLength());
  8681. int64 pos = in.getPosition();
  8682. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8683. char buffer [32];
  8684. zeromem (buffer, sizeof (buffer));
  8685. while (pos > lowestPos)
  8686. {
  8687. in.setPosition (pos - 22);
  8688. pos = in.getPosition();
  8689. memcpy (buffer + 22, buffer, 4);
  8690. if (in.read (buffer, 22) != 22)
  8691. return 0;
  8692. for (int i = 0; i < 22; ++i)
  8693. {
  8694. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8695. {
  8696. in.setPosition (pos + i);
  8697. in.read (buffer, 22);
  8698. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8699. return ByteOrder::littleEndianInt (buffer + 16);
  8700. }
  8701. }
  8702. }
  8703. return 0;
  8704. }
  8705. bool ZipFile::uncompressTo (const File& targetDirectory,
  8706. const bool shouldOverwriteFiles)
  8707. {
  8708. for (int i = 0; i < entries.size(); ++i)
  8709. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8710. return false;
  8711. return true;
  8712. }
  8713. bool ZipFile::uncompressEntry (const int index,
  8714. const File& targetDirectory,
  8715. bool shouldOverwriteFiles)
  8716. {
  8717. const ZipEntryInfo* zei = entries [index];
  8718. if (zei != 0)
  8719. {
  8720. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8721. if (zei->entry.filename.endsWithChar ('/'))
  8722. {
  8723. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8724. }
  8725. else
  8726. {
  8727. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8728. if (in != 0)
  8729. {
  8730. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8731. return false;
  8732. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8733. {
  8734. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8735. if (out != 0)
  8736. {
  8737. out->writeFromInputStream (*in, -1);
  8738. out = 0;
  8739. targetFile.setCreationTime (zei->entry.fileTime);
  8740. targetFile.setLastModificationTime (zei->entry.fileTime);
  8741. targetFile.setLastAccessTime (zei->entry.fileTime);
  8742. return true;
  8743. }
  8744. }
  8745. }
  8746. }
  8747. }
  8748. return false;
  8749. }
  8750. END_JUCE_NAMESPACE
  8751. /*** End of inlined file: juce_ZipFile.cpp ***/
  8752. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8753. #if JUCE_MSVC
  8754. #pragma warning (push)
  8755. #pragma warning (disable: 4514 4996)
  8756. #endif
  8757. #include <cwctype>
  8758. #include <cctype>
  8759. #include <ctime>
  8760. BEGIN_JUCE_NAMESPACE
  8761. int CharacterFunctions::length (const char* const s) throw()
  8762. {
  8763. return (int) strlen (s);
  8764. }
  8765. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8766. {
  8767. return (int) wcslen (s);
  8768. }
  8769. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8770. {
  8771. strncpy (dest, src, maxChars);
  8772. }
  8773. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8774. {
  8775. wcsncpy (dest, src, maxChars);
  8776. }
  8777. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8778. {
  8779. mbstowcs (dest, src, maxChars);
  8780. }
  8781. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8782. {
  8783. wcstombs (dest, src, maxChars);
  8784. }
  8785. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8786. {
  8787. return (int) wcstombs (0, src, 0);
  8788. }
  8789. void CharacterFunctions::append (char* dest, const char* src) throw()
  8790. {
  8791. strcat (dest, src);
  8792. }
  8793. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8794. {
  8795. wcscat (dest, src);
  8796. }
  8797. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8798. {
  8799. return strcmp (s1, s2);
  8800. }
  8801. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8802. {
  8803. jassert (s1 != 0 && s2 != 0);
  8804. return wcscmp (s1, s2);
  8805. }
  8806. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8807. {
  8808. jassert (s1 != 0 && s2 != 0);
  8809. return strncmp (s1, s2, maxChars);
  8810. }
  8811. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8812. {
  8813. jassert (s1 != 0 && s2 != 0);
  8814. return wcsncmp (s1, s2, maxChars);
  8815. }
  8816. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8817. {
  8818. jassert (s1 != 0 && s2 != 0);
  8819. for (;;)
  8820. {
  8821. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8822. if (diff != 0)
  8823. return diff;
  8824. else if (*s1 == 0)
  8825. break;
  8826. ++s1;
  8827. ++s2;
  8828. }
  8829. return 0;
  8830. }
  8831. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8832. {
  8833. return -compare (s2, s1);
  8834. }
  8835. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8836. {
  8837. jassert (s1 != 0 && s2 != 0);
  8838. #if JUCE_WINDOWS
  8839. return stricmp (s1, s2);
  8840. #else
  8841. return strcasecmp (s1, s2);
  8842. #endif
  8843. }
  8844. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8845. {
  8846. jassert (s1 != 0 && s2 != 0);
  8847. #if JUCE_WINDOWS
  8848. return _wcsicmp (s1, s2);
  8849. #else
  8850. for (;;)
  8851. {
  8852. if (*s1 != *s2)
  8853. {
  8854. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8855. if (diff != 0)
  8856. return diff < 0 ? -1 : 1;
  8857. }
  8858. else if (*s1 == 0)
  8859. break;
  8860. ++s1;
  8861. ++s2;
  8862. }
  8863. return 0;
  8864. #endif
  8865. }
  8866. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8867. {
  8868. jassert (s1 != 0 && s2 != 0);
  8869. for (;;)
  8870. {
  8871. if (*s1 != *s2)
  8872. {
  8873. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8874. if (diff != 0)
  8875. return diff < 0 ? -1 : 1;
  8876. }
  8877. else if (*s1 == 0)
  8878. break;
  8879. ++s1;
  8880. ++s2;
  8881. }
  8882. return 0;
  8883. }
  8884. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8885. {
  8886. jassert (s1 != 0 && s2 != 0);
  8887. #if JUCE_WINDOWS
  8888. return strnicmp (s1, s2, maxChars);
  8889. #else
  8890. return strncasecmp (s1, s2, maxChars);
  8891. #endif
  8892. }
  8893. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8894. {
  8895. jassert (s1 != 0 && s2 != 0);
  8896. #if JUCE_WINDOWS
  8897. return _wcsnicmp (s1, s2, maxChars);
  8898. #else
  8899. while (--maxChars >= 0)
  8900. {
  8901. if (*s1 != *s2)
  8902. {
  8903. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8904. if (diff != 0)
  8905. return diff < 0 ? -1 : 1;
  8906. }
  8907. else if (*s1 == 0)
  8908. break;
  8909. ++s1;
  8910. ++s2;
  8911. }
  8912. return 0;
  8913. #endif
  8914. }
  8915. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8916. {
  8917. return strstr (haystack, needle);
  8918. }
  8919. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8920. {
  8921. return wcsstr (haystack, needle);
  8922. }
  8923. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8924. {
  8925. if (haystack != 0)
  8926. {
  8927. int i = 0;
  8928. if (ignoreCase)
  8929. {
  8930. const char n1 = toLowerCase (needle);
  8931. const char n2 = toUpperCase (needle);
  8932. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8933. {
  8934. while (haystack[i] != 0)
  8935. {
  8936. if (haystack[i] == n1 || haystack[i] == n2)
  8937. return i;
  8938. ++i;
  8939. }
  8940. return -1;
  8941. }
  8942. jassert (n1 == needle);
  8943. }
  8944. while (haystack[i] != 0)
  8945. {
  8946. if (haystack[i] == needle)
  8947. return i;
  8948. ++i;
  8949. }
  8950. }
  8951. return -1;
  8952. }
  8953. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8954. {
  8955. if (haystack != 0)
  8956. {
  8957. int i = 0;
  8958. if (ignoreCase)
  8959. {
  8960. const juce_wchar n1 = toLowerCase (needle);
  8961. const juce_wchar n2 = toUpperCase (needle);
  8962. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8963. {
  8964. while (haystack[i] != 0)
  8965. {
  8966. if (haystack[i] == n1 || haystack[i] == n2)
  8967. return i;
  8968. ++i;
  8969. }
  8970. return -1;
  8971. }
  8972. jassert (n1 == needle);
  8973. }
  8974. while (haystack[i] != 0)
  8975. {
  8976. if (haystack[i] == needle)
  8977. return i;
  8978. ++i;
  8979. }
  8980. }
  8981. return -1;
  8982. }
  8983. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8984. {
  8985. jassert (haystack != 0);
  8986. int i = 0;
  8987. while (haystack[i] != 0)
  8988. {
  8989. if (haystack[i] == needle)
  8990. return i;
  8991. ++i;
  8992. }
  8993. return -1;
  8994. }
  8995. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8996. {
  8997. jassert (haystack != 0);
  8998. int i = 0;
  8999. while (haystack[i] != 0)
  9000. {
  9001. if (haystack[i] == needle)
  9002. return i;
  9003. ++i;
  9004. }
  9005. return -1;
  9006. }
  9007. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  9008. {
  9009. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  9010. }
  9011. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  9012. {
  9013. if (allowedChars == 0)
  9014. return 0;
  9015. int i = 0;
  9016. for (;;)
  9017. {
  9018. if (indexOfCharFast (allowedChars, text[i]) < 0)
  9019. break;
  9020. ++i;
  9021. }
  9022. return i;
  9023. }
  9024. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  9025. {
  9026. return (int) strftime (dest, maxChars, format, tm);
  9027. }
  9028. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  9029. {
  9030. return (int) wcsftime (dest, maxChars, format, tm);
  9031. }
  9032. int CharacterFunctions::getIntValue (const char* const s) throw()
  9033. {
  9034. return atoi (s);
  9035. }
  9036. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  9037. {
  9038. #if JUCE_WINDOWS
  9039. return _wtoi (s);
  9040. #else
  9041. int v = 0;
  9042. while (isWhitespace (*s))
  9043. ++s;
  9044. const bool isNeg = *s == '-';
  9045. if (isNeg)
  9046. ++s;
  9047. for (;;)
  9048. {
  9049. const wchar_t c = *s++;
  9050. if (c >= '0' && c <= '9')
  9051. v = v * 10 + (int) (c - '0');
  9052. else
  9053. break;
  9054. }
  9055. return isNeg ? -v : v;
  9056. #endif
  9057. }
  9058. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  9059. {
  9060. #if JUCE_LINUX
  9061. return atoll (s);
  9062. #elif JUCE_WINDOWS
  9063. return _atoi64 (s);
  9064. #else
  9065. int64 v = 0;
  9066. while (isWhitespace (*s))
  9067. ++s;
  9068. const bool isNeg = *s == '-';
  9069. if (isNeg)
  9070. ++s;
  9071. for (;;)
  9072. {
  9073. const char c = *s++;
  9074. if (c >= '0' && c <= '9')
  9075. v = v * 10 + (int64) (c - '0');
  9076. else
  9077. break;
  9078. }
  9079. return isNeg ? -v : v;
  9080. #endif
  9081. }
  9082. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  9083. {
  9084. #if JUCE_WINDOWS
  9085. return _wtoi64 (s);
  9086. #else
  9087. int64 v = 0;
  9088. while (isWhitespace (*s))
  9089. ++s;
  9090. const bool isNeg = *s == '-';
  9091. if (isNeg)
  9092. ++s;
  9093. for (;;)
  9094. {
  9095. const juce_wchar c = *s++;
  9096. if (c >= '0' && c <= '9')
  9097. v = v * 10 + (int64) (c - '0');
  9098. else
  9099. break;
  9100. }
  9101. return isNeg ? -v : v;
  9102. #endif
  9103. }
  9104. namespace
  9105. {
  9106. double juce_mulexp10 (const double value, int exponent) throw()
  9107. {
  9108. if (exponent == 0)
  9109. return value;
  9110. if (value == 0)
  9111. return 0;
  9112. const bool negative = (exponent < 0);
  9113. if (negative)
  9114. exponent = -exponent;
  9115. double result = 1.0, power = 10.0;
  9116. for (int bit = 1; exponent != 0; bit <<= 1)
  9117. {
  9118. if ((exponent & bit) != 0)
  9119. {
  9120. exponent ^= bit;
  9121. result *= power;
  9122. if (exponent == 0)
  9123. break;
  9124. }
  9125. power *= power;
  9126. }
  9127. return negative ? (value / result) : (value * result);
  9128. }
  9129. template <class CharType>
  9130. double juce_atof (const CharType* const original) throw()
  9131. {
  9132. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9133. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9134. int exponent = 0, decPointIndex = 0, digit = 0;
  9135. int lastDigit = 0, numSignificantDigits = 0;
  9136. bool isNegative = false, digitsFound = false;
  9137. const int maxSignificantDigits = 15 + 2;
  9138. const CharType* s = original;
  9139. while (CharacterFunctions::isWhitespace (*s))
  9140. ++s;
  9141. switch (*s)
  9142. {
  9143. case '-': isNegative = true; // fall-through..
  9144. case '+': ++s;
  9145. }
  9146. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9147. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9148. for (;;)
  9149. {
  9150. if (CharacterFunctions::isDigit (*s))
  9151. {
  9152. lastDigit = digit;
  9153. digit = *s++ - '0';
  9154. digitsFound = true;
  9155. if (decPointIndex != 0)
  9156. exponentAdjustment[1]++;
  9157. if (numSignificantDigits == 0 && digit == 0)
  9158. continue;
  9159. if (++numSignificantDigits > maxSignificantDigits)
  9160. {
  9161. if (digit > 5)
  9162. ++accumulator [decPointIndex];
  9163. else if (digit == 5 && (lastDigit & 1) != 0)
  9164. ++accumulator [decPointIndex];
  9165. if (decPointIndex > 0)
  9166. exponentAdjustment[1]--;
  9167. else
  9168. exponentAdjustment[0]++;
  9169. while (CharacterFunctions::isDigit (*s))
  9170. {
  9171. ++s;
  9172. if (decPointIndex == 0)
  9173. exponentAdjustment[0]++;
  9174. }
  9175. }
  9176. else
  9177. {
  9178. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9179. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9180. {
  9181. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9182. + accumulator [decPointIndex];
  9183. accumulator [decPointIndex] = 0;
  9184. exponentAccumulator [decPointIndex] = 0;
  9185. }
  9186. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9187. exponentAccumulator [decPointIndex]++;
  9188. }
  9189. }
  9190. else if (decPointIndex == 0 && *s == '.')
  9191. {
  9192. ++s;
  9193. decPointIndex = 1;
  9194. if (numSignificantDigits > maxSignificantDigits)
  9195. {
  9196. while (CharacterFunctions::isDigit (*s))
  9197. ++s;
  9198. break;
  9199. }
  9200. }
  9201. else
  9202. {
  9203. break;
  9204. }
  9205. }
  9206. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9207. if (decPointIndex != 0)
  9208. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9209. if ((*s == 'e' || *s == 'E') && digitsFound)
  9210. {
  9211. bool negativeExponent = false;
  9212. switch (*++s)
  9213. {
  9214. case '-': negativeExponent = true; // fall-through..
  9215. case '+': ++s;
  9216. }
  9217. while (CharacterFunctions::isDigit (*s))
  9218. exponent = (exponent * 10) + (*s++ - '0');
  9219. if (negativeExponent)
  9220. exponent = -exponent;
  9221. }
  9222. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9223. if (decPointIndex != 0)
  9224. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9225. return isNegative ? -r : r;
  9226. }
  9227. }
  9228. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9229. {
  9230. return juce_atof <char> (s);
  9231. }
  9232. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9233. {
  9234. return juce_atof <juce_wchar> (s);
  9235. }
  9236. char CharacterFunctions::toUpperCase (const char character) throw()
  9237. {
  9238. return (char) toupper (character);
  9239. }
  9240. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9241. {
  9242. return towupper (character);
  9243. }
  9244. void CharacterFunctions::toUpperCase (char* s) throw()
  9245. {
  9246. #if JUCE_WINDOWS
  9247. strupr (s);
  9248. #else
  9249. while (*s != 0)
  9250. {
  9251. *s = toUpperCase (*s);
  9252. ++s;
  9253. }
  9254. #endif
  9255. }
  9256. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9257. {
  9258. #if JUCE_WINDOWS
  9259. _wcsupr (s);
  9260. #else
  9261. while (*s != 0)
  9262. {
  9263. *s = toUpperCase (*s);
  9264. ++s;
  9265. }
  9266. #endif
  9267. }
  9268. bool CharacterFunctions::isUpperCase (const char character) throw()
  9269. {
  9270. return isupper (character) != 0;
  9271. }
  9272. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9273. {
  9274. #if JUCE_WINDOWS
  9275. return iswupper (character) != 0;
  9276. #else
  9277. return toLowerCase (character) != character;
  9278. #endif
  9279. }
  9280. char CharacterFunctions::toLowerCase (const char character) throw()
  9281. {
  9282. return (char) tolower (character);
  9283. }
  9284. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9285. {
  9286. return towlower (character);
  9287. }
  9288. void CharacterFunctions::toLowerCase (char* s) throw()
  9289. {
  9290. #if JUCE_WINDOWS
  9291. strlwr (s);
  9292. #else
  9293. while (*s != 0)
  9294. {
  9295. *s = toLowerCase (*s);
  9296. ++s;
  9297. }
  9298. #endif
  9299. }
  9300. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9301. {
  9302. #if JUCE_WINDOWS
  9303. _wcslwr (s);
  9304. #else
  9305. while (*s != 0)
  9306. {
  9307. *s = toLowerCase (*s);
  9308. ++s;
  9309. }
  9310. #endif
  9311. }
  9312. bool CharacterFunctions::isLowerCase (const char character) throw()
  9313. {
  9314. return islower (character) != 0;
  9315. }
  9316. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9317. {
  9318. #if JUCE_WINDOWS
  9319. return iswlower (character) != 0;
  9320. #else
  9321. return toUpperCase (character) != character;
  9322. #endif
  9323. }
  9324. bool CharacterFunctions::isWhitespace (const char character) throw()
  9325. {
  9326. return character == ' ' || (character <= 13 && character >= 9);
  9327. }
  9328. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9329. {
  9330. return iswspace (character) != 0;
  9331. }
  9332. bool CharacterFunctions::isDigit (const char character) throw()
  9333. {
  9334. return (character >= '0' && character <= '9');
  9335. }
  9336. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9337. {
  9338. return iswdigit (character) != 0;
  9339. }
  9340. bool CharacterFunctions::isLetter (const char character) throw()
  9341. {
  9342. return (character >= 'a' && character <= 'z')
  9343. || (character >= 'A' && character <= 'Z');
  9344. }
  9345. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9346. {
  9347. return iswalpha (character) != 0;
  9348. }
  9349. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9350. {
  9351. return (character >= 'a' && character <= 'z')
  9352. || (character >= 'A' && character <= 'Z')
  9353. || (character >= '0' && character <= '9');
  9354. }
  9355. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9356. {
  9357. return iswalnum (character) != 0;
  9358. }
  9359. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9360. {
  9361. unsigned int d = digit - '0';
  9362. if (d < (unsigned int) 10)
  9363. return (int) d;
  9364. d += (unsigned int) ('0' - 'a');
  9365. if (d < (unsigned int) 6)
  9366. return (int) d + 10;
  9367. d += (unsigned int) ('a' - 'A');
  9368. if (d < (unsigned int) 6)
  9369. return (int) d + 10;
  9370. return -1;
  9371. }
  9372. #if JUCE_MSVC
  9373. #pragma warning (pop)
  9374. #endif
  9375. END_JUCE_NAMESPACE
  9376. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9377. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9378. BEGIN_JUCE_NAMESPACE
  9379. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9380. {
  9381. loadFromText (fileContents);
  9382. }
  9383. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9384. {
  9385. loadFromText (fileToLoad.loadFileAsString());
  9386. }
  9387. LocalisedStrings::~LocalisedStrings()
  9388. {
  9389. }
  9390. const String LocalisedStrings::translate (const String& text) const
  9391. {
  9392. return translations.getValue (text, text);
  9393. }
  9394. namespace
  9395. {
  9396. CriticalSection currentMappingsLock;
  9397. LocalisedStrings* currentMappings = 0;
  9398. int findCloseQuote (const String& text, int startPos)
  9399. {
  9400. juce_wchar lastChar = 0;
  9401. for (;;)
  9402. {
  9403. const juce_wchar c = text [startPos];
  9404. if (c == 0 || (c == '"' && lastChar != '\\'))
  9405. break;
  9406. lastChar = c;
  9407. ++startPos;
  9408. }
  9409. return startPos;
  9410. }
  9411. const String unescapeString (const String& s)
  9412. {
  9413. return s.replace ("\\\"", "\"")
  9414. .replace ("\\\'", "\'")
  9415. .replace ("\\t", "\t")
  9416. .replace ("\\r", "\r")
  9417. .replace ("\\n", "\n");
  9418. }
  9419. }
  9420. void LocalisedStrings::loadFromText (const String& fileContents)
  9421. {
  9422. StringArray lines;
  9423. lines.addLines (fileContents);
  9424. for (int i = 0; i < lines.size(); ++i)
  9425. {
  9426. String line (lines[i].trim());
  9427. if (line.startsWithChar ('"'))
  9428. {
  9429. int closeQuote = findCloseQuote (line, 1);
  9430. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9431. if (originalText.isNotEmpty())
  9432. {
  9433. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9434. closeQuote = findCloseQuote (line, openingQuote + 1);
  9435. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9436. if (newText.isNotEmpty())
  9437. translations.set (originalText, newText);
  9438. }
  9439. }
  9440. else if (line.startsWithIgnoreCase ("language:"))
  9441. {
  9442. languageName = line.substring (9).trim();
  9443. }
  9444. else if (line.startsWithIgnoreCase ("countries:"))
  9445. {
  9446. countryCodes.addTokens (line.substring (10).trim(), true);
  9447. countryCodes.trim();
  9448. countryCodes.removeEmptyStrings();
  9449. }
  9450. }
  9451. }
  9452. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9453. {
  9454. translations.setIgnoresCase (shouldIgnoreCase);
  9455. }
  9456. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9457. {
  9458. const ScopedLock sl (currentMappingsLock);
  9459. delete currentMappings;
  9460. currentMappings = newTranslations;
  9461. }
  9462. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9463. {
  9464. return currentMappings;
  9465. }
  9466. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9467. {
  9468. const ScopedLock sl (currentMappingsLock);
  9469. if (currentMappings != 0)
  9470. return currentMappings->translate (text);
  9471. return text;
  9472. }
  9473. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9474. {
  9475. return translateWithCurrentMappings (String (text));
  9476. }
  9477. END_JUCE_NAMESPACE
  9478. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9479. /*** Start of inlined file: juce_String.cpp ***/
  9480. #if JUCE_MSVC
  9481. #pragma warning (push)
  9482. #pragma warning (disable: 4514)
  9483. #endif
  9484. #include <locale>
  9485. BEGIN_JUCE_NAMESPACE
  9486. #if JUCE_MSVC
  9487. #pragma warning (pop)
  9488. #endif
  9489. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9490. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9491. #endif
  9492. class StringHolder
  9493. {
  9494. public:
  9495. StringHolder()
  9496. : refCount (0x3fffffff), allocatedNumChars (0)
  9497. {
  9498. text[0] = 0;
  9499. }
  9500. static juce_wchar* createUninitialised (const size_t numChars)
  9501. {
  9502. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9503. s->refCount.value = 0;
  9504. s->allocatedNumChars = numChars;
  9505. return &(s->text[0]);
  9506. }
  9507. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9508. {
  9509. juce_wchar* const dest = createUninitialised (numChars);
  9510. copyChars (dest, src, numChars);
  9511. return dest;
  9512. }
  9513. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9514. {
  9515. juce_wchar* const dest = createUninitialised (numChars);
  9516. CharacterFunctions::copy (dest, src, (int) numChars);
  9517. dest [numChars] = 0;
  9518. return dest;
  9519. }
  9520. static inline juce_wchar* getEmpty() throw()
  9521. {
  9522. return &(empty.text[0]);
  9523. }
  9524. static void retain (juce_wchar* const text) throw()
  9525. {
  9526. ++(bufferFromText (text)->refCount);
  9527. }
  9528. static inline void release (StringHolder* const b) throw()
  9529. {
  9530. if (--(b->refCount) == -1 && b != &empty)
  9531. delete[] reinterpret_cast <char*> (b);
  9532. }
  9533. static void release (juce_wchar* const text) throw()
  9534. {
  9535. release (bufferFromText (text));
  9536. }
  9537. static juce_wchar* makeUnique (juce_wchar* const text)
  9538. {
  9539. StringHolder* const b = bufferFromText (text);
  9540. if (b->refCount.get() <= 0)
  9541. return text;
  9542. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9543. release (b);
  9544. return newText;
  9545. }
  9546. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9547. {
  9548. StringHolder* const b = bufferFromText (text);
  9549. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9550. return text;
  9551. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9552. copyChars (newText, text, b->allocatedNumChars);
  9553. release (b);
  9554. return newText;
  9555. }
  9556. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9557. {
  9558. return bufferFromText (text)->allocatedNumChars;
  9559. }
  9560. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9561. {
  9562. jassert (src != 0 && dest != 0);
  9563. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9564. dest [numChars] = 0;
  9565. }
  9566. Atomic<int> refCount;
  9567. size_t allocatedNumChars;
  9568. juce_wchar text[1];
  9569. static StringHolder empty;
  9570. private:
  9571. static inline StringHolder* bufferFromText (void* const text) throw()
  9572. {
  9573. // (Can't use offsetof() here because of warnings about this not being a POD)
  9574. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9575. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9576. }
  9577. };
  9578. StringHolder StringHolder::empty;
  9579. const String String::empty;
  9580. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9581. {
  9582. jassert (t[numChars] == 0); // must have a null terminator
  9583. text = StringHolder::createCopy (t, numChars);
  9584. }
  9585. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9586. {
  9587. if (numExtraChars > 0)
  9588. {
  9589. const int oldLen = length();
  9590. const int newTotalLen = oldLen + numExtraChars;
  9591. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9592. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9593. }
  9594. }
  9595. void String::preallocateStorage (const size_t numChars)
  9596. {
  9597. text = StringHolder::makeUniqueWithSize (text, numChars);
  9598. }
  9599. String::String() throw()
  9600. : text (StringHolder::getEmpty())
  9601. {
  9602. }
  9603. String::~String() throw()
  9604. {
  9605. StringHolder::release (text);
  9606. }
  9607. String::String (const String& other) throw()
  9608. : text (other.text)
  9609. {
  9610. StringHolder::retain (text);
  9611. }
  9612. void String::swapWith (String& other) throw()
  9613. {
  9614. swapVariables (text, other.text);
  9615. }
  9616. String& String::operator= (const String& other) throw()
  9617. {
  9618. juce_wchar* const newText = other.text;
  9619. StringHolder::retain (newText);
  9620. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9621. return *this;
  9622. }
  9623. String::String (const size_t numChars, const int /*dummyVariable*/)
  9624. : text (StringHolder::createUninitialised (numChars))
  9625. {
  9626. }
  9627. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9628. {
  9629. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9630. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9631. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9632. }
  9633. String::String (const char* const t)
  9634. {
  9635. if (t != 0 && *t != 0)
  9636. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9637. else
  9638. text = StringHolder::getEmpty();
  9639. }
  9640. String::String (const juce_wchar* const t)
  9641. {
  9642. if (t != 0 && *t != 0)
  9643. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9644. else
  9645. text = StringHolder::getEmpty();
  9646. }
  9647. String::String (const char* const t, const size_t maxChars)
  9648. {
  9649. int i;
  9650. for (i = 0; (size_t) i < maxChars; ++i)
  9651. if (t[i] == 0)
  9652. break;
  9653. if (i > 0)
  9654. text = StringHolder::createCopy (t, i);
  9655. else
  9656. text = StringHolder::getEmpty();
  9657. }
  9658. String::String (const juce_wchar* const t, const size_t maxChars)
  9659. {
  9660. int i;
  9661. for (i = 0; (size_t) i < maxChars; ++i)
  9662. if (t[i] == 0)
  9663. break;
  9664. if (i > 0)
  9665. text = StringHolder::createCopy (t, i);
  9666. else
  9667. text = StringHolder::getEmpty();
  9668. }
  9669. const String String::charToString (const juce_wchar character)
  9670. {
  9671. String result ((size_t) 1, (int) 0);
  9672. result.text[0] = character;
  9673. result.text[1] = 0;
  9674. return result;
  9675. }
  9676. namespace NumberToStringConverters
  9677. {
  9678. // pass in a pointer to the END of a buffer..
  9679. juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9680. {
  9681. *--t = 0;
  9682. int64 v = (n >= 0) ? n : -n;
  9683. do
  9684. {
  9685. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9686. v /= 10;
  9687. } while (v > 0);
  9688. if (n < 0)
  9689. *--t = '-';
  9690. return t;
  9691. }
  9692. juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9693. {
  9694. *--t = 0;
  9695. do
  9696. {
  9697. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9698. v /= 10;
  9699. } while (v > 0);
  9700. return t;
  9701. }
  9702. juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9703. {
  9704. if (n == (int) 0x80000000) // (would cause an overflow)
  9705. return int64ToString (t, n);
  9706. *--t = 0;
  9707. int v = abs (n);
  9708. do
  9709. {
  9710. *--t = (juce_wchar) ('0' + (v % 10));
  9711. v /= 10;
  9712. } while (v > 0);
  9713. if (n < 0)
  9714. *--t = '-';
  9715. return t;
  9716. }
  9717. juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9718. {
  9719. *--t = 0;
  9720. do
  9721. {
  9722. *--t = (juce_wchar) ('0' + (v % 10));
  9723. v /= 10;
  9724. } while (v > 0);
  9725. return t;
  9726. }
  9727. juce_wchar getDecimalPoint()
  9728. {
  9729. #if JUCE_VC7_OR_EARLIER
  9730. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9731. #else
  9732. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9733. #endif
  9734. return dp;
  9735. }
  9736. juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9737. {
  9738. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9739. {
  9740. juce_wchar* const end = buffer + numChars;
  9741. juce_wchar* t = end;
  9742. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9743. *--t = (juce_wchar) 0;
  9744. while (numDecPlaces >= 0 || v > 0)
  9745. {
  9746. if (numDecPlaces == 0)
  9747. *--t = getDecimalPoint();
  9748. *--t = (juce_wchar) ('0' + (v % 10));
  9749. v /= 10;
  9750. --numDecPlaces;
  9751. }
  9752. if (n < 0)
  9753. *--t = '-';
  9754. len = end - t - 1;
  9755. return t;
  9756. }
  9757. else
  9758. {
  9759. #if JUCE_WINDOWS
  9760. #if JUCE_VC7_OR_EARLIER || JUCE_MINGW
  9761. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9762. #else
  9763. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9764. #endif
  9765. #else
  9766. len = swprintf (buffer, numChars, L"%.9g", n);
  9767. #endif
  9768. return buffer;
  9769. }
  9770. }
  9771. }
  9772. String::String (const int number)
  9773. {
  9774. juce_wchar buffer [16];
  9775. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9776. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9777. createInternal (start, end - start - 1);
  9778. }
  9779. String::String (const unsigned int number)
  9780. {
  9781. juce_wchar buffer [16];
  9782. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9783. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9784. createInternal (start, end - start - 1);
  9785. }
  9786. String::String (const short number)
  9787. {
  9788. juce_wchar buffer [16];
  9789. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9790. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9791. createInternal (start, end - start - 1);
  9792. }
  9793. String::String (const unsigned short number)
  9794. {
  9795. juce_wchar buffer [16];
  9796. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9797. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9798. createInternal (start, end - start - 1);
  9799. }
  9800. String::String (const int64 number)
  9801. {
  9802. juce_wchar buffer [32];
  9803. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9804. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9805. createInternal (start, end - start - 1);
  9806. }
  9807. String::String (const uint64 number)
  9808. {
  9809. juce_wchar buffer [32];
  9810. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9811. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9812. createInternal (start, end - start - 1);
  9813. }
  9814. String::String (const float number, const int numberOfDecimalPlaces)
  9815. {
  9816. juce_wchar buffer [48];
  9817. size_t len;
  9818. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9819. createInternal (start, len);
  9820. }
  9821. String::String (const double number, const int numberOfDecimalPlaces)
  9822. {
  9823. juce_wchar buffer [48];
  9824. size_t len;
  9825. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9826. createInternal (start, len);
  9827. }
  9828. int String::length() const throw()
  9829. {
  9830. return CharacterFunctions::length (text);
  9831. }
  9832. int String::hashCode() const throw()
  9833. {
  9834. const juce_wchar* t = text;
  9835. int result = 0;
  9836. while (*t != (juce_wchar) 0)
  9837. result = 31 * result + *t++;
  9838. return result;
  9839. }
  9840. int64 String::hashCode64() const throw()
  9841. {
  9842. const juce_wchar* t = text;
  9843. int64 result = 0;
  9844. while (*t != (juce_wchar) 0)
  9845. result = 101 * result + *t++;
  9846. return result;
  9847. }
  9848. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9849. {
  9850. return string1.compare (string2) == 0;
  9851. }
  9852. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9853. {
  9854. return string1.compare (string2) == 0;
  9855. }
  9856. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9857. {
  9858. return string1.compare (string2) == 0;
  9859. }
  9860. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9861. {
  9862. return string1.compare (string2) != 0;
  9863. }
  9864. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9865. {
  9866. return string1.compare (string2) != 0;
  9867. }
  9868. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9869. {
  9870. return string1.compare (string2) != 0;
  9871. }
  9872. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9873. {
  9874. return string1.compare (string2) > 0;
  9875. }
  9876. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9877. {
  9878. return string1.compare (string2) < 0;
  9879. }
  9880. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9881. {
  9882. return string1.compare (string2) >= 0;
  9883. }
  9884. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9885. {
  9886. return string1.compare (string2) <= 0;
  9887. }
  9888. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9889. {
  9890. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9891. : isEmpty();
  9892. }
  9893. bool String::equalsIgnoreCase (const char* t) const throw()
  9894. {
  9895. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9896. : isEmpty();
  9897. }
  9898. bool String::equalsIgnoreCase (const String& other) const throw()
  9899. {
  9900. return text == other.text
  9901. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9902. }
  9903. int String::compare (const String& other) const throw()
  9904. {
  9905. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9906. }
  9907. int String::compare (const char* other) const throw()
  9908. {
  9909. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9910. }
  9911. int String::compare (const juce_wchar* other) const throw()
  9912. {
  9913. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9914. }
  9915. int String::compareIgnoreCase (const String& other) const throw()
  9916. {
  9917. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9918. }
  9919. int String::compareLexicographically (const String& other) const throw()
  9920. {
  9921. const juce_wchar* s1 = text;
  9922. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9923. ++s1;
  9924. const juce_wchar* s2 = other.text;
  9925. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9926. ++s2;
  9927. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9928. }
  9929. String& String::operator+= (const juce_wchar* const t)
  9930. {
  9931. if (t != 0)
  9932. appendInternal (t, CharacterFunctions::length (t));
  9933. return *this;
  9934. }
  9935. String& String::operator+= (const String& other)
  9936. {
  9937. if (isEmpty())
  9938. operator= (other);
  9939. else
  9940. appendInternal (other.text, other.length());
  9941. return *this;
  9942. }
  9943. String& String::operator+= (const char ch)
  9944. {
  9945. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9946. return operator+= (static_cast <const juce_wchar*> (asString));
  9947. }
  9948. String& String::operator+= (const juce_wchar ch)
  9949. {
  9950. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9951. return operator+= (static_cast <const juce_wchar*> (asString));
  9952. }
  9953. String& String::operator+= (const int number)
  9954. {
  9955. juce_wchar buffer [16];
  9956. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9957. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9958. appendInternal (start, (int) (end - start));
  9959. return *this;
  9960. }
  9961. String& String::operator+= (const unsigned int number)
  9962. {
  9963. juce_wchar buffer [16];
  9964. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9965. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9966. appendInternal (start, (int) (end - start));
  9967. return *this;
  9968. }
  9969. void String::append (const juce_wchar* const other, const int howMany)
  9970. {
  9971. if (howMany > 0)
  9972. {
  9973. int i;
  9974. for (i = 0; i < howMany; ++i)
  9975. if (other[i] == 0)
  9976. break;
  9977. appendInternal (other, i);
  9978. }
  9979. }
  9980. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9981. {
  9982. String s (string1);
  9983. return s += string2;
  9984. }
  9985. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9986. {
  9987. String s (string1);
  9988. return s += string2;
  9989. }
  9990. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9991. {
  9992. return String::charToString (string1) + string2;
  9993. }
  9994. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9995. {
  9996. return String::charToString (string1) + string2;
  9997. }
  9998. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9999. {
  10000. return string1 += string2;
  10001. }
  10002. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  10003. {
  10004. return string1 += string2;
  10005. }
  10006. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  10007. {
  10008. return string1 += string2;
  10009. }
  10010. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  10011. {
  10012. return string1 += string2;
  10013. }
  10014. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  10015. {
  10016. return string1 += string2;
  10017. }
  10018. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  10019. {
  10020. return string1 += characterToAppend;
  10021. }
  10022. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  10023. {
  10024. return string1 += characterToAppend;
  10025. }
  10026. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  10027. {
  10028. return string1 += string2;
  10029. }
  10030. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  10031. {
  10032. return string1 += string2;
  10033. }
  10034. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  10035. {
  10036. return string1 += string2;
  10037. }
  10038. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  10039. {
  10040. return string1 += (int) number;
  10041. }
  10042. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  10043. {
  10044. return string1 += number;
  10045. }
  10046. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  10047. {
  10048. return string1 += number;
  10049. }
  10050. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  10051. {
  10052. return string1 += (int) number;
  10053. }
  10054. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  10055. {
  10056. return string1 += (unsigned int) number;
  10057. }
  10058. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  10059. {
  10060. return string1 += String (number);
  10061. }
  10062. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  10063. {
  10064. return string1 += String (number);
  10065. }
  10066. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  10067. {
  10068. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  10069. // if lots of large, persistent strings were to be written to streams).
  10070. const int numBytes = text.getNumBytesAsUTF8();
  10071. HeapBlock<char> temp (numBytes + 1);
  10072. text.copyToUTF8 (temp, numBytes + 1);
  10073. stream.write (temp, numBytes);
  10074. return stream;
  10075. }
  10076. int String::indexOfChar (const juce_wchar character) const throw()
  10077. {
  10078. const juce_wchar* t = text;
  10079. for (;;)
  10080. {
  10081. if (*t == character)
  10082. return (int) (t - text);
  10083. if (*t++ == 0)
  10084. return -1;
  10085. }
  10086. }
  10087. int String::lastIndexOfChar (const juce_wchar character) const throw()
  10088. {
  10089. for (int i = length(); --i >= 0;)
  10090. if (text[i] == character)
  10091. return i;
  10092. return -1;
  10093. }
  10094. int String::indexOf (const String& t) const throw()
  10095. {
  10096. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  10097. return r == 0 ? -1 : (int) (r - text);
  10098. }
  10099. int String::indexOfChar (const int startIndex,
  10100. const juce_wchar character) const throw()
  10101. {
  10102. if (startIndex > 0 && startIndex >= length())
  10103. return -1;
  10104. const juce_wchar* t = text + jmax (0, startIndex);
  10105. for (;;)
  10106. {
  10107. if (*t == character)
  10108. return (int) (t - text);
  10109. if (*t == 0)
  10110. return -1;
  10111. ++t;
  10112. }
  10113. }
  10114. int String::indexOfAnyOf (const String& charactersToLookFor,
  10115. const int startIndex,
  10116. const bool ignoreCase) const throw()
  10117. {
  10118. if (startIndex > 0 && startIndex >= length())
  10119. return -1;
  10120. const juce_wchar* t = text + jmax (0, startIndex);
  10121. while (*t != 0)
  10122. {
  10123. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  10124. return (int) (t - text);
  10125. ++t;
  10126. }
  10127. return -1;
  10128. }
  10129. int String::indexOf (const int startIndex, const String& other) const throw()
  10130. {
  10131. if (startIndex > 0 && startIndex >= length())
  10132. return -1;
  10133. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  10134. return found == 0 ? -1 : (int) (found - text);
  10135. }
  10136. int String::indexOfIgnoreCase (const String& other) const throw()
  10137. {
  10138. if (other.isNotEmpty())
  10139. {
  10140. const int len = other.length();
  10141. const int end = length() - len;
  10142. for (int i = 0; i <= end; ++i)
  10143. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10144. return i;
  10145. }
  10146. return -1;
  10147. }
  10148. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10149. {
  10150. if (other.isNotEmpty())
  10151. {
  10152. const int len = other.length();
  10153. const int end = length() - len;
  10154. for (int i = jmax (0, startIndex); i <= end; ++i)
  10155. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10156. return i;
  10157. }
  10158. return -1;
  10159. }
  10160. int String::lastIndexOf (const String& other) const throw()
  10161. {
  10162. if (other.isNotEmpty())
  10163. {
  10164. const int len = other.length();
  10165. int i = length() - len;
  10166. if (i >= 0)
  10167. {
  10168. const juce_wchar* n = text + i;
  10169. while (i >= 0)
  10170. {
  10171. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10172. return i;
  10173. --i;
  10174. }
  10175. }
  10176. }
  10177. return -1;
  10178. }
  10179. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10180. {
  10181. if (other.isNotEmpty())
  10182. {
  10183. const int len = other.length();
  10184. int i = length() - len;
  10185. if (i >= 0)
  10186. {
  10187. const juce_wchar* n = text + i;
  10188. while (i >= 0)
  10189. {
  10190. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10191. return i;
  10192. --i;
  10193. }
  10194. }
  10195. }
  10196. return -1;
  10197. }
  10198. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10199. {
  10200. for (int i = length(); --i >= 0;)
  10201. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10202. return i;
  10203. return -1;
  10204. }
  10205. bool String::contains (const String& other) const throw()
  10206. {
  10207. return indexOf (other) >= 0;
  10208. }
  10209. bool String::containsChar (const juce_wchar character) const throw()
  10210. {
  10211. const juce_wchar* t = text;
  10212. for (;;)
  10213. {
  10214. if (*t == 0)
  10215. return false;
  10216. if (*t == character)
  10217. return true;
  10218. ++t;
  10219. }
  10220. }
  10221. bool String::containsIgnoreCase (const String& t) const throw()
  10222. {
  10223. return indexOfIgnoreCase (t) >= 0;
  10224. }
  10225. int String::indexOfWholeWord (const String& word) const throw()
  10226. {
  10227. if (word.isNotEmpty())
  10228. {
  10229. const int wordLen = word.length();
  10230. const int end = length() - wordLen;
  10231. const juce_wchar* t = text;
  10232. for (int i = 0; i <= end; ++i)
  10233. {
  10234. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10235. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10236. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10237. {
  10238. return i;
  10239. }
  10240. ++t;
  10241. }
  10242. }
  10243. return -1;
  10244. }
  10245. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10246. {
  10247. if (word.isNotEmpty())
  10248. {
  10249. const int wordLen = word.length();
  10250. const int end = length() - wordLen;
  10251. const juce_wchar* t = text;
  10252. for (int i = 0; i <= end; ++i)
  10253. {
  10254. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10255. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10256. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10257. {
  10258. return i;
  10259. }
  10260. ++t;
  10261. }
  10262. }
  10263. return -1;
  10264. }
  10265. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10266. {
  10267. return indexOfWholeWord (wordToLookFor) >= 0;
  10268. }
  10269. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10270. {
  10271. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10272. }
  10273. namespace WildCardHelpers
  10274. {
  10275. int indexOfMatch (const juce_wchar* const wildcard,
  10276. const juce_wchar* const test,
  10277. const bool ignoreCase) throw()
  10278. {
  10279. int start = 0;
  10280. while (test [start] != 0)
  10281. {
  10282. int i = 0;
  10283. for (;;)
  10284. {
  10285. const juce_wchar wc = wildcard [i];
  10286. const juce_wchar c = test [i + start];
  10287. if (wc == c
  10288. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10289. || (wc == '?' && c != 0))
  10290. {
  10291. if (wc == 0)
  10292. return start;
  10293. ++i;
  10294. }
  10295. else
  10296. {
  10297. if (wc == '*' && (wildcard [i + 1] == 0
  10298. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10299. {
  10300. return start;
  10301. }
  10302. break;
  10303. }
  10304. }
  10305. ++start;
  10306. }
  10307. return -1;
  10308. }
  10309. }
  10310. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10311. {
  10312. int i = 0;
  10313. for (;;)
  10314. {
  10315. const juce_wchar wc = wildcard.text [i];
  10316. const juce_wchar c = text [i];
  10317. if (wc == c
  10318. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10319. || (wc == '?' && c != 0))
  10320. {
  10321. if (wc == 0)
  10322. return true;
  10323. ++i;
  10324. }
  10325. else
  10326. {
  10327. return wc == '*' && (wildcard [i + 1] == 0
  10328. || WildCardHelpers::indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10329. }
  10330. }
  10331. }
  10332. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10333. {
  10334. const int len = stringToRepeat.length();
  10335. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10336. juce_wchar* n = result.text;
  10337. *n = 0;
  10338. while (--numberOfTimesToRepeat >= 0)
  10339. {
  10340. StringHolder::copyChars (n, stringToRepeat.text, len);
  10341. n += len;
  10342. }
  10343. return result;
  10344. }
  10345. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10346. {
  10347. jassert (padCharacter != 0);
  10348. const int len = length();
  10349. if (len >= minimumLength || padCharacter == 0)
  10350. return *this;
  10351. String result ((size_t) minimumLength + 1, (int) 0);
  10352. juce_wchar* n = result.text;
  10353. minimumLength -= len;
  10354. while (--minimumLength >= 0)
  10355. *n++ = padCharacter;
  10356. StringHolder::copyChars (n, text, len);
  10357. return result;
  10358. }
  10359. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10360. {
  10361. jassert (padCharacter != 0);
  10362. const int len = length();
  10363. if (len >= minimumLength || padCharacter == 0)
  10364. return *this;
  10365. String result (*this, (size_t) minimumLength);
  10366. juce_wchar* n = result.text + len;
  10367. minimumLength -= len;
  10368. while (--minimumLength >= 0)
  10369. *n++ = padCharacter;
  10370. *n = 0;
  10371. return result;
  10372. }
  10373. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10374. {
  10375. if (index < 0)
  10376. {
  10377. // a negative index to replace from?
  10378. jassertfalse;
  10379. index = 0;
  10380. }
  10381. if (numCharsToReplace < 0)
  10382. {
  10383. // replacing a negative number of characters?
  10384. numCharsToReplace = 0;
  10385. jassertfalse;
  10386. }
  10387. const int len = length();
  10388. if (index + numCharsToReplace > len)
  10389. {
  10390. if (index > len)
  10391. {
  10392. // replacing beyond the end of the string?
  10393. index = len;
  10394. jassertfalse;
  10395. }
  10396. numCharsToReplace = len - index;
  10397. }
  10398. const int newStringLen = stringToInsert.length();
  10399. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10400. if (newTotalLen <= 0)
  10401. return String::empty;
  10402. String result ((size_t) newTotalLen, (int) 0);
  10403. StringHolder::copyChars (result.text, text, index);
  10404. if (newStringLen > 0)
  10405. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10406. const int endStringLen = newTotalLen - (index + newStringLen);
  10407. if (endStringLen > 0)
  10408. StringHolder::copyChars (result.text + (index + newStringLen),
  10409. text + (index + numCharsToReplace),
  10410. endStringLen);
  10411. return result;
  10412. }
  10413. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10414. {
  10415. const int stringToReplaceLen = stringToReplace.length();
  10416. const int stringToInsertLen = stringToInsert.length();
  10417. int i = 0;
  10418. String result (*this);
  10419. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10420. : result.indexOf (i, stringToReplace))) >= 0)
  10421. {
  10422. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10423. i += stringToInsertLen;
  10424. }
  10425. return result;
  10426. }
  10427. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10428. {
  10429. const int index = indexOfChar (charToReplace);
  10430. if (index < 0)
  10431. return *this;
  10432. String result (*this, size_t());
  10433. juce_wchar* t = result.text + index;
  10434. while (*t != 0)
  10435. {
  10436. if (*t == charToReplace)
  10437. *t = charToInsert;
  10438. ++t;
  10439. }
  10440. return result;
  10441. }
  10442. const String String::replaceCharacters (const String& charactersToReplace,
  10443. const String& charactersToInsertInstead) const
  10444. {
  10445. String result (*this, size_t());
  10446. juce_wchar* t = result.text;
  10447. const int len2 = charactersToInsertInstead.length();
  10448. // the two strings passed in are supposed to be the same length!
  10449. jassert (len2 == charactersToReplace.length());
  10450. while (*t != 0)
  10451. {
  10452. const int index = charactersToReplace.indexOfChar (*t);
  10453. if (((unsigned int) index) < (unsigned int) len2)
  10454. *t = charactersToInsertInstead [index];
  10455. ++t;
  10456. }
  10457. return result;
  10458. }
  10459. bool String::startsWith (const String& other) const throw()
  10460. {
  10461. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10462. }
  10463. bool String::startsWithIgnoreCase (const String& other) const throw()
  10464. {
  10465. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10466. }
  10467. bool String::startsWithChar (const juce_wchar character) const throw()
  10468. {
  10469. jassert (character != 0); // strings can't contain a null character!
  10470. return text[0] == character;
  10471. }
  10472. bool String::endsWithChar (const juce_wchar character) const throw()
  10473. {
  10474. jassert (character != 0); // strings can't contain a null character!
  10475. return text[0] != 0
  10476. && text [length() - 1] == character;
  10477. }
  10478. bool String::endsWith (const String& other) const throw()
  10479. {
  10480. const int thisLen = length();
  10481. const int otherLen = other.length();
  10482. return thisLen >= otherLen
  10483. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10484. }
  10485. bool String::endsWithIgnoreCase (const String& other) const throw()
  10486. {
  10487. const int thisLen = length();
  10488. const int otherLen = other.length();
  10489. return thisLen >= otherLen
  10490. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10491. }
  10492. const String String::toUpperCase() const
  10493. {
  10494. String result (*this, size_t());
  10495. CharacterFunctions::toUpperCase (result.text);
  10496. return result;
  10497. }
  10498. const String String::toLowerCase() const
  10499. {
  10500. String result (*this, size_t());
  10501. CharacterFunctions::toLowerCase (result.text);
  10502. return result;
  10503. }
  10504. juce_wchar& String::operator[] (const int index)
  10505. {
  10506. jassert (((unsigned int) index) <= (unsigned int) length());
  10507. text = StringHolder::makeUnique (text);
  10508. return text [index];
  10509. }
  10510. juce_wchar String::getLastCharacter() const throw()
  10511. {
  10512. return isEmpty() ? juce_wchar() : text [length() - 1];
  10513. }
  10514. const String String::substring (int start, int end) const
  10515. {
  10516. if (start < 0)
  10517. start = 0;
  10518. else if (end <= start)
  10519. return empty;
  10520. int len = 0;
  10521. while (len <= end && text [len] != 0)
  10522. ++len;
  10523. if (end >= len)
  10524. {
  10525. if (start == 0)
  10526. return *this;
  10527. end = len;
  10528. }
  10529. return String (text + start, end - start);
  10530. }
  10531. const String String::substring (const int start) const
  10532. {
  10533. if (start <= 0)
  10534. return *this;
  10535. const int len = length();
  10536. if (start >= len)
  10537. return empty;
  10538. return String (text + start, len - start);
  10539. }
  10540. const String String::dropLastCharacters (const int numberToDrop) const
  10541. {
  10542. return String (text, jmax (0, length() - numberToDrop));
  10543. }
  10544. const String String::getLastCharacters (const int numCharacters) const
  10545. {
  10546. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10547. }
  10548. const String String::fromFirstOccurrenceOf (const String& sub,
  10549. const bool includeSubString,
  10550. const bool ignoreCase) const
  10551. {
  10552. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10553. : indexOf (sub);
  10554. if (i < 0)
  10555. return empty;
  10556. return substring (includeSubString ? i : i + sub.length());
  10557. }
  10558. const String String::fromLastOccurrenceOf (const String& sub,
  10559. const bool includeSubString,
  10560. const bool ignoreCase) const
  10561. {
  10562. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10563. : lastIndexOf (sub);
  10564. if (i < 0)
  10565. return *this;
  10566. return substring (includeSubString ? i : i + sub.length());
  10567. }
  10568. const String String::upToFirstOccurrenceOf (const String& sub,
  10569. const bool includeSubString,
  10570. const bool ignoreCase) const
  10571. {
  10572. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10573. : indexOf (sub);
  10574. if (i < 0)
  10575. return *this;
  10576. return substring (0, includeSubString ? i + sub.length() : i);
  10577. }
  10578. const String String::upToLastOccurrenceOf (const String& sub,
  10579. const bool includeSubString,
  10580. const bool ignoreCase) const
  10581. {
  10582. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10583. : lastIndexOf (sub);
  10584. if (i < 0)
  10585. return *this;
  10586. return substring (0, includeSubString ? i + sub.length() : i);
  10587. }
  10588. bool String::isQuotedString() const
  10589. {
  10590. const String trimmed (trimStart());
  10591. return trimmed[0] == '"'
  10592. || trimmed[0] == '\'';
  10593. }
  10594. const String String::unquoted() const
  10595. {
  10596. String s (*this);
  10597. if (s.text[0] == '"' || s.text[0] == '\'')
  10598. s = s.substring (1);
  10599. const int lastCharIndex = s.length() - 1;
  10600. if (lastCharIndex >= 0
  10601. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10602. s [lastCharIndex] = 0;
  10603. return s;
  10604. }
  10605. const String String::quoted (const juce_wchar quoteCharacter) const
  10606. {
  10607. if (isEmpty())
  10608. return charToString (quoteCharacter) + quoteCharacter;
  10609. String t (*this);
  10610. if (! t.startsWithChar (quoteCharacter))
  10611. t = charToString (quoteCharacter) + t;
  10612. if (! t.endsWithChar (quoteCharacter))
  10613. t += quoteCharacter;
  10614. return t;
  10615. }
  10616. const String String::trim() const
  10617. {
  10618. if (isEmpty())
  10619. return empty;
  10620. int start = 0;
  10621. while (CharacterFunctions::isWhitespace (text [start]))
  10622. ++start;
  10623. const int len = length();
  10624. int end = len - 1;
  10625. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10626. --end;
  10627. ++end;
  10628. if (end <= start)
  10629. return empty;
  10630. else if (start > 0 || end < len)
  10631. return String (text + start, end - start);
  10632. return *this;
  10633. }
  10634. const String String::trimStart() const
  10635. {
  10636. if (isEmpty())
  10637. return empty;
  10638. const juce_wchar* t = text;
  10639. while (CharacterFunctions::isWhitespace (*t))
  10640. ++t;
  10641. if (t == text)
  10642. return *this;
  10643. return String (t);
  10644. }
  10645. const String String::trimEnd() const
  10646. {
  10647. if (isEmpty())
  10648. return empty;
  10649. const juce_wchar* endT = text + (length() - 1);
  10650. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10651. --endT;
  10652. return String (text, (int) (++endT - text));
  10653. }
  10654. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10655. {
  10656. const juce_wchar* t = text;
  10657. while (charactersToTrim.containsChar (*t))
  10658. ++t;
  10659. return t == text ? *this : String (t);
  10660. }
  10661. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10662. {
  10663. if (isEmpty())
  10664. return empty;
  10665. const int len = length();
  10666. const juce_wchar* endT = text + (len - 1);
  10667. int numToRemove = 0;
  10668. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10669. {
  10670. ++numToRemove;
  10671. --endT;
  10672. }
  10673. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10674. }
  10675. const String String::retainCharacters (const String& charactersToRetain) const
  10676. {
  10677. if (isEmpty())
  10678. return empty;
  10679. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10680. juce_wchar* dst = result.text;
  10681. const juce_wchar* src = text;
  10682. while (*src != 0)
  10683. {
  10684. if (charactersToRetain.containsChar (*src))
  10685. *dst++ = *src;
  10686. ++src;
  10687. }
  10688. *dst = 0;
  10689. return result;
  10690. }
  10691. const String String::removeCharacters (const String& charactersToRemove) const
  10692. {
  10693. if (isEmpty())
  10694. return empty;
  10695. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10696. juce_wchar* dst = result.text;
  10697. const juce_wchar* src = text;
  10698. while (*src != 0)
  10699. {
  10700. if (! charactersToRemove.containsChar (*src))
  10701. *dst++ = *src;
  10702. ++src;
  10703. }
  10704. *dst = 0;
  10705. return result;
  10706. }
  10707. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10708. {
  10709. int i = 0;
  10710. for (;;)
  10711. {
  10712. if (! permittedCharacters.containsChar (text[i]))
  10713. break;
  10714. ++i;
  10715. }
  10716. return substring (0, i);
  10717. }
  10718. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10719. {
  10720. const juce_wchar* const t = text;
  10721. int i = 0;
  10722. while (t[i] != 0)
  10723. {
  10724. if (charactersToStopAt.containsChar (t[i]))
  10725. return String (text, i);
  10726. ++i;
  10727. }
  10728. return empty;
  10729. }
  10730. bool String::containsOnly (const String& chars) const throw()
  10731. {
  10732. const juce_wchar* t = text;
  10733. while (*t != 0)
  10734. if (! chars.containsChar (*t++))
  10735. return false;
  10736. return true;
  10737. }
  10738. bool String::containsAnyOf (const String& chars) const throw()
  10739. {
  10740. const juce_wchar* t = text;
  10741. while (*t != 0)
  10742. if (chars.containsChar (*t++))
  10743. return true;
  10744. return false;
  10745. }
  10746. bool String::containsNonWhitespaceChars() const throw()
  10747. {
  10748. const juce_wchar* t = text;
  10749. while (*t != 0)
  10750. if (! CharacterFunctions::isWhitespace (*t++))
  10751. return true;
  10752. return false;
  10753. }
  10754. const String String::formatted (const juce_wchar* const pf, ... )
  10755. {
  10756. jassert (pf != 0);
  10757. va_list args;
  10758. va_start (args, pf);
  10759. size_t bufferSize = 256;
  10760. String result (bufferSize, (int) 0);
  10761. result.text[0] = 0;
  10762. for (;;)
  10763. {
  10764. #if JUCE_LINUX && JUCE_64BIT
  10765. va_list tempArgs;
  10766. va_copy (tempArgs, args);
  10767. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10768. va_end (tempArgs);
  10769. #elif JUCE_WINDOWS
  10770. #if JUCE_MSVC
  10771. #pragma warning (push)
  10772. #pragma warning (disable: 4996)
  10773. #endif
  10774. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10775. #if JUCE_MSVC
  10776. #pragma warning (pop)
  10777. #endif
  10778. #else
  10779. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10780. #endif
  10781. if (num > 0)
  10782. return result;
  10783. bufferSize += 256;
  10784. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10785. break; // returns -1 because of an error rather than because it needs more space.
  10786. result.preallocateStorage (bufferSize);
  10787. }
  10788. return empty;
  10789. }
  10790. int String::getIntValue() const throw()
  10791. {
  10792. return CharacterFunctions::getIntValue (text);
  10793. }
  10794. int String::getTrailingIntValue() const throw()
  10795. {
  10796. int n = 0;
  10797. int mult = 1;
  10798. const juce_wchar* t = text + length();
  10799. while (--t >= text)
  10800. {
  10801. const juce_wchar c = *t;
  10802. if (! CharacterFunctions::isDigit (c))
  10803. {
  10804. if (c == '-')
  10805. n = -n;
  10806. break;
  10807. }
  10808. n += mult * (c - '0');
  10809. mult *= 10;
  10810. }
  10811. return n;
  10812. }
  10813. int64 String::getLargeIntValue() const throw()
  10814. {
  10815. return CharacterFunctions::getInt64Value (text);
  10816. }
  10817. float String::getFloatValue() const throw()
  10818. {
  10819. return (float) CharacterFunctions::getDoubleValue (text);
  10820. }
  10821. double String::getDoubleValue() const throw()
  10822. {
  10823. return CharacterFunctions::getDoubleValue (text);
  10824. }
  10825. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10826. const String String::toHexString (const int number)
  10827. {
  10828. juce_wchar buffer[32];
  10829. juce_wchar* const end = buffer + 32;
  10830. juce_wchar* t = end;
  10831. *--t = 0;
  10832. unsigned int v = (unsigned int) number;
  10833. do
  10834. {
  10835. *--t = hexDigits [v & 15];
  10836. v >>= 4;
  10837. } while (v != 0);
  10838. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10839. }
  10840. const String String::toHexString (const int64 number)
  10841. {
  10842. juce_wchar buffer[32];
  10843. juce_wchar* const end = buffer + 32;
  10844. juce_wchar* t = end;
  10845. *--t = 0;
  10846. uint64 v = (uint64) number;
  10847. do
  10848. {
  10849. *--t = hexDigits [(int) (v & 15)];
  10850. v >>= 4;
  10851. } while (v != 0);
  10852. return String (t, (int) (((char*) end) - (char*) t));
  10853. }
  10854. const String String::toHexString (const short number)
  10855. {
  10856. return toHexString ((int) (unsigned short) number);
  10857. }
  10858. const String String::toHexString (const unsigned char* data,
  10859. const int size,
  10860. const int groupSize)
  10861. {
  10862. if (size <= 0)
  10863. return empty;
  10864. int numChars = (size * 2) + 2;
  10865. if (groupSize > 0)
  10866. numChars += size / groupSize;
  10867. String s ((size_t) numChars, (int) 0);
  10868. juce_wchar* d = s.text;
  10869. for (int i = 0; i < size; ++i)
  10870. {
  10871. *d++ = hexDigits [(*data) >> 4];
  10872. *d++ = hexDigits [(*data) & 0xf];
  10873. ++data;
  10874. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10875. *d++ = ' ';
  10876. }
  10877. *d = 0;
  10878. return s;
  10879. }
  10880. int String::getHexValue32() const throw()
  10881. {
  10882. int result = 0;
  10883. const juce_wchar* c = text;
  10884. for (;;)
  10885. {
  10886. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10887. if (hexValue >= 0)
  10888. result = (result << 4) | hexValue;
  10889. else if (*c == 0)
  10890. break;
  10891. ++c;
  10892. }
  10893. return result;
  10894. }
  10895. int64 String::getHexValue64() const throw()
  10896. {
  10897. int64 result = 0;
  10898. const juce_wchar* c = text;
  10899. for (;;)
  10900. {
  10901. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10902. if (hexValue >= 0)
  10903. result = (result << 4) | hexValue;
  10904. else if (*c == 0)
  10905. break;
  10906. ++c;
  10907. }
  10908. return result;
  10909. }
  10910. const String String::createStringFromData (const void* const data_, const int size)
  10911. {
  10912. const char* const data = static_cast <const char*> (data_);
  10913. if (size <= 0 || data == 0)
  10914. {
  10915. return empty;
  10916. }
  10917. else if (size < 2)
  10918. {
  10919. return charToString (data[0]);
  10920. }
  10921. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10922. || (data[0] == (char)-1 && data[1] == (char)-2))
  10923. {
  10924. // assume it's 16-bit unicode
  10925. const bool bigEndian = (data[0] == (char)-2);
  10926. const int numChars = size / 2 - 1;
  10927. String result;
  10928. result.preallocateStorage (numChars + 2);
  10929. const uint16* const src = (const uint16*) (data + 2);
  10930. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10931. if (bigEndian)
  10932. {
  10933. for (int i = 0; i < numChars; ++i)
  10934. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10935. }
  10936. else
  10937. {
  10938. for (int i = 0; i < numChars; ++i)
  10939. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10940. }
  10941. dst [numChars] = 0;
  10942. return result;
  10943. }
  10944. else
  10945. {
  10946. return String::fromUTF8 (data, size);
  10947. }
  10948. }
  10949. const char* String::toUTF8() const
  10950. {
  10951. if (isEmpty())
  10952. {
  10953. return reinterpret_cast <const char*> (text);
  10954. }
  10955. else
  10956. {
  10957. const int currentLen = length() + 1;
  10958. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10959. String* const mutableThis = const_cast <String*> (this);
  10960. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10961. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10962. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10963. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10964. #endif
  10965. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10966. return otherCopy;
  10967. }
  10968. }
  10969. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10970. {
  10971. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10972. int num = 0, index = 0;
  10973. for (;;)
  10974. {
  10975. const uint32 c = (uint32) text [index++];
  10976. if (c >= 0x80)
  10977. {
  10978. int numExtraBytes = 1;
  10979. if (c >= 0x800)
  10980. {
  10981. ++numExtraBytes;
  10982. if (c >= 0x10000)
  10983. {
  10984. ++numExtraBytes;
  10985. if (c >= 0x200000)
  10986. {
  10987. ++numExtraBytes;
  10988. if (c >= 0x4000000)
  10989. ++numExtraBytes;
  10990. }
  10991. }
  10992. }
  10993. if (buffer != 0)
  10994. {
  10995. if (num + numExtraBytes >= maxBufferSizeBytes)
  10996. {
  10997. buffer [num++] = 0;
  10998. break;
  10999. }
  11000. else
  11001. {
  11002. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  11003. while (--numExtraBytes >= 0)
  11004. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  11005. }
  11006. }
  11007. else
  11008. {
  11009. num += numExtraBytes + 1;
  11010. }
  11011. }
  11012. else
  11013. {
  11014. if (buffer != 0)
  11015. {
  11016. if (num + 1 >= maxBufferSizeBytes)
  11017. {
  11018. buffer [num++] = 0;
  11019. break;
  11020. }
  11021. buffer [num] = (uint8) c;
  11022. }
  11023. ++num;
  11024. }
  11025. if (c == 0)
  11026. break;
  11027. }
  11028. return num;
  11029. }
  11030. int String::getNumBytesAsUTF8() const throw()
  11031. {
  11032. int num = 0;
  11033. const juce_wchar* t = text;
  11034. for (;;)
  11035. {
  11036. const uint32 c = (uint32) *t;
  11037. if (c >= 0x80)
  11038. {
  11039. ++num;
  11040. if (c >= 0x800)
  11041. {
  11042. ++num;
  11043. if (c >= 0x10000)
  11044. {
  11045. ++num;
  11046. if (c >= 0x200000)
  11047. {
  11048. ++num;
  11049. if (c >= 0x4000000)
  11050. ++num;
  11051. }
  11052. }
  11053. }
  11054. }
  11055. else if (c == 0)
  11056. break;
  11057. ++num;
  11058. ++t;
  11059. }
  11060. return num;
  11061. }
  11062. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  11063. {
  11064. if (buffer == 0)
  11065. return empty;
  11066. if (bufferSizeBytes < 0)
  11067. bufferSizeBytes = std::numeric_limits<int>::max();
  11068. size_t numBytes;
  11069. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  11070. if (buffer [numBytes] == 0)
  11071. break;
  11072. String result ((size_t) numBytes + 1, (int) 0);
  11073. juce_wchar* dest = result.text;
  11074. size_t i = 0;
  11075. while (i < numBytes)
  11076. {
  11077. const char c = buffer [i++];
  11078. if (c < 0)
  11079. {
  11080. unsigned int mask = 0x7f;
  11081. int bit = 0x40;
  11082. int numExtraValues = 0;
  11083. while (bit != 0 && (c & bit) != 0)
  11084. {
  11085. bit >>= 1;
  11086. mask >>= 1;
  11087. ++numExtraValues;
  11088. }
  11089. int n = (mask & (unsigned char) c);
  11090. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  11091. {
  11092. const char nextByte = buffer[i];
  11093. if ((nextByte & 0xc0) != 0x80)
  11094. break;
  11095. n <<= 6;
  11096. n |= (nextByte & 0x3f);
  11097. ++i;
  11098. }
  11099. *dest++ = (juce_wchar) n;
  11100. }
  11101. else
  11102. {
  11103. *dest++ = (juce_wchar) c;
  11104. }
  11105. }
  11106. *dest = 0;
  11107. return result;
  11108. }
  11109. const char* String::toCString() const
  11110. {
  11111. if (isEmpty())
  11112. {
  11113. return reinterpret_cast <const char*> (text);
  11114. }
  11115. else
  11116. {
  11117. const int len = length();
  11118. String* const mutableThis = const_cast <String*> (this);
  11119. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  11120. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  11121. CharacterFunctions::copy (otherCopy, text, len);
  11122. otherCopy [len] = 0;
  11123. return otherCopy;
  11124. }
  11125. }
  11126. #if JUCE_MSVC
  11127. #pragma warning (push)
  11128. #pragma warning (disable: 4514 4996)
  11129. #endif
  11130. int String::getNumBytesAsCString() const throw()
  11131. {
  11132. return (int) wcstombs (0, text, 0);
  11133. }
  11134. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  11135. {
  11136. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  11137. if (destBuffer != 0 && numBytes >= 0)
  11138. destBuffer [numBytes] = 0;
  11139. return numBytes;
  11140. }
  11141. #if JUCE_MSVC
  11142. #pragma warning (pop)
  11143. #endif
  11144. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11145. {
  11146. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11147. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11148. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11149. }
  11150. String::Concatenator::Concatenator (String& stringToAppendTo)
  11151. : result (stringToAppendTo),
  11152. nextIndex (stringToAppendTo.length())
  11153. {
  11154. }
  11155. String::Concatenator::~Concatenator()
  11156. {
  11157. }
  11158. void String::Concatenator::append (const String& s)
  11159. {
  11160. const int len = s.length();
  11161. if (len > 0)
  11162. {
  11163. result.preallocateStorage (nextIndex + len);
  11164. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11165. nextIndex += len;
  11166. }
  11167. }
  11168. #if JUCE_UNIT_TESTS
  11169. class StringTests : public UnitTest
  11170. {
  11171. public:
  11172. StringTests() : UnitTest ("String class") {}
  11173. void runTest()
  11174. {
  11175. {
  11176. beginTest ("Basics");
  11177. expect (String().length() == 0);
  11178. expect (String() == String::empty);
  11179. String s1, s2 ("abcd");
  11180. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11181. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11182. expect (s2.length() == 4);
  11183. s1 = "abcd";
  11184. expect (s2 == s1 && s1 == s2);
  11185. expect (s1 == "abcd" && s1 == L"abcd");
  11186. expect (String ("abcd") == String (L"abcd"));
  11187. expect (String ("abcdefg", 4) == L"abcd");
  11188. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11189. expect (String::charToString ('x') == "x");
  11190. expect (String::charToString (0) == String::empty);
  11191. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11192. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11193. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11194. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11195. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11196. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11197. expect (s1.indexOf (String::empty) == 0);
  11198. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11199. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11200. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11201. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11202. }
  11203. {
  11204. beginTest ("Operations");
  11205. String s ("012345678");
  11206. expect (s.hashCode() != 0);
  11207. expect (s.hashCode64() != 0);
  11208. expect (s.hashCode() != (s + s).hashCode());
  11209. expect (s.hashCode64() != (s + s).hashCode64());
  11210. expect (s.compare (String ("012345678")) == 0);
  11211. expect (s.compare (String ("012345679")) < 0);
  11212. expect (s.compare (String ("012345676")) > 0);
  11213. expect (s.substring (2, 3) == String::charToString (s[2]));
  11214. expect (s.substring (0, 1) == String::charToString (s[0]));
  11215. expect (s.getLastCharacter() == s [s.length() - 1]);
  11216. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11217. expect (s.substring (0, 3) == L"012");
  11218. expect (s.substring (0, 100) == s);
  11219. expect (s.substring (-1, 100) == s);
  11220. expect (s.substring (3) == "345678");
  11221. expect (s.indexOf (L"45") == 4);
  11222. expect (String ("444445").indexOf ("45") == 4);
  11223. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11224. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11225. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11226. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11227. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11228. expect (s.indexOfChar (L'4') == 4);
  11229. expect (s + s == "012345678012345678");
  11230. expect (s.startsWith (s));
  11231. expect (s.startsWith (s.substring (0, 4)));
  11232. expect (s.startsWith (s.dropLastCharacters (4)));
  11233. expect (s.endsWith (s.substring (5)));
  11234. expect (s.endsWith (s));
  11235. expect (s.contains (s.substring (3, 6)));
  11236. expect (s.contains (s.substring (3)));
  11237. expect (s.startsWithChar (s[0]));
  11238. expect (s.endsWithChar (s.getLastCharacter()));
  11239. expect (s [s.length()] == 0);
  11240. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11241. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11242. String s2 ("123");
  11243. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11244. s2 += "xyz";
  11245. expect (s2 == "1234567890xyz");
  11246. beginTest ("Numeric conversions");
  11247. expect (String::empty.getIntValue() == 0);
  11248. expect (String::empty.getDoubleValue() == 0.0);
  11249. expect (String::empty.getFloatValue() == 0.0f);
  11250. expect (s.getIntValue() == 12345678);
  11251. expect (s.getLargeIntValue() == (int64) 12345678);
  11252. expect (s.getDoubleValue() == 12345678.0);
  11253. expect (s.getFloatValue() == 12345678.0f);
  11254. expect (String (-1234).getIntValue() == -1234);
  11255. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11256. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11257. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11258. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11259. expect (s.getHexValue32() == 0x12345678);
  11260. expect (s.getHexValue64() == (int64) 0x12345678);
  11261. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11262. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11263. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11264. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11265. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11266. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11267. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11268. beginTest ("Subsections");
  11269. String s3;
  11270. s3 = "abcdeFGHIJ";
  11271. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11272. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11273. expect (s3.containsIgnoreCase (s3.substring (3)));
  11274. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11275. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11276. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11277. expect (s3.containsAnyOf (L"zzzFs"));
  11278. expect (s3.startsWith ("abcd"));
  11279. expect (s3.startsWithIgnoreCase (L"abCD"));
  11280. expect (s3.startsWith (String::empty));
  11281. expect (s3.startsWithChar ('a'));
  11282. expect (s3.endsWith (String ("HIJ")));
  11283. expect (s3.endsWithIgnoreCase (L"Hij"));
  11284. expect (s3.endsWith (String::empty));
  11285. expect (s3.endsWithChar (L'J'));
  11286. expect (s3.indexOf ("HIJ") == 7);
  11287. expect (s3.indexOf (L"HIJK") == -1);
  11288. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11289. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11290. String s4 (s3);
  11291. s4.append (String ("xyz123"), 3);
  11292. expect (s4 == s3 + "xyz");
  11293. expect (String (1234) < String (1235));
  11294. expect (String (1235) > String (1234));
  11295. expect (String (1234) >= String (1234));
  11296. expect (String (1234) <= String (1234));
  11297. expect (String (1235) >= String (1234));
  11298. expect (String (1234) <= String (1235));
  11299. String s5 ("word word2 word3");
  11300. expect (s5.containsWholeWord (String ("word2")));
  11301. expect (s5.indexOfWholeWord ("word2") == 5);
  11302. expect (s5.containsWholeWord (L"word"));
  11303. expect (s5.containsWholeWord ("word3"));
  11304. expect (s5.containsWholeWord (s5));
  11305. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11306. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11307. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11308. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11309. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11310. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11311. expect (s5.containsNonWhitespaceChars());
  11312. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11313. expect (s5.matchesWildcard (L"wor*", false));
  11314. expect (s5.matchesWildcard ("wOr*", true));
  11315. expect (s5.matchesWildcard (L"*word3", true));
  11316. expect (s5.matchesWildcard ("*word?", true));
  11317. expect (s5.matchesWildcard (L"Word*3", true));
  11318. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11319. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11320. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11321. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11322. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11323. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11324. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11325. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11326. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11327. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11328. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11329. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11330. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11331. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11332. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11333. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11334. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11335. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11336. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11337. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11338. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11339. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11340. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11341. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11342. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11343. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11344. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11345. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11346. expect (s5.replace ("Word", "", true) == " 2 3");
  11347. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11348. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11349. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11350. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11351. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11352. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11353. expect (s5.retainCharacters (String::empty).isEmpty());
  11354. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11355. expect (s5.removeCharacters (String::empty) == s5);
  11356. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11357. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11358. expect (! s5.isQuotedString());
  11359. expect (s5.quoted().isQuotedString());
  11360. expect (! s5.quoted().unquoted().isQuotedString());
  11361. expect (! String ("x'").isQuotedString());
  11362. expect (String ("'x").isQuotedString());
  11363. String s6 (" \t xyz \t\r\n");
  11364. expect (s6.trim() == String ("xyz"));
  11365. expect (s6.trim().trim() == "xyz");
  11366. expect (s5.trim() == s5);
  11367. expect (s6.trimStart().trimEnd() == s6.trim());
  11368. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11369. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11370. expect (s6.trimStart() != s6.trimEnd());
  11371. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11372. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11373. }
  11374. {
  11375. beginTest ("UTF8");
  11376. String s ("word word2 word3");
  11377. {
  11378. char buffer [100];
  11379. memset (buffer, 0xff, sizeof (buffer));
  11380. s.copyToUTF8 (buffer, 100);
  11381. expect (String::fromUTF8 (buffer, 100) == s);
  11382. juce_wchar bufferUnicode [100];
  11383. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11384. s.copyToUnicode (bufferUnicode, 100);
  11385. expect (String (bufferUnicode, 100) == s);
  11386. }
  11387. {
  11388. juce_wchar wideBuffer [50];
  11389. zerostruct (wideBuffer);
  11390. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11391. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11392. String wide (wideBuffer);
  11393. expect (wide == (const juce_wchar*) wideBuffer);
  11394. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11395. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11396. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11397. }
  11398. }
  11399. }
  11400. };
  11401. static StringTests stringUnitTests;
  11402. #endif
  11403. END_JUCE_NAMESPACE
  11404. /*** End of inlined file: juce_String.cpp ***/
  11405. /*** Start of inlined file: juce_StringArray.cpp ***/
  11406. BEGIN_JUCE_NAMESPACE
  11407. StringArray::StringArray() throw()
  11408. {
  11409. }
  11410. StringArray::StringArray (const StringArray& other)
  11411. : strings (other.strings)
  11412. {
  11413. }
  11414. StringArray::StringArray (const String& firstValue)
  11415. {
  11416. strings.add (firstValue);
  11417. }
  11418. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11419. const int numberOfStrings)
  11420. {
  11421. for (int i = 0; i < numberOfStrings; ++i)
  11422. strings.add (initialStrings [i]);
  11423. }
  11424. StringArray::StringArray (const char* const* const initialStrings,
  11425. const int numberOfStrings)
  11426. {
  11427. for (int i = 0; i < numberOfStrings; ++i)
  11428. strings.add (initialStrings [i]);
  11429. }
  11430. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11431. {
  11432. int i = 0;
  11433. while (initialStrings[i] != 0)
  11434. strings.add (initialStrings [i++]);
  11435. }
  11436. StringArray::StringArray (const char* const* const initialStrings)
  11437. {
  11438. int i = 0;
  11439. while (initialStrings[i] != 0)
  11440. strings.add (initialStrings [i++]);
  11441. }
  11442. StringArray& StringArray::operator= (const StringArray& other)
  11443. {
  11444. strings = other.strings;
  11445. return *this;
  11446. }
  11447. StringArray::~StringArray()
  11448. {
  11449. }
  11450. bool StringArray::operator== (const StringArray& other) const throw()
  11451. {
  11452. if (other.size() != size())
  11453. return false;
  11454. for (int i = size(); --i >= 0;)
  11455. if (other.strings.getReference(i) != strings.getReference(i))
  11456. return false;
  11457. return true;
  11458. }
  11459. bool StringArray::operator!= (const StringArray& other) const throw()
  11460. {
  11461. return ! operator== (other);
  11462. }
  11463. void StringArray::clear()
  11464. {
  11465. strings.clear();
  11466. }
  11467. const String& StringArray::operator[] (const int index) const throw()
  11468. {
  11469. if (((unsigned int) index) < (unsigned int) strings.size())
  11470. return strings.getReference (index);
  11471. return String::empty;
  11472. }
  11473. String& StringArray::getReference (const int index) throw()
  11474. {
  11475. jassert (((unsigned int) index) < (unsigned int) strings.size());
  11476. return strings.getReference (index);
  11477. }
  11478. void StringArray::add (const String& newString)
  11479. {
  11480. strings.add (newString);
  11481. }
  11482. void StringArray::insert (const int index, const String& newString)
  11483. {
  11484. strings.insert (index, newString);
  11485. }
  11486. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11487. {
  11488. if (! contains (newString, ignoreCase))
  11489. add (newString);
  11490. }
  11491. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11492. {
  11493. if (startIndex < 0)
  11494. {
  11495. jassertfalse;
  11496. startIndex = 0;
  11497. }
  11498. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11499. numElementsToAdd = otherArray.size() - startIndex;
  11500. while (--numElementsToAdd >= 0)
  11501. strings.add (otherArray.strings.getReference (startIndex++));
  11502. }
  11503. void StringArray::set (const int index, const String& newString)
  11504. {
  11505. strings.set (index, newString);
  11506. }
  11507. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11508. {
  11509. if (ignoreCase)
  11510. {
  11511. for (int i = size(); --i >= 0;)
  11512. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11513. return true;
  11514. }
  11515. else
  11516. {
  11517. for (int i = size(); --i >= 0;)
  11518. if (stringToLookFor == strings.getReference(i))
  11519. return true;
  11520. }
  11521. return false;
  11522. }
  11523. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11524. {
  11525. if (i < 0)
  11526. i = 0;
  11527. const int numElements = size();
  11528. if (ignoreCase)
  11529. {
  11530. while (i < numElements)
  11531. {
  11532. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11533. return i;
  11534. ++i;
  11535. }
  11536. }
  11537. else
  11538. {
  11539. while (i < numElements)
  11540. {
  11541. if (stringToLookFor == strings.getReference (i))
  11542. return i;
  11543. ++i;
  11544. }
  11545. }
  11546. return -1;
  11547. }
  11548. void StringArray::remove (const int index)
  11549. {
  11550. strings.remove (index);
  11551. }
  11552. void StringArray::removeString (const String& stringToRemove,
  11553. const bool ignoreCase)
  11554. {
  11555. if (ignoreCase)
  11556. {
  11557. for (int i = size(); --i >= 0;)
  11558. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11559. strings.remove (i);
  11560. }
  11561. else
  11562. {
  11563. for (int i = size(); --i >= 0;)
  11564. if (stringToRemove == strings.getReference (i))
  11565. strings.remove (i);
  11566. }
  11567. }
  11568. void StringArray::removeRange (int startIndex, int numberToRemove)
  11569. {
  11570. strings.removeRange (startIndex, numberToRemove);
  11571. }
  11572. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11573. {
  11574. if (removeWhitespaceStrings)
  11575. {
  11576. for (int i = size(); --i >= 0;)
  11577. if (! strings.getReference(i).containsNonWhitespaceChars())
  11578. strings.remove (i);
  11579. }
  11580. else
  11581. {
  11582. for (int i = size(); --i >= 0;)
  11583. if (strings.getReference(i).isEmpty())
  11584. strings.remove (i);
  11585. }
  11586. }
  11587. void StringArray::trim()
  11588. {
  11589. for (int i = size(); --i >= 0;)
  11590. {
  11591. String& s = strings.getReference(i);
  11592. s = s.trim();
  11593. }
  11594. }
  11595. class InternalStringArrayComparator_CaseSensitive
  11596. {
  11597. public:
  11598. static int compareElements (String& first, String& second) { return first.compare (second); }
  11599. };
  11600. class InternalStringArrayComparator_CaseInsensitive
  11601. {
  11602. public:
  11603. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11604. };
  11605. void StringArray::sort (const bool ignoreCase)
  11606. {
  11607. if (ignoreCase)
  11608. {
  11609. InternalStringArrayComparator_CaseInsensitive comp;
  11610. strings.sort (comp);
  11611. }
  11612. else
  11613. {
  11614. InternalStringArrayComparator_CaseSensitive comp;
  11615. strings.sort (comp);
  11616. }
  11617. }
  11618. void StringArray::move (const int currentIndex, int newIndex) throw()
  11619. {
  11620. strings.move (currentIndex, newIndex);
  11621. }
  11622. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11623. {
  11624. const int last = (numberToJoin < 0) ? size()
  11625. : jmin (size(), start + numberToJoin);
  11626. if (start < 0)
  11627. start = 0;
  11628. if (start >= last)
  11629. return String::empty;
  11630. if (start == last - 1)
  11631. return strings.getReference (start);
  11632. const int separatorLen = separator.length();
  11633. int charsNeeded = separatorLen * (last - start - 1);
  11634. for (int i = start; i < last; ++i)
  11635. charsNeeded += strings.getReference(i).length();
  11636. String result;
  11637. result.preallocateStorage (charsNeeded);
  11638. juce_wchar* dest = result;
  11639. while (start < last)
  11640. {
  11641. const String& s = strings.getReference (start);
  11642. const int len = s.length();
  11643. if (len > 0)
  11644. {
  11645. s.copyToUnicode (dest, len);
  11646. dest += len;
  11647. }
  11648. if (++start < last && separatorLen > 0)
  11649. {
  11650. separator.copyToUnicode (dest, separatorLen);
  11651. dest += separatorLen;
  11652. }
  11653. }
  11654. *dest = 0;
  11655. return result;
  11656. }
  11657. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11658. {
  11659. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11660. }
  11661. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11662. {
  11663. int num = 0;
  11664. if (text.isNotEmpty())
  11665. {
  11666. bool insideQuotes = false;
  11667. juce_wchar currentQuoteChar = 0;
  11668. int i = 0;
  11669. int tokenStart = 0;
  11670. for (;;)
  11671. {
  11672. const juce_wchar c = text[i];
  11673. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11674. if (! isBreak)
  11675. {
  11676. if (quoteCharacters.containsChar (c))
  11677. {
  11678. if (insideQuotes)
  11679. {
  11680. // only break out of quotes-mode if we find a matching quote to the
  11681. // one that we opened with..
  11682. if (currentQuoteChar == c)
  11683. insideQuotes = false;
  11684. }
  11685. else
  11686. {
  11687. insideQuotes = true;
  11688. currentQuoteChar = c;
  11689. }
  11690. }
  11691. }
  11692. else
  11693. {
  11694. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11695. ++num;
  11696. tokenStart = i + 1;
  11697. }
  11698. if (c == 0)
  11699. break;
  11700. ++i;
  11701. }
  11702. }
  11703. return num;
  11704. }
  11705. int StringArray::addLines (const String& sourceText)
  11706. {
  11707. int numLines = 0;
  11708. const juce_wchar* text = sourceText;
  11709. while (*text != 0)
  11710. {
  11711. const juce_wchar* const startOfLine = text;
  11712. while (*text != 0)
  11713. {
  11714. if (*text == '\r')
  11715. {
  11716. ++text;
  11717. if (*text == '\n')
  11718. ++text;
  11719. break;
  11720. }
  11721. if (*text == '\n')
  11722. {
  11723. ++text;
  11724. break;
  11725. }
  11726. ++text;
  11727. }
  11728. const juce_wchar* endOfLine = text;
  11729. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11730. --endOfLine;
  11731. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11732. --endOfLine;
  11733. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11734. ++numLines;
  11735. }
  11736. return numLines;
  11737. }
  11738. void StringArray::removeDuplicates (const bool ignoreCase)
  11739. {
  11740. for (int i = 0; i < size() - 1; ++i)
  11741. {
  11742. const String s (strings.getReference(i));
  11743. int nextIndex = i + 1;
  11744. for (;;)
  11745. {
  11746. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11747. if (nextIndex < 0)
  11748. break;
  11749. strings.remove (nextIndex);
  11750. }
  11751. }
  11752. }
  11753. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11754. const bool appendNumberToFirstInstance,
  11755. const juce_wchar* preNumberString,
  11756. const juce_wchar* postNumberString)
  11757. {
  11758. if (preNumberString == 0)
  11759. preNumberString = L" (";
  11760. if (postNumberString == 0)
  11761. postNumberString = L")";
  11762. for (int i = 0; i < size() - 1; ++i)
  11763. {
  11764. String& s = strings.getReference(i);
  11765. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11766. if (nextIndex >= 0)
  11767. {
  11768. const String original (s);
  11769. int number = 0;
  11770. if (appendNumberToFirstInstance)
  11771. s = original + preNumberString + String (++number) + postNumberString;
  11772. else
  11773. ++number;
  11774. while (nextIndex >= 0)
  11775. {
  11776. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11777. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11778. }
  11779. }
  11780. }
  11781. }
  11782. void StringArray::minimiseStorageOverheads()
  11783. {
  11784. strings.minimiseStorageOverheads();
  11785. }
  11786. END_JUCE_NAMESPACE
  11787. /*** End of inlined file: juce_StringArray.cpp ***/
  11788. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11789. BEGIN_JUCE_NAMESPACE
  11790. StringPairArray::StringPairArray (const bool ignoreCase_)
  11791. : ignoreCase (ignoreCase_)
  11792. {
  11793. }
  11794. StringPairArray::StringPairArray (const StringPairArray& other)
  11795. : keys (other.keys),
  11796. values (other.values),
  11797. ignoreCase (other.ignoreCase)
  11798. {
  11799. }
  11800. StringPairArray::~StringPairArray()
  11801. {
  11802. }
  11803. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11804. {
  11805. keys = other.keys;
  11806. values = other.values;
  11807. return *this;
  11808. }
  11809. bool StringPairArray::operator== (const StringPairArray& other) const
  11810. {
  11811. for (int i = keys.size(); --i >= 0;)
  11812. if (other [keys[i]] != values[i])
  11813. return false;
  11814. return true;
  11815. }
  11816. bool StringPairArray::operator!= (const StringPairArray& other) const
  11817. {
  11818. return ! operator== (other);
  11819. }
  11820. const String& StringPairArray::operator[] (const String& key) const
  11821. {
  11822. return values [keys.indexOf (key, ignoreCase)];
  11823. }
  11824. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11825. {
  11826. const int i = keys.indexOf (key, ignoreCase);
  11827. if (i >= 0)
  11828. return values[i];
  11829. return defaultReturnValue;
  11830. }
  11831. void StringPairArray::set (const String& key, const String& value)
  11832. {
  11833. const int i = keys.indexOf (key, ignoreCase);
  11834. if (i >= 0)
  11835. {
  11836. values.set (i, value);
  11837. }
  11838. else
  11839. {
  11840. keys.add (key);
  11841. values.add (value);
  11842. }
  11843. }
  11844. void StringPairArray::addArray (const StringPairArray& other)
  11845. {
  11846. for (int i = 0; i < other.size(); ++i)
  11847. set (other.keys[i], other.values[i]);
  11848. }
  11849. void StringPairArray::clear()
  11850. {
  11851. keys.clear();
  11852. values.clear();
  11853. }
  11854. void StringPairArray::remove (const String& key)
  11855. {
  11856. remove (keys.indexOf (key, ignoreCase));
  11857. }
  11858. void StringPairArray::remove (const int index)
  11859. {
  11860. keys.remove (index);
  11861. values.remove (index);
  11862. }
  11863. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11864. {
  11865. ignoreCase = shouldIgnoreCase;
  11866. }
  11867. const String StringPairArray::getDescription() const
  11868. {
  11869. String s;
  11870. for (int i = 0; i < keys.size(); ++i)
  11871. {
  11872. s << keys[i] << " = " << values[i];
  11873. if (i < keys.size())
  11874. s << ", ";
  11875. }
  11876. return s;
  11877. }
  11878. void StringPairArray::minimiseStorageOverheads()
  11879. {
  11880. keys.minimiseStorageOverheads();
  11881. values.minimiseStorageOverheads();
  11882. }
  11883. END_JUCE_NAMESPACE
  11884. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11885. /*** Start of inlined file: juce_StringPool.cpp ***/
  11886. BEGIN_JUCE_NAMESPACE
  11887. StringPool::StringPool() throw() {}
  11888. StringPool::~StringPool() {}
  11889. namespace StringPoolHelpers
  11890. {
  11891. template <class StringType>
  11892. const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11893. {
  11894. int start = 0;
  11895. int end = strings.size();
  11896. for (;;)
  11897. {
  11898. if (start >= end)
  11899. {
  11900. jassert (start <= end);
  11901. strings.insert (start, newString);
  11902. return strings.getReference (start);
  11903. }
  11904. else
  11905. {
  11906. const String& startString = strings.getReference (start);
  11907. if (startString == newString)
  11908. return startString;
  11909. const int halfway = (start + end) >> 1;
  11910. if (halfway == start)
  11911. {
  11912. if (startString.compare (newString) < 0)
  11913. ++start;
  11914. strings.insert (start, newString);
  11915. return strings.getReference (start);
  11916. }
  11917. const int comp = strings.getReference (halfway).compare (newString);
  11918. if (comp == 0)
  11919. return strings.getReference (halfway);
  11920. else if (comp < 0)
  11921. start = halfway;
  11922. else
  11923. end = halfway;
  11924. }
  11925. }
  11926. }
  11927. }
  11928. const juce_wchar* StringPool::getPooledString (const String& s)
  11929. {
  11930. if (s.isEmpty())
  11931. return String::empty;
  11932. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11933. }
  11934. const juce_wchar* StringPool::getPooledString (const char* const s)
  11935. {
  11936. if (s == 0 || *s == 0)
  11937. return String::empty;
  11938. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11939. }
  11940. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11941. {
  11942. if (s == 0 || *s == 0)
  11943. return String::empty;
  11944. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11945. }
  11946. int StringPool::size() const throw()
  11947. {
  11948. return strings.size();
  11949. }
  11950. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11951. {
  11952. return strings [index];
  11953. }
  11954. END_JUCE_NAMESPACE
  11955. /*** End of inlined file: juce_StringPool.cpp ***/
  11956. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11957. BEGIN_JUCE_NAMESPACE
  11958. XmlDocument::XmlDocument (const String& documentText)
  11959. : originalText (documentText),
  11960. ignoreEmptyTextElements (true)
  11961. {
  11962. }
  11963. XmlDocument::XmlDocument (const File& file)
  11964. : ignoreEmptyTextElements (true),
  11965. inputSource (new FileInputSource (file))
  11966. {
  11967. }
  11968. XmlDocument::~XmlDocument()
  11969. {
  11970. }
  11971. XmlElement* XmlDocument::parse (const File& file)
  11972. {
  11973. XmlDocument doc (file);
  11974. return doc.getDocumentElement();
  11975. }
  11976. XmlElement* XmlDocument::parse (const String& xmlData)
  11977. {
  11978. XmlDocument doc (xmlData);
  11979. return doc.getDocumentElement();
  11980. }
  11981. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11982. {
  11983. inputSource = newSource;
  11984. }
  11985. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11986. {
  11987. ignoreEmptyTextElements = shouldBeIgnored;
  11988. }
  11989. namespace XmlIdentifierChars
  11990. {
  11991. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11992. {
  11993. return CharacterFunctions::isLetterOrDigit (c)
  11994. || c == '_' || c == '-' || c == ':' || c == '.';
  11995. }
  11996. bool isIdentifierChar (const juce_wchar c) throw()
  11997. {
  11998. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11999. return (c < numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  12000. : isIdentifierCharSlow (c);
  12001. }
  12002. /*static void generateIdentifierCharConstants()
  12003. {
  12004. uint32 n[8];
  12005. zerostruct (n);
  12006. for (int i = 0; i < 256; ++i)
  12007. if (isIdentifierCharSlow (i))
  12008. n[i >> 5] |= (1 << (i & 31));
  12009. String s;
  12010. for (int i = 0; i < 8; ++i)
  12011. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  12012. DBG (s);
  12013. }*/
  12014. }
  12015. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  12016. {
  12017. String textToParse (originalText);
  12018. if (textToParse.isEmpty() && inputSource != 0)
  12019. {
  12020. ScopedPointer <InputStream> in (inputSource->createInputStream());
  12021. if (in != 0)
  12022. {
  12023. MemoryOutputStream data;
  12024. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  12025. textToParse = data.toString();
  12026. if (! onlyReadOuterDocumentElement)
  12027. originalText = textToParse;
  12028. }
  12029. }
  12030. input = textToParse;
  12031. lastError = String::empty;
  12032. errorOccurred = false;
  12033. outOfData = false;
  12034. needToLoadDTD = true;
  12035. if (textToParse.isEmpty())
  12036. {
  12037. lastError = "not enough input";
  12038. }
  12039. else
  12040. {
  12041. skipHeader();
  12042. if (input != 0)
  12043. {
  12044. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  12045. if (! errorOccurred)
  12046. return result.release();
  12047. }
  12048. else
  12049. {
  12050. lastError = "incorrect xml header";
  12051. }
  12052. }
  12053. return 0;
  12054. }
  12055. const String& XmlDocument::getLastParseError() const throw()
  12056. {
  12057. return lastError;
  12058. }
  12059. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  12060. {
  12061. lastError = desc;
  12062. errorOccurred = ! carryOn;
  12063. }
  12064. const String XmlDocument::getFileContents (const String& filename) const
  12065. {
  12066. if (inputSource != 0)
  12067. {
  12068. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  12069. if (in != 0)
  12070. return in->readEntireStreamAsString();
  12071. }
  12072. return String::empty;
  12073. }
  12074. juce_wchar XmlDocument::readNextChar() throw()
  12075. {
  12076. if (*input != 0)
  12077. return *input++;
  12078. outOfData = true;
  12079. return 0;
  12080. }
  12081. int XmlDocument::findNextTokenLength() throw()
  12082. {
  12083. int len = 0;
  12084. juce_wchar c = *input;
  12085. while (XmlIdentifierChars::isIdentifierChar (c))
  12086. c = input [++len];
  12087. return len;
  12088. }
  12089. void XmlDocument::skipHeader()
  12090. {
  12091. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  12092. if (found != 0)
  12093. {
  12094. input = found;
  12095. input = CharacterFunctions::find (input, JUCE_T("?>"));
  12096. if (input == 0)
  12097. return;
  12098. input += 2;
  12099. }
  12100. skipNextWhiteSpace();
  12101. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  12102. if (docType == 0)
  12103. return;
  12104. input = docType + 9;
  12105. int n = 1;
  12106. while (n > 0)
  12107. {
  12108. const juce_wchar c = readNextChar();
  12109. if (outOfData)
  12110. return;
  12111. if (c == '<')
  12112. ++n;
  12113. else if (c == '>')
  12114. --n;
  12115. }
  12116. docType += 9;
  12117. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  12118. }
  12119. void XmlDocument::skipNextWhiteSpace()
  12120. {
  12121. for (;;)
  12122. {
  12123. juce_wchar c = *input;
  12124. while (CharacterFunctions::isWhitespace (c))
  12125. c = *++input;
  12126. if (c == 0)
  12127. {
  12128. outOfData = true;
  12129. break;
  12130. }
  12131. else if (c == '<')
  12132. {
  12133. if (input[1] == '!'
  12134. && input[2] == '-'
  12135. && input[3] == '-')
  12136. {
  12137. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12138. if (closeComment == 0)
  12139. {
  12140. outOfData = true;
  12141. break;
  12142. }
  12143. input = closeComment + 3;
  12144. continue;
  12145. }
  12146. else if (input[1] == '?')
  12147. {
  12148. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12149. if (closeBracket == 0)
  12150. {
  12151. outOfData = true;
  12152. break;
  12153. }
  12154. input = closeBracket + 2;
  12155. continue;
  12156. }
  12157. }
  12158. break;
  12159. }
  12160. }
  12161. void XmlDocument::readQuotedString (String& result)
  12162. {
  12163. const juce_wchar quote = readNextChar();
  12164. while (! outOfData)
  12165. {
  12166. const juce_wchar c = readNextChar();
  12167. if (c == quote)
  12168. break;
  12169. if (c == '&')
  12170. {
  12171. --input;
  12172. readEntity (result);
  12173. }
  12174. else
  12175. {
  12176. --input;
  12177. const juce_wchar* const start = input;
  12178. for (;;)
  12179. {
  12180. const juce_wchar character = *input;
  12181. if (character == quote)
  12182. {
  12183. result.append (start, (int) (input - start));
  12184. ++input;
  12185. return;
  12186. }
  12187. else if (character == '&')
  12188. {
  12189. result.append (start, (int) (input - start));
  12190. break;
  12191. }
  12192. else if (character == 0)
  12193. {
  12194. outOfData = true;
  12195. setLastError ("unmatched quotes", false);
  12196. break;
  12197. }
  12198. ++input;
  12199. }
  12200. }
  12201. }
  12202. }
  12203. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12204. {
  12205. XmlElement* node = 0;
  12206. skipNextWhiteSpace();
  12207. if (outOfData)
  12208. return 0;
  12209. input = CharacterFunctions::find (input, JUCE_T("<"));
  12210. if (input != 0)
  12211. {
  12212. ++input;
  12213. int tagLen = findNextTokenLength();
  12214. if (tagLen == 0)
  12215. {
  12216. // no tag name - but allow for a gap after the '<' before giving an error
  12217. skipNextWhiteSpace();
  12218. tagLen = findNextTokenLength();
  12219. if (tagLen == 0)
  12220. {
  12221. setLastError ("tag name missing", false);
  12222. return node;
  12223. }
  12224. }
  12225. node = new XmlElement (String (input, tagLen));
  12226. input += tagLen;
  12227. XmlElement::XmlAttributeNode* lastAttribute = 0;
  12228. // look for attributes
  12229. for (;;)
  12230. {
  12231. skipNextWhiteSpace();
  12232. const juce_wchar c = *input;
  12233. // empty tag..
  12234. if (c == '/' && input[1] == '>')
  12235. {
  12236. input += 2;
  12237. break;
  12238. }
  12239. // parse the guts of the element..
  12240. if (c == '>')
  12241. {
  12242. ++input;
  12243. if (alsoParseSubElements)
  12244. readChildElements (node);
  12245. break;
  12246. }
  12247. // get an attribute..
  12248. if (XmlIdentifierChars::isIdentifierChar (c))
  12249. {
  12250. const int attNameLen = findNextTokenLength();
  12251. if (attNameLen > 0)
  12252. {
  12253. const juce_wchar* attNameStart = input;
  12254. input += attNameLen;
  12255. skipNextWhiteSpace();
  12256. if (readNextChar() == '=')
  12257. {
  12258. skipNextWhiteSpace();
  12259. const juce_wchar nextChar = *input;
  12260. if (nextChar == '"' || nextChar == '\'')
  12261. {
  12262. XmlElement::XmlAttributeNode* const newAtt
  12263. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12264. String::empty);
  12265. readQuotedString (newAtt->value);
  12266. if (lastAttribute == 0)
  12267. node->attributes = newAtt;
  12268. else
  12269. lastAttribute->next = newAtt;
  12270. lastAttribute = newAtt;
  12271. continue;
  12272. }
  12273. }
  12274. }
  12275. }
  12276. else
  12277. {
  12278. if (! outOfData)
  12279. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12280. }
  12281. break;
  12282. }
  12283. }
  12284. return node;
  12285. }
  12286. void XmlDocument::readChildElements (XmlElement* parent)
  12287. {
  12288. XmlElement* lastChildNode = 0;
  12289. for (;;)
  12290. {
  12291. const juce_wchar* const preWhitespaceInput = input;
  12292. skipNextWhiteSpace();
  12293. if (outOfData)
  12294. {
  12295. setLastError ("unmatched tags", false);
  12296. break;
  12297. }
  12298. if (*input == '<')
  12299. {
  12300. if (input[1] == '/')
  12301. {
  12302. // our close tag..
  12303. input = CharacterFunctions::find (input, JUCE_T(">"));
  12304. ++input;
  12305. break;
  12306. }
  12307. else if (input[1] == '!'
  12308. && input[2] == '['
  12309. && input[3] == 'C'
  12310. && input[4] == 'D'
  12311. && input[5] == 'A'
  12312. && input[6] == 'T'
  12313. && input[7] == 'A'
  12314. && input[8] == '[')
  12315. {
  12316. input += 9;
  12317. const juce_wchar* const inputStart = input;
  12318. int len = 0;
  12319. for (;;)
  12320. {
  12321. if (*input == 0)
  12322. {
  12323. setLastError ("unterminated CDATA section", false);
  12324. outOfData = true;
  12325. break;
  12326. }
  12327. else if (input[0] == ']'
  12328. && input[1] == ']'
  12329. && input[2] == '>')
  12330. {
  12331. input += 3;
  12332. break;
  12333. }
  12334. ++input;
  12335. ++len;
  12336. }
  12337. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  12338. if (lastChildNode != 0)
  12339. lastChildNode->nextElement = e;
  12340. else
  12341. parent->addChildElement (e);
  12342. lastChildNode = e;
  12343. }
  12344. else
  12345. {
  12346. // this is some other element, so parse and add it..
  12347. XmlElement* const n = readNextElement (true);
  12348. if (n != 0)
  12349. {
  12350. if (lastChildNode == 0)
  12351. parent->addChildElement (n);
  12352. else
  12353. lastChildNode->nextElement = n;
  12354. lastChildNode = n;
  12355. }
  12356. else
  12357. {
  12358. return;
  12359. }
  12360. }
  12361. }
  12362. else // must be a character block
  12363. {
  12364. input = preWhitespaceInput; // roll back to include the leading whitespace
  12365. String textElementContent;
  12366. for (;;)
  12367. {
  12368. const juce_wchar c = *input;
  12369. if (c == '<')
  12370. break;
  12371. if (c == 0)
  12372. {
  12373. setLastError ("unmatched tags", false);
  12374. outOfData = true;
  12375. return;
  12376. }
  12377. if (c == '&')
  12378. {
  12379. String entity;
  12380. readEntity (entity);
  12381. if (entity.startsWithChar ('<') && entity [1] != 0)
  12382. {
  12383. const juce_wchar* const oldInput = input;
  12384. const bool oldOutOfData = outOfData;
  12385. input = entity;
  12386. outOfData = false;
  12387. for (;;)
  12388. {
  12389. XmlElement* const n = readNextElement (true);
  12390. if (n == 0)
  12391. break;
  12392. if (lastChildNode == 0)
  12393. parent->addChildElement (n);
  12394. else
  12395. lastChildNode->nextElement = n;
  12396. lastChildNode = n;
  12397. }
  12398. input = oldInput;
  12399. outOfData = oldOutOfData;
  12400. }
  12401. else
  12402. {
  12403. textElementContent += entity;
  12404. }
  12405. }
  12406. else
  12407. {
  12408. const juce_wchar* start = input;
  12409. int len = 0;
  12410. for (;;)
  12411. {
  12412. const juce_wchar nextChar = *input;
  12413. if (nextChar == '<' || nextChar == '&')
  12414. {
  12415. break;
  12416. }
  12417. else if (nextChar == 0)
  12418. {
  12419. setLastError ("unmatched tags", false);
  12420. outOfData = true;
  12421. return;
  12422. }
  12423. ++input;
  12424. ++len;
  12425. }
  12426. textElementContent.append (start, len);
  12427. }
  12428. }
  12429. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12430. {
  12431. XmlElement* const textElement = XmlElement::createTextElement (textElementContent);
  12432. if (lastChildNode != 0)
  12433. lastChildNode->nextElement = textElement;
  12434. else
  12435. parent->addChildElement (textElement);
  12436. lastChildNode = textElement;
  12437. }
  12438. }
  12439. }
  12440. }
  12441. void XmlDocument::readEntity (String& result)
  12442. {
  12443. // skip over the ampersand
  12444. ++input;
  12445. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12446. {
  12447. input += 4;
  12448. result += '&';
  12449. }
  12450. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12451. {
  12452. input += 5;
  12453. result += '"';
  12454. }
  12455. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12456. {
  12457. input += 5;
  12458. result += '\'';
  12459. }
  12460. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12461. {
  12462. input += 3;
  12463. result += '<';
  12464. }
  12465. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12466. {
  12467. input += 3;
  12468. result += '>';
  12469. }
  12470. else if (*input == '#')
  12471. {
  12472. int charCode = 0;
  12473. ++input;
  12474. if (*input == 'x' || *input == 'X')
  12475. {
  12476. ++input;
  12477. int numChars = 0;
  12478. while (input[0] != ';')
  12479. {
  12480. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12481. if (hexValue < 0 || ++numChars > 8)
  12482. {
  12483. setLastError ("illegal escape sequence", true);
  12484. break;
  12485. }
  12486. charCode = (charCode << 4) | hexValue;
  12487. ++input;
  12488. }
  12489. ++input;
  12490. }
  12491. else if (input[0] >= '0' && input[0] <= '9')
  12492. {
  12493. int numChars = 0;
  12494. while (input[0] != ';')
  12495. {
  12496. if (++numChars > 12)
  12497. {
  12498. setLastError ("illegal escape sequence", true);
  12499. break;
  12500. }
  12501. charCode = charCode * 10 + (input[0] - '0');
  12502. ++input;
  12503. }
  12504. ++input;
  12505. }
  12506. else
  12507. {
  12508. setLastError ("illegal escape sequence", true);
  12509. result += '&';
  12510. return;
  12511. }
  12512. result << (juce_wchar) charCode;
  12513. }
  12514. else
  12515. {
  12516. const juce_wchar* const entityNameStart = input;
  12517. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12518. if (closingSemiColon == 0)
  12519. {
  12520. outOfData = true;
  12521. result += '&';
  12522. }
  12523. else
  12524. {
  12525. input = closingSemiColon + 1;
  12526. result += expandExternalEntity (String (entityNameStart,
  12527. (int) (closingSemiColon - entityNameStart)));
  12528. }
  12529. }
  12530. }
  12531. const String XmlDocument::expandEntity (const String& ent)
  12532. {
  12533. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12534. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12535. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12536. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12537. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12538. if (ent[0] == '#')
  12539. {
  12540. if (ent[1] == 'x' || ent[1] == 'X')
  12541. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12542. if (ent[1] >= '0' && ent[1] <= '9')
  12543. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12544. setLastError ("illegal escape sequence", false);
  12545. return String::charToString ('&');
  12546. }
  12547. return expandExternalEntity (ent);
  12548. }
  12549. const String XmlDocument::expandExternalEntity (const String& entity)
  12550. {
  12551. if (needToLoadDTD)
  12552. {
  12553. if (dtdText.isNotEmpty())
  12554. {
  12555. dtdText = dtdText.trimCharactersAtEnd (">");
  12556. tokenisedDTD.addTokens (dtdText, true);
  12557. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12558. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12559. {
  12560. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12561. tokenisedDTD.clear();
  12562. tokenisedDTD.addTokens (getFileContents (fn), true);
  12563. }
  12564. else
  12565. {
  12566. tokenisedDTD.clear();
  12567. const int openBracket = dtdText.indexOfChar ('[');
  12568. if (openBracket > 0)
  12569. {
  12570. const int closeBracket = dtdText.lastIndexOfChar (']');
  12571. if (closeBracket > openBracket)
  12572. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12573. closeBracket), true);
  12574. }
  12575. }
  12576. for (int i = tokenisedDTD.size(); --i >= 0;)
  12577. {
  12578. if (tokenisedDTD[i].startsWithChar ('%')
  12579. && tokenisedDTD[i].endsWithChar (';'))
  12580. {
  12581. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12582. StringArray newToks;
  12583. newToks.addTokens (parsed, true);
  12584. tokenisedDTD.remove (i);
  12585. for (int j = newToks.size(); --j >= 0;)
  12586. tokenisedDTD.insert (i, newToks[j]);
  12587. }
  12588. }
  12589. }
  12590. needToLoadDTD = false;
  12591. }
  12592. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12593. {
  12594. if (tokenisedDTD[i] == entity)
  12595. {
  12596. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12597. {
  12598. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12599. // check for sub-entities..
  12600. int ampersand = ent.indexOfChar ('&');
  12601. while (ampersand >= 0)
  12602. {
  12603. const int semiColon = ent.indexOf (i + 1, ";");
  12604. if (semiColon < 0)
  12605. {
  12606. setLastError ("entity without terminating semi-colon", false);
  12607. break;
  12608. }
  12609. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12610. ent = ent.substring (0, ampersand)
  12611. + resolved
  12612. + ent.substring (semiColon + 1);
  12613. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12614. }
  12615. return ent;
  12616. }
  12617. }
  12618. }
  12619. setLastError ("unknown entity", true);
  12620. return entity;
  12621. }
  12622. const String XmlDocument::getParameterEntity (const String& entity)
  12623. {
  12624. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12625. {
  12626. if (tokenisedDTD[i] == entity)
  12627. {
  12628. if (tokenisedDTD [i - 1] == "%"
  12629. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12630. {
  12631. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12632. if (ent.equalsIgnoreCase ("system"))
  12633. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12634. else
  12635. return ent.trim().unquoted();
  12636. }
  12637. }
  12638. }
  12639. return entity;
  12640. }
  12641. END_JUCE_NAMESPACE
  12642. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12643. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12644. BEGIN_JUCE_NAMESPACE
  12645. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12646. : name (other.name),
  12647. value (other.value),
  12648. next (0)
  12649. {
  12650. }
  12651. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12652. : name (name_),
  12653. value (value_),
  12654. next (0)
  12655. {
  12656. #if JUCE_DEBUG
  12657. // this checks whether the attribute name string contains any illegals characters..
  12658. for (const juce_wchar* t = name; *t != 0; ++t)
  12659. jassert (CharacterFunctions::isLetterOrDigit (*t) || *t == '_' || *t == '-' || *t == ':');
  12660. #endif
  12661. }
  12662. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12663. {
  12664. return name.equalsIgnoreCase (nameToMatch);
  12665. }
  12666. XmlElement::XmlElement (const String& tagName_) throw()
  12667. : tagName (tagName_),
  12668. firstChildElement (0),
  12669. nextElement (0),
  12670. attributes (0)
  12671. {
  12672. // the tag name mustn't be empty, or it'll look like a text element!
  12673. jassert (tagName_.containsNonWhitespaceChars())
  12674. // The tag can't contain spaces or other characters that would create invalid XML!
  12675. jassert (! tagName_.containsAnyOf (" <>/&"));
  12676. }
  12677. XmlElement::XmlElement (int /*dummy*/) throw()
  12678. : firstChildElement (0),
  12679. nextElement (0),
  12680. attributes (0)
  12681. {
  12682. }
  12683. XmlElement::XmlElement (const XmlElement& other)
  12684. : tagName (other.tagName),
  12685. firstChildElement (0),
  12686. nextElement (0),
  12687. attributes (0)
  12688. {
  12689. copyChildrenAndAttributesFrom (other);
  12690. }
  12691. XmlElement& XmlElement::operator= (const XmlElement& other)
  12692. {
  12693. if (this != &other)
  12694. {
  12695. removeAllAttributes();
  12696. deleteAllChildElements();
  12697. tagName = other.tagName;
  12698. copyChildrenAndAttributesFrom (other);
  12699. }
  12700. return *this;
  12701. }
  12702. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12703. {
  12704. XmlElement* child = other.firstChildElement;
  12705. XmlElement* lastChild = 0;
  12706. while (child != 0)
  12707. {
  12708. XmlElement* const copiedChild = new XmlElement (*child);
  12709. if (lastChild != 0)
  12710. lastChild->nextElement = copiedChild;
  12711. else
  12712. firstChildElement = copiedChild;
  12713. lastChild = copiedChild;
  12714. child = child->nextElement;
  12715. }
  12716. const XmlAttributeNode* att = other.attributes;
  12717. XmlAttributeNode* lastAtt = 0;
  12718. while (att != 0)
  12719. {
  12720. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12721. if (lastAtt != 0)
  12722. lastAtt->next = newAtt;
  12723. else
  12724. attributes = newAtt;
  12725. lastAtt = newAtt;
  12726. att = att->next;
  12727. }
  12728. }
  12729. XmlElement::~XmlElement() throw()
  12730. {
  12731. XmlElement* child = firstChildElement;
  12732. while (child != 0)
  12733. {
  12734. XmlElement* const nextChild = child->nextElement;
  12735. delete child;
  12736. child = nextChild;
  12737. }
  12738. XmlAttributeNode* att = attributes;
  12739. while (att != 0)
  12740. {
  12741. XmlAttributeNode* const nextAtt = att->next;
  12742. delete att;
  12743. att = nextAtt;
  12744. }
  12745. }
  12746. namespace XmlOutputFunctions
  12747. {
  12748. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12749. {
  12750. if ((character >= 'a' && character <= 'z')
  12751. || (character >= 'A' && character <= 'Z')
  12752. || (character >= '0' && character <= '9'))
  12753. return true;
  12754. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12755. do
  12756. {
  12757. if (((juce_wchar) (uint8) *t) == character)
  12758. return true;
  12759. }
  12760. while (*++t != 0);
  12761. return false;
  12762. }
  12763. void generateLegalCharConstants()
  12764. {
  12765. uint8 n[32];
  12766. zerostruct (n);
  12767. for (int i = 0; i < 256; ++i)
  12768. if (isLegalXmlCharSlow (i))
  12769. n[i >> 3] |= (1 << (i & 7));
  12770. String s;
  12771. for (int i = 0; i < 32; ++i)
  12772. s << (int) n[i] << ", ";
  12773. DBG (s);
  12774. }*/
  12775. bool isLegalXmlChar (const uint32 c) throw()
  12776. {
  12777. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12778. return c < sizeof (legalChars) * 8
  12779. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12780. }
  12781. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12782. {
  12783. const juce_wchar* t = text;
  12784. for (;;)
  12785. {
  12786. const juce_wchar character = *t++;
  12787. if (character == 0)
  12788. break;
  12789. if (isLegalXmlChar ((uint32) character))
  12790. {
  12791. outputStream << (char) character;
  12792. }
  12793. else
  12794. {
  12795. switch (character)
  12796. {
  12797. case '&': outputStream << "&amp;"; break;
  12798. case '"': outputStream << "&quot;"; break;
  12799. case '>': outputStream << "&gt;"; break;
  12800. case '<': outputStream << "&lt;"; break;
  12801. case '\n':
  12802. case '\r':
  12803. if (! changeNewLines)
  12804. {
  12805. outputStream << (char) character;
  12806. break;
  12807. }
  12808. // Note: deliberate fall-through here!
  12809. default:
  12810. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12811. break;
  12812. }
  12813. }
  12814. }
  12815. }
  12816. void writeSpaces (OutputStream& out, int numSpaces)
  12817. {
  12818. if (numSpaces > 0)
  12819. {
  12820. const char blanks[] = " ";
  12821. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12822. while (numSpaces > blankSize)
  12823. {
  12824. out.write (blanks, blankSize);
  12825. numSpaces -= blankSize;
  12826. }
  12827. out.write (blanks, numSpaces);
  12828. }
  12829. }
  12830. void writeNewLine (OutputStream& out)
  12831. {
  12832. out.write ("\r\n", 2);
  12833. }
  12834. }
  12835. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12836. const int indentationLevel,
  12837. const int lineWrapLength) const
  12838. {
  12839. using namespace XmlOutputFunctions;
  12840. writeSpaces (outputStream, indentationLevel);
  12841. if (! isTextElement())
  12842. {
  12843. outputStream.writeByte ('<');
  12844. outputStream << tagName;
  12845. {
  12846. const int attIndent = indentationLevel + tagName.length() + 1;
  12847. int lineLen = 0;
  12848. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12849. {
  12850. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12851. {
  12852. writeNewLine (outputStream);
  12853. writeSpaces (outputStream, attIndent);
  12854. lineLen = 0;
  12855. }
  12856. const int64 startPos = outputStream.getPosition();
  12857. outputStream.writeByte (' ');
  12858. outputStream << att->name;
  12859. outputStream.write ("=\"", 2);
  12860. escapeIllegalXmlChars (outputStream, att->value, true);
  12861. outputStream.writeByte ('"');
  12862. lineLen += (int) (outputStream.getPosition() - startPos);
  12863. }
  12864. }
  12865. if (firstChildElement != 0)
  12866. {
  12867. outputStream.writeByte ('>');
  12868. XmlElement* child = firstChildElement;
  12869. bool lastWasTextNode = false;
  12870. while (child != 0)
  12871. {
  12872. if (child->isTextElement())
  12873. {
  12874. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12875. lastWasTextNode = true;
  12876. }
  12877. else
  12878. {
  12879. if (indentationLevel >= 0 && ! lastWasTextNode)
  12880. writeNewLine (outputStream);
  12881. child->writeElementAsText (outputStream,
  12882. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12883. lastWasTextNode = false;
  12884. }
  12885. child = child->nextElement;
  12886. }
  12887. if (indentationLevel >= 0 && ! lastWasTextNode)
  12888. {
  12889. writeNewLine (outputStream);
  12890. writeSpaces (outputStream, indentationLevel);
  12891. }
  12892. outputStream.write ("</", 2);
  12893. outputStream << tagName;
  12894. outputStream.writeByte ('>');
  12895. }
  12896. else
  12897. {
  12898. outputStream.write ("/>", 2);
  12899. }
  12900. }
  12901. else
  12902. {
  12903. escapeIllegalXmlChars (outputStream, getText(), false);
  12904. }
  12905. }
  12906. const String XmlElement::createDocument (const String& dtdToUse,
  12907. const bool allOnOneLine,
  12908. const bool includeXmlHeader,
  12909. const String& encodingType,
  12910. const int lineWrapLength) const
  12911. {
  12912. MemoryOutputStream mem (2048);
  12913. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12914. return mem.toUTF8();
  12915. }
  12916. void XmlElement::writeToStream (OutputStream& output,
  12917. const String& dtdToUse,
  12918. const bool allOnOneLine,
  12919. const bool includeXmlHeader,
  12920. const String& encodingType,
  12921. const int lineWrapLength) const
  12922. {
  12923. using namespace XmlOutputFunctions;
  12924. if (includeXmlHeader)
  12925. {
  12926. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12927. if (allOnOneLine)
  12928. {
  12929. output.writeByte (' ');
  12930. }
  12931. else
  12932. {
  12933. writeNewLine (output);
  12934. writeNewLine (output);
  12935. }
  12936. }
  12937. if (dtdToUse.isNotEmpty())
  12938. {
  12939. output << dtdToUse;
  12940. if (allOnOneLine)
  12941. output.writeByte (' ');
  12942. else
  12943. writeNewLine (output);
  12944. }
  12945. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12946. if (! allOnOneLine)
  12947. writeNewLine (output);
  12948. }
  12949. bool XmlElement::writeToFile (const File& file,
  12950. const String& dtdToUse,
  12951. const String& encodingType,
  12952. const int lineWrapLength) const
  12953. {
  12954. if (file.hasWriteAccess())
  12955. {
  12956. TemporaryFile tempFile (file);
  12957. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12958. if (out != 0)
  12959. {
  12960. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12961. out = 0;
  12962. return tempFile.overwriteTargetFileWithTemporary();
  12963. }
  12964. }
  12965. return false;
  12966. }
  12967. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12968. {
  12969. #if JUCE_DEBUG
  12970. // if debugging, check that the case is actually the same, because
  12971. // valid xml is case-sensitive, and although this lets it pass, it's
  12972. // better not to..
  12973. if (tagName.equalsIgnoreCase (tagNameWanted))
  12974. {
  12975. jassert (tagName == tagNameWanted);
  12976. return true;
  12977. }
  12978. else
  12979. {
  12980. return false;
  12981. }
  12982. #else
  12983. return tagName.equalsIgnoreCase (tagNameWanted);
  12984. #endif
  12985. }
  12986. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12987. {
  12988. XmlElement* e = nextElement;
  12989. while (e != 0 && ! e->hasTagName (requiredTagName))
  12990. e = e->nextElement;
  12991. return e;
  12992. }
  12993. int XmlElement::getNumAttributes() const throw()
  12994. {
  12995. int count = 0;
  12996. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  12997. ++count;
  12998. return count;
  12999. }
  13000. const String& XmlElement::getAttributeName (const int index) const throw()
  13001. {
  13002. int count = 0;
  13003. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13004. {
  13005. if (count == index)
  13006. return att->name;
  13007. ++count;
  13008. }
  13009. return String::empty;
  13010. }
  13011. const String& XmlElement::getAttributeValue (const int index) const throw()
  13012. {
  13013. int count = 0;
  13014. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13015. {
  13016. if (count == index)
  13017. return att->value;
  13018. ++count;
  13019. }
  13020. return String::empty;
  13021. }
  13022. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  13023. {
  13024. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13025. if (att->hasName (attributeName))
  13026. return true;
  13027. return false;
  13028. }
  13029. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  13030. {
  13031. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13032. if (att->hasName (attributeName))
  13033. return att->value;
  13034. return String::empty;
  13035. }
  13036. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  13037. {
  13038. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13039. if (att->hasName (attributeName))
  13040. return att->value;
  13041. return defaultReturnValue;
  13042. }
  13043. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  13044. {
  13045. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13046. if (att->hasName (attributeName))
  13047. return att->value.getIntValue();
  13048. return defaultReturnValue;
  13049. }
  13050. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  13051. {
  13052. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13053. if (att->hasName (attributeName))
  13054. return att->value.getDoubleValue();
  13055. return defaultReturnValue;
  13056. }
  13057. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  13058. {
  13059. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13060. {
  13061. if (att->hasName (attributeName))
  13062. {
  13063. juce_wchar firstChar = att->value[0];
  13064. if (CharacterFunctions::isWhitespace (firstChar))
  13065. firstChar = att->value.trimStart() [0];
  13066. return firstChar == '1'
  13067. || firstChar == 't'
  13068. || firstChar == 'y'
  13069. || firstChar == 'T'
  13070. || firstChar == 'Y';
  13071. }
  13072. }
  13073. return defaultReturnValue;
  13074. }
  13075. bool XmlElement::compareAttribute (const String& attributeName,
  13076. const String& stringToCompareAgainst,
  13077. const bool ignoreCase) const throw()
  13078. {
  13079. for (const XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13080. if (att->hasName (attributeName))
  13081. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  13082. : att->value == stringToCompareAgainst;
  13083. return false;
  13084. }
  13085. void XmlElement::setAttribute (const String& attributeName, const String& value)
  13086. {
  13087. if (attributes == 0)
  13088. {
  13089. attributes = new XmlAttributeNode (attributeName, value);
  13090. }
  13091. else
  13092. {
  13093. XmlAttributeNode* att = attributes;
  13094. for (;;)
  13095. {
  13096. if (att->hasName (attributeName))
  13097. {
  13098. att->value = value;
  13099. break;
  13100. }
  13101. else if (att->next == 0)
  13102. {
  13103. att->next = new XmlAttributeNode (attributeName, value);
  13104. break;
  13105. }
  13106. att = att->next;
  13107. }
  13108. }
  13109. }
  13110. void XmlElement::setAttribute (const String& attributeName, const int number)
  13111. {
  13112. setAttribute (attributeName, String (number));
  13113. }
  13114. void XmlElement::setAttribute (const String& attributeName, const double number)
  13115. {
  13116. setAttribute (attributeName, String (number));
  13117. }
  13118. void XmlElement::removeAttribute (const String& attributeName) throw()
  13119. {
  13120. XmlAttributeNode* lastAtt = 0;
  13121. for (XmlAttributeNode* att = attributes; att != 0; att = att->next)
  13122. {
  13123. if (att->hasName (attributeName))
  13124. {
  13125. if (lastAtt == 0)
  13126. attributes = att->next;
  13127. else
  13128. lastAtt->next = att->next;
  13129. delete att;
  13130. break;
  13131. }
  13132. lastAtt = att;
  13133. }
  13134. }
  13135. void XmlElement::removeAllAttributes() throw()
  13136. {
  13137. while (attributes != 0)
  13138. {
  13139. XmlAttributeNode* const nextAtt = attributes->next;
  13140. delete attributes;
  13141. attributes = nextAtt;
  13142. }
  13143. }
  13144. int XmlElement::getNumChildElements() const throw()
  13145. {
  13146. int count = 0;
  13147. const XmlElement* child = firstChildElement;
  13148. while (child != 0)
  13149. {
  13150. ++count;
  13151. child = child->nextElement;
  13152. }
  13153. return count;
  13154. }
  13155. XmlElement* XmlElement::getChildElement (const int index) const throw()
  13156. {
  13157. int count = 0;
  13158. XmlElement* child = firstChildElement;
  13159. while (child != 0 && count < index)
  13160. {
  13161. child = child->nextElement;
  13162. ++count;
  13163. }
  13164. return child;
  13165. }
  13166. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  13167. {
  13168. XmlElement* child = firstChildElement;
  13169. while (child != 0)
  13170. {
  13171. if (child->hasTagName (childName))
  13172. break;
  13173. child = child->nextElement;
  13174. }
  13175. return child;
  13176. }
  13177. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  13178. {
  13179. if (newNode != 0)
  13180. {
  13181. if (firstChildElement == 0)
  13182. {
  13183. firstChildElement = newNode;
  13184. }
  13185. else
  13186. {
  13187. XmlElement* child = firstChildElement;
  13188. while (child->nextElement != 0)
  13189. child = child->nextElement;
  13190. child->nextElement = newNode;
  13191. // if this is non-zero, then something's probably
  13192. // gone wrong..
  13193. jassert (newNode->nextElement == 0);
  13194. }
  13195. }
  13196. }
  13197. void XmlElement::insertChildElement (XmlElement* const newNode,
  13198. int indexToInsertAt) throw()
  13199. {
  13200. if (newNode != 0)
  13201. {
  13202. removeChildElement (newNode, false);
  13203. if (indexToInsertAt == 0)
  13204. {
  13205. newNode->nextElement = firstChildElement;
  13206. firstChildElement = newNode;
  13207. }
  13208. else
  13209. {
  13210. if (firstChildElement == 0)
  13211. {
  13212. firstChildElement = newNode;
  13213. }
  13214. else
  13215. {
  13216. if (indexToInsertAt < 0)
  13217. indexToInsertAt = std::numeric_limits<int>::max();
  13218. XmlElement* child = firstChildElement;
  13219. while (child->nextElement != 0 && --indexToInsertAt > 0)
  13220. child = child->nextElement;
  13221. newNode->nextElement = child->nextElement;
  13222. child->nextElement = newNode;
  13223. }
  13224. }
  13225. }
  13226. }
  13227. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  13228. {
  13229. XmlElement* const newElement = new XmlElement (childTagName);
  13230. addChildElement (newElement);
  13231. return newElement;
  13232. }
  13233. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  13234. XmlElement* const newNode) throw()
  13235. {
  13236. if (newNode != 0)
  13237. {
  13238. XmlElement* child = firstChildElement;
  13239. XmlElement* previousNode = 0;
  13240. while (child != 0)
  13241. {
  13242. if (child == currentChildElement)
  13243. {
  13244. if (child != newNode)
  13245. {
  13246. if (previousNode == 0)
  13247. firstChildElement = newNode;
  13248. else
  13249. previousNode->nextElement = newNode;
  13250. newNode->nextElement = child->nextElement;
  13251. delete child;
  13252. }
  13253. return true;
  13254. }
  13255. previousNode = child;
  13256. child = child->nextElement;
  13257. }
  13258. }
  13259. return false;
  13260. }
  13261. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13262. const bool shouldDeleteTheChild) throw()
  13263. {
  13264. if (childToRemove != 0)
  13265. {
  13266. if (firstChildElement == childToRemove)
  13267. {
  13268. firstChildElement = childToRemove->nextElement;
  13269. childToRemove->nextElement = 0;
  13270. }
  13271. else
  13272. {
  13273. XmlElement* child = firstChildElement;
  13274. XmlElement* last = 0;
  13275. while (child != 0)
  13276. {
  13277. if (child == childToRemove)
  13278. {
  13279. if (last == 0)
  13280. firstChildElement = child->nextElement;
  13281. else
  13282. last->nextElement = child->nextElement;
  13283. childToRemove->nextElement = 0;
  13284. break;
  13285. }
  13286. last = child;
  13287. child = child->nextElement;
  13288. }
  13289. }
  13290. if (shouldDeleteTheChild)
  13291. delete childToRemove;
  13292. }
  13293. }
  13294. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13295. const bool ignoreOrderOfAttributes) const throw()
  13296. {
  13297. if (this != other)
  13298. {
  13299. if (other == 0 || tagName != other->tagName)
  13300. return false;
  13301. if (ignoreOrderOfAttributes)
  13302. {
  13303. int totalAtts = 0;
  13304. const XmlAttributeNode* att = attributes;
  13305. while (att != 0)
  13306. {
  13307. if (! other->compareAttribute (att->name, att->value))
  13308. return false;
  13309. att = att->next;
  13310. ++totalAtts;
  13311. }
  13312. if (totalAtts != other->getNumAttributes())
  13313. return false;
  13314. }
  13315. else
  13316. {
  13317. const XmlAttributeNode* thisAtt = attributes;
  13318. const XmlAttributeNode* otherAtt = other->attributes;
  13319. for (;;)
  13320. {
  13321. if (thisAtt == 0 || otherAtt == 0)
  13322. {
  13323. if (thisAtt == otherAtt) // both 0, so it's a match
  13324. break;
  13325. return false;
  13326. }
  13327. if (thisAtt->name != otherAtt->name
  13328. || thisAtt->value != otherAtt->value)
  13329. {
  13330. return false;
  13331. }
  13332. thisAtt = thisAtt->next;
  13333. otherAtt = otherAtt->next;
  13334. }
  13335. }
  13336. const XmlElement* thisChild = firstChildElement;
  13337. const XmlElement* otherChild = other->firstChildElement;
  13338. for (;;)
  13339. {
  13340. if (thisChild == 0 || otherChild == 0)
  13341. {
  13342. if (thisChild == otherChild) // both 0, so it's a match
  13343. break;
  13344. return false;
  13345. }
  13346. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13347. return false;
  13348. thisChild = thisChild->nextElement;
  13349. otherChild = otherChild->nextElement;
  13350. }
  13351. }
  13352. return true;
  13353. }
  13354. void XmlElement::deleteAllChildElements() throw()
  13355. {
  13356. while (firstChildElement != 0)
  13357. {
  13358. XmlElement* const nextChild = firstChildElement->nextElement;
  13359. delete firstChildElement;
  13360. firstChildElement = nextChild;
  13361. }
  13362. }
  13363. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13364. {
  13365. XmlElement* child = firstChildElement;
  13366. while (child != 0)
  13367. {
  13368. if (child->hasTagName (name))
  13369. {
  13370. XmlElement* const nextChild = child->nextElement;
  13371. removeChildElement (child, true);
  13372. child = nextChild;
  13373. }
  13374. else
  13375. {
  13376. child = child->nextElement;
  13377. }
  13378. }
  13379. }
  13380. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13381. {
  13382. const XmlElement* child = firstChildElement;
  13383. while (child != 0)
  13384. {
  13385. if (child == possibleChild)
  13386. return true;
  13387. child = child->nextElement;
  13388. }
  13389. return false;
  13390. }
  13391. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13392. {
  13393. if (this == elementToLookFor || elementToLookFor == 0)
  13394. return 0;
  13395. XmlElement* child = firstChildElement;
  13396. while (child != 0)
  13397. {
  13398. if (elementToLookFor == child)
  13399. return this;
  13400. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13401. if (found != 0)
  13402. return found;
  13403. child = child->nextElement;
  13404. }
  13405. return 0;
  13406. }
  13407. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13408. {
  13409. XmlElement* e = firstChildElement;
  13410. while (e != 0)
  13411. {
  13412. *elems++ = e;
  13413. e = e->nextElement;
  13414. }
  13415. }
  13416. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13417. {
  13418. XmlElement* e = firstChildElement = elems[0];
  13419. for (int i = 1; i < num; ++i)
  13420. {
  13421. e->nextElement = elems[i];
  13422. e = e->nextElement;
  13423. }
  13424. e->nextElement = 0;
  13425. }
  13426. bool XmlElement::isTextElement() const throw()
  13427. {
  13428. return tagName.isEmpty();
  13429. }
  13430. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13431. const String& XmlElement::getText() const throw()
  13432. {
  13433. jassert (isTextElement()); // you're trying to get the text from an element that
  13434. // isn't actually a text element.. If this contains text sub-nodes, you
  13435. // probably want to use getAllSubText instead.
  13436. return getStringAttribute (juce_xmltextContentAttributeName);
  13437. }
  13438. void XmlElement::setText (const String& newText)
  13439. {
  13440. if (isTextElement())
  13441. setAttribute (juce_xmltextContentAttributeName, newText);
  13442. else
  13443. jassertfalse; // you can only change the text in a text element, not a normal one.
  13444. }
  13445. const String XmlElement::getAllSubText() const
  13446. {
  13447. if (isTextElement())
  13448. return getText();
  13449. String result;
  13450. String::Concatenator concatenator (result);
  13451. const XmlElement* child = firstChildElement;
  13452. while (child != 0)
  13453. {
  13454. concatenator.append (child->getAllSubText());
  13455. child = child->nextElement;
  13456. }
  13457. return result;
  13458. }
  13459. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13460. const String& defaultReturnValue) const
  13461. {
  13462. const XmlElement* const child = getChildByName (childTagName);
  13463. if (child != 0)
  13464. return child->getAllSubText();
  13465. return defaultReturnValue;
  13466. }
  13467. XmlElement* XmlElement::createTextElement (const String& text)
  13468. {
  13469. XmlElement* const e = new XmlElement ((int) 0);
  13470. e->setAttribute (juce_xmltextContentAttributeName, text);
  13471. return e;
  13472. }
  13473. void XmlElement::addTextElement (const String& text)
  13474. {
  13475. addChildElement (createTextElement (text));
  13476. }
  13477. void XmlElement::deleteAllTextElements() throw()
  13478. {
  13479. XmlElement* child = firstChildElement;
  13480. while (child != 0)
  13481. {
  13482. XmlElement* const next = child->nextElement;
  13483. if (child->isTextElement())
  13484. removeChildElement (child, true);
  13485. child = next;
  13486. }
  13487. }
  13488. END_JUCE_NAMESPACE
  13489. /*** End of inlined file: juce_XmlElement.cpp ***/
  13490. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13491. BEGIN_JUCE_NAMESPACE
  13492. ReadWriteLock::ReadWriteLock() throw()
  13493. : numWaitingWriters (0),
  13494. numWriters (0),
  13495. writerThreadId (0)
  13496. {
  13497. }
  13498. ReadWriteLock::~ReadWriteLock() throw()
  13499. {
  13500. jassert (readerThreads.size() == 0);
  13501. jassert (numWriters == 0);
  13502. }
  13503. void ReadWriteLock::enterRead() const throw()
  13504. {
  13505. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13506. const ScopedLock sl (accessLock);
  13507. for (;;)
  13508. {
  13509. jassert (readerThreads.size() % 2 == 0);
  13510. int i;
  13511. for (i = 0; i < readerThreads.size(); i += 2)
  13512. if (readerThreads.getUnchecked(i) == threadId)
  13513. break;
  13514. if (i < readerThreads.size()
  13515. || numWriters + numWaitingWriters == 0
  13516. || (threadId == writerThreadId && numWriters > 0))
  13517. {
  13518. if (i < readerThreads.size())
  13519. {
  13520. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13521. }
  13522. else
  13523. {
  13524. readerThreads.add (threadId);
  13525. readerThreads.add ((Thread::ThreadID) 1);
  13526. }
  13527. return;
  13528. }
  13529. const ScopedUnlock ul (accessLock);
  13530. waitEvent.wait (100);
  13531. }
  13532. }
  13533. void ReadWriteLock::exitRead() const throw()
  13534. {
  13535. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13536. const ScopedLock sl (accessLock);
  13537. for (int i = 0; i < readerThreads.size(); i += 2)
  13538. {
  13539. if (readerThreads.getUnchecked(i) == threadId)
  13540. {
  13541. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13542. if (newCount == 0)
  13543. {
  13544. readerThreads.removeRange (i, 2);
  13545. waitEvent.signal();
  13546. }
  13547. else
  13548. {
  13549. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13550. }
  13551. return;
  13552. }
  13553. }
  13554. jassertfalse; // unlocking a lock that wasn't locked..
  13555. }
  13556. void ReadWriteLock::enterWrite() const throw()
  13557. {
  13558. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13559. const ScopedLock sl (accessLock);
  13560. for (;;)
  13561. {
  13562. if (readerThreads.size() + numWriters == 0
  13563. || threadId == writerThreadId
  13564. || (readerThreads.size() == 2
  13565. && readerThreads.getUnchecked(0) == threadId))
  13566. {
  13567. writerThreadId = threadId;
  13568. ++numWriters;
  13569. break;
  13570. }
  13571. ++numWaitingWriters;
  13572. accessLock.exit();
  13573. waitEvent.wait (100);
  13574. accessLock.enter();
  13575. --numWaitingWriters;
  13576. }
  13577. }
  13578. bool ReadWriteLock::tryEnterWrite() const throw()
  13579. {
  13580. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13581. const ScopedLock sl (accessLock);
  13582. if (readerThreads.size() + numWriters == 0
  13583. || threadId == writerThreadId
  13584. || (readerThreads.size() == 2
  13585. && readerThreads.getUnchecked(0) == threadId))
  13586. {
  13587. writerThreadId = threadId;
  13588. ++numWriters;
  13589. return true;
  13590. }
  13591. return false;
  13592. }
  13593. void ReadWriteLock::exitWrite() const throw()
  13594. {
  13595. const ScopedLock sl (accessLock);
  13596. // check this thread actually had the lock..
  13597. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13598. if (--numWriters == 0)
  13599. {
  13600. writerThreadId = 0;
  13601. waitEvent.signal();
  13602. }
  13603. }
  13604. END_JUCE_NAMESPACE
  13605. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13606. /*** Start of inlined file: juce_Thread.cpp ***/
  13607. BEGIN_JUCE_NAMESPACE
  13608. // these functions are implemented in the platform-specific code.
  13609. void* juce_createThread (void* userData);
  13610. void juce_killThread (void* handle);
  13611. bool juce_setThreadPriority (void* handle, int priority);
  13612. void juce_setCurrentThreadName (const String& name);
  13613. #if JUCE_WINDOWS
  13614. void juce_CloseThreadHandle (void* handle);
  13615. #endif
  13616. void Thread::threadEntryPoint (Thread* const thread)
  13617. {
  13618. {
  13619. const ScopedLock sl (runningThreadsLock);
  13620. runningThreads.add (thread);
  13621. }
  13622. JUCE_TRY
  13623. {
  13624. thread->threadId_ = Thread::getCurrentThreadId();
  13625. if (thread->threadName_.isNotEmpty())
  13626. juce_setCurrentThreadName (thread->threadName_);
  13627. if (thread->startSuspensionEvent_.wait (10000))
  13628. {
  13629. if (thread->affinityMask_ != 0)
  13630. setCurrentThreadAffinityMask (thread->affinityMask_);
  13631. thread->run();
  13632. }
  13633. }
  13634. JUCE_CATCH_ALL_ASSERT
  13635. {
  13636. const ScopedLock sl (runningThreadsLock);
  13637. jassert (runningThreads.contains (thread));
  13638. runningThreads.removeValue (thread);
  13639. }
  13640. #if JUCE_WINDOWS
  13641. juce_CloseThreadHandle (thread->threadHandle_);
  13642. #endif
  13643. thread->threadHandle_ = 0;
  13644. thread->threadId_ = 0;
  13645. }
  13646. // used to wrap the incoming call from the platform-specific code
  13647. void JUCE_API juce_threadEntryPoint (void* userData)
  13648. {
  13649. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13650. }
  13651. Thread::Thread (const String& threadName)
  13652. : threadName_ (threadName),
  13653. threadHandle_ (0),
  13654. threadPriority_ (5),
  13655. threadId_ (0),
  13656. affinityMask_ (0),
  13657. threadShouldExit_ (false)
  13658. {
  13659. }
  13660. Thread::~Thread()
  13661. {
  13662. /* If your thread class's destructor has been called without first stopping the thread, that
  13663. means that this partially destructed object is still performing some work - and that's not
  13664. unlikely to be a safe approach to take!
  13665. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13666. your subclass's destructor.
  13667. */
  13668. jassert (! isThreadRunning());
  13669. stopThread (100);
  13670. }
  13671. void Thread::startThread()
  13672. {
  13673. const ScopedLock sl (startStopLock);
  13674. threadShouldExit_ = false;
  13675. if (threadHandle_ == 0)
  13676. {
  13677. threadHandle_ = juce_createThread (this);
  13678. juce_setThreadPriority (threadHandle_, threadPriority_);
  13679. startSuspensionEvent_.signal();
  13680. }
  13681. }
  13682. void Thread::startThread (const int priority)
  13683. {
  13684. const ScopedLock sl (startStopLock);
  13685. if (threadHandle_ == 0)
  13686. {
  13687. threadPriority_ = priority;
  13688. startThread();
  13689. }
  13690. else
  13691. {
  13692. setPriority (priority);
  13693. }
  13694. }
  13695. bool Thread::isThreadRunning() const
  13696. {
  13697. return threadHandle_ != 0;
  13698. }
  13699. void Thread::signalThreadShouldExit()
  13700. {
  13701. threadShouldExit_ = true;
  13702. }
  13703. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13704. {
  13705. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13706. jassert (getThreadId() != getCurrentThreadId());
  13707. const int sleepMsPerIteration = 5;
  13708. int count = timeOutMilliseconds / sleepMsPerIteration;
  13709. while (isThreadRunning())
  13710. {
  13711. if (timeOutMilliseconds > 0 && --count < 0)
  13712. return false;
  13713. sleep (sleepMsPerIteration);
  13714. }
  13715. return true;
  13716. }
  13717. void Thread::stopThread (const int timeOutMilliseconds)
  13718. {
  13719. // agh! You can't stop the thread that's calling this method! How on earth
  13720. // would that work??
  13721. jassert (getCurrentThreadId() != getThreadId());
  13722. const ScopedLock sl (startStopLock);
  13723. if (isThreadRunning())
  13724. {
  13725. signalThreadShouldExit();
  13726. notify();
  13727. if (timeOutMilliseconds != 0)
  13728. waitForThreadToExit (timeOutMilliseconds);
  13729. if (isThreadRunning())
  13730. {
  13731. // very bad karma if this point is reached, as
  13732. // there are bound to be locks and events left in
  13733. // silly states when a thread is killed by force..
  13734. jassertfalse;
  13735. Logger::writeToLog ("!! killing thread by force !!");
  13736. juce_killThread (threadHandle_);
  13737. threadHandle_ = 0;
  13738. threadId_ = 0;
  13739. const ScopedLock sl2 (runningThreadsLock);
  13740. runningThreads.removeValue (this);
  13741. }
  13742. }
  13743. }
  13744. bool Thread::setPriority (const int priority)
  13745. {
  13746. const ScopedLock sl (startStopLock);
  13747. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13748. if (worked)
  13749. threadPriority_ = priority;
  13750. return worked;
  13751. }
  13752. bool Thread::setCurrentThreadPriority (const int priority)
  13753. {
  13754. return juce_setThreadPriority (0, priority);
  13755. }
  13756. void Thread::setAffinityMask (const uint32 affinityMask)
  13757. {
  13758. affinityMask_ = affinityMask;
  13759. }
  13760. bool Thread::wait (const int timeOutMilliseconds) const
  13761. {
  13762. return defaultEvent_.wait (timeOutMilliseconds);
  13763. }
  13764. void Thread::notify() const
  13765. {
  13766. defaultEvent_.signal();
  13767. }
  13768. int Thread::getNumRunningThreads()
  13769. {
  13770. return runningThreads.size();
  13771. }
  13772. Thread* Thread::getCurrentThread()
  13773. {
  13774. const ThreadID thisId = getCurrentThreadId();
  13775. const ScopedLock sl (runningThreadsLock);
  13776. for (int i = runningThreads.size(); --i >= 0;)
  13777. {
  13778. Thread* const t = runningThreads.getUnchecked(i);
  13779. if (t->threadId_ == thisId)
  13780. return t;
  13781. }
  13782. return 0;
  13783. }
  13784. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13785. {
  13786. {
  13787. const ScopedLock sl (runningThreadsLock);
  13788. for (int i = runningThreads.size(); --i >= 0;)
  13789. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13790. }
  13791. for (;;)
  13792. {
  13793. Thread* firstThread;
  13794. {
  13795. const ScopedLock sl (runningThreadsLock);
  13796. firstThread = runningThreads.getFirst();
  13797. }
  13798. if (firstThread == 0)
  13799. break;
  13800. firstThread->stopThread (timeOutMilliseconds);
  13801. }
  13802. }
  13803. Array<Thread*> Thread::runningThreads;
  13804. CriticalSection Thread::runningThreadsLock;
  13805. END_JUCE_NAMESPACE
  13806. /*** End of inlined file: juce_Thread.cpp ***/
  13807. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13808. BEGIN_JUCE_NAMESPACE
  13809. ThreadPoolJob::ThreadPoolJob (const String& name)
  13810. : jobName (name),
  13811. pool (0),
  13812. shouldStop (false),
  13813. isActive (false),
  13814. shouldBeDeleted (false)
  13815. {
  13816. }
  13817. ThreadPoolJob::~ThreadPoolJob()
  13818. {
  13819. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13820. // to remove it first!
  13821. jassert (pool == 0 || ! pool->contains (this));
  13822. }
  13823. const String ThreadPoolJob::getJobName() const
  13824. {
  13825. return jobName;
  13826. }
  13827. void ThreadPoolJob::setJobName (const String& newName)
  13828. {
  13829. jobName = newName;
  13830. }
  13831. void ThreadPoolJob::signalJobShouldExit()
  13832. {
  13833. shouldStop = true;
  13834. }
  13835. class ThreadPool::ThreadPoolThread : public Thread
  13836. {
  13837. public:
  13838. ThreadPoolThread (ThreadPool& pool_)
  13839. : Thread ("Pool"),
  13840. pool (pool_),
  13841. busy (false)
  13842. {
  13843. }
  13844. ~ThreadPoolThread()
  13845. {
  13846. }
  13847. void run()
  13848. {
  13849. while (! threadShouldExit())
  13850. {
  13851. if (! pool.runNextJob())
  13852. wait (500);
  13853. }
  13854. }
  13855. private:
  13856. ThreadPool& pool;
  13857. bool volatile busy;
  13858. ThreadPoolThread (const ThreadPoolThread&);
  13859. ThreadPoolThread& operator= (const ThreadPoolThread&);
  13860. };
  13861. ThreadPool::ThreadPool (const int numThreads,
  13862. const bool startThreadsOnlyWhenNeeded,
  13863. const int stopThreadsWhenNotUsedTimeoutMs)
  13864. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13865. priority (5)
  13866. {
  13867. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13868. for (int i = jmax (1, numThreads); --i >= 0;)
  13869. threads.add (new ThreadPoolThread (*this));
  13870. if (! startThreadsOnlyWhenNeeded)
  13871. for (int i = threads.size(); --i >= 0;)
  13872. threads.getUnchecked(i)->startThread (priority);
  13873. }
  13874. ThreadPool::~ThreadPool()
  13875. {
  13876. removeAllJobs (true, 4000);
  13877. int i;
  13878. for (i = threads.size(); --i >= 0;)
  13879. threads.getUnchecked(i)->signalThreadShouldExit();
  13880. for (i = threads.size(); --i >= 0;)
  13881. threads.getUnchecked(i)->stopThread (500);
  13882. }
  13883. void ThreadPool::addJob (ThreadPoolJob* const job)
  13884. {
  13885. jassert (job != 0);
  13886. jassert (job->pool == 0);
  13887. if (job->pool == 0)
  13888. {
  13889. job->pool = this;
  13890. job->shouldStop = false;
  13891. job->isActive = false;
  13892. {
  13893. const ScopedLock sl (lock);
  13894. jobs.add (job);
  13895. int numRunning = 0;
  13896. for (int i = threads.size(); --i >= 0;)
  13897. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13898. ++numRunning;
  13899. if (numRunning < threads.size())
  13900. {
  13901. bool startedOne = false;
  13902. int n = 1000;
  13903. while (--n >= 0 && ! startedOne)
  13904. {
  13905. for (int i = threads.size(); --i >= 0;)
  13906. {
  13907. if (! threads.getUnchecked(i)->isThreadRunning())
  13908. {
  13909. threads.getUnchecked(i)->startThread (priority);
  13910. startedOne = true;
  13911. break;
  13912. }
  13913. }
  13914. if (! startedOne)
  13915. Thread::sleep (2);
  13916. }
  13917. }
  13918. }
  13919. for (int i = threads.size(); --i >= 0;)
  13920. threads.getUnchecked(i)->notify();
  13921. }
  13922. }
  13923. int ThreadPool::getNumJobs() const
  13924. {
  13925. return jobs.size();
  13926. }
  13927. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13928. {
  13929. const ScopedLock sl (lock);
  13930. return jobs [index];
  13931. }
  13932. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13933. {
  13934. const ScopedLock sl (lock);
  13935. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13936. }
  13937. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13938. {
  13939. const ScopedLock sl (lock);
  13940. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13941. }
  13942. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13943. const int timeOutMs) const
  13944. {
  13945. if (job != 0)
  13946. {
  13947. const uint32 start = Time::getMillisecondCounter();
  13948. while (contains (job))
  13949. {
  13950. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13951. return false;
  13952. jobFinishedSignal.wait (2);
  13953. }
  13954. }
  13955. return true;
  13956. }
  13957. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13958. const bool interruptIfRunning,
  13959. const int timeOutMs)
  13960. {
  13961. bool dontWait = true;
  13962. if (job != 0)
  13963. {
  13964. const ScopedLock sl (lock);
  13965. if (jobs.contains (job))
  13966. {
  13967. if (job->isActive)
  13968. {
  13969. if (interruptIfRunning)
  13970. job->signalJobShouldExit();
  13971. dontWait = false;
  13972. }
  13973. else
  13974. {
  13975. jobs.removeValue (job);
  13976. job->pool = 0;
  13977. }
  13978. }
  13979. }
  13980. return dontWait || waitForJobToFinish (job, timeOutMs);
  13981. }
  13982. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13983. const int timeOutMs,
  13984. const bool deleteInactiveJobs,
  13985. ThreadPool::JobSelector* selectedJobsToRemove)
  13986. {
  13987. Array <ThreadPoolJob*> jobsToWaitFor;
  13988. {
  13989. const ScopedLock sl (lock);
  13990. for (int i = jobs.size(); --i >= 0;)
  13991. {
  13992. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13993. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13994. {
  13995. if (job->isActive)
  13996. {
  13997. jobsToWaitFor.add (job);
  13998. if (interruptRunningJobs)
  13999. job->signalJobShouldExit();
  14000. }
  14001. else
  14002. {
  14003. jobs.remove (i);
  14004. if (deleteInactiveJobs)
  14005. delete job;
  14006. else
  14007. job->pool = 0;
  14008. }
  14009. }
  14010. }
  14011. }
  14012. const uint32 start = Time::getMillisecondCounter();
  14013. for (;;)
  14014. {
  14015. for (int i = jobsToWaitFor.size(); --i >= 0;)
  14016. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  14017. jobsToWaitFor.remove (i);
  14018. if (jobsToWaitFor.size() == 0)
  14019. break;
  14020. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  14021. return false;
  14022. jobFinishedSignal.wait (20);
  14023. }
  14024. return true;
  14025. }
  14026. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  14027. {
  14028. StringArray s;
  14029. const ScopedLock sl (lock);
  14030. for (int i = 0; i < jobs.size(); ++i)
  14031. {
  14032. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  14033. if (job->isActive || ! onlyReturnActiveJobs)
  14034. s.add (job->getJobName());
  14035. }
  14036. return s;
  14037. }
  14038. bool ThreadPool::setThreadPriorities (const int newPriority)
  14039. {
  14040. bool ok = true;
  14041. if (priority != newPriority)
  14042. {
  14043. priority = newPriority;
  14044. for (int i = threads.size(); --i >= 0;)
  14045. if (! threads.getUnchecked(i)->setPriority (newPriority))
  14046. ok = false;
  14047. }
  14048. return ok;
  14049. }
  14050. bool ThreadPool::runNextJob()
  14051. {
  14052. ThreadPoolJob* job = 0;
  14053. {
  14054. const ScopedLock sl (lock);
  14055. for (int i = 0; i < jobs.size(); ++i)
  14056. {
  14057. job = jobs[i];
  14058. if (job != 0 && ! (job->isActive || job->shouldStop))
  14059. break;
  14060. job = 0;
  14061. }
  14062. if (job != 0)
  14063. job->isActive = true;
  14064. }
  14065. if (job != 0)
  14066. {
  14067. JUCE_TRY
  14068. {
  14069. ThreadPoolJob::JobStatus result = job->runJob();
  14070. lastJobEndTime = Time::getApproximateMillisecondCounter();
  14071. const ScopedLock sl (lock);
  14072. if (jobs.contains (job))
  14073. {
  14074. job->isActive = false;
  14075. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  14076. {
  14077. job->pool = 0;
  14078. job->shouldStop = true;
  14079. jobs.removeValue (job);
  14080. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  14081. delete job;
  14082. jobFinishedSignal.signal();
  14083. }
  14084. else
  14085. {
  14086. // move the job to the end of the queue if it wants another go
  14087. jobs.move (jobs.indexOf (job), -1);
  14088. }
  14089. }
  14090. }
  14091. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  14092. catch (...)
  14093. {
  14094. const ScopedLock sl (lock);
  14095. jobs.removeValue (job);
  14096. }
  14097. #endif
  14098. }
  14099. else
  14100. {
  14101. if (threadStopTimeout > 0
  14102. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  14103. {
  14104. const ScopedLock sl (lock);
  14105. if (jobs.size() == 0)
  14106. for (int i = threads.size(); --i >= 0;)
  14107. threads.getUnchecked(i)->signalThreadShouldExit();
  14108. }
  14109. else
  14110. {
  14111. return false;
  14112. }
  14113. }
  14114. return true;
  14115. }
  14116. END_JUCE_NAMESPACE
  14117. /*** End of inlined file: juce_ThreadPool.cpp ***/
  14118. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  14119. BEGIN_JUCE_NAMESPACE
  14120. TimeSliceThread::TimeSliceThread (const String& threadName)
  14121. : Thread (threadName),
  14122. index (0),
  14123. clientBeingCalled (0),
  14124. clientsChanged (false)
  14125. {
  14126. }
  14127. TimeSliceThread::~TimeSliceThread()
  14128. {
  14129. stopThread (2000);
  14130. }
  14131. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  14132. {
  14133. const ScopedLock sl (listLock);
  14134. clients.addIfNotAlreadyThere (client);
  14135. clientsChanged = true;
  14136. notify();
  14137. }
  14138. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  14139. {
  14140. const ScopedLock sl1 (listLock);
  14141. clientsChanged = true;
  14142. // if there's a chance we're in the middle of calling this client, we need to
  14143. // also lock the outer lock..
  14144. if (clientBeingCalled == client)
  14145. {
  14146. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  14147. const ScopedLock sl2 (callbackLock);
  14148. const ScopedLock sl3 (listLock);
  14149. clients.removeValue (client);
  14150. }
  14151. else
  14152. {
  14153. clients.removeValue (client);
  14154. }
  14155. }
  14156. int TimeSliceThread::getNumClients() const
  14157. {
  14158. return clients.size();
  14159. }
  14160. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  14161. {
  14162. const ScopedLock sl (listLock);
  14163. return clients [i];
  14164. }
  14165. void TimeSliceThread::run()
  14166. {
  14167. int numCallsSinceBusy = 0;
  14168. while (! threadShouldExit())
  14169. {
  14170. int timeToWait = 500;
  14171. {
  14172. const ScopedLock sl (callbackLock);
  14173. {
  14174. const ScopedLock sl2 (listLock);
  14175. if (clients.size() > 0)
  14176. {
  14177. index = (index + 1) % clients.size();
  14178. clientBeingCalled = clients [index];
  14179. }
  14180. else
  14181. {
  14182. index = 0;
  14183. clientBeingCalled = 0;
  14184. }
  14185. if (clientsChanged)
  14186. {
  14187. clientsChanged = false;
  14188. numCallsSinceBusy = 0;
  14189. }
  14190. }
  14191. if (clientBeingCalled != 0)
  14192. {
  14193. if (clientBeingCalled->useTimeSlice())
  14194. numCallsSinceBusy = 0;
  14195. else
  14196. ++numCallsSinceBusy;
  14197. if (numCallsSinceBusy >= clients.size())
  14198. timeToWait = 500;
  14199. else if (index == 0)
  14200. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  14201. else
  14202. timeToWait = 0;
  14203. }
  14204. }
  14205. if (timeToWait > 0)
  14206. wait (timeToWait);
  14207. }
  14208. }
  14209. END_JUCE_NAMESPACE
  14210. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  14211. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14212. BEGIN_JUCE_NAMESPACE
  14213. DeletedAtShutdown::DeletedAtShutdown()
  14214. {
  14215. const ScopedLock sl (getLock());
  14216. getObjects().add (this);
  14217. }
  14218. DeletedAtShutdown::~DeletedAtShutdown()
  14219. {
  14220. const ScopedLock sl (getLock());
  14221. getObjects().removeValue (this);
  14222. }
  14223. void DeletedAtShutdown::deleteAll()
  14224. {
  14225. // make a local copy of the array, so it can't get into a loop if something
  14226. // creates another DeletedAtShutdown object during its destructor.
  14227. Array <DeletedAtShutdown*> localCopy;
  14228. {
  14229. const ScopedLock sl (getLock());
  14230. localCopy = getObjects();
  14231. }
  14232. for (int i = localCopy.size(); --i >= 0;)
  14233. {
  14234. JUCE_TRY
  14235. {
  14236. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  14237. // double-check that it's not already been deleted during another object's destructor.
  14238. {
  14239. const ScopedLock sl (getLock());
  14240. if (! getObjects().contains (deletee))
  14241. deletee = 0;
  14242. }
  14243. delete deletee;
  14244. }
  14245. JUCE_CATCH_EXCEPTION
  14246. }
  14247. // if no objects got re-created during shutdown, this should have been emptied by their
  14248. // destructors
  14249. jassert (getObjects().size() == 0);
  14250. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  14251. }
  14252. CriticalSection& DeletedAtShutdown::getLock()
  14253. {
  14254. static CriticalSection lock;
  14255. return lock;
  14256. }
  14257. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  14258. {
  14259. static Array <DeletedAtShutdown*> objects;
  14260. return objects;
  14261. }
  14262. END_JUCE_NAMESPACE
  14263. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14264. /*** Start of inlined file: juce_UnitTest.cpp ***/
  14265. BEGIN_JUCE_NAMESPACE
  14266. UnitTest::UnitTest (const String& name_)
  14267. : name (name_), runner (0)
  14268. {
  14269. getAllTests().add (this);
  14270. }
  14271. UnitTest::~UnitTest()
  14272. {
  14273. getAllTests().removeValue (this);
  14274. }
  14275. Array<UnitTest*>& UnitTest::getAllTests()
  14276. {
  14277. static Array<UnitTest*> tests;
  14278. return tests;
  14279. }
  14280. void UnitTest::initialise() {}
  14281. void UnitTest::shutdown() {}
  14282. void UnitTest::performTest (UnitTestRunner* const runner_)
  14283. {
  14284. jassert (runner_ != 0);
  14285. runner = runner_;
  14286. initialise();
  14287. runTest();
  14288. shutdown();
  14289. }
  14290. void UnitTest::logMessage (const String& message)
  14291. {
  14292. runner->logMessage (message);
  14293. }
  14294. void UnitTest::beginTest (const String& testName)
  14295. {
  14296. runner->beginNewTest (this, testName);
  14297. }
  14298. void UnitTest::expect (const bool result, const String& failureMessage)
  14299. {
  14300. if (result)
  14301. runner->addPass();
  14302. else
  14303. runner->addFail (failureMessage);
  14304. }
  14305. UnitTestRunner::UnitTestRunner()
  14306. : currentTest (0), assertOnFailure (false)
  14307. {
  14308. }
  14309. UnitTestRunner::~UnitTestRunner()
  14310. {
  14311. }
  14312. int UnitTestRunner::getNumResults() const throw()
  14313. {
  14314. return results.size();
  14315. }
  14316. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  14317. {
  14318. return results [index];
  14319. }
  14320. void UnitTestRunner::resultsUpdated()
  14321. {
  14322. }
  14323. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14324. {
  14325. results.clear();
  14326. assertOnFailure = assertOnFailure_;
  14327. resultsUpdated();
  14328. for (int i = 0; i < tests.size(); ++i)
  14329. {
  14330. try
  14331. {
  14332. tests.getUnchecked(i)->performTest (this);
  14333. }
  14334. catch (...)
  14335. {
  14336. addFail ("An unhandled exception was thrown!");
  14337. }
  14338. }
  14339. endTest();
  14340. }
  14341. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14342. {
  14343. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14344. }
  14345. void UnitTestRunner::logMessage (const String& message)
  14346. {
  14347. Logger::writeToLog (message);
  14348. }
  14349. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14350. {
  14351. endTest();
  14352. currentTest = test;
  14353. TestResult* const r = new TestResult();
  14354. r->unitTestName = test->getName();
  14355. r->subcategoryName = subCategory;
  14356. r->passes = 0;
  14357. r->failures = 0;
  14358. results.add (r);
  14359. logMessage ("-----------------------------------------------------------------");
  14360. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14361. resultsUpdated();
  14362. }
  14363. void UnitTestRunner::endTest()
  14364. {
  14365. if (results.size() > 0)
  14366. {
  14367. TestResult* const r = results.getLast();
  14368. if (r->failures > 0)
  14369. {
  14370. String m ("FAILED!!");
  14371. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14372. << " failed, out of a total of " << (r->passes + r->failures);
  14373. logMessage (String::empty);
  14374. logMessage (m);
  14375. logMessage (String::empty);
  14376. }
  14377. else
  14378. {
  14379. logMessage ("All tests completed successfully");
  14380. }
  14381. }
  14382. }
  14383. void UnitTestRunner::addPass()
  14384. {
  14385. {
  14386. const ScopedLock sl (results.getLock());
  14387. TestResult* const r = results.getLast();
  14388. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14389. r->passes++;
  14390. String message ("Test ");
  14391. message << (r->failures + r->passes) << " passed";
  14392. logMessage (message);
  14393. }
  14394. resultsUpdated();
  14395. }
  14396. void UnitTestRunner::addFail (const String& failureMessage)
  14397. {
  14398. {
  14399. const ScopedLock sl (results.getLock());
  14400. TestResult* const r = results.getLast();
  14401. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14402. r->failures++;
  14403. String message ("!!! Test ");
  14404. message << (r->failures + r->passes) << " failed";
  14405. if (failureMessage.isNotEmpty())
  14406. message << ": " << failureMessage;
  14407. r->messages.add (message);
  14408. logMessage (message);
  14409. }
  14410. resultsUpdated();
  14411. if (assertOnFailure) { jassertfalse }
  14412. }
  14413. END_JUCE_NAMESPACE
  14414. /*** End of inlined file: juce_UnitTest.cpp ***/
  14415. #endif
  14416. #if JUCE_BUILD_MISC
  14417. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14418. BEGIN_JUCE_NAMESPACE
  14419. class ValueTree::SetPropertyAction : public UndoableAction
  14420. {
  14421. public:
  14422. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14423. const var& newValue_, const var& oldValue_,
  14424. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14425. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14426. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14427. {
  14428. }
  14429. ~SetPropertyAction() {}
  14430. bool perform()
  14431. {
  14432. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14433. if (isDeletingProperty)
  14434. target->removeProperty (name, 0);
  14435. else
  14436. target->setProperty (name, newValue, 0);
  14437. return true;
  14438. }
  14439. bool undo()
  14440. {
  14441. if (isAddingNewProperty)
  14442. target->removeProperty (name, 0);
  14443. else
  14444. target->setProperty (name, oldValue, 0);
  14445. return true;
  14446. }
  14447. int getSizeInUnits()
  14448. {
  14449. return (int) sizeof (*this); //xxx should be more accurate
  14450. }
  14451. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14452. {
  14453. if (! (isAddingNewProperty || isDeletingProperty))
  14454. {
  14455. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14456. if (next != 0 && next->target == target && next->name == name
  14457. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14458. {
  14459. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14460. }
  14461. }
  14462. return 0;
  14463. }
  14464. private:
  14465. const SharedObjectPtr target;
  14466. const Identifier name;
  14467. const var newValue;
  14468. var oldValue;
  14469. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14470. SetPropertyAction (const SetPropertyAction&);
  14471. SetPropertyAction& operator= (const SetPropertyAction&);
  14472. };
  14473. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14474. {
  14475. public:
  14476. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14477. const SharedObjectPtr& newChild_)
  14478. : target (target_),
  14479. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14480. childIndex (childIndex_),
  14481. isDeleting (newChild_ == 0)
  14482. {
  14483. jassert (child != 0);
  14484. }
  14485. ~AddOrRemoveChildAction() {}
  14486. bool perform()
  14487. {
  14488. if (isDeleting)
  14489. target->removeChild (childIndex, 0);
  14490. else
  14491. target->addChild (child, childIndex, 0);
  14492. return true;
  14493. }
  14494. bool undo()
  14495. {
  14496. if (isDeleting)
  14497. {
  14498. target->addChild (child, childIndex, 0);
  14499. }
  14500. else
  14501. {
  14502. // If you hit this, it seems that your object's state is getting confused - probably
  14503. // because you've interleaved some undoable and non-undoable operations?
  14504. jassert (childIndex < target->children.size());
  14505. target->removeChild (childIndex, 0);
  14506. }
  14507. return true;
  14508. }
  14509. int getSizeInUnits()
  14510. {
  14511. return (int) sizeof (*this); //xxx should be more accurate
  14512. }
  14513. private:
  14514. const SharedObjectPtr target, child;
  14515. const int childIndex;
  14516. const bool isDeleting;
  14517. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  14518. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  14519. };
  14520. class ValueTree::MoveChildAction : public UndoableAction
  14521. {
  14522. public:
  14523. MoveChildAction (const SharedObjectPtr& parent_,
  14524. const int startIndex_, const int endIndex_)
  14525. : parent (parent_),
  14526. startIndex (startIndex_),
  14527. endIndex (endIndex_)
  14528. {
  14529. }
  14530. ~MoveChildAction() {}
  14531. bool perform()
  14532. {
  14533. parent->moveChild (startIndex, endIndex, 0);
  14534. return true;
  14535. }
  14536. bool undo()
  14537. {
  14538. parent->moveChild (endIndex, startIndex, 0);
  14539. return true;
  14540. }
  14541. int getSizeInUnits()
  14542. {
  14543. return (int) sizeof (*this); //xxx should be more accurate
  14544. }
  14545. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14546. {
  14547. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14548. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14549. return new MoveChildAction (parent, startIndex, next->endIndex);
  14550. return 0;
  14551. }
  14552. private:
  14553. const SharedObjectPtr parent;
  14554. const int startIndex, endIndex;
  14555. MoveChildAction (const MoveChildAction&);
  14556. MoveChildAction& operator= (const MoveChildAction&);
  14557. };
  14558. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14559. : type (type_), parent (0)
  14560. {
  14561. }
  14562. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14563. : type (other.type), properties (other.properties), parent (0)
  14564. {
  14565. for (int i = 0; i < other.children.size(); ++i)
  14566. {
  14567. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14568. child->parent = this;
  14569. children.add (child);
  14570. }
  14571. }
  14572. ValueTree::SharedObject::~SharedObject()
  14573. {
  14574. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14575. for (int i = children.size(); --i >= 0;)
  14576. {
  14577. const SharedObjectPtr c (children.getUnchecked(i));
  14578. c->parent = 0;
  14579. children.remove (i);
  14580. c->sendParentChangeMessage();
  14581. }
  14582. }
  14583. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14584. {
  14585. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14586. {
  14587. ValueTree* const v = valueTreesWithListeners[i];
  14588. if (v != 0)
  14589. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14590. }
  14591. }
  14592. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14593. {
  14594. ValueTree tree (this);
  14595. ValueTree::SharedObject* t = this;
  14596. while (t != 0)
  14597. {
  14598. t->sendPropertyChangeMessage (tree, property);
  14599. t = t->parent;
  14600. }
  14601. }
  14602. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14603. {
  14604. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14605. {
  14606. ValueTree* const v = valueTreesWithListeners[i];
  14607. if (v != 0)
  14608. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14609. }
  14610. }
  14611. void ValueTree::SharedObject::sendChildChangeMessage()
  14612. {
  14613. ValueTree tree (this);
  14614. ValueTree::SharedObject* t = this;
  14615. while (t != 0)
  14616. {
  14617. t->sendChildChangeMessage (tree);
  14618. t = t->parent;
  14619. }
  14620. }
  14621. void ValueTree::SharedObject::sendParentChangeMessage()
  14622. {
  14623. ValueTree tree (this);
  14624. int i;
  14625. for (i = children.size(); --i >= 0;)
  14626. {
  14627. SharedObject* const t = children[i];
  14628. if (t != 0)
  14629. t->sendParentChangeMessage();
  14630. }
  14631. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14632. {
  14633. ValueTree* const v = valueTreesWithListeners[i];
  14634. if (v != 0)
  14635. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14636. }
  14637. }
  14638. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14639. {
  14640. return properties [name];
  14641. }
  14642. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14643. {
  14644. return properties.getWithDefault (name, defaultReturnValue);
  14645. }
  14646. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14647. {
  14648. if (undoManager == 0)
  14649. {
  14650. if (properties.set (name, newValue))
  14651. sendPropertyChangeMessage (name);
  14652. }
  14653. else
  14654. {
  14655. var* const existingValue = properties.getVarPointer (name);
  14656. if (existingValue != 0)
  14657. {
  14658. if (*existingValue != newValue)
  14659. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14660. }
  14661. else
  14662. {
  14663. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14664. }
  14665. }
  14666. }
  14667. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14668. {
  14669. return properties.contains (name);
  14670. }
  14671. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14672. {
  14673. if (undoManager == 0)
  14674. {
  14675. if (properties.remove (name))
  14676. sendPropertyChangeMessage (name);
  14677. }
  14678. else
  14679. {
  14680. if (properties.contains (name))
  14681. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14682. }
  14683. }
  14684. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14685. {
  14686. if (undoManager == 0)
  14687. {
  14688. while (properties.size() > 0)
  14689. {
  14690. const Identifier name (properties.getName (properties.size() - 1));
  14691. properties.remove (name);
  14692. sendPropertyChangeMessage (name);
  14693. }
  14694. }
  14695. else
  14696. {
  14697. for (int i = properties.size(); --i >= 0;)
  14698. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14699. }
  14700. }
  14701. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14702. {
  14703. for (int i = 0; i < children.size(); ++i)
  14704. if (children.getUnchecked(i)->type == typeToMatch)
  14705. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14706. return ValueTree::invalid;
  14707. }
  14708. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14709. {
  14710. for (int i = 0; i < children.size(); ++i)
  14711. if (children.getUnchecked(i)->type == typeToMatch)
  14712. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14713. SharedObject* const newObject = new SharedObject (typeToMatch);
  14714. addChild (newObject, -1, undoManager);
  14715. return ValueTree (newObject);
  14716. }
  14717. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14718. {
  14719. for (int i = 0; i < children.size(); ++i)
  14720. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14721. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14722. return ValueTree::invalid;
  14723. }
  14724. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14725. {
  14726. const SharedObject* p = parent;
  14727. while (p != 0)
  14728. {
  14729. if (p == possibleParent)
  14730. return true;
  14731. p = p->parent;
  14732. }
  14733. return false;
  14734. }
  14735. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14736. {
  14737. return children.indexOf (child.object);
  14738. }
  14739. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14740. {
  14741. if (child != 0 && child->parent != this)
  14742. {
  14743. if (child != this && ! isAChildOf (child))
  14744. {
  14745. // You should always make sure that a child is removed from its previous parent before
  14746. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14747. // undomanager should be used when removing it from its current parent..
  14748. jassert (child->parent == 0);
  14749. if (child->parent != 0)
  14750. {
  14751. jassert (child->parent->children.indexOf (child) >= 0);
  14752. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14753. }
  14754. if (undoManager == 0)
  14755. {
  14756. children.insert (index, child);
  14757. child->parent = this;
  14758. sendChildChangeMessage();
  14759. child->sendParentChangeMessage();
  14760. }
  14761. else
  14762. {
  14763. if (index < 0)
  14764. index = children.size();
  14765. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14766. }
  14767. }
  14768. else
  14769. {
  14770. // You're attempting to create a recursive loop! A node
  14771. // can't be a child of one of its own children!
  14772. jassertfalse;
  14773. }
  14774. }
  14775. }
  14776. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14777. {
  14778. const SharedObjectPtr child (children [childIndex]);
  14779. if (child != 0)
  14780. {
  14781. if (undoManager == 0)
  14782. {
  14783. children.remove (childIndex);
  14784. child->parent = 0;
  14785. sendChildChangeMessage();
  14786. child->sendParentChangeMessage();
  14787. }
  14788. else
  14789. {
  14790. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14791. }
  14792. }
  14793. }
  14794. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14795. {
  14796. while (children.size() > 0)
  14797. removeChild (children.size() - 1, undoManager);
  14798. }
  14799. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14800. {
  14801. // The source index must be a valid index!
  14802. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14803. if (currentIndex != newIndex
  14804. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14805. {
  14806. if (undoManager == 0)
  14807. {
  14808. children.move (currentIndex, newIndex);
  14809. sendChildChangeMessage();
  14810. }
  14811. else
  14812. {
  14813. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14814. newIndex = children.size() - 1;
  14815. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14816. }
  14817. }
  14818. }
  14819. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14820. {
  14821. jassert (newOrder.size() == children.size());
  14822. if (undoManager == 0)
  14823. {
  14824. children = newOrder;
  14825. sendChildChangeMessage();
  14826. }
  14827. else
  14828. {
  14829. for (int i = 0; i < children.size(); ++i)
  14830. {
  14831. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14832. {
  14833. jassert (children.contains (newOrder.getUnchecked(i)));
  14834. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14835. }
  14836. }
  14837. }
  14838. }
  14839. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14840. {
  14841. if (type != other.type
  14842. || properties.size() != other.properties.size()
  14843. || children.size() != other.children.size()
  14844. || properties != other.properties)
  14845. return false;
  14846. for (int i = 0; i < children.size(); ++i)
  14847. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14848. return false;
  14849. return true;
  14850. }
  14851. ValueTree::ValueTree() throw()
  14852. : object (0)
  14853. {
  14854. }
  14855. const ValueTree ValueTree::invalid;
  14856. ValueTree::ValueTree (const Identifier& type_)
  14857. : object (new ValueTree::SharedObject (type_))
  14858. {
  14859. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14860. }
  14861. ValueTree::ValueTree (SharedObject* const object_)
  14862. : object (object_)
  14863. {
  14864. }
  14865. ValueTree::ValueTree (const ValueTree& other)
  14866. : object (other.object)
  14867. {
  14868. }
  14869. ValueTree& ValueTree::operator= (const ValueTree& other)
  14870. {
  14871. if (listeners.size() > 0)
  14872. {
  14873. if (object != 0)
  14874. object->valueTreesWithListeners.removeValue (this);
  14875. if (other.object != 0)
  14876. other.object->valueTreesWithListeners.add (this);
  14877. }
  14878. object = other.object;
  14879. return *this;
  14880. }
  14881. ValueTree::~ValueTree()
  14882. {
  14883. if (listeners.size() > 0 && object != 0)
  14884. object->valueTreesWithListeners.removeValue (this);
  14885. }
  14886. bool ValueTree::operator== (const ValueTree& other) const throw()
  14887. {
  14888. return object == other.object;
  14889. }
  14890. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14891. {
  14892. return object != other.object;
  14893. }
  14894. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14895. {
  14896. return object == other.object
  14897. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14898. }
  14899. ValueTree ValueTree::createCopy() const
  14900. {
  14901. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14902. }
  14903. bool ValueTree::hasType (const Identifier& typeName) const
  14904. {
  14905. return object != 0 && object->type == typeName;
  14906. }
  14907. const Identifier ValueTree::getType() const
  14908. {
  14909. return object != 0 ? object->type : Identifier();
  14910. }
  14911. ValueTree ValueTree::getParent() const
  14912. {
  14913. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14914. }
  14915. ValueTree ValueTree::getSibling (const int delta) const
  14916. {
  14917. if (object == 0 || object->parent == 0)
  14918. return invalid;
  14919. const int index = object->parent->indexOf (*this) + delta;
  14920. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14921. }
  14922. const var& ValueTree::operator[] (const Identifier& name) const
  14923. {
  14924. return object == 0 ? var::null : object->getProperty (name);
  14925. }
  14926. const var& ValueTree::getProperty (const Identifier& name) const
  14927. {
  14928. return object == 0 ? var::null : object->getProperty (name);
  14929. }
  14930. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14931. {
  14932. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14933. }
  14934. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14935. {
  14936. jassert (name.toString().isNotEmpty());
  14937. if (object != 0 && name.toString().isNotEmpty())
  14938. object->setProperty (name, newValue, undoManager);
  14939. }
  14940. bool ValueTree::hasProperty (const Identifier& name) const
  14941. {
  14942. return object != 0 && object->hasProperty (name);
  14943. }
  14944. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14945. {
  14946. if (object != 0)
  14947. object->removeProperty (name, undoManager);
  14948. }
  14949. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14950. {
  14951. if (object != 0)
  14952. object->removeAllProperties (undoManager);
  14953. }
  14954. int ValueTree::getNumProperties() const
  14955. {
  14956. return object == 0 ? 0 : object->properties.size();
  14957. }
  14958. const Identifier ValueTree::getPropertyName (const int index) const
  14959. {
  14960. return object == 0 ? Identifier()
  14961. : object->properties.getName (index);
  14962. }
  14963. class ValueTreePropertyValueSource : public Value::ValueSource,
  14964. public ValueTree::Listener
  14965. {
  14966. public:
  14967. ValueTreePropertyValueSource (const ValueTree& tree_,
  14968. const Identifier& property_,
  14969. UndoManager* const undoManager_)
  14970. : tree (tree_),
  14971. property (property_),
  14972. undoManager (undoManager_)
  14973. {
  14974. tree.addListener (this);
  14975. }
  14976. ~ValueTreePropertyValueSource()
  14977. {
  14978. tree.removeListener (this);
  14979. }
  14980. const var getValue() const
  14981. {
  14982. return tree [property];
  14983. }
  14984. void setValue (const var& newValue)
  14985. {
  14986. tree.setProperty (property, newValue, undoManager);
  14987. }
  14988. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14989. {
  14990. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14991. sendChangeMessage (false);
  14992. }
  14993. void valueTreeChildrenChanged (ValueTree&) {}
  14994. void valueTreeParentChanged (ValueTree&) {}
  14995. private:
  14996. ValueTree tree;
  14997. const Identifier property;
  14998. UndoManager* const undoManager;
  14999. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  15000. };
  15001. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  15002. {
  15003. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  15004. }
  15005. int ValueTree::getNumChildren() const
  15006. {
  15007. return object == 0 ? 0 : object->children.size();
  15008. }
  15009. ValueTree ValueTree::getChild (int index) const
  15010. {
  15011. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  15012. }
  15013. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  15014. {
  15015. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  15016. }
  15017. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  15018. {
  15019. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  15020. }
  15021. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  15022. {
  15023. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  15024. }
  15025. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  15026. {
  15027. return object != 0 && object->isAChildOf (possibleParent.object);
  15028. }
  15029. int ValueTree::indexOf (const ValueTree& child) const
  15030. {
  15031. return object != 0 ? object->indexOf (child) : -1;
  15032. }
  15033. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  15034. {
  15035. if (object != 0)
  15036. object->addChild (child.object, index, undoManager);
  15037. }
  15038. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  15039. {
  15040. if (object != 0)
  15041. object->removeChild (childIndex, undoManager);
  15042. }
  15043. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  15044. {
  15045. if (object != 0)
  15046. object->removeChild (object->children.indexOf (child.object), undoManager);
  15047. }
  15048. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  15049. {
  15050. if (object != 0)
  15051. object->removeAllChildren (undoManager);
  15052. }
  15053. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  15054. {
  15055. if (object != 0)
  15056. object->moveChild (currentIndex, newIndex, undoManager);
  15057. }
  15058. void ValueTree::addListener (Listener* listener)
  15059. {
  15060. if (listener != 0)
  15061. {
  15062. if (listeners.size() == 0 && object != 0)
  15063. object->valueTreesWithListeners.add (this);
  15064. listeners.add (listener);
  15065. }
  15066. }
  15067. void ValueTree::removeListener (Listener* listener)
  15068. {
  15069. listeners.remove (listener);
  15070. if (listeners.size() == 0 && object != 0)
  15071. object->valueTreesWithListeners.removeValue (this);
  15072. }
  15073. XmlElement* ValueTree::SharedObject::createXml() const
  15074. {
  15075. XmlElement* xml = new XmlElement (type.toString());
  15076. int i;
  15077. for (i = 0; i < properties.size(); ++i)
  15078. {
  15079. Identifier name (properties.getName(i));
  15080. const var& v = properties [name];
  15081. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  15082. xml->setAttribute (name.toString(), v.toString());
  15083. }
  15084. for (i = 0; i < children.size(); ++i)
  15085. xml->addChildElement (children.getUnchecked(i)->createXml());
  15086. return xml;
  15087. }
  15088. XmlElement* ValueTree::createXml() const
  15089. {
  15090. return object != 0 ? object->createXml() : 0;
  15091. }
  15092. ValueTree ValueTree::fromXml (const XmlElement& xml)
  15093. {
  15094. ValueTree v (xml.getTagName());
  15095. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  15096. for (int i = 0; i < numAtts; ++i)
  15097. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  15098. forEachXmlChildElement (xml, e)
  15099. {
  15100. v.addChild (fromXml (*e), -1, 0);
  15101. }
  15102. return v;
  15103. }
  15104. void ValueTree::writeToStream (OutputStream& output)
  15105. {
  15106. output.writeString (getType().toString());
  15107. const int numProps = getNumProperties();
  15108. output.writeCompressedInt (numProps);
  15109. int i;
  15110. for (i = 0; i < numProps; ++i)
  15111. {
  15112. const Identifier name (getPropertyName(i));
  15113. output.writeString (name.toString());
  15114. getProperty(name).writeToStream (output);
  15115. }
  15116. const int numChildren = getNumChildren();
  15117. output.writeCompressedInt (numChildren);
  15118. for (i = 0; i < numChildren; ++i)
  15119. getChild (i).writeToStream (output);
  15120. }
  15121. ValueTree ValueTree::readFromStream (InputStream& input)
  15122. {
  15123. const String type (input.readString());
  15124. if (type.isEmpty())
  15125. return ValueTree::invalid;
  15126. ValueTree v (type);
  15127. const int numProps = input.readCompressedInt();
  15128. if (numProps < 0)
  15129. {
  15130. jassertfalse; // trying to read corrupted data!
  15131. return v;
  15132. }
  15133. int i;
  15134. for (i = 0; i < numProps; ++i)
  15135. {
  15136. const String name (input.readString());
  15137. jassert (name.isNotEmpty());
  15138. const var value (var::readFromStream (input));
  15139. v.setProperty (name, value, 0);
  15140. }
  15141. const int numChildren = input.readCompressedInt();
  15142. for (i = 0; i < numChildren; ++i)
  15143. v.addChild (readFromStream (input), -1, 0);
  15144. return v;
  15145. }
  15146. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  15147. {
  15148. MemoryInputStream in (data, numBytes, false);
  15149. return readFromStream (in);
  15150. }
  15151. END_JUCE_NAMESPACE
  15152. /*** End of inlined file: juce_ValueTree.cpp ***/
  15153. /*** Start of inlined file: juce_Value.cpp ***/
  15154. BEGIN_JUCE_NAMESPACE
  15155. Value::ValueSource::ValueSource()
  15156. {
  15157. }
  15158. Value::ValueSource::~ValueSource()
  15159. {
  15160. }
  15161. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  15162. {
  15163. if (synchronous)
  15164. {
  15165. for (int i = valuesWithListeners.size(); --i >= 0;)
  15166. {
  15167. Value* const v = valuesWithListeners[i];
  15168. if (v != 0)
  15169. v->callListeners();
  15170. }
  15171. }
  15172. else
  15173. {
  15174. triggerAsyncUpdate();
  15175. }
  15176. }
  15177. void Value::ValueSource::handleAsyncUpdate()
  15178. {
  15179. sendChangeMessage (true);
  15180. }
  15181. class SimpleValueSource : public Value::ValueSource
  15182. {
  15183. public:
  15184. SimpleValueSource()
  15185. {
  15186. }
  15187. SimpleValueSource (const var& initialValue)
  15188. : value (initialValue)
  15189. {
  15190. }
  15191. ~SimpleValueSource()
  15192. {
  15193. }
  15194. const var getValue() const
  15195. {
  15196. return value;
  15197. }
  15198. void setValue (const var& newValue)
  15199. {
  15200. if (newValue != value)
  15201. {
  15202. value = newValue;
  15203. sendChangeMessage (false);
  15204. }
  15205. }
  15206. private:
  15207. var value;
  15208. SimpleValueSource (const SimpleValueSource&);
  15209. SimpleValueSource& operator= (const SimpleValueSource&);
  15210. };
  15211. Value::Value()
  15212. : value (new SimpleValueSource())
  15213. {
  15214. }
  15215. Value::Value (ValueSource* const value_)
  15216. : value (value_)
  15217. {
  15218. jassert (value_ != 0);
  15219. }
  15220. Value::Value (const var& initialValue)
  15221. : value (new SimpleValueSource (initialValue))
  15222. {
  15223. }
  15224. Value::Value (const Value& other)
  15225. : value (other.value)
  15226. {
  15227. }
  15228. Value& Value::operator= (const Value& other)
  15229. {
  15230. value = other.value;
  15231. return *this;
  15232. }
  15233. Value::~Value()
  15234. {
  15235. if (listeners.size() > 0)
  15236. value->valuesWithListeners.removeValue (this);
  15237. }
  15238. const var Value::getValue() const
  15239. {
  15240. return value->getValue();
  15241. }
  15242. Value::operator const var() const
  15243. {
  15244. return getValue();
  15245. }
  15246. void Value::setValue (const var& newValue)
  15247. {
  15248. value->setValue (newValue);
  15249. }
  15250. const String Value::toString() const
  15251. {
  15252. return value->getValue().toString();
  15253. }
  15254. Value& Value::operator= (const var& newValue)
  15255. {
  15256. value->setValue (newValue);
  15257. return *this;
  15258. }
  15259. void Value::referTo (const Value& valueToReferTo)
  15260. {
  15261. if (valueToReferTo.value != value)
  15262. {
  15263. if (listeners.size() > 0)
  15264. {
  15265. value->valuesWithListeners.removeValue (this);
  15266. valueToReferTo.value->valuesWithListeners.add (this);
  15267. }
  15268. value = valueToReferTo.value;
  15269. callListeners();
  15270. }
  15271. }
  15272. bool Value::refersToSameSourceAs (const Value& other) const
  15273. {
  15274. return value == other.value;
  15275. }
  15276. bool Value::operator== (const Value& other) const
  15277. {
  15278. return value == other.value || value->getValue() == other.getValue();
  15279. }
  15280. bool Value::operator!= (const Value& other) const
  15281. {
  15282. return value != other.value && value->getValue() != other.getValue();
  15283. }
  15284. void Value::addListener (ValueListener* const listener)
  15285. {
  15286. if (listener != 0)
  15287. {
  15288. if (listeners.size() == 0)
  15289. value->valuesWithListeners.add (this);
  15290. listeners.add (listener);
  15291. }
  15292. }
  15293. void Value::removeListener (ValueListener* const listener)
  15294. {
  15295. listeners.remove (listener);
  15296. if (listeners.size() == 0)
  15297. value->valuesWithListeners.removeValue (this);
  15298. }
  15299. void Value::callListeners()
  15300. {
  15301. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15302. listeners.call (&ValueListener::valueChanged, v);
  15303. }
  15304. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15305. {
  15306. return stream << value.toString();
  15307. }
  15308. END_JUCE_NAMESPACE
  15309. /*** End of inlined file: juce_Value.cpp ***/
  15310. /*** Start of inlined file: juce_Application.cpp ***/
  15311. BEGIN_JUCE_NAMESPACE
  15312. #if JUCE_MAC
  15313. extern void juce_initialiseMacMainMenu();
  15314. #endif
  15315. JUCEApplication::JUCEApplication()
  15316. : appReturnValue (0),
  15317. stillInitialising (true)
  15318. {
  15319. jassert (isStandaloneApp() && appInstance == 0);
  15320. appInstance = this;
  15321. }
  15322. JUCEApplication::~JUCEApplication()
  15323. {
  15324. if (appLock != 0)
  15325. {
  15326. appLock->exit();
  15327. appLock = 0;
  15328. }
  15329. jassert (appInstance == this);
  15330. appInstance = 0;
  15331. }
  15332. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15333. JUCEApplication* JUCEApplication::appInstance = 0;
  15334. bool JUCEApplication::moreThanOneInstanceAllowed()
  15335. {
  15336. return true;
  15337. }
  15338. void JUCEApplication::anotherInstanceStarted (const String&)
  15339. {
  15340. }
  15341. void JUCEApplication::systemRequestedQuit()
  15342. {
  15343. quit();
  15344. }
  15345. void JUCEApplication::quit()
  15346. {
  15347. MessageManager::getInstance()->stopDispatchLoop();
  15348. }
  15349. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15350. {
  15351. appReturnValue = newReturnValue;
  15352. }
  15353. void JUCEApplication::actionListenerCallback (const String& message)
  15354. {
  15355. if (message.startsWith (getApplicationName() + "/"))
  15356. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15357. }
  15358. void JUCEApplication::unhandledException (const std::exception*,
  15359. const String&,
  15360. const int)
  15361. {
  15362. jassertfalse;
  15363. }
  15364. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15365. const char* const sourceFile,
  15366. const int lineNumber)
  15367. {
  15368. if (appInstance != 0)
  15369. appInstance->unhandledException (e, sourceFile, lineNumber);
  15370. }
  15371. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15372. {
  15373. return 0;
  15374. }
  15375. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15376. {
  15377. commands.add (StandardApplicationCommandIDs::quit);
  15378. }
  15379. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15380. {
  15381. if (commandID == StandardApplicationCommandIDs::quit)
  15382. {
  15383. result.setInfo (TRANS("Quit"),
  15384. TRANS("Quits the application"),
  15385. "Application",
  15386. 0);
  15387. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15388. }
  15389. }
  15390. bool JUCEApplication::perform (const InvocationInfo& info)
  15391. {
  15392. if (info.commandID == StandardApplicationCommandIDs::quit)
  15393. {
  15394. systemRequestedQuit();
  15395. return true;
  15396. }
  15397. return false;
  15398. }
  15399. bool JUCEApplication::initialiseApp (const String& commandLine)
  15400. {
  15401. commandLineParameters = commandLine.trim();
  15402. #if ! JUCE_IOS
  15403. jassert (appLock == 0); // initialiseApp must only be called once!
  15404. if (! moreThanOneInstanceAllowed())
  15405. {
  15406. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15407. if (! appLock->enter(0))
  15408. {
  15409. appLock = 0;
  15410. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15411. DBG ("Another instance is running - quitting...");
  15412. return false;
  15413. }
  15414. }
  15415. #endif
  15416. // let the app do its setting-up..
  15417. initialise (commandLineParameters);
  15418. #if JUCE_MAC
  15419. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15420. #endif
  15421. // register for broadcast new app messages
  15422. MessageManager::getInstance()->registerBroadcastListener (this);
  15423. stillInitialising = false;
  15424. return true;
  15425. }
  15426. int JUCEApplication::shutdownApp()
  15427. {
  15428. jassert (appInstance == this);
  15429. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15430. JUCE_TRY
  15431. {
  15432. // give the app a chance to clean up..
  15433. shutdown();
  15434. }
  15435. JUCE_CATCH_EXCEPTION
  15436. return getApplicationReturnValue();
  15437. }
  15438. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15439. void JUCEApplication::appWillTerminateByForce()
  15440. {
  15441. {
  15442. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15443. if (app != 0)
  15444. app->shutdownApp();
  15445. }
  15446. shutdownJuce_GUI();
  15447. }
  15448. int JUCEApplication::main (const String& commandLine)
  15449. {
  15450. ScopedJuceInitialiser_GUI libraryInitialiser;
  15451. jassert (createInstance != 0);
  15452. int returnCode = 0;
  15453. {
  15454. const ScopedPointer<JUCEApplication> app (createInstance());
  15455. if (! app->initialiseApp (commandLine))
  15456. return 0;
  15457. JUCE_TRY
  15458. {
  15459. // loop until a quit message is received..
  15460. MessageManager::getInstance()->runDispatchLoop();
  15461. }
  15462. JUCE_CATCH_EXCEPTION
  15463. returnCode = app->shutdownApp();
  15464. }
  15465. return returnCode;
  15466. }
  15467. #if JUCE_IOS
  15468. extern int juce_iOSMain (int argc, const char* argv[]);
  15469. #endif
  15470. #if ! JUCE_WINDOWS
  15471. extern const char* juce_Argv0;
  15472. #endif
  15473. int JUCEApplication::main (int argc, const char* argv[])
  15474. {
  15475. JUCE_AUTORELEASEPOOL
  15476. #if ! JUCE_WINDOWS
  15477. jassert (createInstance != 0);
  15478. juce_Argv0 = argv[0];
  15479. #endif
  15480. #if JUCE_IOS
  15481. return juce_iOSMain (argc, argv);
  15482. #else
  15483. String cmd;
  15484. for (int i = 1; i < argc; ++i)
  15485. cmd << argv[i] << ' ';
  15486. return JUCEApplication::main (cmd);
  15487. #endif
  15488. }
  15489. END_JUCE_NAMESPACE
  15490. /*** End of inlined file: juce_Application.cpp ***/
  15491. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15492. BEGIN_JUCE_NAMESPACE
  15493. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15494. : commandID (commandID_),
  15495. flags (0)
  15496. {
  15497. }
  15498. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15499. const String& description_,
  15500. const String& categoryName_,
  15501. const int flags_) throw()
  15502. {
  15503. shortName = shortName_;
  15504. description = description_;
  15505. categoryName = categoryName_;
  15506. flags = flags_;
  15507. }
  15508. void ApplicationCommandInfo::setActive (const bool b) throw()
  15509. {
  15510. if (b)
  15511. flags &= ~isDisabled;
  15512. else
  15513. flags |= isDisabled;
  15514. }
  15515. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15516. {
  15517. if (b)
  15518. flags |= isTicked;
  15519. else
  15520. flags &= ~isTicked;
  15521. }
  15522. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15523. {
  15524. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15525. }
  15526. END_JUCE_NAMESPACE
  15527. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15528. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15529. BEGIN_JUCE_NAMESPACE
  15530. ApplicationCommandManager::ApplicationCommandManager()
  15531. : firstTarget (0)
  15532. {
  15533. keyMappings = new KeyPressMappingSet (this);
  15534. Desktop::getInstance().addFocusChangeListener (this);
  15535. }
  15536. ApplicationCommandManager::~ApplicationCommandManager()
  15537. {
  15538. Desktop::getInstance().removeFocusChangeListener (this);
  15539. keyMappings = 0;
  15540. }
  15541. void ApplicationCommandManager::clearCommands()
  15542. {
  15543. commands.clear();
  15544. keyMappings->clearAllKeyPresses();
  15545. triggerAsyncUpdate();
  15546. }
  15547. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15548. {
  15549. // zero isn't a valid command ID!
  15550. jassert (newCommand.commandID != 0);
  15551. // the name isn't optional!
  15552. jassert (newCommand.shortName.isNotEmpty());
  15553. if (getCommandForID (newCommand.commandID) == 0)
  15554. {
  15555. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15556. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15557. commands.add (newInfo);
  15558. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15559. triggerAsyncUpdate();
  15560. }
  15561. else
  15562. {
  15563. // trying to re-register the same command with different parameters?
  15564. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15565. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15566. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15567. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15568. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15569. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15570. }
  15571. }
  15572. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15573. {
  15574. if (target != 0)
  15575. {
  15576. Array <CommandID> commandIDs;
  15577. target->getAllCommands (commandIDs);
  15578. for (int i = 0; i < commandIDs.size(); ++i)
  15579. {
  15580. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15581. target->getCommandInfo (info.commandID, info);
  15582. registerCommand (info);
  15583. }
  15584. }
  15585. }
  15586. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15587. {
  15588. for (int i = commands.size(); --i >= 0;)
  15589. {
  15590. if (commands.getUnchecked (i)->commandID == commandID)
  15591. {
  15592. commands.remove (i);
  15593. triggerAsyncUpdate();
  15594. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15595. for (int j = keys.size(); --j >= 0;)
  15596. keyMappings->removeKeyPress (keys.getReference (j));
  15597. }
  15598. }
  15599. }
  15600. void ApplicationCommandManager::commandStatusChanged()
  15601. {
  15602. triggerAsyncUpdate();
  15603. }
  15604. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15605. {
  15606. for (int i = commands.size(); --i >= 0;)
  15607. if (commands.getUnchecked(i)->commandID == commandID)
  15608. return commands.getUnchecked(i);
  15609. return 0;
  15610. }
  15611. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15612. {
  15613. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15614. return (ci != 0) ? ci->shortName : String::empty;
  15615. }
  15616. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15617. {
  15618. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15619. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15620. : String::empty;
  15621. }
  15622. const StringArray ApplicationCommandManager::getCommandCategories() const
  15623. {
  15624. StringArray s;
  15625. for (int i = 0; i < commands.size(); ++i)
  15626. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15627. return s;
  15628. }
  15629. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15630. {
  15631. Array <CommandID> results;
  15632. for (int i = 0; i < commands.size(); ++i)
  15633. if (commands.getUnchecked(i)->categoryName == categoryName)
  15634. results.add (commands.getUnchecked(i)->commandID);
  15635. return results;
  15636. }
  15637. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15638. {
  15639. ApplicationCommandTarget::InvocationInfo info (commandID);
  15640. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15641. return invoke (info, asynchronously);
  15642. }
  15643. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15644. {
  15645. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15646. // manager first..
  15647. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15648. ApplicationCommandInfo commandInfo (0);
  15649. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15650. if (target == 0)
  15651. return false;
  15652. ApplicationCommandTarget::InvocationInfo info (info_);
  15653. info.commandFlags = commandInfo.flags;
  15654. sendListenerInvokeCallback (info);
  15655. const bool ok = target->invoke (info, asynchronously);
  15656. commandStatusChanged();
  15657. return ok;
  15658. }
  15659. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15660. {
  15661. return firstTarget != 0 ? firstTarget
  15662. : findDefaultComponentTarget();
  15663. }
  15664. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15665. {
  15666. firstTarget = newTarget;
  15667. }
  15668. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15669. ApplicationCommandInfo& upToDateInfo)
  15670. {
  15671. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15672. if (target == 0)
  15673. target = JUCEApplication::getInstance();
  15674. if (target != 0)
  15675. target = target->getTargetForCommand (commandID);
  15676. if (target != 0)
  15677. target->getCommandInfo (commandID, upToDateInfo);
  15678. return target;
  15679. }
  15680. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15681. {
  15682. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15683. if (target == 0 && c != 0)
  15684. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15685. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15686. return target;
  15687. }
  15688. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15689. {
  15690. Component* c = Component::getCurrentlyFocusedComponent();
  15691. if (c == 0)
  15692. {
  15693. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15694. if (activeWindow != 0)
  15695. {
  15696. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15697. if (c == 0)
  15698. c = activeWindow;
  15699. }
  15700. }
  15701. if (c == 0 && Process::isForegroundProcess())
  15702. {
  15703. // getting a bit desperate now - try all desktop comps..
  15704. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15705. {
  15706. ApplicationCommandTarget* const target
  15707. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15708. ->getPeer()->getLastFocusedSubcomponent());
  15709. if (target != 0)
  15710. return target;
  15711. }
  15712. }
  15713. if (c != 0)
  15714. {
  15715. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15716. // if we're focused on a ResizableWindow, chances are that it's the content
  15717. // component that really should get the event. And if not, the event will
  15718. // still be passed up to the top level window anyway, so let's send it to the
  15719. // content comp.
  15720. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15721. c = resizableWindow->getContentComponent();
  15722. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15723. if (target != 0)
  15724. return target;
  15725. }
  15726. return JUCEApplication::getInstance();
  15727. }
  15728. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15729. {
  15730. listeners.add (listener);
  15731. }
  15732. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15733. {
  15734. listeners.remove (listener);
  15735. }
  15736. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15737. {
  15738. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15739. }
  15740. void ApplicationCommandManager::handleAsyncUpdate()
  15741. {
  15742. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15743. }
  15744. void ApplicationCommandManager::globalFocusChanged (Component*)
  15745. {
  15746. commandStatusChanged();
  15747. }
  15748. END_JUCE_NAMESPACE
  15749. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15750. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15751. BEGIN_JUCE_NAMESPACE
  15752. ApplicationCommandTarget::ApplicationCommandTarget()
  15753. {
  15754. }
  15755. ApplicationCommandTarget::~ApplicationCommandTarget()
  15756. {
  15757. messageInvoker = 0;
  15758. }
  15759. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15760. {
  15761. if (isCommandActive (info.commandID))
  15762. {
  15763. if (async)
  15764. {
  15765. if (messageInvoker == 0)
  15766. messageInvoker = new CommandTargetMessageInvoker (this);
  15767. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15768. return true;
  15769. }
  15770. else
  15771. {
  15772. const bool success = perform (info);
  15773. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15774. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15775. // returns the command's info.
  15776. return success;
  15777. }
  15778. }
  15779. return false;
  15780. }
  15781. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15782. {
  15783. Component* c = dynamic_cast <Component*> (this);
  15784. if (c != 0)
  15785. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15786. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15787. return 0;
  15788. }
  15789. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15790. {
  15791. ApplicationCommandTarget* target = this;
  15792. int depth = 0;
  15793. while (target != 0)
  15794. {
  15795. Array <CommandID> commandIDs;
  15796. target->getAllCommands (commandIDs);
  15797. if (commandIDs.contains (commandID))
  15798. return target;
  15799. target = target->getNextCommandTarget();
  15800. ++depth;
  15801. jassert (depth < 100); // could be a recursive command chain??
  15802. jassert (target != this); // definitely a recursive command chain!
  15803. if (depth > 100 || target == this)
  15804. break;
  15805. }
  15806. if (target == 0)
  15807. {
  15808. target = JUCEApplication::getInstance();
  15809. if (target != 0)
  15810. {
  15811. Array <CommandID> commandIDs;
  15812. target->getAllCommands (commandIDs);
  15813. if (commandIDs.contains (commandID))
  15814. return target;
  15815. }
  15816. }
  15817. return 0;
  15818. }
  15819. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15820. {
  15821. ApplicationCommandInfo info (commandID);
  15822. info.flags = ApplicationCommandInfo::isDisabled;
  15823. getCommandInfo (commandID, info);
  15824. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15825. }
  15826. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15827. {
  15828. ApplicationCommandTarget* target = this;
  15829. int depth = 0;
  15830. while (target != 0)
  15831. {
  15832. if (target->tryToInvoke (info, async))
  15833. return true;
  15834. target = target->getNextCommandTarget();
  15835. ++depth;
  15836. jassert (depth < 100); // could be a recursive command chain??
  15837. jassert (target != this); // definitely a recursive command chain!
  15838. if (depth > 100 || target == this)
  15839. break;
  15840. }
  15841. if (target == 0)
  15842. {
  15843. target = JUCEApplication::getInstance();
  15844. if (target != 0)
  15845. return target->tryToInvoke (info, async);
  15846. }
  15847. return false;
  15848. }
  15849. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15850. {
  15851. ApplicationCommandTarget::InvocationInfo info (commandID);
  15852. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15853. return invoke (info, asynchronously);
  15854. }
  15855. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15856. : commandID (commandID_),
  15857. commandFlags (0),
  15858. invocationMethod (direct),
  15859. originatingComponent (0),
  15860. isKeyDown (false),
  15861. millisecsSinceKeyPressed (0)
  15862. {
  15863. }
  15864. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15865. : owner (owner_)
  15866. {
  15867. }
  15868. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15869. {
  15870. }
  15871. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15872. {
  15873. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15874. owner->tryToInvoke (*info, false);
  15875. }
  15876. END_JUCE_NAMESPACE
  15877. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15878. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15879. BEGIN_JUCE_NAMESPACE
  15880. juce_ImplementSingleton (ApplicationProperties)
  15881. ApplicationProperties::ApplicationProperties()
  15882. : msBeforeSaving (3000),
  15883. options (PropertiesFile::storeAsBinary),
  15884. commonSettingsAreReadOnly (0),
  15885. processLock (0)
  15886. {
  15887. }
  15888. ApplicationProperties::~ApplicationProperties()
  15889. {
  15890. closeFiles();
  15891. clearSingletonInstance();
  15892. }
  15893. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15894. const String& fileNameSuffix,
  15895. const String& folderName_,
  15896. const int millisecondsBeforeSaving,
  15897. const int propertiesFileOptions,
  15898. InterProcessLock* processLock_)
  15899. {
  15900. appName = applicationName;
  15901. fileSuffix = fileNameSuffix;
  15902. folderName = folderName_;
  15903. msBeforeSaving = millisecondsBeforeSaving;
  15904. options = propertiesFileOptions;
  15905. processLock = processLock_;
  15906. }
  15907. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15908. const bool testCommonSettings,
  15909. const bool showWarningDialogOnFailure)
  15910. {
  15911. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15912. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15913. if (! (userOk && commonOk))
  15914. {
  15915. if (showWarningDialogOnFailure)
  15916. {
  15917. String filenames;
  15918. if (userProps != 0 && ! userOk)
  15919. filenames << '\n' << userProps->getFile().getFullPathName();
  15920. if (commonProps != 0 && ! commonOk)
  15921. filenames << '\n' << commonProps->getFile().getFullPathName();
  15922. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15923. appName + TRANS(" - Unable to save settings"),
  15924. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15925. + appName + TRANS(" needs to be able to write to the following files:\n")
  15926. + filenames
  15927. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15928. }
  15929. return false;
  15930. }
  15931. return true;
  15932. }
  15933. void ApplicationProperties::openFiles()
  15934. {
  15935. // You need to call setStorageParameters() before trying to get hold of the
  15936. // properties!
  15937. jassert (appName.isNotEmpty());
  15938. if (appName.isNotEmpty())
  15939. {
  15940. if (userProps == 0)
  15941. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15942. false, msBeforeSaving, options, processLock);
  15943. if (commonProps == 0)
  15944. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15945. true, msBeforeSaving, options, processLock);
  15946. userProps->setFallbackPropertySet (commonProps);
  15947. }
  15948. }
  15949. PropertiesFile* ApplicationProperties::getUserSettings()
  15950. {
  15951. if (userProps == 0)
  15952. openFiles();
  15953. return userProps;
  15954. }
  15955. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15956. {
  15957. if (commonProps == 0)
  15958. openFiles();
  15959. if (returnUserPropsIfReadOnly)
  15960. {
  15961. if (commonSettingsAreReadOnly == 0)
  15962. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15963. if (commonSettingsAreReadOnly > 0)
  15964. return userProps;
  15965. }
  15966. return commonProps;
  15967. }
  15968. bool ApplicationProperties::saveIfNeeded()
  15969. {
  15970. return (userProps == 0 || userProps->saveIfNeeded())
  15971. && (commonProps == 0 || commonProps->saveIfNeeded());
  15972. }
  15973. void ApplicationProperties::closeFiles()
  15974. {
  15975. userProps = 0;
  15976. commonProps = 0;
  15977. }
  15978. END_JUCE_NAMESPACE
  15979. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15980. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15981. BEGIN_JUCE_NAMESPACE
  15982. namespace PropertyFileConstants
  15983. {
  15984. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15985. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15986. static const char* const fileTag = "PROPERTIES";
  15987. static const char* const valueTag = "VALUE";
  15988. static const char* const nameAttribute = "name";
  15989. static const char* const valueAttribute = "val";
  15990. }
  15991. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15992. const int options_, InterProcessLock* const processLock_)
  15993. : PropertySet (ignoreCaseOfKeyNames),
  15994. file (f),
  15995. timerInterval (millisecondsBeforeSaving),
  15996. options (options_),
  15997. loadedOk (false),
  15998. needsWriting (false),
  15999. processLock (processLock_)
  16000. {
  16001. // You need to correctly specify just one storage format for the file
  16002. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  16003. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  16004. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  16005. ProcessScopedLock pl (createProcessLock());
  16006. if (pl != 0 && ! pl->isLocked())
  16007. return; // locking failure..
  16008. ScopedPointer<InputStream> fileStream (f.createInputStream());
  16009. if (fileStream != 0)
  16010. {
  16011. int magicNumber = fileStream->readInt();
  16012. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  16013. {
  16014. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  16015. magicNumber = PropertyFileConstants::magicNumber;
  16016. }
  16017. if (magicNumber == PropertyFileConstants::magicNumber)
  16018. {
  16019. loadedOk = true;
  16020. BufferedInputStream in (fileStream.release(), 2048, true);
  16021. int numValues = in.readInt();
  16022. while (--numValues >= 0 && ! in.isExhausted())
  16023. {
  16024. const String key (in.readString());
  16025. const String value (in.readString());
  16026. jassert (key.isNotEmpty());
  16027. if (key.isNotEmpty())
  16028. getAllProperties().set (key, value);
  16029. }
  16030. }
  16031. else
  16032. {
  16033. // Not a binary props file - let's see if it's XML..
  16034. fileStream = 0;
  16035. XmlDocument parser (f);
  16036. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  16037. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  16038. {
  16039. doc = parser.getDocumentElement();
  16040. if (doc != 0)
  16041. {
  16042. loadedOk = true;
  16043. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  16044. {
  16045. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  16046. if (name.isNotEmpty())
  16047. {
  16048. getAllProperties().set (name,
  16049. e->getFirstChildElement() != 0
  16050. ? e->getFirstChildElement()->createDocument (String::empty, true)
  16051. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  16052. }
  16053. }
  16054. }
  16055. else
  16056. {
  16057. // must be a pretty broken XML file we're trying to parse here,
  16058. // or a sign that this object needs an InterProcessLock,
  16059. // or just a failure reading the file. This last reason is why
  16060. // we don't jassertfalse here.
  16061. }
  16062. }
  16063. }
  16064. }
  16065. else
  16066. {
  16067. loadedOk = ! f.exists();
  16068. }
  16069. }
  16070. PropertiesFile::~PropertiesFile()
  16071. {
  16072. if (! saveIfNeeded())
  16073. jassertfalse;
  16074. }
  16075. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  16076. {
  16077. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  16078. }
  16079. bool PropertiesFile::saveIfNeeded()
  16080. {
  16081. const ScopedLock sl (getLock());
  16082. return (! needsWriting) || save();
  16083. }
  16084. bool PropertiesFile::needsToBeSaved() const
  16085. {
  16086. const ScopedLock sl (getLock());
  16087. return needsWriting;
  16088. }
  16089. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  16090. {
  16091. const ScopedLock sl (getLock());
  16092. needsWriting = needsToBeSaved_;
  16093. }
  16094. bool PropertiesFile::save()
  16095. {
  16096. const ScopedLock sl (getLock());
  16097. stopTimer();
  16098. if (file == File::nonexistent
  16099. || file.isDirectory()
  16100. || ! file.getParentDirectory().createDirectory())
  16101. return false;
  16102. if ((options & storeAsXML) != 0)
  16103. {
  16104. XmlElement doc (PropertyFileConstants::fileTag);
  16105. for (int i = 0; i < getAllProperties().size(); ++i)
  16106. {
  16107. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  16108. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  16109. // if the value seems to contain xml, store it as such..
  16110. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  16111. if (childElement != 0)
  16112. e->addChildElement (childElement);
  16113. else
  16114. e->setAttribute (PropertyFileConstants::valueAttribute,
  16115. getAllProperties().getAllValues() [i]);
  16116. }
  16117. ProcessScopedLock pl (createProcessLock());
  16118. if (pl != 0 && ! pl->isLocked())
  16119. return false; // locking failure..
  16120. if (doc.writeToFile (file, String::empty))
  16121. {
  16122. needsWriting = false;
  16123. return true;
  16124. }
  16125. }
  16126. else
  16127. {
  16128. ProcessScopedLock pl (createProcessLock());
  16129. if (pl != 0 && ! pl->isLocked())
  16130. return false; // locking failure..
  16131. TemporaryFile tempFile (file);
  16132. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  16133. if (out != 0)
  16134. {
  16135. if ((options & storeAsCompressedBinary) != 0)
  16136. {
  16137. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  16138. out->flush();
  16139. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  16140. }
  16141. else
  16142. {
  16143. // have you set up the storage option flags correctly?
  16144. jassert ((options & storeAsBinary) != 0);
  16145. out->writeInt (PropertyFileConstants::magicNumber);
  16146. }
  16147. const int numProperties = getAllProperties().size();
  16148. out->writeInt (numProperties);
  16149. for (int i = 0; i < numProperties; ++i)
  16150. {
  16151. out->writeString (getAllProperties().getAllKeys() [i]);
  16152. out->writeString (getAllProperties().getAllValues() [i]);
  16153. }
  16154. out = 0;
  16155. if (tempFile.overwriteTargetFileWithTemporary())
  16156. {
  16157. needsWriting = false;
  16158. return true;
  16159. }
  16160. }
  16161. }
  16162. return false;
  16163. }
  16164. void PropertiesFile::timerCallback()
  16165. {
  16166. saveIfNeeded();
  16167. }
  16168. void PropertiesFile::propertyChanged()
  16169. {
  16170. sendChangeMessage();
  16171. needsWriting = true;
  16172. if (timerInterval > 0)
  16173. startTimer (timerInterval);
  16174. else if (timerInterval == 0)
  16175. saveIfNeeded();
  16176. }
  16177. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  16178. const String& fileNameSuffix,
  16179. const String& folderName,
  16180. const bool commonToAllUsers)
  16181. {
  16182. // mustn't have illegal characters in this name..
  16183. jassert (applicationName == File::createLegalFileName (applicationName));
  16184. #if JUCE_MAC || JUCE_IOS
  16185. File dir (commonToAllUsers ? "/Library/Preferences"
  16186. : "~/Library/Preferences");
  16187. if (folderName.isNotEmpty())
  16188. dir = dir.getChildFile (folderName);
  16189. #endif
  16190. #ifdef JUCE_LINUX
  16191. const File dir ((commonToAllUsers ? "/var/" : "~/")
  16192. + (folderName.isNotEmpty() ? folderName
  16193. : ("." + applicationName)));
  16194. #endif
  16195. #if JUCE_WINDOWS
  16196. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  16197. : File::userApplicationDataDirectory));
  16198. if (dir == File::nonexistent)
  16199. return File::nonexistent;
  16200. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  16201. : applicationName);
  16202. #endif
  16203. return dir.getChildFile (applicationName)
  16204. .withFileExtension (fileNameSuffix);
  16205. }
  16206. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  16207. const String& fileNameSuffix,
  16208. const String& folderName,
  16209. const bool commonToAllUsers,
  16210. const int millisecondsBeforeSaving,
  16211. const int propertiesFileOptions,
  16212. InterProcessLock* processLock_)
  16213. {
  16214. const File file (getDefaultAppSettingsFile (applicationName,
  16215. fileNameSuffix,
  16216. folderName,
  16217. commonToAllUsers));
  16218. jassert (file != File::nonexistent);
  16219. if (file == File::nonexistent)
  16220. return 0;
  16221. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  16222. }
  16223. END_JUCE_NAMESPACE
  16224. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  16225. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  16226. BEGIN_JUCE_NAMESPACE
  16227. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  16228. const String& fileWildcard_,
  16229. const String& openFileDialogTitle_,
  16230. const String& saveFileDialogTitle_)
  16231. : changedSinceSave (false),
  16232. fileExtension (fileExtension_),
  16233. fileWildcard (fileWildcard_),
  16234. openFileDialogTitle (openFileDialogTitle_),
  16235. saveFileDialogTitle (saveFileDialogTitle_)
  16236. {
  16237. }
  16238. FileBasedDocument::~FileBasedDocument()
  16239. {
  16240. }
  16241. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  16242. {
  16243. if (changedSinceSave != hasChanged)
  16244. {
  16245. changedSinceSave = hasChanged;
  16246. sendChangeMessage();
  16247. }
  16248. }
  16249. void FileBasedDocument::changed()
  16250. {
  16251. changedSinceSave = true;
  16252. sendChangeMessage();
  16253. }
  16254. void FileBasedDocument::setFile (const File& newFile)
  16255. {
  16256. if (documentFile != newFile)
  16257. {
  16258. documentFile = newFile;
  16259. changed();
  16260. }
  16261. }
  16262. bool FileBasedDocument::loadFrom (const File& newFile,
  16263. const bool showMessageOnFailure)
  16264. {
  16265. MouseCursor::showWaitCursor();
  16266. const File oldFile (documentFile);
  16267. documentFile = newFile;
  16268. String error;
  16269. if (newFile.existsAsFile())
  16270. {
  16271. error = loadDocument (newFile);
  16272. if (error.isEmpty())
  16273. {
  16274. setChangedFlag (false);
  16275. MouseCursor::hideWaitCursor();
  16276. setLastDocumentOpened (newFile);
  16277. return true;
  16278. }
  16279. }
  16280. else
  16281. {
  16282. error = "The file doesn't exist";
  16283. }
  16284. documentFile = oldFile;
  16285. MouseCursor::hideWaitCursor();
  16286. if (showMessageOnFailure)
  16287. {
  16288. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16289. TRANS("Failed to open file..."),
  16290. TRANS("There was an error while trying to load the file:\n\n")
  16291. + newFile.getFullPathName()
  16292. + "\n\n"
  16293. + error);
  16294. }
  16295. return false;
  16296. }
  16297. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16298. {
  16299. FileChooser fc (openFileDialogTitle,
  16300. getLastDocumentOpened(),
  16301. fileWildcard);
  16302. if (fc.browseForFileToOpen())
  16303. return loadFrom (fc.getResult(), showMessageOnFailure);
  16304. return false;
  16305. }
  16306. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16307. const bool showMessageOnFailure)
  16308. {
  16309. return saveAs (documentFile,
  16310. false,
  16311. askUserForFileIfNotSpecified,
  16312. showMessageOnFailure);
  16313. }
  16314. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16315. const bool warnAboutOverwritingExistingFiles,
  16316. const bool askUserForFileIfNotSpecified,
  16317. const bool showMessageOnFailure)
  16318. {
  16319. if (newFile == File::nonexistent)
  16320. {
  16321. if (askUserForFileIfNotSpecified)
  16322. {
  16323. return saveAsInteractive (true);
  16324. }
  16325. else
  16326. {
  16327. // can't save to an unspecified file
  16328. jassertfalse;
  16329. return failedToWriteToFile;
  16330. }
  16331. }
  16332. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16333. {
  16334. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16335. TRANS("File already exists"),
  16336. TRANS("There's already a file called:\n\n")
  16337. + newFile.getFullPathName()
  16338. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16339. TRANS("overwrite"),
  16340. TRANS("cancel")))
  16341. {
  16342. return userCancelledSave;
  16343. }
  16344. }
  16345. MouseCursor::showWaitCursor();
  16346. const File oldFile (documentFile);
  16347. documentFile = newFile;
  16348. String error (saveDocument (newFile));
  16349. if (error.isEmpty())
  16350. {
  16351. setChangedFlag (false);
  16352. MouseCursor::hideWaitCursor();
  16353. return savedOk;
  16354. }
  16355. documentFile = oldFile;
  16356. MouseCursor::hideWaitCursor();
  16357. if (showMessageOnFailure)
  16358. {
  16359. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16360. TRANS("Error writing to file..."),
  16361. TRANS("An error occurred while trying to save \"")
  16362. + getDocumentTitle()
  16363. + TRANS("\" to the file:\n\n")
  16364. + newFile.getFullPathName()
  16365. + "\n\n"
  16366. + error);
  16367. }
  16368. return failedToWriteToFile;
  16369. }
  16370. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16371. {
  16372. if (! hasChangedSinceSaved())
  16373. return savedOk;
  16374. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16375. TRANS("Closing document..."),
  16376. TRANS("Do you want to save the changes to \"")
  16377. + getDocumentTitle() + "\"?",
  16378. TRANS("save"),
  16379. TRANS("discard changes"),
  16380. TRANS("cancel"));
  16381. if (r == 1)
  16382. {
  16383. // save changes
  16384. return save (true, true);
  16385. }
  16386. else if (r == 2)
  16387. {
  16388. // discard changes
  16389. return savedOk;
  16390. }
  16391. return userCancelledSave;
  16392. }
  16393. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16394. {
  16395. File f;
  16396. if (documentFile.existsAsFile())
  16397. f = documentFile;
  16398. else
  16399. f = getLastDocumentOpened();
  16400. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16401. if (legalFilename.isEmpty())
  16402. legalFilename = "unnamed";
  16403. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16404. f = f.getSiblingFile (legalFilename);
  16405. else
  16406. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16407. f = f.withFileExtension (fileExtension)
  16408. .getNonexistentSibling (true);
  16409. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16410. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16411. {
  16412. File chosen (fc.getResult());
  16413. if (chosen.getFileExtension().isEmpty())
  16414. {
  16415. chosen = chosen.withFileExtension (fileExtension);
  16416. if (chosen.exists())
  16417. {
  16418. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16419. TRANS("File already exists"),
  16420. TRANS("There's already a file called:")
  16421. + "\n\n" + chosen.getFullPathName()
  16422. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16423. TRANS("overwrite"),
  16424. TRANS("cancel")))
  16425. {
  16426. return userCancelledSave;
  16427. }
  16428. }
  16429. }
  16430. setLastDocumentOpened (chosen);
  16431. return saveAs (chosen, false, false, true);
  16432. }
  16433. return userCancelledSave;
  16434. }
  16435. END_JUCE_NAMESPACE
  16436. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16437. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16438. BEGIN_JUCE_NAMESPACE
  16439. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16440. : maxNumberOfItems (10)
  16441. {
  16442. }
  16443. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16444. {
  16445. }
  16446. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16447. {
  16448. maxNumberOfItems = jmax (1, newMaxNumber);
  16449. while (getNumFiles() > maxNumberOfItems)
  16450. files.remove (getNumFiles() - 1);
  16451. }
  16452. int RecentlyOpenedFilesList::getNumFiles() const
  16453. {
  16454. return files.size();
  16455. }
  16456. const File RecentlyOpenedFilesList::getFile (const int index) const
  16457. {
  16458. return File (files [index]);
  16459. }
  16460. void RecentlyOpenedFilesList::clear()
  16461. {
  16462. files.clear();
  16463. }
  16464. void RecentlyOpenedFilesList::addFile (const File& file)
  16465. {
  16466. const String path (file.getFullPathName());
  16467. files.removeString (path, true);
  16468. files.insert (0, path);
  16469. setMaxNumberOfItems (maxNumberOfItems);
  16470. }
  16471. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16472. {
  16473. for (int i = getNumFiles(); --i >= 0;)
  16474. if (! getFile(i).exists())
  16475. files.remove (i);
  16476. }
  16477. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16478. const int baseItemId,
  16479. const bool showFullPaths,
  16480. const bool dontAddNonExistentFiles,
  16481. const File** filesToAvoid)
  16482. {
  16483. int num = 0;
  16484. for (int i = 0; i < getNumFiles(); ++i)
  16485. {
  16486. const File f (getFile(i));
  16487. if ((! dontAddNonExistentFiles) || f.exists())
  16488. {
  16489. bool needsAvoiding = false;
  16490. if (filesToAvoid != 0)
  16491. {
  16492. const File** avoid = filesToAvoid;
  16493. while (*avoid != 0)
  16494. {
  16495. if (f == **avoid)
  16496. {
  16497. needsAvoiding = true;
  16498. break;
  16499. }
  16500. ++avoid;
  16501. }
  16502. }
  16503. if (! needsAvoiding)
  16504. {
  16505. menuToAddTo.addItem (baseItemId + i,
  16506. showFullPaths ? f.getFullPathName()
  16507. : f.getFileName());
  16508. ++num;
  16509. }
  16510. }
  16511. }
  16512. return num;
  16513. }
  16514. const String RecentlyOpenedFilesList::toString() const
  16515. {
  16516. return files.joinIntoString ("\n");
  16517. }
  16518. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16519. {
  16520. clear();
  16521. files.addLines (stringifiedVersion);
  16522. setMaxNumberOfItems (maxNumberOfItems);
  16523. }
  16524. END_JUCE_NAMESPACE
  16525. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16526. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16527. BEGIN_JUCE_NAMESPACE
  16528. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16529. const int minimumTransactions)
  16530. : totalUnitsStored (0),
  16531. nextIndex (0),
  16532. newTransaction (true),
  16533. reentrancyCheck (false)
  16534. {
  16535. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16536. minimumTransactions);
  16537. }
  16538. UndoManager::~UndoManager()
  16539. {
  16540. clearUndoHistory();
  16541. }
  16542. void UndoManager::clearUndoHistory()
  16543. {
  16544. transactions.clear();
  16545. transactionNames.clear();
  16546. totalUnitsStored = 0;
  16547. nextIndex = 0;
  16548. sendChangeMessage();
  16549. }
  16550. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16551. {
  16552. return totalUnitsStored;
  16553. }
  16554. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16555. const int minimumTransactions)
  16556. {
  16557. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16558. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16559. }
  16560. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16561. {
  16562. if (command_ != 0)
  16563. {
  16564. ScopedPointer<UndoableAction> command (command_);
  16565. if (actionName.isNotEmpty())
  16566. currentTransactionName = actionName;
  16567. if (reentrancyCheck)
  16568. {
  16569. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16570. // undo() methods, or else these actions won't actually get done.
  16571. return false;
  16572. }
  16573. else if (command->perform())
  16574. {
  16575. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16576. if (commandSet != 0 && ! newTransaction)
  16577. {
  16578. UndoableAction* lastAction = commandSet->getLast();
  16579. if (lastAction != 0)
  16580. {
  16581. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16582. if (coalescedAction != 0)
  16583. {
  16584. command = coalescedAction;
  16585. totalUnitsStored -= lastAction->getSizeInUnits();
  16586. commandSet->removeLast();
  16587. }
  16588. }
  16589. }
  16590. else
  16591. {
  16592. commandSet = new OwnedArray<UndoableAction>();
  16593. transactions.insert (nextIndex, commandSet);
  16594. transactionNames.insert (nextIndex, currentTransactionName);
  16595. ++nextIndex;
  16596. }
  16597. totalUnitsStored += command->getSizeInUnits();
  16598. commandSet->add (command.release());
  16599. newTransaction = false;
  16600. while (nextIndex < transactions.size())
  16601. {
  16602. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16603. for (int i = lastSet->size(); --i >= 0;)
  16604. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16605. transactions.removeLast();
  16606. transactionNames.remove (transactionNames.size() - 1);
  16607. }
  16608. while (nextIndex > 0
  16609. && totalUnitsStored > maxNumUnitsToKeep
  16610. && transactions.size() > minimumTransactionsToKeep)
  16611. {
  16612. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16613. for (int i = firstSet->size(); --i >= 0;)
  16614. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16615. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16616. transactions.remove (0);
  16617. transactionNames.remove (0);
  16618. --nextIndex;
  16619. }
  16620. sendChangeMessage();
  16621. return true;
  16622. }
  16623. }
  16624. return false;
  16625. }
  16626. void UndoManager::beginNewTransaction (const String& actionName)
  16627. {
  16628. newTransaction = true;
  16629. currentTransactionName = actionName;
  16630. }
  16631. void UndoManager::setCurrentTransactionName (const String& newName)
  16632. {
  16633. currentTransactionName = newName;
  16634. }
  16635. bool UndoManager::canUndo() const
  16636. {
  16637. return nextIndex > 0;
  16638. }
  16639. bool UndoManager::canRedo() const
  16640. {
  16641. return nextIndex < transactions.size();
  16642. }
  16643. const String UndoManager::getUndoDescription() const
  16644. {
  16645. return transactionNames [nextIndex - 1];
  16646. }
  16647. const String UndoManager::getRedoDescription() const
  16648. {
  16649. return transactionNames [nextIndex];
  16650. }
  16651. bool UndoManager::undo()
  16652. {
  16653. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16654. if (commandSet == 0)
  16655. return false;
  16656. reentrancyCheck = true;
  16657. bool failed = false;
  16658. for (int i = commandSet->size(); --i >= 0;)
  16659. {
  16660. if (! commandSet->getUnchecked(i)->undo())
  16661. {
  16662. jassertfalse;
  16663. failed = true;
  16664. break;
  16665. }
  16666. }
  16667. reentrancyCheck = false;
  16668. if (failed)
  16669. clearUndoHistory();
  16670. else
  16671. --nextIndex;
  16672. beginNewTransaction();
  16673. sendChangeMessage();
  16674. return true;
  16675. }
  16676. bool UndoManager::redo()
  16677. {
  16678. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16679. if (commandSet == 0)
  16680. return false;
  16681. reentrancyCheck = true;
  16682. bool failed = false;
  16683. for (int i = 0; i < commandSet->size(); ++i)
  16684. {
  16685. if (! commandSet->getUnchecked(i)->perform())
  16686. {
  16687. jassertfalse;
  16688. failed = true;
  16689. break;
  16690. }
  16691. }
  16692. reentrancyCheck = false;
  16693. if (failed)
  16694. clearUndoHistory();
  16695. else
  16696. ++nextIndex;
  16697. beginNewTransaction();
  16698. sendChangeMessage();
  16699. return true;
  16700. }
  16701. bool UndoManager::undoCurrentTransactionOnly()
  16702. {
  16703. return newTransaction ? false : undo();
  16704. }
  16705. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16706. {
  16707. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16708. if (commandSet != 0 && ! newTransaction)
  16709. {
  16710. for (int i = 0; i < commandSet->size(); ++i)
  16711. actionsFound.add (commandSet->getUnchecked(i));
  16712. }
  16713. }
  16714. int UndoManager::getNumActionsInCurrentTransaction() const
  16715. {
  16716. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16717. if (commandSet != 0 && ! newTransaction)
  16718. return commandSet->size();
  16719. return 0;
  16720. }
  16721. END_JUCE_NAMESPACE
  16722. /*** End of inlined file: juce_UndoManager.cpp ***/
  16723. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16724. BEGIN_JUCE_NAMESPACE
  16725. static const char* const aiffFormatName = "AIFF file";
  16726. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16727. class AiffAudioFormatReader : public AudioFormatReader
  16728. {
  16729. public:
  16730. int bytesPerFrame;
  16731. int64 dataChunkStart;
  16732. bool littleEndian;
  16733. AiffAudioFormatReader (InputStream* in)
  16734. : AudioFormatReader (in, TRANS (aiffFormatName))
  16735. {
  16736. if (input->readInt() == chunkName ("FORM"))
  16737. {
  16738. const int len = input->readIntBigEndian();
  16739. const int64 end = input->getPosition() + len;
  16740. const int nextType = input->readInt();
  16741. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16742. {
  16743. bool hasGotVer = false;
  16744. bool hasGotData = false;
  16745. bool hasGotType = false;
  16746. while (input->getPosition() < end)
  16747. {
  16748. const int type = input->readInt();
  16749. const uint32 length = (uint32) input->readIntBigEndian();
  16750. const int64 chunkEnd = input->getPosition() + length;
  16751. if (type == chunkName ("FVER"))
  16752. {
  16753. hasGotVer = true;
  16754. const int ver = input->readIntBigEndian();
  16755. if (ver != 0 && ver != (int) 0xa2805140)
  16756. break;
  16757. }
  16758. else if (type == chunkName ("COMM"))
  16759. {
  16760. hasGotType = true;
  16761. numChannels = (unsigned int) input->readShortBigEndian();
  16762. lengthInSamples = input->readIntBigEndian();
  16763. bitsPerSample = input->readShortBigEndian();
  16764. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16765. unsigned char sampleRateBytes[10];
  16766. input->read (sampleRateBytes, 10);
  16767. const int byte0 = sampleRateBytes[0];
  16768. if ((byte0 & 0x80) != 0
  16769. || byte0 <= 0x3F || byte0 > 0x40
  16770. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16771. break;
  16772. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16773. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16774. sampleRate = (int) sampRate;
  16775. if (length <= 18)
  16776. {
  16777. // some types don't have a chunk large enough to include a compression
  16778. // type, so assume it's just big-endian pcm
  16779. littleEndian = false;
  16780. }
  16781. else
  16782. {
  16783. const int compType = input->readInt();
  16784. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16785. {
  16786. littleEndian = false;
  16787. }
  16788. else if (compType == chunkName ("sowt"))
  16789. {
  16790. littleEndian = true;
  16791. }
  16792. else
  16793. {
  16794. sampleRate = 0;
  16795. break;
  16796. }
  16797. }
  16798. }
  16799. else if (type == chunkName ("SSND"))
  16800. {
  16801. hasGotData = true;
  16802. const int offset = input->readIntBigEndian();
  16803. dataChunkStart = input->getPosition() + 4 + offset;
  16804. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16805. }
  16806. else if ((hasGotVer && hasGotData && hasGotType)
  16807. || chunkEnd < input->getPosition()
  16808. || input->isExhausted())
  16809. {
  16810. break;
  16811. }
  16812. input->setPosition (chunkEnd);
  16813. }
  16814. }
  16815. }
  16816. }
  16817. ~AiffAudioFormatReader()
  16818. {
  16819. }
  16820. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16821. int64 startSampleInFile, int numSamples)
  16822. {
  16823. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16824. if (samplesAvailable < numSamples)
  16825. {
  16826. for (int i = numDestChannels; --i >= 0;)
  16827. if (destSamples[i] != 0)
  16828. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16829. numSamples = (int) samplesAvailable;
  16830. }
  16831. if (numSamples <= 0)
  16832. return true;
  16833. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16834. while (numSamples > 0)
  16835. {
  16836. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16837. char tempBuffer [tempBufSize];
  16838. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16839. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16840. if (bytesRead < numThisTime * bytesPerFrame)
  16841. {
  16842. jassert (bytesRead >= 0);
  16843. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16844. }
  16845. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16846. if (littleEndian)
  16847. {
  16848. switch (bitsPerSample)
  16849. {
  16850. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16851. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16852. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16853. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16854. default: jassertfalse; break;
  16855. }
  16856. }
  16857. else
  16858. {
  16859. switch (bitsPerSample)
  16860. {
  16861. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16862. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16863. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16864. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16865. default: jassertfalse; break;
  16866. }
  16867. }
  16868. startOffsetInDestBuffer += numThisTime;
  16869. numSamples -= numThisTime;
  16870. }
  16871. return true;
  16872. }
  16873. juce_UseDebuggingNewOperator
  16874. private:
  16875. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16876. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16877. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16878. };
  16879. class AiffAudioFormatWriter : public AudioFormatWriter
  16880. {
  16881. public:
  16882. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16883. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16884. lengthInSamples (0),
  16885. bytesWritten (0),
  16886. writeFailed (false)
  16887. {
  16888. headerPosition = out->getPosition();
  16889. writeHeader();
  16890. }
  16891. ~AiffAudioFormatWriter()
  16892. {
  16893. if ((bytesWritten & 1) != 0)
  16894. output->writeByte (0);
  16895. writeHeader();
  16896. }
  16897. bool write (const int** data, int numSamples)
  16898. {
  16899. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16900. if (writeFailed)
  16901. return false;
  16902. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16903. tempBlock.ensureSize (bytes, false);
  16904. switch (bitsPerSample)
  16905. {
  16906. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16907. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16908. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16909. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16910. default: jassertfalse; break;
  16911. }
  16912. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16913. || ! output->write (tempBlock.getData(), bytes))
  16914. {
  16915. // failed to write to disk, so let's try writing the header.
  16916. // If it's just run out of disk space, then if it does manage
  16917. // to write the header, we'll still have a useable file..
  16918. writeHeader();
  16919. writeFailed = true;
  16920. return false;
  16921. }
  16922. else
  16923. {
  16924. bytesWritten += bytes;
  16925. lengthInSamples += numSamples;
  16926. return true;
  16927. }
  16928. }
  16929. juce_UseDebuggingNewOperator
  16930. private:
  16931. MemoryBlock tempBlock;
  16932. uint32 lengthInSamples, bytesWritten;
  16933. int64 headerPosition;
  16934. bool writeFailed;
  16935. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16936. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16937. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16938. void writeHeader()
  16939. {
  16940. const bool couldSeekOk = output->setPosition (headerPosition);
  16941. (void) couldSeekOk;
  16942. // if this fails, you've given it an output stream that can't seek! It needs
  16943. // to be able to seek back to write the header
  16944. jassert (couldSeekOk);
  16945. const int headerLen = 54;
  16946. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16947. audioBytes += (audioBytes & 1);
  16948. output->writeInt (chunkName ("FORM"));
  16949. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16950. output->writeInt (chunkName ("AIFF"));
  16951. output->writeInt (chunkName ("COMM"));
  16952. output->writeIntBigEndian (18);
  16953. output->writeShortBigEndian ((short) numChannels);
  16954. output->writeIntBigEndian (lengthInSamples);
  16955. output->writeShortBigEndian ((short) bitsPerSample);
  16956. uint8 sampleRateBytes[10];
  16957. zeromem (sampleRateBytes, 10);
  16958. if (sampleRate <= 1)
  16959. {
  16960. sampleRateBytes[0] = 0x3f;
  16961. sampleRateBytes[1] = 0xff;
  16962. sampleRateBytes[2] = 0x80;
  16963. }
  16964. else
  16965. {
  16966. int mask = 0x40000000;
  16967. sampleRateBytes[0] = 0x40;
  16968. if (sampleRate >= mask)
  16969. {
  16970. jassertfalse;
  16971. sampleRateBytes[1] = 0x1d;
  16972. }
  16973. else
  16974. {
  16975. int n = (int) sampleRate;
  16976. int i;
  16977. for (i = 0; i <= 32 ; ++i)
  16978. {
  16979. if ((n & mask) != 0)
  16980. break;
  16981. mask >>= 1;
  16982. }
  16983. n = n << (i + 1);
  16984. sampleRateBytes[1] = (uint8) (29 - i);
  16985. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16986. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16987. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16988. sampleRateBytes[5] = (uint8) (n & 0xff);
  16989. }
  16990. }
  16991. output->write (sampleRateBytes, 10);
  16992. output->writeInt (chunkName ("SSND"));
  16993. output->writeIntBigEndian (audioBytes + 8);
  16994. output->writeInt (0);
  16995. output->writeInt (0);
  16996. jassert (output->getPosition() == headerLen);
  16997. }
  16998. };
  16999. AiffAudioFormat::AiffAudioFormat()
  17000. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  17001. {
  17002. }
  17003. AiffAudioFormat::~AiffAudioFormat()
  17004. {
  17005. }
  17006. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  17007. {
  17008. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17009. return Array <int> (rates);
  17010. }
  17011. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  17012. {
  17013. const int depths[] = { 8, 16, 24, 0 };
  17014. return Array <int> (depths);
  17015. }
  17016. bool AiffAudioFormat::canDoStereo() { return true; }
  17017. bool AiffAudioFormat::canDoMono() { return true; }
  17018. #if JUCE_MAC
  17019. bool AiffAudioFormat::canHandleFile (const File& f)
  17020. {
  17021. if (AudioFormat::canHandleFile (f))
  17022. return true;
  17023. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  17024. return type == 'AIFF' || type == 'AIFC'
  17025. || type == 'aiff' || type == 'aifc';
  17026. }
  17027. #endif
  17028. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  17029. {
  17030. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  17031. if (w->sampleRate != 0)
  17032. return w.release();
  17033. if (! deleteStreamIfOpeningFails)
  17034. w->input = 0;
  17035. return 0;
  17036. }
  17037. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  17038. double sampleRate,
  17039. unsigned int numberOfChannels,
  17040. int bitsPerSample,
  17041. const StringPairArray& /*metadataValues*/,
  17042. int /*qualityOptionIndex*/)
  17043. {
  17044. if (getPossibleBitDepths().contains (bitsPerSample))
  17045. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  17046. return 0;
  17047. }
  17048. END_JUCE_NAMESPACE
  17049. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  17050. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  17051. BEGIN_JUCE_NAMESPACE
  17052. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  17053. : formatName (name),
  17054. fileExtensions (extensions)
  17055. {
  17056. }
  17057. AudioFormat::~AudioFormat()
  17058. {
  17059. }
  17060. bool AudioFormat::canHandleFile (const File& f)
  17061. {
  17062. for (int i = 0; i < fileExtensions.size(); ++i)
  17063. if (f.hasFileExtension (fileExtensions[i]))
  17064. return true;
  17065. return false;
  17066. }
  17067. const String& AudioFormat::getFormatName() const { return formatName; }
  17068. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  17069. bool AudioFormat::isCompressed() { return false; }
  17070. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  17071. END_JUCE_NAMESPACE
  17072. /*** End of inlined file: juce_AudioFormat.cpp ***/
  17073. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  17074. BEGIN_JUCE_NAMESPACE
  17075. AudioFormatReader::AudioFormatReader (InputStream* const in,
  17076. const String& formatName_)
  17077. : sampleRate (0),
  17078. bitsPerSample (0),
  17079. lengthInSamples (0),
  17080. numChannels (0),
  17081. usesFloatingPointData (false),
  17082. input (in),
  17083. formatName (formatName_)
  17084. {
  17085. }
  17086. AudioFormatReader::~AudioFormatReader()
  17087. {
  17088. delete input;
  17089. }
  17090. bool AudioFormatReader::read (int* const* destSamples,
  17091. int numDestChannels,
  17092. int64 startSampleInSource,
  17093. int numSamplesToRead,
  17094. const bool fillLeftoverChannelsWithCopies)
  17095. {
  17096. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  17097. int startOffsetInDestBuffer = 0;
  17098. if (startSampleInSource < 0)
  17099. {
  17100. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  17101. for (int i = numDestChannels; --i >= 0;)
  17102. if (destSamples[i] != 0)
  17103. zeromem (destSamples[i], sizeof (int) * silence);
  17104. startOffsetInDestBuffer += silence;
  17105. numSamplesToRead -= silence;
  17106. startSampleInSource = 0;
  17107. }
  17108. if (numSamplesToRead <= 0)
  17109. return true;
  17110. if (! readSamples (const_cast<int**> (destSamples),
  17111. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  17112. startSampleInSource, numSamplesToRead))
  17113. return false;
  17114. if (numDestChannels > (int) numChannels)
  17115. {
  17116. if (fillLeftoverChannelsWithCopies)
  17117. {
  17118. int* lastFullChannel = destSamples[0];
  17119. for (int i = (int) numChannels; --i > 0;)
  17120. {
  17121. if (destSamples[i] != 0)
  17122. {
  17123. lastFullChannel = destSamples[i];
  17124. break;
  17125. }
  17126. }
  17127. if (lastFullChannel != 0)
  17128. for (int i = numChannels; i < numDestChannels; ++i)
  17129. if (destSamples[i] != 0)
  17130. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17131. }
  17132. else
  17133. {
  17134. for (int i = numChannels; i < numDestChannels; ++i)
  17135. if (destSamples[i] != 0)
  17136. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17137. }
  17138. }
  17139. return true;
  17140. }
  17141. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  17142. {
  17143. float mn = buffer[0];
  17144. float mx = mn;
  17145. for (int i = 1; i < num; ++i)
  17146. {
  17147. const float s = buffer[i];
  17148. if (s > mx) mx = s;
  17149. if (s < mn) mn = s;
  17150. }
  17151. maxVal = mx;
  17152. minVal = mn;
  17153. }
  17154. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17155. int64 numSamples,
  17156. float& lowestLeft, float& highestLeft,
  17157. float& lowestRight, float& highestRight)
  17158. {
  17159. if (numSamples <= 0)
  17160. {
  17161. lowestLeft = 0;
  17162. lowestRight = 0;
  17163. highestLeft = 0;
  17164. highestRight = 0;
  17165. return;
  17166. }
  17167. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17168. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17169. int* tempBuffer[3];
  17170. tempBuffer[0] = tempSpace.getData();
  17171. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17172. tempBuffer[2] = 0;
  17173. if (usesFloatingPointData)
  17174. {
  17175. float lmin = 1.0e6f;
  17176. float lmax = -lmin;
  17177. float rmin = lmin;
  17178. float rmax = lmax;
  17179. while (numSamples > 0)
  17180. {
  17181. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17182. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17183. numSamples -= numToDo;
  17184. startSampleInFile += numToDo;
  17185. float bufmin, bufmax;
  17186. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufmax, bufmin);
  17187. lmin = jmin (lmin, bufmin);
  17188. lmax = jmax (lmax, bufmax);
  17189. if (numChannels > 1)
  17190. {
  17191. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufmax, bufmin);
  17192. rmin = jmin (rmin, bufmin);
  17193. rmax = jmax (rmax, bufmax);
  17194. }
  17195. }
  17196. if (numChannels <= 1)
  17197. {
  17198. rmax = lmax;
  17199. rmin = lmin;
  17200. }
  17201. lowestLeft = lmin;
  17202. highestLeft = lmax;
  17203. lowestRight = rmin;
  17204. highestRight = rmax;
  17205. }
  17206. else
  17207. {
  17208. int lmax = std::numeric_limits<int>::min();
  17209. int lmin = std::numeric_limits<int>::max();
  17210. int rmax = std::numeric_limits<int>::min();
  17211. int rmin = std::numeric_limits<int>::max();
  17212. while (numSamples > 0)
  17213. {
  17214. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17215. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17216. numSamples -= numToDo;
  17217. startSampleInFile += numToDo;
  17218. for (int j = numChannels; --j >= 0;)
  17219. {
  17220. int bufMax = std::numeric_limits<int>::min();
  17221. int bufMin = std::numeric_limits<int>::max();
  17222. const int* const b = tempBuffer[j];
  17223. for (int i = 0; i < numToDo; ++i)
  17224. {
  17225. const int samp = b[i];
  17226. if (samp < bufMin)
  17227. bufMin = samp;
  17228. if (samp > bufMax)
  17229. bufMax = samp;
  17230. }
  17231. if (j == 0)
  17232. {
  17233. lmax = jmax (lmax, bufMax);
  17234. lmin = jmin (lmin, bufMin);
  17235. }
  17236. else
  17237. {
  17238. rmax = jmax (rmax, bufMax);
  17239. rmin = jmin (rmin, bufMin);
  17240. }
  17241. }
  17242. }
  17243. if (numChannels <= 1)
  17244. {
  17245. rmax = lmax;
  17246. rmin = lmin;
  17247. }
  17248. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17249. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17250. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17251. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17252. }
  17253. }
  17254. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17255. int64 numSamplesToSearch,
  17256. const double magnitudeRangeMinimum,
  17257. const double magnitudeRangeMaximum,
  17258. const int minimumConsecutiveSamples)
  17259. {
  17260. if (numSamplesToSearch == 0)
  17261. return -1;
  17262. const int bufferSize = 4096;
  17263. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17264. int* tempBuffer[3];
  17265. tempBuffer[0] = tempSpace.getData();
  17266. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17267. tempBuffer[2] = 0;
  17268. int consecutive = 0;
  17269. int64 firstMatchPos = -1;
  17270. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17271. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17272. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17273. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17274. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17275. while (numSamplesToSearch != 0)
  17276. {
  17277. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17278. int64 bufferStart = startSample;
  17279. if (numSamplesToSearch < 0)
  17280. bufferStart -= numThisTime;
  17281. if (bufferStart >= (int) lengthInSamples)
  17282. break;
  17283. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17284. int num = numThisTime;
  17285. while (--num >= 0)
  17286. {
  17287. if (numSamplesToSearch < 0)
  17288. --startSample;
  17289. bool matches = false;
  17290. const int index = (int) (startSample - bufferStart);
  17291. if (usesFloatingPointData)
  17292. {
  17293. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17294. if (sample1 >= magnitudeRangeMinimum
  17295. && sample1 <= magnitudeRangeMaximum)
  17296. {
  17297. matches = true;
  17298. }
  17299. else if (numChannels > 1)
  17300. {
  17301. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17302. matches = (sample2 >= magnitudeRangeMinimum
  17303. && sample2 <= magnitudeRangeMaximum);
  17304. }
  17305. }
  17306. else
  17307. {
  17308. const int sample1 = abs (tempBuffer[0] [index]);
  17309. if (sample1 >= intMagnitudeRangeMinimum
  17310. && sample1 <= intMagnitudeRangeMaximum)
  17311. {
  17312. matches = true;
  17313. }
  17314. else if (numChannels > 1)
  17315. {
  17316. const int sample2 = abs (tempBuffer[1][index]);
  17317. matches = (sample2 >= intMagnitudeRangeMinimum
  17318. && sample2 <= intMagnitudeRangeMaximum);
  17319. }
  17320. }
  17321. if (matches)
  17322. {
  17323. if (firstMatchPos < 0)
  17324. firstMatchPos = startSample;
  17325. if (++consecutive >= minimumConsecutiveSamples)
  17326. {
  17327. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17328. return -1;
  17329. return firstMatchPos;
  17330. }
  17331. }
  17332. else
  17333. {
  17334. consecutive = 0;
  17335. firstMatchPos = -1;
  17336. }
  17337. if (numSamplesToSearch > 0)
  17338. ++startSample;
  17339. }
  17340. if (numSamplesToSearch > 0)
  17341. numSamplesToSearch -= numThisTime;
  17342. else
  17343. numSamplesToSearch += numThisTime;
  17344. }
  17345. return -1;
  17346. }
  17347. END_JUCE_NAMESPACE
  17348. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17349. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17350. BEGIN_JUCE_NAMESPACE
  17351. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17352. const String& formatName_,
  17353. const double rate,
  17354. const unsigned int numChannels_,
  17355. const unsigned int bitsPerSample_)
  17356. : sampleRate (rate),
  17357. numChannels (numChannels_),
  17358. bitsPerSample (bitsPerSample_),
  17359. usesFloatingPointData (false),
  17360. output (out),
  17361. formatName (formatName_)
  17362. {
  17363. }
  17364. AudioFormatWriter::~AudioFormatWriter()
  17365. {
  17366. delete output;
  17367. }
  17368. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17369. int64 startSample,
  17370. int64 numSamplesToRead)
  17371. {
  17372. const int bufferSize = 16384;
  17373. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17374. int* buffers [128];
  17375. zerostruct (buffers);
  17376. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17377. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17378. if (numSamplesToRead < 0)
  17379. numSamplesToRead = reader.lengthInSamples;
  17380. while (numSamplesToRead > 0)
  17381. {
  17382. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17383. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17384. return false;
  17385. if (reader.usesFloatingPointData != isFloatingPoint())
  17386. {
  17387. int** bufferChan = buffers;
  17388. while (*bufferChan != 0)
  17389. {
  17390. int* b = *bufferChan++;
  17391. if (isFloatingPoint())
  17392. {
  17393. // int -> float
  17394. const double factor = 1.0 / std::numeric_limits<int>::max();
  17395. for (int i = 0; i < numToDo; ++i)
  17396. ((float*) b)[i] = (float) (factor * b[i]);
  17397. }
  17398. else
  17399. {
  17400. // float -> int
  17401. for (int i = 0; i < numToDo; ++i)
  17402. {
  17403. const double samp = *(const float*) b;
  17404. if (samp <= -1.0)
  17405. *b++ = std::numeric_limits<int>::min();
  17406. else if (samp >= 1.0)
  17407. *b++ = std::numeric_limits<int>::max();
  17408. else
  17409. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17410. }
  17411. }
  17412. }
  17413. }
  17414. if (! write (const_cast<const int**> (buffers), numToDo))
  17415. return false;
  17416. numSamplesToRead -= numToDo;
  17417. startSample += numToDo;
  17418. }
  17419. return true;
  17420. }
  17421. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17422. {
  17423. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17424. while (numSamplesToRead > 0)
  17425. {
  17426. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17427. AudioSourceChannelInfo info;
  17428. info.buffer = &tempBuffer;
  17429. info.startSample = 0;
  17430. info.numSamples = numToDo;
  17431. info.clearActiveBufferRegion();
  17432. source.getNextAudioBlock (info);
  17433. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17434. return false;
  17435. numSamplesToRead -= numToDo;
  17436. }
  17437. return true;
  17438. }
  17439. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17440. {
  17441. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17442. if (numSamples <= 0)
  17443. return true;
  17444. HeapBlock<int> tempBuffer;
  17445. HeapBlock<int*> chans (numChannels + 1);
  17446. chans [numChannels] = 0;
  17447. if (isFloatingPoint())
  17448. {
  17449. for (int i = numChannels; --i >= 0;)
  17450. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17451. }
  17452. else
  17453. {
  17454. tempBuffer.malloc (numSamples * numChannels);
  17455. for (unsigned int i = 0; i < numChannels; ++i)
  17456. {
  17457. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17458. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17459. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17460. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17461. destData.convertSamples (sourceData, numSamples);
  17462. }
  17463. }
  17464. return write ((const int**) chans.getData(), numSamples);
  17465. }
  17466. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17467. public AbstractFifo
  17468. {
  17469. public:
  17470. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize)
  17471. : AbstractFifo (bufferSize),
  17472. buffer (numChannels, bufferSize),
  17473. timeSliceThread (timeSliceThread_),
  17474. writer (writer_), isRunning (true)
  17475. {
  17476. timeSliceThread.addTimeSliceClient (this);
  17477. }
  17478. ~Buffer()
  17479. {
  17480. isRunning = false;
  17481. timeSliceThread.removeTimeSliceClient (this);
  17482. while (useTimeSlice())
  17483. {}
  17484. }
  17485. bool write (const float** data, int numSamples)
  17486. {
  17487. if (numSamples <= 0 || ! isRunning)
  17488. return true;
  17489. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17490. int start1, size1, start2, size2;
  17491. prepareToWrite (numSamples, start1, size1, start2, size2);
  17492. if (size1 + size2 < numSamples)
  17493. return false;
  17494. for (int i = buffer.getNumChannels(); --i >= 0;)
  17495. {
  17496. buffer.copyFrom (i, start1, data[i], size1);
  17497. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17498. }
  17499. finishedWrite (size1 + size2);
  17500. timeSliceThread.notify();
  17501. return true;
  17502. }
  17503. bool useTimeSlice()
  17504. {
  17505. const int numToDo = getTotalSize() / 4;
  17506. int start1, size1, start2, size2;
  17507. prepareToRead (numToDo, start1, size1, start2, size2);
  17508. if (size1 <= 0)
  17509. return false;
  17510. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17511. if (size2 > 0)
  17512. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17513. finishedRead (size1 + size2);
  17514. return true;
  17515. }
  17516. private:
  17517. AudioSampleBuffer buffer;
  17518. TimeSliceThread& timeSliceThread;
  17519. ScopedPointer<AudioFormatWriter> writer;
  17520. volatile bool isRunning;
  17521. Buffer (const Buffer&);
  17522. Buffer& operator= (const Buffer&);
  17523. };
  17524. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17525. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17526. {
  17527. }
  17528. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17529. {
  17530. }
  17531. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17532. {
  17533. return buffer->write (data, numSamples);
  17534. }
  17535. END_JUCE_NAMESPACE
  17536. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17537. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17538. BEGIN_JUCE_NAMESPACE
  17539. AudioFormatManager::AudioFormatManager()
  17540. : defaultFormatIndex (0)
  17541. {
  17542. }
  17543. AudioFormatManager::~AudioFormatManager()
  17544. {
  17545. clearFormats();
  17546. clearSingletonInstance();
  17547. }
  17548. juce_ImplementSingleton (AudioFormatManager);
  17549. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17550. const bool makeThisTheDefaultFormat)
  17551. {
  17552. jassert (newFormat != 0);
  17553. if (newFormat != 0)
  17554. {
  17555. #if JUCE_DEBUG
  17556. for (int i = getNumKnownFormats(); --i >= 0;)
  17557. {
  17558. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17559. {
  17560. jassertfalse; // trying to add the same format twice!
  17561. }
  17562. }
  17563. #endif
  17564. if (makeThisTheDefaultFormat)
  17565. defaultFormatIndex = getNumKnownFormats();
  17566. knownFormats.add (newFormat);
  17567. }
  17568. }
  17569. void AudioFormatManager::registerBasicFormats()
  17570. {
  17571. #if JUCE_MAC
  17572. registerFormat (new AiffAudioFormat(), true);
  17573. registerFormat (new WavAudioFormat(), false);
  17574. #else
  17575. registerFormat (new WavAudioFormat(), true);
  17576. registerFormat (new AiffAudioFormat(), false);
  17577. #endif
  17578. #if JUCE_USE_FLAC
  17579. registerFormat (new FlacAudioFormat(), false);
  17580. #endif
  17581. #if JUCE_USE_OGGVORBIS
  17582. registerFormat (new OggVorbisAudioFormat(), false);
  17583. #endif
  17584. }
  17585. void AudioFormatManager::clearFormats()
  17586. {
  17587. knownFormats.clear();
  17588. defaultFormatIndex = 0;
  17589. }
  17590. int AudioFormatManager::getNumKnownFormats() const
  17591. {
  17592. return knownFormats.size();
  17593. }
  17594. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17595. {
  17596. return knownFormats [index];
  17597. }
  17598. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17599. {
  17600. return getKnownFormat (defaultFormatIndex);
  17601. }
  17602. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17603. {
  17604. String e (fileExtension);
  17605. if (! e.startsWithChar ('.'))
  17606. e = "." + e;
  17607. for (int i = 0; i < getNumKnownFormats(); ++i)
  17608. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17609. return getKnownFormat(i);
  17610. return 0;
  17611. }
  17612. const String AudioFormatManager::getWildcardForAllFormats() const
  17613. {
  17614. StringArray allExtensions;
  17615. int i;
  17616. for (i = 0; i < getNumKnownFormats(); ++i)
  17617. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17618. allExtensions.trim();
  17619. allExtensions.removeEmptyStrings();
  17620. String s;
  17621. for (i = 0; i < allExtensions.size(); ++i)
  17622. {
  17623. s << '*';
  17624. if (! allExtensions[i].startsWithChar ('.'))
  17625. s << '.';
  17626. s << allExtensions[i];
  17627. if (i < allExtensions.size() - 1)
  17628. s << ';';
  17629. }
  17630. return s;
  17631. }
  17632. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17633. {
  17634. // you need to actually register some formats before the manager can
  17635. // use them to open a file!
  17636. jassert (getNumKnownFormats() > 0);
  17637. for (int i = 0; i < getNumKnownFormats(); ++i)
  17638. {
  17639. AudioFormat* const af = getKnownFormat(i);
  17640. if (af->canHandleFile (file))
  17641. {
  17642. InputStream* const in = file.createInputStream();
  17643. if (in != 0)
  17644. {
  17645. AudioFormatReader* const r = af->createReaderFor (in, true);
  17646. if (r != 0)
  17647. return r;
  17648. }
  17649. }
  17650. }
  17651. return 0;
  17652. }
  17653. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17654. {
  17655. // you need to actually register some formats before the manager can
  17656. // use them to open a file!
  17657. jassert (getNumKnownFormats() > 0);
  17658. ScopedPointer <InputStream> in (audioFileStream);
  17659. if (in != 0)
  17660. {
  17661. const int64 originalStreamPos = in->getPosition();
  17662. for (int i = 0; i < getNumKnownFormats(); ++i)
  17663. {
  17664. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17665. if (r != 0)
  17666. {
  17667. in.release();
  17668. return r;
  17669. }
  17670. in->setPosition (originalStreamPos);
  17671. // the stream that is passed-in must be capable of being repositioned so
  17672. // that all the formats can have a go at opening it.
  17673. jassert (in->getPosition() == originalStreamPos);
  17674. }
  17675. }
  17676. return 0;
  17677. }
  17678. END_JUCE_NAMESPACE
  17679. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17680. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17681. BEGIN_JUCE_NAMESPACE
  17682. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17683. const int64 startSample_,
  17684. const int64 length_,
  17685. const bool deleteSourceWhenDeleted_)
  17686. : AudioFormatReader (0, source_->getFormatName()),
  17687. source (source_),
  17688. startSample (startSample_),
  17689. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17690. {
  17691. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17692. sampleRate = source->sampleRate;
  17693. bitsPerSample = source->bitsPerSample;
  17694. lengthInSamples = length;
  17695. numChannels = source->numChannels;
  17696. usesFloatingPointData = source->usesFloatingPointData;
  17697. }
  17698. AudioSubsectionReader::~AudioSubsectionReader()
  17699. {
  17700. if (deleteSourceWhenDeleted)
  17701. delete source;
  17702. }
  17703. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17704. int64 startSampleInFile, int numSamples)
  17705. {
  17706. if (startSampleInFile + numSamples > length)
  17707. {
  17708. for (int i = numDestChannels; --i >= 0;)
  17709. if (destSamples[i] != 0)
  17710. zeromem (destSamples[i], sizeof (int) * numSamples);
  17711. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17712. if (numSamples <= 0)
  17713. return true;
  17714. }
  17715. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17716. startSampleInFile + startSample, numSamples);
  17717. }
  17718. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17719. int64 numSamples,
  17720. float& lowestLeft,
  17721. float& highestLeft,
  17722. float& lowestRight,
  17723. float& highestRight)
  17724. {
  17725. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17726. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17727. source->readMaxLevels (startSampleInFile + startSample,
  17728. numSamples,
  17729. lowestLeft,
  17730. highestLeft,
  17731. lowestRight,
  17732. highestRight);
  17733. }
  17734. END_JUCE_NAMESPACE
  17735. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17736. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17737. BEGIN_JUCE_NAMESPACE
  17738. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17739. AudioFormatManager& formatManagerToUse_,
  17740. AudioThumbnailCache& cacheToUse)
  17741. : formatManagerToUse (formatManagerToUse_),
  17742. cache (cacheToUse),
  17743. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17744. timeBeforeDeletingReader (2000)
  17745. {
  17746. clear();
  17747. }
  17748. AudioThumbnail::~AudioThumbnail()
  17749. {
  17750. cache.removeThumbnail (this);
  17751. const ScopedLock sl (readerLock);
  17752. reader = 0;
  17753. }
  17754. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17755. {
  17756. jassert (data.getData() != 0);
  17757. return static_cast <DataFormat*> (data.getData());
  17758. }
  17759. void AudioThumbnail::setSource (InputSource* const newSource)
  17760. {
  17761. cache.removeThumbnail (this);
  17762. timerCallback(); // stops the timer and deletes the reader
  17763. source = newSource;
  17764. clear();
  17765. if (newSource != 0
  17766. && ! (cache.loadThumb (*this, newSource->hashCode())
  17767. && isFullyLoaded()))
  17768. {
  17769. {
  17770. const ScopedLock sl (readerLock);
  17771. reader = createReader();
  17772. }
  17773. if (reader != 0)
  17774. {
  17775. initialiseFromAudioFile (*reader);
  17776. cache.addThumbnail (this);
  17777. }
  17778. }
  17779. sendChangeMessage();
  17780. }
  17781. bool AudioThumbnail::useTimeSlice()
  17782. {
  17783. const ScopedLock sl (readerLock);
  17784. if (isFullyLoaded())
  17785. {
  17786. if (reader != 0)
  17787. startTimer (timeBeforeDeletingReader);
  17788. cache.removeThumbnail (this);
  17789. return false;
  17790. }
  17791. if (reader == 0)
  17792. reader = createReader();
  17793. if (reader != 0)
  17794. {
  17795. readNextBlockFromAudioFile (*reader);
  17796. stopTimer();
  17797. sendChangeMessage();
  17798. const bool justFinished = isFullyLoaded();
  17799. if (justFinished)
  17800. cache.storeThumb (*this, source->hashCode());
  17801. return ! justFinished;
  17802. }
  17803. return false;
  17804. }
  17805. AudioFormatReader* AudioThumbnail::createReader() const
  17806. {
  17807. if (source != 0)
  17808. {
  17809. InputStream* const audioFileStream = source->createInputStream();
  17810. if (audioFileStream != 0)
  17811. return formatManagerToUse.createReaderFor (audioFileStream);
  17812. }
  17813. return 0;
  17814. }
  17815. void AudioThumbnail::timerCallback()
  17816. {
  17817. stopTimer();
  17818. const ScopedLock sl (readerLock);
  17819. reader = 0;
  17820. }
  17821. void AudioThumbnail::clear()
  17822. {
  17823. data.setSize (sizeof (DataFormat) + 3);
  17824. DataFormat* const d = getData();
  17825. d->thumbnailMagic[0] = 'j';
  17826. d->thumbnailMagic[1] = 'a';
  17827. d->thumbnailMagic[2] = 't';
  17828. d->thumbnailMagic[3] = 'm';
  17829. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17830. d->totalSamples = 0;
  17831. d->numFinishedSamples = 0;
  17832. d->numThumbnailSamples = 0;
  17833. d->numChannels = 0;
  17834. d->sampleRate = 0;
  17835. numSamplesCached = 0;
  17836. cacheNeedsRefilling = true;
  17837. }
  17838. void AudioThumbnail::loadFrom (InputStream& input)
  17839. {
  17840. const ScopedLock sl (readerLock);
  17841. data.setSize (0);
  17842. input.readIntoMemoryBlock (data);
  17843. DataFormat* const d = getData();
  17844. d->flipEndiannessIfBigEndian();
  17845. if (! (d->thumbnailMagic[0] == 'j'
  17846. && d->thumbnailMagic[1] == 'a'
  17847. && d->thumbnailMagic[2] == 't'
  17848. && d->thumbnailMagic[3] == 'm'))
  17849. {
  17850. clear();
  17851. }
  17852. numSamplesCached = 0;
  17853. cacheNeedsRefilling = true;
  17854. }
  17855. void AudioThumbnail::saveTo (OutputStream& output) const
  17856. {
  17857. const ScopedLock sl (readerLock);
  17858. DataFormat* const d = getData();
  17859. d->flipEndiannessIfBigEndian();
  17860. output.write (d, (int) data.getSize());
  17861. d->flipEndiannessIfBigEndian();
  17862. }
  17863. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17864. {
  17865. DataFormat* d = getData();
  17866. d->totalSamples = fileReader.lengthInSamples;
  17867. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17868. d->numFinishedSamples = 0;
  17869. d->sampleRate = roundToInt (fileReader.sampleRate);
  17870. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17871. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17872. d = getData();
  17873. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17874. return d->totalSamples > 0;
  17875. }
  17876. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17877. {
  17878. DataFormat* const d = getData();
  17879. if (d->numFinishedSamples < d->totalSamples)
  17880. {
  17881. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17882. generateSection (fileReader,
  17883. d->numFinishedSamples,
  17884. numToDo);
  17885. d->numFinishedSamples += numToDo;
  17886. }
  17887. cacheNeedsRefilling = true;
  17888. return d->numFinishedSamples < d->totalSamples;
  17889. }
  17890. int AudioThumbnail::getNumChannels() const throw()
  17891. {
  17892. return getData()->numChannels;
  17893. }
  17894. double AudioThumbnail::getTotalLength() const throw()
  17895. {
  17896. const DataFormat* const d = getData();
  17897. if (d->sampleRate > 0)
  17898. return d->totalSamples / (double) d->sampleRate;
  17899. else
  17900. return 0.0;
  17901. }
  17902. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17903. int64 startSample,
  17904. int numSamples)
  17905. {
  17906. DataFormat* const d = getData();
  17907. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17908. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17909. char* const l = getChannelData (0);
  17910. char* const r = getChannelData (1);
  17911. for (int i = firstDataPos; i < lastDataPos; ++i)
  17912. {
  17913. const int sourceStart = i * d->samplesPerThumbSample;
  17914. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17915. float lowestLeft, highestLeft, lowestRight, highestRight;
  17916. fileReader.readMaxLevels (sourceStart,
  17917. sourceEnd - sourceStart,
  17918. lowestLeft,
  17919. highestLeft,
  17920. lowestRight,
  17921. highestRight);
  17922. int n = i * 2;
  17923. if (r != 0)
  17924. {
  17925. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17926. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17927. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17928. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17929. }
  17930. else
  17931. {
  17932. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17933. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17934. }
  17935. }
  17936. }
  17937. char* AudioThumbnail::getChannelData (int channel) const
  17938. {
  17939. DataFormat* const d = getData();
  17940. if (channel >= 0 && channel < d->numChannels)
  17941. return d->data + (channel * 2 * d->numThumbnailSamples);
  17942. return 0;
  17943. }
  17944. bool AudioThumbnail::isFullyLoaded() const throw()
  17945. {
  17946. const DataFormat* const d = getData();
  17947. return d->numFinishedSamples >= d->totalSamples;
  17948. }
  17949. void AudioThumbnail::refillCache (const int numSamples,
  17950. double startTime,
  17951. const double timePerPixel)
  17952. {
  17953. const DataFormat* const d = getData();
  17954. if (numSamples <= 0
  17955. || timePerPixel <= 0.0
  17956. || d->sampleRate <= 0)
  17957. {
  17958. numSamplesCached = 0;
  17959. cacheNeedsRefilling = true;
  17960. return;
  17961. }
  17962. if (numSamples == numSamplesCached
  17963. && numChannelsCached == d->numChannels
  17964. && startTime == cachedStart
  17965. && timePerPixel == cachedTimePerPixel
  17966. && ! cacheNeedsRefilling)
  17967. {
  17968. return;
  17969. }
  17970. numSamplesCached = numSamples;
  17971. numChannelsCached = d->numChannels;
  17972. cachedStart = startTime;
  17973. cachedTimePerPixel = timePerPixel;
  17974. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17975. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17976. const ScopedLock sl (readerLock);
  17977. cacheNeedsRefilling = false;
  17978. if (needExtraDetail && reader == 0)
  17979. reader = createReader();
  17980. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17981. {
  17982. startTimer (timeBeforeDeletingReader);
  17983. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17984. int sample = roundToInt (startTime * d->sampleRate);
  17985. for (int i = numSamples; --i >= 0;)
  17986. {
  17987. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17988. if (sample >= 0)
  17989. {
  17990. if (sample >= reader->lengthInSamples)
  17991. break;
  17992. float lmin, lmax, rmin, rmax;
  17993. reader->readMaxLevels (sample,
  17994. jmax (1, nextSample - sample),
  17995. lmin, lmax, rmin, rmax);
  17996. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17997. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17998. if (numChannelsCached > 1)
  17999. {
  18000. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  18001. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  18002. }
  18003. cacheData += 2 * numChannelsCached;
  18004. }
  18005. startTime += timePerPixel;
  18006. sample = nextSample;
  18007. }
  18008. }
  18009. else
  18010. {
  18011. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  18012. {
  18013. char* const channelData = getChannelData (channelNum);
  18014. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  18015. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  18016. startTime = cachedStart;
  18017. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  18018. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  18019. for (int i = numSamples; --i >= 0;)
  18020. {
  18021. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  18022. if (sample >= 0 && channelData != 0)
  18023. {
  18024. char mx = -128;
  18025. char mn = 127;
  18026. while (sample <= nextSample)
  18027. {
  18028. if (sample >= numFinished)
  18029. break;
  18030. const int n = sample << 1;
  18031. const char sampMin = channelData [n];
  18032. const char sampMax = channelData [n + 1];
  18033. if (sampMin < mn)
  18034. mn = sampMin;
  18035. if (sampMax > mx)
  18036. mx = sampMax;
  18037. ++sample;
  18038. }
  18039. if (mn <= mx)
  18040. {
  18041. cacheData[0] = mn;
  18042. cacheData[1] = mx;
  18043. }
  18044. else
  18045. {
  18046. cacheData[0] = 1;
  18047. cacheData[1] = 0;
  18048. }
  18049. }
  18050. else
  18051. {
  18052. cacheData[0] = 1;
  18053. cacheData[1] = 0;
  18054. }
  18055. cacheData += numChannelsCached * 2;
  18056. startTime += timePerPixel;
  18057. sample = nextSample;
  18058. }
  18059. }
  18060. }
  18061. }
  18062. void AudioThumbnail::drawChannel (Graphics& g,
  18063. int x, int y, int w, int h,
  18064. double startTime,
  18065. double endTime,
  18066. int channelNum,
  18067. const float verticalZoomFactor)
  18068. {
  18069. refillCache (w, startTime, (endTime - startTime) / w);
  18070. if (numSamplesCached >= w
  18071. && channelNum >= 0
  18072. && channelNum < numChannelsCached)
  18073. {
  18074. const float topY = (float) y;
  18075. const float bottomY = topY + h;
  18076. const float midY = topY + h * 0.5f;
  18077. const float vscale = verticalZoomFactor * h / 256.0f;
  18078. const Rectangle<int> clip (g.getClipBounds());
  18079. const int skipLeft = jlimit (0, w, clip.getX() - x);
  18080. w -= skipLeft;
  18081. x += skipLeft;
  18082. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  18083. + (channelNum << 1)
  18084. + skipLeft * (numChannelsCached << 1);
  18085. while (--w >= 0)
  18086. {
  18087. const char mn = cacheData[0];
  18088. const char mx = cacheData[1];
  18089. cacheData += numChannelsCached << 1;
  18090. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  18091. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  18092. jmin (midY - mn * vscale + 0.3f, bottomY));
  18093. if (++x >= clip.getRight())
  18094. break;
  18095. }
  18096. }
  18097. }
  18098. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  18099. {
  18100. #if JUCE_BIG_ENDIAN
  18101. struct Flipper
  18102. {
  18103. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  18104. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  18105. };
  18106. Flipper::flip (samplesPerThumbSample);
  18107. Flipper::flip (totalSamples);
  18108. Flipper::flip (numFinishedSamples);
  18109. Flipper::flip (numThumbnailSamples);
  18110. Flipper::flip (numChannels);
  18111. Flipper::flip (sampleRate);
  18112. #endif
  18113. }
  18114. END_JUCE_NAMESPACE
  18115. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18116. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18117. BEGIN_JUCE_NAMESPACE
  18118. struct ThumbnailCacheEntry
  18119. {
  18120. int64 hash;
  18121. uint32 lastUsed;
  18122. MemoryBlock data;
  18123. juce_UseDebuggingNewOperator
  18124. };
  18125. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18126. : TimeSliceThread ("thumb cache"),
  18127. maxNumThumbsToStore (maxNumThumbsToStore_)
  18128. {
  18129. startThread (2);
  18130. }
  18131. AudioThumbnailCache::~AudioThumbnailCache()
  18132. {
  18133. }
  18134. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18135. {
  18136. for (int i = thumbs.size(); --i >= 0;)
  18137. {
  18138. if (thumbs[i]->hash == hashCode)
  18139. {
  18140. MemoryInputStream in (thumbs[i]->data, false);
  18141. thumb.loadFrom (in);
  18142. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  18143. return true;
  18144. }
  18145. }
  18146. return false;
  18147. }
  18148. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18149. const int64 hashCode)
  18150. {
  18151. MemoryOutputStream out;
  18152. thumb.saveTo (out);
  18153. ThumbnailCacheEntry* te = 0;
  18154. for (int i = thumbs.size(); --i >= 0;)
  18155. {
  18156. if (thumbs[i]->hash == hashCode)
  18157. {
  18158. te = thumbs[i];
  18159. break;
  18160. }
  18161. }
  18162. if (te == 0)
  18163. {
  18164. te = new ThumbnailCacheEntry();
  18165. te->hash = hashCode;
  18166. if (thumbs.size() < maxNumThumbsToStore)
  18167. {
  18168. thumbs.add (te);
  18169. }
  18170. else
  18171. {
  18172. int oldest = 0;
  18173. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  18174. int i;
  18175. for (i = thumbs.size(); --i >= 0;)
  18176. if (thumbs[i]->lastUsed < oldestTime)
  18177. oldest = i;
  18178. thumbs.set (i, te);
  18179. }
  18180. }
  18181. te->lastUsed = Time::getMillisecondCounter();
  18182. te->data.setSize (0);
  18183. te->data.append (out.getData(), out.getDataSize());
  18184. }
  18185. void AudioThumbnailCache::clear()
  18186. {
  18187. thumbs.clear();
  18188. }
  18189. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  18190. {
  18191. addTimeSliceClient (thumb);
  18192. }
  18193. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  18194. {
  18195. removeTimeSliceClient (thumb);
  18196. }
  18197. END_JUCE_NAMESPACE
  18198. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18199. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18200. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18201. #if ! JUCE_WINDOWS
  18202. #include <QuickTime/Movies.h>
  18203. #include <QuickTime/QTML.h>
  18204. #include <QuickTime/QuickTimeComponents.h>
  18205. #include <QuickTime/MediaHandlers.h>
  18206. #include <QuickTime/ImageCodec.h>
  18207. #else
  18208. #if JUCE_MSVC
  18209. #pragma warning (push)
  18210. #pragma warning (disable : 4100)
  18211. #endif
  18212. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18213. add its header directory to your include path.
  18214. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18215. flag in juce_Config.h
  18216. */
  18217. #include <Movies.h>
  18218. #include <QTML.h>
  18219. #include <QuickTimeComponents.h>
  18220. #include <MediaHandlers.h>
  18221. #include <ImageCodec.h>
  18222. #if JUCE_MSVC
  18223. #pragma warning (pop)
  18224. #endif
  18225. #endif
  18226. BEGIN_JUCE_NAMESPACE
  18227. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18228. static const char* const quickTimeFormatName = "QuickTime file";
  18229. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18230. class QTAudioReader : public AudioFormatReader
  18231. {
  18232. public:
  18233. QTAudioReader (InputStream* const input_, const int trackNum_)
  18234. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18235. ok (false),
  18236. movie (0),
  18237. trackNum (trackNum_),
  18238. lastSampleRead (0),
  18239. lastThreadId (0),
  18240. extractor (0),
  18241. dataHandle (0)
  18242. {
  18243. JUCE_AUTORELEASEPOOL
  18244. bufferList.calloc (256, 1);
  18245. #if JUCE_WINDOWS
  18246. if (InitializeQTML (0) != noErr)
  18247. return;
  18248. #endif
  18249. if (EnterMovies() != noErr)
  18250. return;
  18251. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18252. if (! opened)
  18253. return;
  18254. {
  18255. const int numTracks = GetMovieTrackCount (movie);
  18256. int trackCount = 0;
  18257. for (int i = 1; i <= numTracks; ++i)
  18258. {
  18259. track = GetMovieIndTrack (movie, i);
  18260. media = GetTrackMedia (track);
  18261. OSType mediaType;
  18262. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18263. if (mediaType == SoundMediaType
  18264. && trackCount++ == trackNum_)
  18265. {
  18266. ok = true;
  18267. break;
  18268. }
  18269. }
  18270. }
  18271. if (! ok)
  18272. return;
  18273. ok = false;
  18274. lengthInSamples = GetMediaDecodeDuration (media);
  18275. usesFloatingPointData = false;
  18276. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18277. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18278. / GetMediaTimeScale (media);
  18279. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18280. unsigned long output_layout_size;
  18281. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18282. kQTPropertyClass_MovieAudioExtraction_Audio,
  18283. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18284. 0, &output_layout_size, 0);
  18285. if (err != noErr)
  18286. return;
  18287. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18288. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18289. err = MovieAudioExtractionGetProperty (extractor,
  18290. kQTPropertyClass_MovieAudioExtraction_Audio,
  18291. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18292. output_layout_size, qt_audio_channel_layout, 0);
  18293. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18294. err = MovieAudioExtractionSetProperty (extractor,
  18295. kQTPropertyClass_MovieAudioExtraction_Audio,
  18296. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18297. output_layout_size,
  18298. qt_audio_channel_layout);
  18299. err = MovieAudioExtractionGetProperty (extractor,
  18300. kQTPropertyClass_MovieAudioExtraction_Audio,
  18301. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18302. sizeof (inputStreamDesc),
  18303. &inputStreamDesc, 0);
  18304. if (err != noErr)
  18305. return;
  18306. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18307. | kAudioFormatFlagIsPacked
  18308. | kAudioFormatFlagsNativeEndian;
  18309. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18310. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18311. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18312. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18313. err = MovieAudioExtractionSetProperty (extractor,
  18314. kQTPropertyClass_MovieAudioExtraction_Audio,
  18315. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18316. sizeof (inputStreamDesc),
  18317. &inputStreamDesc);
  18318. if (err != noErr)
  18319. return;
  18320. Boolean allChannelsDiscrete = false;
  18321. err = MovieAudioExtractionSetProperty (extractor,
  18322. kQTPropertyClass_MovieAudioExtraction_Movie,
  18323. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18324. sizeof (allChannelsDiscrete),
  18325. &allChannelsDiscrete);
  18326. if (err != noErr)
  18327. return;
  18328. bufferList->mNumberBuffers = 1;
  18329. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18330. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18331. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18332. bufferList->mBuffers[0].mData = dataBuffer;
  18333. sampleRate = inputStreamDesc.mSampleRate;
  18334. bitsPerSample = 16;
  18335. numChannels = inputStreamDesc.mChannelsPerFrame;
  18336. detachThread();
  18337. ok = true;
  18338. }
  18339. ~QTAudioReader()
  18340. {
  18341. JUCE_AUTORELEASEPOOL
  18342. checkThreadIsAttached();
  18343. if (dataHandle != 0)
  18344. DisposeHandle (dataHandle);
  18345. if (extractor != 0)
  18346. {
  18347. MovieAudioExtractionEnd (extractor);
  18348. extractor = 0;
  18349. }
  18350. DisposeMovie (movie);
  18351. #if JUCE_MAC
  18352. ExitMoviesOnThread ();
  18353. #endif
  18354. }
  18355. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18356. int64 startSampleInFile, int numSamples)
  18357. {
  18358. JUCE_AUTORELEASEPOOL
  18359. checkThreadIsAttached();
  18360. bool ok = true;
  18361. while (numSamples > 0)
  18362. {
  18363. if (lastSampleRead != startSampleInFile)
  18364. {
  18365. TimeRecord time;
  18366. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18367. time.base = 0;
  18368. time.value.hi = 0;
  18369. time.value.lo = (UInt32) startSampleInFile;
  18370. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18371. kQTPropertyClass_MovieAudioExtraction_Movie,
  18372. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18373. sizeof (time), &time);
  18374. if (err != noErr)
  18375. {
  18376. ok = false;
  18377. break;
  18378. }
  18379. }
  18380. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18381. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18382. UInt32 outFlags = 0;
  18383. UInt32 actualNumFrames = framesToDo;
  18384. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18385. if (err != noErr)
  18386. {
  18387. ok = false;
  18388. break;
  18389. }
  18390. lastSampleRead = startSampleInFile + actualNumFrames;
  18391. const int samplesReceived = actualNumFrames;
  18392. for (int j = numDestChannels; --j >= 0;)
  18393. {
  18394. if (destSamples[j] != 0)
  18395. {
  18396. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18397. for (int i = 0; i < samplesReceived; ++i)
  18398. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18399. }
  18400. }
  18401. startOffsetInDestBuffer += samplesReceived;
  18402. startSampleInFile += samplesReceived;
  18403. numSamples -= samplesReceived;
  18404. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18405. {
  18406. for (int j = numDestChannels; --j >= 0;)
  18407. if (destSamples[j] != 0)
  18408. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18409. break;
  18410. }
  18411. }
  18412. detachThread();
  18413. return ok;
  18414. }
  18415. juce_UseDebuggingNewOperator
  18416. bool ok;
  18417. private:
  18418. Movie movie;
  18419. Media media;
  18420. Track track;
  18421. const int trackNum;
  18422. double trackUnitsPerFrame;
  18423. int samplesPerFrame;
  18424. int64 lastSampleRead;
  18425. Thread::ThreadID lastThreadId;
  18426. MovieAudioExtractionRef extractor;
  18427. AudioStreamBasicDescription inputStreamDesc;
  18428. HeapBlock <AudioBufferList> bufferList;
  18429. HeapBlock <char> dataBuffer;
  18430. Handle dataHandle;
  18431. void checkThreadIsAttached()
  18432. {
  18433. #if JUCE_MAC
  18434. if (Thread::getCurrentThreadId() != lastThreadId)
  18435. EnterMoviesOnThread (0);
  18436. AttachMovieToCurrentThread (movie);
  18437. #endif
  18438. }
  18439. void detachThread()
  18440. {
  18441. #if JUCE_MAC
  18442. DetachMovieFromCurrentThread (movie);
  18443. #endif
  18444. }
  18445. QTAudioReader (const QTAudioReader&);
  18446. QTAudioReader& operator= (const QTAudioReader&);
  18447. };
  18448. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18449. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18450. {
  18451. }
  18452. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18453. {
  18454. }
  18455. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18456. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18457. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18458. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18459. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18460. const bool deleteStreamIfOpeningFails)
  18461. {
  18462. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18463. if (r->ok)
  18464. return r.release();
  18465. if (! deleteStreamIfOpeningFails)
  18466. r->input = 0;
  18467. return 0;
  18468. }
  18469. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18470. double /*sampleRateToUse*/,
  18471. unsigned int /*numberOfChannels*/,
  18472. int /*bitsPerSample*/,
  18473. const StringPairArray& /*metadataValues*/,
  18474. int /*qualityOptionIndex*/)
  18475. {
  18476. jassertfalse; // not yet implemented!
  18477. return 0;
  18478. }
  18479. END_JUCE_NAMESPACE
  18480. #endif
  18481. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18482. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18483. BEGIN_JUCE_NAMESPACE
  18484. static const char* const wavFormatName = "WAV file";
  18485. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18486. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18487. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18488. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18489. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18490. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18491. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18492. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18493. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18494. const String& originator,
  18495. const String& originatorRef,
  18496. const Time& date,
  18497. const int64 timeReferenceSamples,
  18498. const String& codingHistory)
  18499. {
  18500. StringPairArray m;
  18501. m.set (bwavDescription, description);
  18502. m.set (bwavOriginator, originator);
  18503. m.set (bwavOriginatorRef, originatorRef);
  18504. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18505. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18506. m.set (bwavTimeReference, String (timeReferenceSamples));
  18507. m.set (bwavCodingHistory, codingHistory);
  18508. return m;
  18509. }
  18510. #if JUCE_MSVC
  18511. #pragma pack (push, 1)
  18512. #define PACKED
  18513. #elif JUCE_GCC
  18514. #define PACKED __attribute__((packed))
  18515. #else
  18516. #define PACKED
  18517. #endif
  18518. struct BWAVChunk
  18519. {
  18520. char description [256];
  18521. char originator [32];
  18522. char originatorRef [32];
  18523. char originationDate [10];
  18524. char originationTime [8];
  18525. uint32 timeRefLow;
  18526. uint32 timeRefHigh;
  18527. uint16 version;
  18528. uint8 umid[64];
  18529. uint8 reserved[190];
  18530. char codingHistory[1];
  18531. void copyTo (StringPairArray& values) const
  18532. {
  18533. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18534. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18535. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18536. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18537. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18538. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18539. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18540. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18541. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18542. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18543. }
  18544. static MemoryBlock createFrom (const StringPairArray& values)
  18545. {
  18546. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18547. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18548. data.fillWith (0);
  18549. BWAVChunk* b = (BWAVChunk*) data.getData();
  18550. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18551. // as they get called in the right order..
  18552. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18553. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18554. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18555. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18556. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18557. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18558. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18559. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18560. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18561. if (b->description[0] != 0
  18562. || b->originator[0] != 0
  18563. || b->originationDate[0] != 0
  18564. || b->originationTime[0] != 0
  18565. || b->codingHistory[0] != 0
  18566. || time != 0)
  18567. {
  18568. return data;
  18569. }
  18570. return MemoryBlock();
  18571. }
  18572. } PACKED;
  18573. struct SMPLChunk
  18574. {
  18575. struct SampleLoop
  18576. {
  18577. uint32 identifier;
  18578. uint32 type;
  18579. uint32 start;
  18580. uint32 end;
  18581. uint32 fraction;
  18582. uint32 playCount;
  18583. } PACKED;
  18584. uint32 manufacturer;
  18585. uint32 product;
  18586. uint32 samplePeriod;
  18587. uint32 midiUnityNote;
  18588. uint32 midiPitchFraction;
  18589. uint32 smpteFormat;
  18590. uint32 smpteOffset;
  18591. uint32 numSampleLoops;
  18592. uint32 samplerData;
  18593. SampleLoop loops[1];
  18594. void copyTo (StringPairArray& values, const int totalSize) const
  18595. {
  18596. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18597. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18598. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18599. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18600. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18601. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18602. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18603. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18604. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18605. for (uint32 i = 0; i < numSampleLoops; ++i)
  18606. {
  18607. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18608. break;
  18609. const String prefix ("Loop" + String(i));
  18610. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18611. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18612. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18613. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18614. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18615. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18616. }
  18617. }
  18618. static MemoryBlock createFrom (const StringPairArray& values)
  18619. {
  18620. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18621. if (numLoops <= 0)
  18622. return MemoryBlock();
  18623. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18624. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18625. data.fillWith (0);
  18626. SMPLChunk* s = (SMPLChunk*) data.getData();
  18627. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18628. // as they get called in the right order..
  18629. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18630. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18631. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18632. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18633. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18634. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18635. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18636. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18637. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18638. for (int i = 0; i < numLoops; ++i)
  18639. {
  18640. const String prefix ("Loop" + String(i));
  18641. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18642. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18643. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18644. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18645. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18646. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18647. }
  18648. return data;
  18649. }
  18650. } PACKED;
  18651. struct ExtensibleWavSubFormat
  18652. {
  18653. uint32 data1;
  18654. uint16 data2;
  18655. uint16 data3;
  18656. uint8 data4[8];
  18657. } PACKED;
  18658. #if JUCE_MSVC
  18659. #pragma pack (pop)
  18660. #endif
  18661. #undef PACKED
  18662. class WavAudioFormatReader : public AudioFormatReader
  18663. {
  18664. public:
  18665. WavAudioFormatReader (InputStream* const in)
  18666. : AudioFormatReader (in, TRANS (wavFormatName)),
  18667. bwavChunkStart (0),
  18668. bwavSize (0),
  18669. dataLength (0)
  18670. {
  18671. if (input->readInt() == chunkName ("RIFF"))
  18672. {
  18673. const uint32 len = (uint32) input->readInt();
  18674. const int64 end = input->getPosition() + len;
  18675. bool hasGotType = false;
  18676. bool hasGotData = false;
  18677. if (input->readInt() == chunkName ("WAVE"))
  18678. {
  18679. while (input->getPosition() < end
  18680. && ! input->isExhausted())
  18681. {
  18682. const int chunkType = input->readInt();
  18683. uint32 length = (uint32) input->readInt();
  18684. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18685. if (chunkType == chunkName ("fmt "))
  18686. {
  18687. // read the format chunk
  18688. const unsigned short format = input->readShort();
  18689. const short numChans = input->readShort();
  18690. sampleRate = input->readInt();
  18691. const int bytesPerSec = input->readInt();
  18692. numChannels = numChans;
  18693. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18694. bitsPerSample = 8 * bytesPerFrame / numChans;
  18695. if (format == 3)
  18696. {
  18697. usesFloatingPointData = true;
  18698. }
  18699. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18700. {
  18701. if (length < 40) // too short
  18702. {
  18703. bytesPerFrame = 0;
  18704. }
  18705. else
  18706. {
  18707. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18708. ExtensibleWavSubFormat subFormat;
  18709. subFormat.data1 = input->readInt();
  18710. subFormat.data2 = input->readShort();
  18711. subFormat.data3 = input->readShort();
  18712. input->read (subFormat.data4, sizeof (subFormat.data4));
  18713. const ExtensibleWavSubFormat pcmFormat
  18714. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18715. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18716. {
  18717. const ExtensibleWavSubFormat ambisonicFormat
  18718. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18719. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18720. bytesPerFrame = 0;
  18721. }
  18722. }
  18723. }
  18724. else if (format != 1)
  18725. {
  18726. bytesPerFrame = 0;
  18727. }
  18728. hasGotType = true;
  18729. }
  18730. else if (chunkType == chunkName ("data"))
  18731. {
  18732. // get the data chunk's position
  18733. dataLength = length;
  18734. dataChunkStart = input->getPosition();
  18735. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18736. hasGotData = true;
  18737. }
  18738. else if (chunkType == chunkName ("bext"))
  18739. {
  18740. bwavChunkStart = input->getPosition();
  18741. bwavSize = length;
  18742. // Broadcast-wav extension chunk..
  18743. HeapBlock <BWAVChunk> bwav;
  18744. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18745. input->read (bwav, length);
  18746. bwav->copyTo (metadataValues);
  18747. }
  18748. else if (chunkType == chunkName ("smpl"))
  18749. {
  18750. HeapBlock <SMPLChunk> smpl;
  18751. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18752. input->read (smpl, length);
  18753. smpl->copyTo (metadataValues, length);
  18754. }
  18755. else if (chunkEnd <= input->getPosition())
  18756. {
  18757. break;
  18758. }
  18759. input->setPosition (chunkEnd);
  18760. }
  18761. }
  18762. }
  18763. }
  18764. ~WavAudioFormatReader()
  18765. {
  18766. }
  18767. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18768. int64 startSampleInFile, int numSamples)
  18769. {
  18770. jassert (destSamples != 0);
  18771. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18772. if (samplesAvailable < numSamples)
  18773. {
  18774. for (int i = numDestChannels; --i >= 0;)
  18775. if (destSamples[i] != 0)
  18776. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18777. numSamples = (int) samplesAvailable;
  18778. }
  18779. if (numSamples <= 0)
  18780. return true;
  18781. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18782. while (numSamples > 0)
  18783. {
  18784. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18785. char tempBuffer [tempBufSize];
  18786. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18787. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18788. if (bytesRead < numThisTime * bytesPerFrame)
  18789. {
  18790. jassert (bytesRead >= 0);
  18791. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18792. }
  18793. switch (bitsPerSample)
  18794. {
  18795. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18796. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18797. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18798. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18799. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18800. default: jassertfalse; break;
  18801. }
  18802. startOffsetInDestBuffer += numThisTime;
  18803. numSamples -= numThisTime;
  18804. }
  18805. return true;
  18806. }
  18807. int64 bwavChunkStart, bwavSize;
  18808. juce_UseDebuggingNewOperator
  18809. private:
  18810. ScopedPointer<AudioData::Converter> converter;
  18811. int bytesPerFrame;
  18812. int64 dataChunkStart, dataLength;
  18813. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18814. WavAudioFormatReader (const WavAudioFormatReader&);
  18815. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18816. };
  18817. class WavAudioFormatWriter : public AudioFormatWriter
  18818. {
  18819. public:
  18820. WavAudioFormatWriter (OutputStream* const out,
  18821. const double sampleRate_,
  18822. const unsigned int numChannels_,
  18823. const int bits,
  18824. const StringPairArray& metadataValues)
  18825. : AudioFormatWriter (out,
  18826. TRANS (wavFormatName),
  18827. sampleRate_,
  18828. numChannels_,
  18829. bits),
  18830. lengthInSamples (0),
  18831. bytesWritten (0),
  18832. writeFailed (false)
  18833. {
  18834. if (metadataValues.size() > 0)
  18835. {
  18836. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18837. smplChunk = SMPLChunk::createFrom (metadataValues);
  18838. }
  18839. headerPosition = out->getPosition();
  18840. writeHeader();
  18841. }
  18842. ~WavAudioFormatWriter()
  18843. {
  18844. writeHeader();
  18845. }
  18846. bool write (const int** data, int numSamples)
  18847. {
  18848. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18849. if (writeFailed)
  18850. return false;
  18851. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18852. tempBlock.ensureSize (bytes, false);
  18853. switch (bitsPerSample)
  18854. {
  18855. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18856. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18857. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18858. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18859. default: jassertfalse; break;
  18860. }
  18861. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18862. || ! output->write (tempBlock.getData(), bytes))
  18863. {
  18864. // failed to write to disk, so let's try writing the header.
  18865. // If it's just run out of disk space, then if it does manage
  18866. // to write the header, we'll still have a useable file..
  18867. writeHeader();
  18868. writeFailed = true;
  18869. return false;
  18870. }
  18871. else
  18872. {
  18873. bytesWritten += bytes;
  18874. lengthInSamples += numSamples;
  18875. return true;
  18876. }
  18877. }
  18878. juce_UseDebuggingNewOperator
  18879. private:
  18880. ScopedPointer<AudioData::Converter> converter;
  18881. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18882. uint32 lengthInSamples, bytesWritten;
  18883. int64 headerPosition;
  18884. bool writeFailed;
  18885. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18886. void writeHeader()
  18887. {
  18888. const bool seekedOk = output->setPosition (headerPosition);
  18889. (void) seekedOk;
  18890. // if this fails, you've given it an output stream that can't seek! It needs
  18891. // to be able to seek back to write the header
  18892. jassert (seekedOk);
  18893. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18894. output->writeInt (chunkName ("RIFF"));
  18895. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18896. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18897. output->writeInt (chunkName ("WAVE"));
  18898. output->writeInt (chunkName ("fmt "));
  18899. output->writeInt (16);
  18900. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18901. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18902. output->writeShort ((short) numChannels);
  18903. output->writeInt ((int) sampleRate);
  18904. output->writeInt (bytesPerFrame * (int) sampleRate);
  18905. output->writeShort ((short) bytesPerFrame);
  18906. output->writeShort ((short) bitsPerSample);
  18907. if (bwavChunk.getSize() > 0)
  18908. {
  18909. output->writeInt (chunkName ("bext"));
  18910. output->writeInt ((int) bwavChunk.getSize());
  18911. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18912. }
  18913. if (smplChunk.getSize() > 0)
  18914. {
  18915. output->writeInt (chunkName ("smpl"));
  18916. output->writeInt ((int) smplChunk.getSize());
  18917. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18918. }
  18919. output->writeInt (chunkName ("data"));
  18920. output->writeInt (lengthInSamples * bytesPerFrame);
  18921. usesFloatingPointData = (bitsPerSample == 32);
  18922. }
  18923. WavAudioFormatWriter (const WavAudioFormatWriter&);
  18924. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  18925. };
  18926. WavAudioFormat::WavAudioFormat()
  18927. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18928. {
  18929. }
  18930. WavAudioFormat::~WavAudioFormat()
  18931. {
  18932. }
  18933. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18934. {
  18935. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18936. return Array <int> (rates);
  18937. }
  18938. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18939. {
  18940. const int depths[] = { 8, 16, 24, 32, 0 };
  18941. return Array <int> (depths);
  18942. }
  18943. bool WavAudioFormat::canDoStereo() { return true; }
  18944. bool WavAudioFormat::canDoMono() { return true; }
  18945. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18946. const bool deleteStreamIfOpeningFails)
  18947. {
  18948. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18949. if (r->sampleRate != 0)
  18950. return r.release();
  18951. if (! deleteStreamIfOpeningFails)
  18952. r->input = 0;
  18953. return 0;
  18954. }
  18955. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18956. double sampleRate,
  18957. unsigned int numChannels,
  18958. int bitsPerSample,
  18959. const StringPairArray& metadataValues,
  18960. int /*qualityOptionIndex*/)
  18961. {
  18962. if (getPossibleBitDepths().contains (bitsPerSample))
  18963. {
  18964. return new WavAudioFormatWriter (out,
  18965. sampleRate,
  18966. numChannels,
  18967. bitsPerSample,
  18968. metadataValues);
  18969. }
  18970. return 0;
  18971. }
  18972. namespace
  18973. {
  18974. bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18975. {
  18976. TemporaryFile tempFile (file);
  18977. WavAudioFormat wav;
  18978. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18979. if (reader != 0)
  18980. {
  18981. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18982. if (outStream != 0)
  18983. {
  18984. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18985. reader->numChannels, reader->bitsPerSample,
  18986. metadata, 0));
  18987. if (writer != 0)
  18988. {
  18989. outStream.release();
  18990. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18991. writer = 0;
  18992. reader = 0;
  18993. return ok && tempFile.overwriteTargetFileWithTemporary();
  18994. }
  18995. }
  18996. }
  18997. return false;
  18998. }
  18999. }
  19000. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  19001. {
  19002. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  19003. if (reader != 0)
  19004. {
  19005. const int64 bwavPos = reader->bwavChunkStart;
  19006. const int64 bwavSize = reader->bwavSize;
  19007. reader = 0;
  19008. if (bwavSize > 0)
  19009. {
  19010. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  19011. if (chunk.getSize() <= (size_t) bwavSize)
  19012. {
  19013. // the new one will fit in the space available, so write it directly..
  19014. const int64 oldSize = wavFile.getSize();
  19015. {
  19016. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  19017. out->setPosition (bwavPos);
  19018. out->write (chunk.getData(), (int) chunk.getSize());
  19019. out->setPosition (oldSize);
  19020. }
  19021. jassert (wavFile.getSize() == oldSize);
  19022. return true;
  19023. }
  19024. }
  19025. }
  19026. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  19027. }
  19028. END_JUCE_NAMESPACE
  19029. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  19030. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  19031. #if JUCE_USE_CDREADER
  19032. BEGIN_JUCE_NAMESPACE
  19033. int AudioCDReader::getNumTracks() const
  19034. {
  19035. return trackStartSamples.size() - 1;
  19036. }
  19037. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  19038. {
  19039. return trackStartSamples [trackNum];
  19040. }
  19041. const Array<int>& AudioCDReader::getTrackOffsets() const
  19042. {
  19043. return trackStartSamples;
  19044. }
  19045. int AudioCDReader::getCDDBId()
  19046. {
  19047. int checksum = 0;
  19048. const int numTracks = getNumTracks();
  19049. for (int i = 0; i < numTracks; ++i)
  19050. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  19051. checksum += offset % 10;
  19052. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  19053. // CCLLLLTT: checksum, length, tracks
  19054. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  19055. }
  19056. END_JUCE_NAMESPACE
  19057. #endif
  19058. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  19059. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19060. BEGIN_JUCE_NAMESPACE
  19061. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  19062. const bool deleteReaderWhenThisIsDeleted)
  19063. : reader (reader_),
  19064. deleteReader (deleteReaderWhenThisIsDeleted),
  19065. nextPlayPos (0),
  19066. looping (false)
  19067. {
  19068. jassert (reader != 0);
  19069. }
  19070. AudioFormatReaderSource::~AudioFormatReaderSource()
  19071. {
  19072. releaseResources();
  19073. if (deleteReader)
  19074. delete reader;
  19075. }
  19076. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  19077. {
  19078. nextPlayPos = newPosition;
  19079. }
  19080. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  19081. {
  19082. looping = shouldLoop;
  19083. }
  19084. int AudioFormatReaderSource::getNextReadPosition() const
  19085. {
  19086. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  19087. : nextPlayPos;
  19088. }
  19089. int AudioFormatReaderSource::getTotalLength() const
  19090. {
  19091. return (int) reader->lengthInSamples;
  19092. }
  19093. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19094. double /*sampleRate*/)
  19095. {
  19096. }
  19097. void AudioFormatReaderSource::releaseResources()
  19098. {
  19099. }
  19100. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19101. {
  19102. if (info.numSamples > 0)
  19103. {
  19104. const int start = nextPlayPos;
  19105. if (looping)
  19106. {
  19107. const int newStart = start % (int) reader->lengthInSamples;
  19108. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  19109. if (newEnd > newStart)
  19110. {
  19111. info.buffer->readFromAudioReader (reader,
  19112. info.startSample,
  19113. newEnd - newStart,
  19114. newStart,
  19115. true, true);
  19116. }
  19117. else
  19118. {
  19119. const int endSamps = (int) reader->lengthInSamples - newStart;
  19120. info.buffer->readFromAudioReader (reader,
  19121. info.startSample,
  19122. endSamps,
  19123. newStart,
  19124. true, true);
  19125. info.buffer->readFromAudioReader (reader,
  19126. info.startSample + endSamps,
  19127. newEnd,
  19128. 0,
  19129. true, true);
  19130. }
  19131. nextPlayPos = newEnd;
  19132. }
  19133. else
  19134. {
  19135. info.buffer->readFromAudioReader (reader,
  19136. info.startSample,
  19137. info.numSamples,
  19138. start,
  19139. true, true);
  19140. nextPlayPos += info.numSamples;
  19141. }
  19142. }
  19143. }
  19144. END_JUCE_NAMESPACE
  19145. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19146. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19147. BEGIN_JUCE_NAMESPACE
  19148. AudioSourcePlayer::AudioSourcePlayer()
  19149. : source (0),
  19150. sampleRate (0),
  19151. bufferSize (0),
  19152. tempBuffer (2, 8),
  19153. lastGain (1.0f),
  19154. gain (1.0f)
  19155. {
  19156. }
  19157. AudioSourcePlayer::~AudioSourcePlayer()
  19158. {
  19159. setSource (0);
  19160. }
  19161. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19162. {
  19163. if (source != newSource)
  19164. {
  19165. AudioSource* const oldSource = source;
  19166. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19167. newSource->prepareToPlay (bufferSize, sampleRate);
  19168. {
  19169. const ScopedLock sl (readLock);
  19170. source = newSource;
  19171. }
  19172. if (oldSource != 0)
  19173. oldSource->releaseResources();
  19174. }
  19175. }
  19176. void AudioSourcePlayer::setGain (const float newGain) throw()
  19177. {
  19178. gain = newGain;
  19179. }
  19180. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19181. int totalNumInputChannels,
  19182. float** outputChannelData,
  19183. int totalNumOutputChannels,
  19184. int numSamples)
  19185. {
  19186. // these should have been prepared by audioDeviceAboutToStart()...
  19187. jassert (sampleRate > 0 && bufferSize > 0);
  19188. const ScopedLock sl (readLock);
  19189. if (source != 0)
  19190. {
  19191. AudioSourceChannelInfo info;
  19192. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19193. // messy stuff needed to compact the channels down into an array
  19194. // of non-zero pointers..
  19195. for (i = 0; i < totalNumInputChannels; ++i)
  19196. {
  19197. if (inputChannelData[i] != 0)
  19198. {
  19199. inputChans [numInputs++] = inputChannelData[i];
  19200. if (numInputs >= numElementsInArray (inputChans))
  19201. break;
  19202. }
  19203. }
  19204. for (i = 0; i < totalNumOutputChannels; ++i)
  19205. {
  19206. if (outputChannelData[i] != 0)
  19207. {
  19208. outputChans [numOutputs++] = outputChannelData[i];
  19209. if (numOutputs >= numElementsInArray (outputChans))
  19210. break;
  19211. }
  19212. }
  19213. if (numInputs > numOutputs)
  19214. {
  19215. // if there aren't enough output channels for the number of
  19216. // inputs, we need to create some temporary extra ones (can't
  19217. // use the input data in case it gets written to)
  19218. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19219. false, false, true);
  19220. for (i = 0; i < numOutputs; ++i)
  19221. {
  19222. channels[numActiveChans] = outputChans[i];
  19223. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19224. ++numActiveChans;
  19225. }
  19226. for (i = numOutputs; i < numInputs; ++i)
  19227. {
  19228. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19229. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19230. ++numActiveChans;
  19231. }
  19232. }
  19233. else
  19234. {
  19235. for (i = 0; i < numInputs; ++i)
  19236. {
  19237. channels[numActiveChans] = outputChans[i];
  19238. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19239. ++numActiveChans;
  19240. }
  19241. for (i = numInputs; i < numOutputs; ++i)
  19242. {
  19243. channels[numActiveChans] = outputChans[i];
  19244. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19245. ++numActiveChans;
  19246. }
  19247. }
  19248. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19249. info.buffer = &buffer;
  19250. info.startSample = 0;
  19251. info.numSamples = numSamples;
  19252. source->getNextAudioBlock (info);
  19253. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19254. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19255. lastGain = gain;
  19256. }
  19257. else
  19258. {
  19259. for (int i = 0; i < totalNumOutputChannels; ++i)
  19260. if (outputChannelData[i] != 0)
  19261. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19262. }
  19263. }
  19264. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19265. {
  19266. sampleRate = device->getCurrentSampleRate();
  19267. bufferSize = device->getCurrentBufferSizeSamples();
  19268. zeromem (channels, sizeof (channels));
  19269. if (source != 0)
  19270. source->prepareToPlay (bufferSize, sampleRate);
  19271. }
  19272. void AudioSourcePlayer::audioDeviceStopped()
  19273. {
  19274. if (source != 0)
  19275. source->releaseResources();
  19276. sampleRate = 0.0;
  19277. bufferSize = 0;
  19278. tempBuffer.setSize (2, 8);
  19279. }
  19280. END_JUCE_NAMESPACE
  19281. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19282. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19283. BEGIN_JUCE_NAMESPACE
  19284. AudioTransportSource::AudioTransportSource()
  19285. : source (0),
  19286. resamplerSource (0),
  19287. bufferingSource (0),
  19288. positionableSource (0),
  19289. masterSource (0),
  19290. gain (1.0f),
  19291. lastGain (1.0f),
  19292. playing (false),
  19293. stopped (true),
  19294. sampleRate (44100.0),
  19295. sourceSampleRate (0.0),
  19296. blockSize (128),
  19297. readAheadBufferSize (0),
  19298. isPrepared (false),
  19299. inputStreamEOF (false)
  19300. {
  19301. }
  19302. AudioTransportSource::~AudioTransportSource()
  19303. {
  19304. setSource (0);
  19305. releaseResources();
  19306. }
  19307. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19308. int readAheadBufferSize_,
  19309. double sourceSampleRateToCorrectFor)
  19310. {
  19311. if (source == newSource)
  19312. {
  19313. if (source == 0)
  19314. return;
  19315. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19316. }
  19317. readAheadBufferSize = readAheadBufferSize_;
  19318. sourceSampleRate = sourceSampleRateToCorrectFor;
  19319. ResamplingAudioSource* newResamplerSource = 0;
  19320. BufferingAudioSource* newBufferingSource = 0;
  19321. PositionableAudioSource* newPositionableSource = 0;
  19322. AudioSource* newMasterSource = 0;
  19323. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19324. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19325. AudioSource* oldMasterSource = masterSource;
  19326. if (newSource != 0)
  19327. {
  19328. newPositionableSource = newSource;
  19329. if (readAheadBufferSize_ > 0)
  19330. newPositionableSource = newBufferingSource
  19331. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19332. newPositionableSource->setNextReadPosition (0);
  19333. if (sourceSampleRateToCorrectFor != 0)
  19334. newMasterSource = newResamplerSource
  19335. = new ResamplingAudioSource (newPositionableSource, false);
  19336. else
  19337. newMasterSource = newPositionableSource;
  19338. if (isPrepared)
  19339. {
  19340. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19341. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19342. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19343. }
  19344. }
  19345. {
  19346. const ScopedLock sl (callbackLock);
  19347. source = newSource;
  19348. resamplerSource = newResamplerSource;
  19349. bufferingSource = newBufferingSource;
  19350. masterSource = newMasterSource;
  19351. positionableSource = newPositionableSource;
  19352. playing = false;
  19353. }
  19354. if (oldMasterSource != 0)
  19355. oldMasterSource->releaseResources();
  19356. }
  19357. void AudioTransportSource::start()
  19358. {
  19359. if ((! playing) && masterSource != 0)
  19360. {
  19361. {
  19362. const ScopedLock sl (callbackLock);
  19363. playing = true;
  19364. stopped = false;
  19365. inputStreamEOF = false;
  19366. }
  19367. sendChangeMessage();
  19368. }
  19369. }
  19370. void AudioTransportSource::stop()
  19371. {
  19372. if (playing)
  19373. {
  19374. {
  19375. const ScopedLock sl (callbackLock);
  19376. playing = false;
  19377. }
  19378. int n = 500;
  19379. while (--n >= 0 && ! stopped)
  19380. Thread::sleep (2);
  19381. sendChangeMessage();
  19382. }
  19383. }
  19384. void AudioTransportSource::setPosition (double newPosition)
  19385. {
  19386. if (sampleRate > 0.0)
  19387. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19388. }
  19389. double AudioTransportSource::getCurrentPosition() const
  19390. {
  19391. if (sampleRate > 0.0)
  19392. return getNextReadPosition() / sampleRate;
  19393. else
  19394. return 0.0;
  19395. }
  19396. void AudioTransportSource::setNextReadPosition (int newPosition)
  19397. {
  19398. if (positionableSource != 0)
  19399. {
  19400. if (sampleRate > 0 && sourceSampleRate > 0)
  19401. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19402. positionableSource->setNextReadPosition (newPosition);
  19403. }
  19404. }
  19405. int AudioTransportSource::getNextReadPosition() const
  19406. {
  19407. if (positionableSource != 0)
  19408. {
  19409. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19410. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19411. }
  19412. return 0;
  19413. }
  19414. int AudioTransportSource::getTotalLength() const
  19415. {
  19416. const ScopedLock sl (callbackLock);
  19417. if (positionableSource != 0)
  19418. {
  19419. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19420. return roundToInt (positionableSource->getTotalLength() * ratio);
  19421. }
  19422. return 0;
  19423. }
  19424. bool AudioTransportSource::isLooping() const
  19425. {
  19426. const ScopedLock sl (callbackLock);
  19427. return positionableSource != 0
  19428. && positionableSource->isLooping();
  19429. }
  19430. void AudioTransportSource::setGain (const float newGain) throw()
  19431. {
  19432. gain = newGain;
  19433. }
  19434. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19435. double sampleRate_)
  19436. {
  19437. const ScopedLock sl (callbackLock);
  19438. sampleRate = sampleRate_;
  19439. blockSize = samplesPerBlockExpected;
  19440. if (masterSource != 0)
  19441. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19442. if (resamplerSource != 0 && sourceSampleRate != 0)
  19443. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19444. isPrepared = true;
  19445. }
  19446. void AudioTransportSource::releaseResources()
  19447. {
  19448. const ScopedLock sl (callbackLock);
  19449. if (masterSource != 0)
  19450. masterSource->releaseResources();
  19451. isPrepared = false;
  19452. }
  19453. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19454. {
  19455. const ScopedLock sl (callbackLock);
  19456. inputStreamEOF = false;
  19457. if (masterSource != 0 && ! stopped)
  19458. {
  19459. masterSource->getNextAudioBlock (info);
  19460. if (! playing)
  19461. {
  19462. // just stopped playing, so fade out the last block..
  19463. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19464. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19465. if (info.numSamples > 256)
  19466. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19467. }
  19468. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19469. && ! positionableSource->isLooping())
  19470. {
  19471. playing = false;
  19472. inputStreamEOF = true;
  19473. sendChangeMessage();
  19474. }
  19475. stopped = ! playing;
  19476. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19477. {
  19478. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19479. lastGain, gain);
  19480. }
  19481. }
  19482. else
  19483. {
  19484. info.clearActiveBufferRegion();
  19485. stopped = true;
  19486. }
  19487. lastGain = gain;
  19488. }
  19489. END_JUCE_NAMESPACE
  19490. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19491. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19492. BEGIN_JUCE_NAMESPACE
  19493. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19494. public Thread,
  19495. private Timer
  19496. {
  19497. public:
  19498. SharedBufferingAudioSourceThread()
  19499. : Thread ("Audio Buffer")
  19500. {
  19501. }
  19502. ~SharedBufferingAudioSourceThread()
  19503. {
  19504. stopThread (10000);
  19505. clearSingletonInstance();
  19506. }
  19507. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19508. void addSource (BufferingAudioSource* source)
  19509. {
  19510. const ScopedLock sl (lock);
  19511. if (! sources.contains (source))
  19512. {
  19513. sources.add (source);
  19514. startThread();
  19515. stopTimer();
  19516. }
  19517. notify();
  19518. }
  19519. void removeSource (BufferingAudioSource* source)
  19520. {
  19521. const ScopedLock sl (lock);
  19522. sources.removeValue (source);
  19523. if (sources.size() == 0)
  19524. startTimer (5000);
  19525. }
  19526. private:
  19527. Array <BufferingAudioSource*> sources;
  19528. CriticalSection lock;
  19529. void run()
  19530. {
  19531. while (! threadShouldExit())
  19532. {
  19533. bool busy = false;
  19534. for (int i = sources.size(); --i >= 0;)
  19535. {
  19536. if (threadShouldExit())
  19537. return;
  19538. const ScopedLock sl (lock);
  19539. BufferingAudioSource* const b = sources[i];
  19540. if (b != 0 && b->readNextBufferChunk())
  19541. busy = true;
  19542. }
  19543. if (! busy)
  19544. wait (500);
  19545. }
  19546. }
  19547. void timerCallback()
  19548. {
  19549. stopTimer();
  19550. if (sources.size() == 0)
  19551. deleteInstance();
  19552. }
  19553. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19554. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19555. };
  19556. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19557. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19558. const bool deleteSourceWhenDeleted_,
  19559. int numberOfSamplesToBuffer_)
  19560. : source (source_),
  19561. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19562. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19563. buffer (2, 0),
  19564. bufferValidStart (0),
  19565. bufferValidEnd (0),
  19566. nextPlayPos (0),
  19567. wasSourceLooping (false)
  19568. {
  19569. jassert (source_ != 0);
  19570. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19571. // not using a larger buffer..
  19572. }
  19573. BufferingAudioSource::~BufferingAudioSource()
  19574. {
  19575. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19576. if (thread != 0)
  19577. thread->removeSource (this);
  19578. if (deleteSourceWhenDeleted)
  19579. delete source;
  19580. }
  19581. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19582. {
  19583. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19584. sampleRate = sampleRate_;
  19585. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19586. buffer.clear();
  19587. bufferValidStart = 0;
  19588. bufferValidEnd = 0;
  19589. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19590. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19591. buffer.getNumSamples() / 2))
  19592. {
  19593. SharedBufferingAudioSourceThread::getInstance()->notify();
  19594. Thread::sleep (5);
  19595. }
  19596. }
  19597. void BufferingAudioSource::releaseResources()
  19598. {
  19599. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19600. if (thread != 0)
  19601. thread->removeSource (this);
  19602. buffer.setSize (2, 0);
  19603. source->releaseResources();
  19604. }
  19605. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19606. {
  19607. const ScopedLock sl (bufferStartPosLock);
  19608. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19609. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19610. if (validStart == validEnd)
  19611. {
  19612. // total cache miss
  19613. info.clearActiveBufferRegion();
  19614. }
  19615. else
  19616. {
  19617. if (validStart > 0)
  19618. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19619. if (validEnd < info.numSamples)
  19620. info.buffer->clear (info.startSample + validEnd,
  19621. info.numSamples - validEnd); // partial cache miss at end
  19622. if (validStart < validEnd)
  19623. {
  19624. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19625. {
  19626. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19627. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19628. if (startBufferIndex < endBufferIndex)
  19629. {
  19630. info.buffer->copyFrom (chan, info.startSample + validStart,
  19631. buffer,
  19632. chan, startBufferIndex,
  19633. validEnd - validStart);
  19634. }
  19635. else
  19636. {
  19637. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19638. info.buffer->copyFrom (chan, info.startSample + validStart,
  19639. buffer,
  19640. chan, startBufferIndex,
  19641. initialSize);
  19642. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19643. buffer,
  19644. chan, 0,
  19645. (validEnd - validStart) - initialSize);
  19646. }
  19647. }
  19648. }
  19649. nextPlayPos += info.numSamples;
  19650. if (source->isLooping() && nextPlayPos > 0)
  19651. nextPlayPos %= source->getTotalLength();
  19652. }
  19653. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19654. if (thread != 0)
  19655. thread->notify();
  19656. }
  19657. int BufferingAudioSource::getNextReadPosition() const
  19658. {
  19659. return (source->isLooping() && nextPlayPos > 0)
  19660. ? nextPlayPos % source->getTotalLength()
  19661. : nextPlayPos;
  19662. }
  19663. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19664. {
  19665. const ScopedLock sl (bufferStartPosLock);
  19666. nextPlayPos = newPosition;
  19667. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19668. if (thread != 0)
  19669. thread->notify();
  19670. }
  19671. bool BufferingAudioSource::readNextBufferChunk()
  19672. {
  19673. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19674. {
  19675. const ScopedLock sl (bufferStartPosLock);
  19676. if (wasSourceLooping != isLooping())
  19677. {
  19678. wasSourceLooping = isLooping();
  19679. bufferValidStart = 0;
  19680. bufferValidEnd = 0;
  19681. }
  19682. newBVS = jmax (0, nextPlayPos);
  19683. newBVE = newBVS + buffer.getNumSamples() - 4;
  19684. sectionToReadStart = 0;
  19685. sectionToReadEnd = 0;
  19686. const int maxChunkSize = 2048;
  19687. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19688. {
  19689. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19690. sectionToReadStart = newBVS;
  19691. sectionToReadEnd = newBVE;
  19692. bufferValidStart = 0;
  19693. bufferValidEnd = 0;
  19694. }
  19695. else if (abs (newBVS - bufferValidStart) > 512
  19696. || abs (newBVE - bufferValidEnd) > 512)
  19697. {
  19698. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19699. sectionToReadStart = bufferValidEnd;
  19700. sectionToReadEnd = newBVE;
  19701. bufferValidStart = newBVS;
  19702. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19703. }
  19704. }
  19705. if (sectionToReadStart != sectionToReadEnd)
  19706. {
  19707. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19708. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19709. if (bufferIndexStart < bufferIndexEnd)
  19710. {
  19711. readBufferSection (sectionToReadStart,
  19712. sectionToReadEnd - sectionToReadStart,
  19713. bufferIndexStart);
  19714. }
  19715. else
  19716. {
  19717. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19718. readBufferSection (sectionToReadStart,
  19719. initialSize,
  19720. bufferIndexStart);
  19721. readBufferSection (sectionToReadStart + initialSize,
  19722. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19723. 0);
  19724. }
  19725. const ScopedLock sl2 (bufferStartPosLock);
  19726. bufferValidStart = newBVS;
  19727. bufferValidEnd = newBVE;
  19728. return true;
  19729. }
  19730. else
  19731. {
  19732. return false;
  19733. }
  19734. }
  19735. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19736. {
  19737. if (source->getNextReadPosition() != start)
  19738. source->setNextReadPosition (start);
  19739. AudioSourceChannelInfo info;
  19740. info.buffer = &buffer;
  19741. info.startSample = bufferOffset;
  19742. info.numSamples = length;
  19743. source->getNextAudioBlock (info);
  19744. }
  19745. END_JUCE_NAMESPACE
  19746. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19747. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19748. BEGIN_JUCE_NAMESPACE
  19749. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19750. const bool deleteSourceWhenDeleted_)
  19751. : requiredNumberOfChannels (2),
  19752. source (source_),
  19753. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19754. buffer (2, 16)
  19755. {
  19756. remappedInfo.buffer = &buffer;
  19757. remappedInfo.startSample = 0;
  19758. }
  19759. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19760. {
  19761. if (deleteSourceWhenDeleted)
  19762. delete source;
  19763. }
  19764. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19765. {
  19766. const ScopedLock sl (lock);
  19767. requiredNumberOfChannels = requiredNumberOfChannels_;
  19768. }
  19769. void ChannelRemappingAudioSource::clearAllMappings()
  19770. {
  19771. const ScopedLock sl (lock);
  19772. remappedInputs.clear();
  19773. remappedOutputs.clear();
  19774. }
  19775. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19776. {
  19777. const ScopedLock sl (lock);
  19778. while (remappedInputs.size() < destIndex)
  19779. remappedInputs.add (-1);
  19780. remappedInputs.set (destIndex, sourceIndex);
  19781. }
  19782. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19783. {
  19784. const ScopedLock sl (lock);
  19785. while (remappedOutputs.size() < sourceIndex)
  19786. remappedOutputs.add (-1);
  19787. remappedOutputs.set (sourceIndex, destIndex);
  19788. }
  19789. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19790. {
  19791. const ScopedLock sl (lock);
  19792. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19793. return remappedInputs.getUnchecked (inputChannelIndex);
  19794. return -1;
  19795. }
  19796. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19797. {
  19798. const ScopedLock sl (lock);
  19799. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19800. return remappedOutputs .getUnchecked (outputChannelIndex);
  19801. return -1;
  19802. }
  19803. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19804. {
  19805. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19806. }
  19807. void ChannelRemappingAudioSource::releaseResources()
  19808. {
  19809. source->releaseResources();
  19810. }
  19811. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19812. {
  19813. const ScopedLock sl (lock);
  19814. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19815. const int numChans = bufferToFill.buffer->getNumChannels();
  19816. int i;
  19817. for (i = 0; i < buffer.getNumChannels(); ++i)
  19818. {
  19819. const int remappedChan = getRemappedInputChannel (i);
  19820. if (remappedChan >= 0 && remappedChan < numChans)
  19821. {
  19822. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19823. remappedChan,
  19824. bufferToFill.startSample,
  19825. bufferToFill.numSamples);
  19826. }
  19827. else
  19828. {
  19829. buffer.clear (i, 0, bufferToFill.numSamples);
  19830. }
  19831. }
  19832. remappedInfo.numSamples = bufferToFill.numSamples;
  19833. source->getNextAudioBlock (remappedInfo);
  19834. bufferToFill.clearActiveBufferRegion();
  19835. for (i = 0; i < requiredNumberOfChannels; ++i)
  19836. {
  19837. const int remappedChan = getRemappedOutputChannel (i);
  19838. if (remappedChan >= 0 && remappedChan < numChans)
  19839. {
  19840. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19841. buffer, i, 0, bufferToFill.numSamples);
  19842. }
  19843. }
  19844. }
  19845. XmlElement* ChannelRemappingAudioSource::createXml() const
  19846. {
  19847. XmlElement* e = new XmlElement ("MAPPINGS");
  19848. String ins, outs;
  19849. int i;
  19850. const ScopedLock sl (lock);
  19851. for (i = 0; i < remappedInputs.size(); ++i)
  19852. ins << remappedInputs.getUnchecked(i) << ' ';
  19853. for (i = 0; i < remappedOutputs.size(); ++i)
  19854. outs << remappedOutputs.getUnchecked(i) << ' ';
  19855. e->setAttribute ("inputs", ins.trimEnd());
  19856. e->setAttribute ("outputs", outs.trimEnd());
  19857. return e;
  19858. }
  19859. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19860. {
  19861. if (e.hasTagName ("MAPPINGS"))
  19862. {
  19863. const ScopedLock sl (lock);
  19864. clearAllMappings();
  19865. StringArray ins, outs;
  19866. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19867. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19868. int i;
  19869. for (i = 0; i < ins.size(); ++i)
  19870. remappedInputs.add (ins[i].getIntValue());
  19871. for (i = 0; i < outs.size(); ++i)
  19872. remappedOutputs.add (outs[i].getIntValue());
  19873. }
  19874. }
  19875. END_JUCE_NAMESPACE
  19876. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19877. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19878. BEGIN_JUCE_NAMESPACE
  19879. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19880. const bool deleteInputWhenDeleted_)
  19881. : input (inputSource),
  19882. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19883. {
  19884. jassert (inputSource != 0);
  19885. for (int i = 2; --i >= 0;)
  19886. iirFilters.add (new IIRFilter());
  19887. }
  19888. IIRFilterAudioSource::~IIRFilterAudioSource()
  19889. {
  19890. if (deleteInputWhenDeleted)
  19891. delete input;
  19892. }
  19893. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19894. {
  19895. for (int i = iirFilters.size(); --i >= 0;)
  19896. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19897. }
  19898. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19899. {
  19900. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19901. for (int i = iirFilters.size(); --i >= 0;)
  19902. iirFilters.getUnchecked(i)->reset();
  19903. }
  19904. void IIRFilterAudioSource::releaseResources()
  19905. {
  19906. input->releaseResources();
  19907. }
  19908. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19909. {
  19910. input->getNextAudioBlock (bufferToFill);
  19911. const int numChannels = bufferToFill.buffer->getNumChannels();
  19912. while (numChannels > iirFilters.size())
  19913. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19914. for (int i = 0; i < numChannels; ++i)
  19915. iirFilters.getUnchecked(i)
  19916. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19917. bufferToFill.numSamples);
  19918. }
  19919. END_JUCE_NAMESPACE
  19920. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19921. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19922. BEGIN_JUCE_NAMESPACE
  19923. MixerAudioSource::MixerAudioSource()
  19924. : tempBuffer (2, 0),
  19925. currentSampleRate (0.0),
  19926. bufferSizeExpected (0)
  19927. {
  19928. }
  19929. MixerAudioSource::~MixerAudioSource()
  19930. {
  19931. removeAllInputs();
  19932. }
  19933. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19934. {
  19935. if (input != 0 && ! inputs.contains (input))
  19936. {
  19937. double localRate;
  19938. int localBufferSize;
  19939. {
  19940. const ScopedLock sl (lock);
  19941. localRate = currentSampleRate;
  19942. localBufferSize = bufferSizeExpected;
  19943. }
  19944. if (localRate != 0.0)
  19945. input->prepareToPlay (localBufferSize, localRate);
  19946. const ScopedLock sl (lock);
  19947. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19948. inputs.add (input);
  19949. }
  19950. }
  19951. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19952. {
  19953. if (input != 0)
  19954. {
  19955. int index;
  19956. {
  19957. const ScopedLock sl (lock);
  19958. index = inputs.indexOf (input);
  19959. if (index >= 0)
  19960. {
  19961. inputsToDelete.shiftBits (index, 1);
  19962. inputs.remove (index);
  19963. }
  19964. }
  19965. if (index >= 0)
  19966. {
  19967. input->releaseResources();
  19968. if (deleteInput)
  19969. delete input;
  19970. }
  19971. }
  19972. }
  19973. void MixerAudioSource::removeAllInputs()
  19974. {
  19975. OwnedArray<AudioSource> toDelete;
  19976. {
  19977. const ScopedLock sl (lock);
  19978. for (int i = inputs.size(); --i >= 0;)
  19979. if (inputsToDelete[i])
  19980. toDelete.add (inputs.getUnchecked(i));
  19981. }
  19982. }
  19983. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19984. {
  19985. tempBuffer.setSize (2, samplesPerBlockExpected);
  19986. const ScopedLock sl (lock);
  19987. currentSampleRate = sampleRate;
  19988. bufferSizeExpected = samplesPerBlockExpected;
  19989. for (int i = inputs.size(); --i >= 0;)
  19990. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19991. }
  19992. void MixerAudioSource::releaseResources()
  19993. {
  19994. const ScopedLock sl (lock);
  19995. for (int i = inputs.size(); --i >= 0;)
  19996. inputs.getUnchecked(i)->releaseResources();
  19997. tempBuffer.setSize (2, 0);
  19998. currentSampleRate = 0;
  19999. bufferSizeExpected = 0;
  20000. }
  20001. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20002. {
  20003. const ScopedLock sl (lock);
  20004. if (inputs.size() > 0)
  20005. {
  20006. inputs.getUnchecked(0)->getNextAudioBlock (info);
  20007. if (inputs.size() > 1)
  20008. {
  20009. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  20010. info.buffer->getNumSamples());
  20011. AudioSourceChannelInfo info2;
  20012. info2.buffer = &tempBuffer;
  20013. info2.numSamples = info.numSamples;
  20014. info2.startSample = 0;
  20015. for (int i = 1; i < inputs.size(); ++i)
  20016. {
  20017. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  20018. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  20019. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  20020. }
  20021. }
  20022. }
  20023. else
  20024. {
  20025. info.clearActiveBufferRegion();
  20026. }
  20027. }
  20028. END_JUCE_NAMESPACE
  20029. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  20030. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  20031. BEGIN_JUCE_NAMESPACE
  20032. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  20033. const bool deleteInputWhenDeleted_,
  20034. const int numChannels_)
  20035. : input (inputSource),
  20036. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  20037. ratio (1.0),
  20038. lastRatio (1.0),
  20039. buffer (numChannels_, 0),
  20040. sampsInBuffer (0),
  20041. numChannels (numChannels_)
  20042. {
  20043. jassert (input != 0);
  20044. }
  20045. ResamplingAudioSource::~ResamplingAudioSource()
  20046. {
  20047. if (deleteInputWhenDeleted)
  20048. delete input;
  20049. }
  20050. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  20051. {
  20052. jassert (samplesInPerOutputSample > 0);
  20053. const ScopedLock sl (ratioLock);
  20054. ratio = jmax (0.0, samplesInPerOutputSample);
  20055. }
  20056. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  20057. double sampleRate)
  20058. {
  20059. const ScopedLock sl (ratioLock);
  20060. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20061. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  20062. buffer.clear();
  20063. sampsInBuffer = 0;
  20064. bufferPos = 0;
  20065. subSampleOffset = 0.0;
  20066. filterStates.calloc (numChannels);
  20067. srcBuffers.calloc (numChannels);
  20068. destBuffers.calloc (numChannels);
  20069. createLowPass (ratio);
  20070. resetFilters();
  20071. }
  20072. void ResamplingAudioSource::releaseResources()
  20073. {
  20074. input->releaseResources();
  20075. buffer.setSize (numChannels, 0);
  20076. }
  20077. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20078. {
  20079. const ScopedLock sl (ratioLock);
  20080. if (lastRatio != ratio)
  20081. {
  20082. createLowPass (ratio);
  20083. lastRatio = ratio;
  20084. }
  20085. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  20086. int bufferSize = buffer.getNumSamples();
  20087. if (bufferSize < sampsNeeded + 8)
  20088. {
  20089. bufferPos %= bufferSize;
  20090. bufferSize = sampsNeeded + 32;
  20091. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  20092. }
  20093. bufferPos %= bufferSize;
  20094. int endOfBufferPos = bufferPos + sampsInBuffer;
  20095. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  20096. while (sampsNeeded > sampsInBuffer)
  20097. {
  20098. endOfBufferPos %= bufferSize;
  20099. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  20100. bufferSize - endOfBufferPos);
  20101. AudioSourceChannelInfo readInfo;
  20102. readInfo.buffer = &buffer;
  20103. readInfo.numSamples = numToDo;
  20104. readInfo.startSample = endOfBufferPos;
  20105. input->getNextAudioBlock (readInfo);
  20106. if (ratio > 1.0001)
  20107. {
  20108. // for down-sampling, pre-apply the filter..
  20109. for (int i = channelsToProcess; --i >= 0;)
  20110. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20111. }
  20112. sampsInBuffer += numToDo;
  20113. endOfBufferPos += numToDo;
  20114. }
  20115. for (int channel = 0; channel < channelsToProcess; ++channel)
  20116. {
  20117. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20118. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20119. }
  20120. int nextPos = (bufferPos + 1) % bufferSize;
  20121. for (int m = info.numSamples; --m >= 0;)
  20122. {
  20123. const float alpha = (float) subSampleOffset;
  20124. const float invAlpha = 1.0f - alpha;
  20125. for (int channel = 0; channel < channelsToProcess; ++channel)
  20126. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20127. subSampleOffset += ratio;
  20128. jassert (sampsInBuffer > 0);
  20129. while (subSampleOffset >= 1.0)
  20130. {
  20131. if (++bufferPos >= bufferSize)
  20132. bufferPos = 0;
  20133. --sampsInBuffer;
  20134. nextPos = (bufferPos + 1) % bufferSize;
  20135. subSampleOffset -= 1.0;
  20136. }
  20137. }
  20138. if (ratio < 0.9999)
  20139. {
  20140. // for up-sampling, apply the filter after transposing..
  20141. for (int i = channelsToProcess; --i >= 0;)
  20142. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20143. }
  20144. else if (ratio <= 1.0001)
  20145. {
  20146. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20147. for (int i = channelsToProcess; --i >= 0;)
  20148. {
  20149. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20150. FilterState& fs = filterStates[i];
  20151. if (info.numSamples > 1)
  20152. {
  20153. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20154. }
  20155. else
  20156. {
  20157. fs.y2 = fs.y1;
  20158. fs.x2 = fs.x1;
  20159. }
  20160. fs.y1 = fs.x1 = *endOfBuffer;
  20161. }
  20162. }
  20163. jassert (sampsInBuffer >= 0);
  20164. }
  20165. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20166. {
  20167. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20168. : 0.5 * frequencyRatio;
  20169. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  20170. const double nSquared = n * n;
  20171. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20172. setFilterCoefficients (c1,
  20173. c1 * 2.0f,
  20174. c1,
  20175. 1.0,
  20176. c1 * 2.0 * (1.0 - nSquared),
  20177. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20178. }
  20179. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20180. {
  20181. const double a = 1.0 / c4;
  20182. c1 *= a;
  20183. c2 *= a;
  20184. c3 *= a;
  20185. c5 *= a;
  20186. c6 *= a;
  20187. coefficients[0] = c1;
  20188. coefficients[1] = c2;
  20189. coefficients[2] = c3;
  20190. coefficients[3] = c4;
  20191. coefficients[4] = c5;
  20192. coefficients[5] = c6;
  20193. }
  20194. void ResamplingAudioSource::resetFilters()
  20195. {
  20196. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20197. }
  20198. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20199. {
  20200. while (--num >= 0)
  20201. {
  20202. const double in = *samples;
  20203. double out = coefficients[0] * in
  20204. + coefficients[1] * fs.x1
  20205. + coefficients[2] * fs.x2
  20206. - coefficients[4] * fs.y1
  20207. - coefficients[5] * fs.y2;
  20208. #if JUCE_INTEL
  20209. if (! (out < -1.0e-8 || out > 1.0e-8))
  20210. out = 0;
  20211. #endif
  20212. fs.x2 = fs.x1;
  20213. fs.x1 = in;
  20214. fs.y2 = fs.y1;
  20215. fs.y1 = out;
  20216. *samples++ = (float) out;
  20217. }
  20218. }
  20219. END_JUCE_NAMESPACE
  20220. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20221. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20222. BEGIN_JUCE_NAMESPACE
  20223. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20224. : frequency (1000.0),
  20225. sampleRate (44100.0),
  20226. currentPhase (0.0),
  20227. phasePerSample (0.0),
  20228. amplitude (0.5f)
  20229. {
  20230. }
  20231. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20232. {
  20233. }
  20234. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20235. {
  20236. amplitude = newAmplitude;
  20237. }
  20238. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20239. {
  20240. frequency = newFrequencyHz;
  20241. phasePerSample = 0.0;
  20242. }
  20243. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20244. double sampleRate_)
  20245. {
  20246. currentPhase = 0.0;
  20247. phasePerSample = 0.0;
  20248. sampleRate = sampleRate_;
  20249. }
  20250. void ToneGeneratorAudioSource::releaseResources()
  20251. {
  20252. }
  20253. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20254. {
  20255. if (phasePerSample == 0.0)
  20256. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20257. for (int i = 0; i < info.numSamples; ++i)
  20258. {
  20259. const float sample = amplitude * (float) std::sin (currentPhase);
  20260. currentPhase += phasePerSample;
  20261. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20262. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20263. }
  20264. }
  20265. END_JUCE_NAMESPACE
  20266. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20267. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20268. BEGIN_JUCE_NAMESPACE
  20269. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20270. : sampleRate (0),
  20271. bufferSize (0),
  20272. useDefaultInputChannels (true),
  20273. useDefaultOutputChannels (true)
  20274. {
  20275. }
  20276. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20277. {
  20278. return outputDeviceName == other.outputDeviceName
  20279. && inputDeviceName == other.inputDeviceName
  20280. && sampleRate == other.sampleRate
  20281. && bufferSize == other.bufferSize
  20282. && inputChannels == other.inputChannels
  20283. && useDefaultInputChannels == other.useDefaultInputChannels
  20284. && outputChannels == other.outputChannels
  20285. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20286. }
  20287. AudioDeviceManager::AudioDeviceManager()
  20288. : currentAudioDevice (0),
  20289. numInputChansNeeded (0),
  20290. numOutputChansNeeded (2),
  20291. listNeedsScanning (true),
  20292. useInputNames (false),
  20293. inputLevelMeasurementEnabledCount (0),
  20294. inputLevel (0),
  20295. tempBuffer (2, 2),
  20296. defaultMidiOutput (0),
  20297. cpuUsageMs (0),
  20298. timeToCpuScale (0)
  20299. {
  20300. callbackHandler.owner = this;
  20301. }
  20302. AudioDeviceManager::~AudioDeviceManager()
  20303. {
  20304. currentAudioDevice = 0;
  20305. defaultMidiOutput = 0;
  20306. }
  20307. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20308. {
  20309. if (availableDeviceTypes.size() == 0)
  20310. {
  20311. createAudioDeviceTypes (availableDeviceTypes);
  20312. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20313. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20314. if (availableDeviceTypes.size() > 0)
  20315. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20316. }
  20317. }
  20318. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20319. {
  20320. scanDevicesIfNeeded();
  20321. return availableDeviceTypes;
  20322. }
  20323. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20324. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20325. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20326. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20327. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20328. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20329. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20330. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20331. {
  20332. (void) list; // (to avoid 'unused param' warnings)
  20333. #if JUCE_WINDOWS
  20334. #if JUCE_WASAPI
  20335. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20336. list.add (juce_createAudioIODeviceType_WASAPI());
  20337. #endif
  20338. #if JUCE_DIRECTSOUND
  20339. list.add (juce_createAudioIODeviceType_DirectSound());
  20340. #endif
  20341. #if JUCE_ASIO
  20342. list.add (juce_createAudioIODeviceType_ASIO());
  20343. #endif
  20344. #endif
  20345. #if JUCE_MAC
  20346. list.add (juce_createAudioIODeviceType_CoreAudio());
  20347. #endif
  20348. #if JUCE_IOS
  20349. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20350. #endif
  20351. #if JUCE_LINUX && JUCE_ALSA
  20352. list.add (juce_createAudioIODeviceType_ALSA());
  20353. #endif
  20354. #if JUCE_LINUX && JUCE_JACK
  20355. list.add (juce_createAudioIODeviceType_JACK());
  20356. #endif
  20357. }
  20358. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20359. const int numOutputChannelsNeeded,
  20360. const XmlElement* const e,
  20361. const bool selectDefaultDeviceOnFailure,
  20362. const String& preferredDefaultDeviceName,
  20363. const AudioDeviceSetup* preferredSetupOptions)
  20364. {
  20365. scanDevicesIfNeeded();
  20366. numInputChansNeeded = numInputChannelsNeeded;
  20367. numOutputChansNeeded = numOutputChannelsNeeded;
  20368. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20369. {
  20370. lastExplicitSettings = new XmlElement (*e);
  20371. String error;
  20372. AudioDeviceSetup setup;
  20373. if (preferredSetupOptions != 0)
  20374. setup = *preferredSetupOptions;
  20375. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20376. {
  20377. setup.inputDeviceName = setup.outputDeviceName
  20378. = e->getStringAttribute ("audioDeviceName");
  20379. }
  20380. else
  20381. {
  20382. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20383. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20384. }
  20385. currentDeviceType = e->getStringAttribute ("deviceType");
  20386. if (currentDeviceType.isEmpty())
  20387. {
  20388. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20389. if (type != 0)
  20390. currentDeviceType = type->getTypeName();
  20391. else if (availableDeviceTypes.size() > 0)
  20392. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20393. }
  20394. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20395. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20396. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20397. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20398. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20399. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20400. error = setAudioDeviceSetup (setup, true);
  20401. midiInsFromXml.clear();
  20402. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20403. midiInsFromXml.add (c->getStringAttribute ("name"));
  20404. const StringArray allMidiIns (MidiInput::getDevices());
  20405. for (int i = allMidiIns.size(); --i >= 0;)
  20406. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20407. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20408. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20409. false, preferredDefaultDeviceName);
  20410. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20411. return error;
  20412. }
  20413. else
  20414. {
  20415. AudioDeviceSetup setup;
  20416. if (preferredSetupOptions != 0)
  20417. {
  20418. setup = *preferredSetupOptions;
  20419. }
  20420. else if (preferredDefaultDeviceName.isNotEmpty())
  20421. {
  20422. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20423. {
  20424. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20425. StringArray outs (type->getDeviceNames (false));
  20426. int i;
  20427. for (i = 0; i < outs.size(); ++i)
  20428. {
  20429. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20430. {
  20431. setup.outputDeviceName = outs[i];
  20432. break;
  20433. }
  20434. }
  20435. StringArray ins (type->getDeviceNames (true));
  20436. for (i = 0; i < ins.size(); ++i)
  20437. {
  20438. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20439. {
  20440. setup.inputDeviceName = ins[i];
  20441. break;
  20442. }
  20443. }
  20444. }
  20445. }
  20446. insertDefaultDeviceNames (setup);
  20447. return setAudioDeviceSetup (setup, false);
  20448. }
  20449. }
  20450. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20451. {
  20452. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20453. if (type != 0)
  20454. {
  20455. if (setup.outputDeviceName.isEmpty())
  20456. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20457. if (setup.inputDeviceName.isEmpty())
  20458. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20459. }
  20460. }
  20461. XmlElement* AudioDeviceManager::createStateXml() const
  20462. {
  20463. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20464. }
  20465. void AudioDeviceManager::scanDevicesIfNeeded()
  20466. {
  20467. if (listNeedsScanning)
  20468. {
  20469. listNeedsScanning = false;
  20470. createDeviceTypesIfNeeded();
  20471. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20472. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20473. }
  20474. }
  20475. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20476. {
  20477. scanDevicesIfNeeded();
  20478. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20479. {
  20480. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20481. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20482. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20483. {
  20484. return type;
  20485. }
  20486. }
  20487. return 0;
  20488. }
  20489. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20490. {
  20491. setup = currentSetup;
  20492. }
  20493. void AudioDeviceManager::deleteCurrentDevice()
  20494. {
  20495. currentAudioDevice = 0;
  20496. currentSetup.inputDeviceName = String::empty;
  20497. currentSetup.outputDeviceName = String::empty;
  20498. }
  20499. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20500. const bool treatAsChosenDevice)
  20501. {
  20502. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20503. {
  20504. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20505. && currentDeviceType != type)
  20506. {
  20507. currentDeviceType = type;
  20508. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20509. insertDefaultDeviceNames (s);
  20510. setAudioDeviceSetup (s, treatAsChosenDevice);
  20511. sendChangeMessage();
  20512. break;
  20513. }
  20514. }
  20515. }
  20516. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20517. {
  20518. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20519. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20520. return availableDeviceTypes[i];
  20521. return availableDeviceTypes[0];
  20522. }
  20523. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20524. const bool treatAsChosenDevice)
  20525. {
  20526. jassert (&newSetup != &currentSetup); // this will have no effect
  20527. if (newSetup == currentSetup && currentAudioDevice != 0)
  20528. return String::empty;
  20529. if (! (newSetup == currentSetup))
  20530. sendChangeMessage();
  20531. stopDevice();
  20532. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20533. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20534. String error;
  20535. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20536. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20537. {
  20538. deleteCurrentDevice();
  20539. if (treatAsChosenDevice)
  20540. updateXml();
  20541. return String::empty;
  20542. }
  20543. if (currentSetup.inputDeviceName != newInputDeviceName
  20544. || currentSetup.outputDeviceName != newOutputDeviceName
  20545. || currentAudioDevice == 0)
  20546. {
  20547. deleteCurrentDevice();
  20548. scanDevicesIfNeeded();
  20549. if (newOutputDeviceName.isNotEmpty()
  20550. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20551. {
  20552. return "No such device: " + newOutputDeviceName;
  20553. }
  20554. if (newInputDeviceName.isNotEmpty()
  20555. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20556. {
  20557. return "No such device: " + newInputDeviceName;
  20558. }
  20559. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20560. if (currentAudioDevice == 0)
  20561. 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!";
  20562. else
  20563. error = currentAudioDevice->getLastError();
  20564. if (error.isNotEmpty())
  20565. {
  20566. deleteCurrentDevice();
  20567. return error;
  20568. }
  20569. if (newSetup.useDefaultInputChannels)
  20570. {
  20571. inputChannels.clear();
  20572. inputChannels.setRange (0, numInputChansNeeded, true);
  20573. }
  20574. if (newSetup.useDefaultOutputChannels)
  20575. {
  20576. outputChannels.clear();
  20577. outputChannels.setRange (0, numOutputChansNeeded, true);
  20578. }
  20579. if (newInputDeviceName.isEmpty())
  20580. inputChannels.clear();
  20581. if (newOutputDeviceName.isEmpty())
  20582. outputChannels.clear();
  20583. }
  20584. if (! newSetup.useDefaultInputChannels)
  20585. inputChannels = newSetup.inputChannels;
  20586. if (! newSetup.useDefaultOutputChannels)
  20587. outputChannels = newSetup.outputChannels;
  20588. currentSetup = newSetup;
  20589. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20590. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20591. error = currentAudioDevice->open (inputChannels,
  20592. outputChannels,
  20593. currentSetup.sampleRate,
  20594. currentSetup.bufferSize);
  20595. if (error.isEmpty())
  20596. {
  20597. currentDeviceType = currentAudioDevice->getTypeName();
  20598. currentAudioDevice->start (&callbackHandler);
  20599. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20600. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20601. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20602. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20603. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20604. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20605. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20606. if (treatAsChosenDevice)
  20607. updateXml();
  20608. }
  20609. else
  20610. {
  20611. deleteCurrentDevice();
  20612. }
  20613. return error;
  20614. }
  20615. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20616. {
  20617. jassert (currentAudioDevice != 0);
  20618. if (rate > 0)
  20619. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20620. if (currentAudioDevice->getSampleRate (i) == rate)
  20621. return rate;
  20622. double lowestAbove44 = 0.0;
  20623. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20624. {
  20625. const double sr = currentAudioDevice->getSampleRate (i);
  20626. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20627. lowestAbove44 = sr;
  20628. }
  20629. if (lowestAbove44 > 0.0)
  20630. return lowestAbove44;
  20631. return currentAudioDevice->getSampleRate (0);
  20632. }
  20633. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20634. {
  20635. jassert (currentAudioDevice != 0);
  20636. if (bufferSize > 0)
  20637. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20638. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20639. return bufferSize;
  20640. return currentAudioDevice->getDefaultBufferSize();
  20641. }
  20642. void AudioDeviceManager::stopDevice()
  20643. {
  20644. if (currentAudioDevice != 0)
  20645. currentAudioDevice->stop();
  20646. testSound = 0;
  20647. }
  20648. void AudioDeviceManager::closeAudioDevice()
  20649. {
  20650. stopDevice();
  20651. currentAudioDevice = 0;
  20652. }
  20653. void AudioDeviceManager::restartLastAudioDevice()
  20654. {
  20655. if (currentAudioDevice == 0)
  20656. {
  20657. if (currentSetup.inputDeviceName.isEmpty()
  20658. && currentSetup.outputDeviceName.isEmpty())
  20659. {
  20660. // This method will only reload the last device that was running
  20661. // before closeAudioDevice() was called - you need to actually open
  20662. // one first, with setAudioDevice().
  20663. jassertfalse;
  20664. return;
  20665. }
  20666. AudioDeviceSetup s (currentSetup);
  20667. setAudioDeviceSetup (s, false);
  20668. }
  20669. }
  20670. void AudioDeviceManager::updateXml()
  20671. {
  20672. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20673. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20674. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20675. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20676. if (currentAudioDevice != 0)
  20677. {
  20678. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20679. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20680. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20681. if (! currentSetup.useDefaultInputChannels)
  20682. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20683. if (! currentSetup.useDefaultOutputChannels)
  20684. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20685. }
  20686. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20687. {
  20688. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20689. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20690. }
  20691. if (midiInsFromXml.size() > 0)
  20692. {
  20693. // Add any midi devices that have been enabled before, but which aren't currently
  20694. // open because the device has been disconnected.
  20695. const StringArray availableMidiDevices (MidiInput::getDevices());
  20696. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20697. {
  20698. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20699. {
  20700. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20701. m->setAttribute ("name", midiInsFromXml[i]);
  20702. }
  20703. }
  20704. }
  20705. if (defaultMidiOutputName.isNotEmpty())
  20706. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20707. }
  20708. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20709. {
  20710. {
  20711. const ScopedLock sl (audioCallbackLock);
  20712. if (callbacks.contains (newCallback))
  20713. return;
  20714. }
  20715. if (currentAudioDevice != 0 && newCallback != 0)
  20716. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20717. const ScopedLock sl (audioCallbackLock);
  20718. callbacks.add (newCallback);
  20719. }
  20720. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20721. {
  20722. if (callback != 0)
  20723. {
  20724. bool needsDeinitialising = currentAudioDevice != 0;
  20725. {
  20726. const ScopedLock sl (audioCallbackLock);
  20727. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20728. callbacks.removeValue (callback);
  20729. }
  20730. if (needsDeinitialising)
  20731. callback->audioDeviceStopped();
  20732. }
  20733. }
  20734. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20735. int numInputChannels,
  20736. float** outputChannelData,
  20737. int numOutputChannels,
  20738. int numSamples)
  20739. {
  20740. const ScopedLock sl (audioCallbackLock);
  20741. if (inputLevelMeasurementEnabledCount > 0)
  20742. {
  20743. for (int j = 0; j < numSamples; ++j)
  20744. {
  20745. float s = 0;
  20746. for (int i = 0; i < numInputChannels; ++i)
  20747. s += std::abs (inputChannelData[i][j]);
  20748. s /= numInputChannels;
  20749. const double decayFactor = 0.99992;
  20750. if (s > inputLevel)
  20751. inputLevel = s;
  20752. else if (inputLevel > 0.001f)
  20753. inputLevel *= decayFactor;
  20754. else
  20755. inputLevel = 0;
  20756. }
  20757. }
  20758. if (callbacks.size() > 0)
  20759. {
  20760. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20761. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20762. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20763. outputChannelData, numOutputChannels, numSamples);
  20764. float** const tempChans = tempBuffer.getArrayOfChannels();
  20765. for (int i = callbacks.size(); --i > 0;)
  20766. {
  20767. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20768. tempChans, numOutputChannels, numSamples);
  20769. for (int chan = 0; chan < numOutputChannels; ++chan)
  20770. {
  20771. const float* const src = tempChans [chan];
  20772. float* const dst = outputChannelData [chan];
  20773. if (src != 0 && dst != 0)
  20774. for (int j = 0; j < numSamples; ++j)
  20775. dst[j] += src[j];
  20776. }
  20777. }
  20778. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20779. const double filterAmount = 0.2;
  20780. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20781. }
  20782. else
  20783. {
  20784. for (int i = 0; i < numOutputChannels; ++i)
  20785. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20786. }
  20787. if (testSound != 0)
  20788. {
  20789. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20790. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20791. for (int i = 0; i < numOutputChannels; ++i)
  20792. for (int j = 0; j < numSamps; ++j)
  20793. outputChannelData [i][j] += src[j];
  20794. testSoundPosition += numSamps;
  20795. if (testSoundPosition >= testSound->getNumSamples())
  20796. testSound = 0;
  20797. }
  20798. }
  20799. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20800. {
  20801. cpuUsageMs = 0;
  20802. const double sampleRate = device->getCurrentSampleRate();
  20803. const int blockSize = device->getCurrentBufferSizeSamples();
  20804. if (sampleRate > 0.0 && blockSize > 0)
  20805. {
  20806. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20807. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20808. }
  20809. {
  20810. const ScopedLock sl (audioCallbackLock);
  20811. for (int i = callbacks.size(); --i >= 0;)
  20812. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20813. }
  20814. sendChangeMessage();
  20815. }
  20816. void AudioDeviceManager::audioDeviceStoppedInt()
  20817. {
  20818. cpuUsageMs = 0;
  20819. timeToCpuScale = 0;
  20820. sendChangeMessage();
  20821. const ScopedLock sl (audioCallbackLock);
  20822. for (int i = callbacks.size(); --i >= 0;)
  20823. callbacks.getUnchecked(i)->audioDeviceStopped();
  20824. }
  20825. double AudioDeviceManager::getCpuUsage() const
  20826. {
  20827. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20828. }
  20829. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20830. const bool enabled)
  20831. {
  20832. if (enabled != isMidiInputEnabled (name))
  20833. {
  20834. if (enabled)
  20835. {
  20836. const int index = MidiInput::getDevices().indexOf (name);
  20837. if (index >= 0)
  20838. {
  20839. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20840. if (min != 0)
  20841. {
  20842. enabledMidiInputs.add (min);
  20843. min->start();
  20844. }
  20845. }
  20846. }
  20847. else
  20848. {
  20849. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20850. if (enabledMidiInputs[i]->getName() == name)
  20851. enabledMidiInputs.remove (i);
  20852. }
  20853. updateXml();
  20854. sendChangeMessage();
  20855. }
  20856. }
  20857. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20858. {
  20859. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20860. if (enabledMidiInputs[i]->getName() == name)
  20861. return true;
  20862. return false;
  20863. }
  20864. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20865. MidiInputCallback* callback)
  20866. {
  20867. removeMidiInputCallback (name, callback);
  20868. if (name.isEmpty())
  20869. {
  20870. midiCallbacks.add (callback);
  20871. midiCallbackDevices.add (0);
  20872. }
  20873. else
  20874. {
  20875. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20876. {
  20877. if (enabledMidiInputs[i]->getName() == name)
  20878. {
  20879. const ScopedLock sl (midiCallbackLock);
  20880. midiCallbacks.add (callback);
  20881. midiCallbackDevices.add (enabledMidiInputs[i]);
  20882. break;
  20883. }
  20884. }
  20885. }
  20886. }
  20887. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20888. MidiInputCallback* /*callback*/)
  20889. {
  20890. const ScopedLock sl (midiCallbackLock);
  20891. for (int i = midiCallbacks.size(); --i >= 0;)
  20892. {
  20893. String devName;
  20894. if (midiCallbackDevices.getUnchecked(i) != 0)
  20895. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20896. if (devName == name)
  20897. {
  20898. midiCallbacks.remove (i);
  20899. midiCallbackDevices.remove (i);
  20900. }
  20901. }
  20902. }
  20903. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20904. const MidiMessage& message)
  20905. {
  20906. if (! message.isActiveSense())
  20907. {
  20908. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20909. const ScopedLock sl (midiCallbackLock);
  20910. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20911. {
  20912. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20913. if (md == source || (md == 0 && isDefaultSource))
  20914. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20915. }
  20916. }
  20917. }
  20918. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20919. {
  20920. if (defaultMidiOutputName != deviceName)
  20921. {
  20922. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20923. {
  20924. const ScopedLock sl (audioCallbackLock);
  20925. oldCallbacks = callbacks;
  20926. callbacks.clear();
  20927. }
  20928. if (currentAudioDevice != 0)
  20929. for (int i = oldCallbacks.size(); --i >= 0;)
  20930. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20931. defaultMidiOutput = 0;
  20932. defaultMidiOutputName = deviceName;
  20933. if (deviceName.isNotEmpty())
  20934. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20935. if (currentAudioDevice != 0)
  20936. for (int i = oldCallbacks.size(); --i >= 0;)
  20937. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20938. {
  20939. const ScopedLock sl (audioCallbackLock);
  20940. callbacks = oldCallbacks;
  20941. }
  20942. updateXml();
  20943. sendChangeMessage();
  20944. }
  20945. }
  20946. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20947. int numInputChannels,
  20948. float** outputChannelData,
  20949. int numOutputChannels,
  20950. int numSamples)
  20951. {
  20952. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20953. }
  20954. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20955. {
  20956. owner->audioDeviceAboutToStartInt (device);
  20957. }
  20958. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20959. {
  20960. owner->audioDeviceStoppedInt();
  20961. }
  20962. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20963. {
  20964. owner->handleIncomingMidiMessageInt (source, message);
  20965. }
  20966. void AudioDeviceManager::playTestSound()
  20967. {
  20968. { // cunningly nested to swap, unlock and delete in that order.
  20969. ScopedPointer <AudioSampleBuffer> oldSound;
  20970. {
  20971. const ScopedLock sl (audioCallbackLock);
  20972. oldSound = testSound;
  20973. }
  20974. }
  20975. testSoundPosition = 0;
  20976. if (currentAudioDevice != 0)
  20977. {
  20978. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20979. const int soundLength = (int) sampleRate;
  20980. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20981. float* samples = newSound->getSampleData (0);
  20982. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20983. const float amplitude = 0.5f;
  20984. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20985. for (int i = 0; i < soundLength; ++i)
  20986. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20987. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20988. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20989. const ScopedLock sl (audioCallbackLock);
  20990. testSound = newSound;
  20991. }
  20992. }
  20993. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20994. {
  20995. const ScopedLock sl (audioCallbackLock);
  20996. if (enableMeasurement)
  20997. ++inputLevelMeasurementEnabledCount;
  20998. else
  20999. --inputLevelMeasurementEnabledCount;
  21000. inputLevel = 0;
  21001. }
  21002. double AudioDeviceManager::getCurrentInputLevel() const
  21003. {
  21004. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  21005. return inputLevel;
  21006. }
  21007. END_JUCE_NAMESPACE
  21008. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  21009. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  21010. BEGIN_JUCE_NAMESPACE
  21011. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  21012. : name (deviceName),
  21013. typeName (typeName_)
  21014. {
  21015. }
  21016. AudioIODevice::~AudioIODevice()
  21017. {
  21018. }
  21019. bool AudioIODevice::hasControlPanel() const
  21020. {
  21021. return false;
  21022. }
  21023. bool AudioIODevice::showControlPanel()
  21024. {
  21025. jassertfalse; // this should only be called for devices which return true from
  21026. // their hasControlPanel() method.
  21027. return false;
  21028. }
  21029. END_JUCE_NAMESPACE
  21030. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  21031. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  21032. BEGIN_JUCE_NAMESPACE
  21033. AudioIODeviceType::AudioIODeviceType (const String& name)
  21034. : typeName (name)
  21035. {
  21036. }
  21037. AudioIODeviceType::~AudioIODeviceType()
  21038. {
  21039. }
  21040. END_JUCE_NAMESPACE
  21041. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  21042. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  21043. BEGIN_JUCE_NAMESPACE
  21044. MidiOutput::MidiOutput()
  21045. : Thread ("midi out"),
  21046. internal (0),
  21047. firstMessage (0)
  21048. {
  21049. }
  21050. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  21051. const double sampleNumber)
  21052. : message (data, len, sampleNumber)
  21053. {
  21054. }
  21055. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  21056. const double millisecondCounterToStartAt,
  21057. double samplesPerSecondForBuffer)
  21058. {
  21059. // You've got to call startBackgroundThread() for this to actually work..
  21060. jassert (isThreadRunning());
  21061. // this needs to be a value in the future - RTFM for this method!
  21062. jassert (millisecondCounterToStartAt > 0);
  21063. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  21064. MidiBuffer::Iterator i (buffer);
  21065. const uint8* data;
  21066. int len, time;
  21067. while (i.getNextEvent (data, len, time))
  21068. {
  21069. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  21070. PendingMessage* const m
  21071. = new PendingMessage (data, len, eventTime);
  21072. const ScopedLock sl (lock);
  21073. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  21074. {
  21075. m->next = firstMessage;
  21076. firstMessage = m;
  21077. }
  21078. else
  21079. {
  21080. PendingMessage* mm = firstMessage;
  21081. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  21082. mm = mm->next;
  21083. m->next = mm->next;
  21084. mm->next = m;
  21085. }
  21086. }
  21087. notify();
  21088. }
  21089. void MidiOutput::clearAllPendingMessages()
  21090. {
  21091. const ScopedLock sl (lock);
  21092. while (firstMessage != 0)
  21093. {
  21094. PendingMessage* const m = firstMessage;
  21095. firstMessage = firstMessage->next;
  21096. delete m;
  21097. }
  21098. }
  21099. void MidiOutput::startBackgroundThread()
  21100. {
  21101. startThread (9);
  21102. }
  21103. void MidiOutput::stopBackgroundThread()
  21104. {
  21105. stopThread (5000);
  21106. }
  21107. void MidiOutput::run()
  21108. {
  21109. while (! threadShouldExit())
  21110. {
  21111. uint32 now = Time::getMillisecondCounter();
  21112. uint32 eventTime = 0;
  21113. uint32 timeToWait = 500;
  21114. PendingMessage* message;
  21115. {
  21116. const ScopedLock sl (lock);
  21117. message = firstMessage;
  21118. if (message != 0)
  21119. {
  21120. eventTime = roundToInt (message->message.getTimeStamp());
  21121. if (eventTime > now + 20)
  21122. {
  21123. timeToWait = eventTime - (now + 20);
  21124. message = 0;
  21125. }
  21126. else
  21127. {
  21128. firstMessage = message->next;
  21129. }
  21130. }
  21131. }
  21132. if (message != 0)
  21133. {
  21134. if (eventTime > now)
  21135. {
  21136. Time::waitForMillisecondCounter (eventTime);
  21137. if (threadShouldExit())
  21138. break;
  21139. }
  21140. if (eventTime > now - 200)
  21141. sendMessageNow (message->message);
  21142. delete message;
  21143. }
  21144. else
  21145. {
  21146. jassert (timeToWait < 1000 * 30);
  21147. wait (timeToWait);
  21148. }
  21149. }
  21150. clearAllPendingMessages();
  21151. }
  21152. END_JUCE_NAMESPACE
  21153. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21154. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21155. BEGIN_JUCE_NAMESPACE
  21156. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21157. {
  21158. const double maxVal = (double) 0x7fff;
  21159. char* intData = static_cast <char*> (dest);
  21160. if (dest != (void*) source || destBytesPerSample <= 4)
  21161. {
  21162. for (int i = 0; i < numSamples; ++i)
  21163. {
  21164. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21165. intData += destBytesPerSample;
  21166. }
  21167. }
  21168. else
  21169. {
  21170. intData += destBytesPerSample * numSamples;
  21171. for (int i = numSamples; --i >= 0;)
  21172. {
  21173. intData -= destBytesPerSample;
  21174. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21175. }
  21176. }
  21177. }
  21178. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21179. {
  21180. const double maxVal = (double) 0x7fff;
  21181. char* intData = static_cast <char*> (dest);
  21182. if (dest != (void*) source || destBytesPerSample <= 4)
  21183. {
  21184. for (int i = 0; i < numSamples; ++i)
  21185. {
  21186. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21187. intData += destBytesPerSample;
  21188. }
  21189. }
  21190. else
  21191. {
  21192. intData += destBytesPerSample * numSamples;
  21193. for (int i = numSamples; --i >= 0;)
  21194. {
  21195. intData -= destBytesPerSample;
  21196. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21197. }
  21198. }
  21199. }
  21200. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21201. {
  21202. const double maxVal = (double) 0x7fffff;
  21203. char* intData = static_cast <char*> (dest);
  21204. if (dest != (void*) source || destBytesPerSample <= 4)
  21205. {
  21206. for (int i = 0; i < numSamples; ++i)
  21207. {
  21208. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21209. intData += destBytesPerSample;
  21210. }
  21211. }
  21212. else
  21213. {
  21214. intData += destBytesPerSample * numSamples;
  21215. for (int i = numSamples; --i >= 0;)
  21216. {
  21217. intData -= destBytesPerSample;
  21218. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21219. }
  21220. }
  21221. }
  21222. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21223. {
  21224. const double maxVal = (double) 0x7fffff;
  21225. char* intData = static_cast <char*> (dest);
  21226. if (dest != (void*) source || destBytesPerSample <= 4)
  21227. {
  21228. for (int i = 0; i < numSamples; ++i)
  21229. {
  21230. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21231. intData += destBytesPerSample;
  21232. }
  21233. }
  21234. else
  21235. {
  21236. intData += destBytesPerSample * numSamples;
  21237. for (int i = numSamples; --i >= 0;)
  21238. {
  21239. intData -= destBytesPerSample;
  21240. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21241. }
  21242. }
  21243. }
  21244. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21245. {
  21246. const double maxVal = (double) 0x7fffffff;
  21247. char* intData = static_cast <char*> (dest);
  21248. if (dest != (void*) source || destBytesPerSample <= 4)
  21249. {
  21250. for (int i = 0; i < numSamples; ++i)
  21251. {
  21252. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21253. intData += destBytesPerSample;
  21254. }
  21255. }
  21256. else
  21257. {
  21258. intData += destBytesPerSample * numSamples;
  21259. for (int i = numSamples; --i >= 0;)
  21260. {
  21261. intData -= destBytesPerSample;
  21262. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21263. }
  21264. }
  21265. }
  21266. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21267. {
  21268. const double maxVal = (double) 0x7fffffff;
  21269. char* intData = static_cast <char*> (dest);
  21270. if (dest != (void*) source || destBytesPerSample <= 4)
  21271. {
  21272. for (int i = 0; i < numSamples; ++i)
  21273. {
  21274. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21275. intData += destBytesPerSample;
  21276. }
  21277. }
  21278. else
  21279. {
  21280. intData += destBytesPerSample * numSamples;
  21281. for (int i = numSamples; --i >= 0;)
  21282. {
  21283. intData -= destBytesPerSample;
  21284. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21285. }
  21286. }
  21287. }
  21288. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21289. {
  21290. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21291. char* d = static_cast <char*> (dest);
  21292. for (int i = 0; i < numSamples; ++i)
  21293. {
  21294. *(float*) d = source[i];
  21295. #if JUCE_BIG_ENDIAN
  21296. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21297. #endif
  21298. d += destBytesPerSample;
  21299. }
  21300. }
  21301. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21302. {
  21303. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21304. char* d = static_cast <char*> (dest);
  21305. for (int i = 0; i < numSamples; ++i)
  21306. {
  21307. *(float*) d = source[i];
  21308. #if JUCE_LITTLE_ENDIAN
  21309. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21310. #endif
  21311. d += destBytesPerSample;
  21312. }
  21313. }
  21314. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21315. {
  21316. const float scale = 1.0f / 0x7fff;
  21317. const char* intData = static_cast <const char*> (source);
  21318. if (source != (void*) dest || srcBytesPerSample >= 4)
  21319. {
  21320. for (int i = 0; i < numSamples; ++i)
  21321. {
  21322. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21323. intData += srcBytesPerSample;
  21324. }
  21325. }
  21326. else
  21327. {
  21328. intData += srcBytesPerSample * numSamples;
  21329. for (int i = numSamples; --i >= 0;)
  21330. {
  21331. intData -= srcBytesPerSample;
  21332. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21333. }
  21334. }
  21335. }
  21336. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21337. {
  21338. const float scale = 1.0f / 0x7fff;
  21339. const char* intData = static_cast <const char*> (source);
  21340. if (source != (void*) dest || srcBytesPerSample >= 4)
  21341. {
  21342. for (int i = 0; i < numSamples; ++i)
  21343. {
  21344. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21345. intData += srcBytesPerSample;
  21346. }
  21347. }
  21348. else
  21349. {
  21350. intData += srcBytesPerSample * numSamples;
  21351. for (int i = numSamples; --i >= 0;)
  21352. {
  21353. intData -= srcBytesPerSample;
  21354. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21355. }
  21356. }
  21357. }
  21358. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21359. {
  21360. const float scale = 1.0f / 0x7fffff;
  21361. const char* intData = static_cast <const char*> (source);
  21362. if (source != (void*) dest || srcBytesPerSample >= 4)
  21363. {
  21364. for (int i = 0; i < numSamples; ++i)
  21365. {
  21366. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21367. intData += srcBytesPerSample;
  21368. }
  21369. }
  21370. else
  21371. {
  21372. intData += srcBytesPerSample * numSamples;
  21373. for (int i = numSamples; --i >= 0;)
  21374. {
  21375. intData -= srcBytesPerSample;
  21376. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21377. }
  21378. }
  21379. }
  21380. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21381. {
  21382. const float scale = 1.0f / 0x7fffff;
  21383. const char* intData = static_cast <const char*> (source);
  21384. if (source != (void*) dest || srcBytesPerSample >= 4)
  21385. {
  21386. for (int i = 0; i < numSamples; ++i)
  21387. {
  21388. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21389. intData += srcBytesPerSample;
  21390. }
  21391. }
  21392. else
  21393. {
  21394. intData += srcBytesPerSample * numSamples;
  21395. for (int i = numSamples; --i >= 0;)
  21396. {
  21397. intData -= srcBytesPerSample;
  21398. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21399. }
  21400. }
  21401. }
  21402. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21403. {
  21404. const float scale = 1.0f / 0x7fffffff;
  21405. const char* intData = static_cast <const char*> (source);
  21406. if (source != (void*) dest || srcBytesPerSample >= 4)
  21407. {
  21408. for (int i = 0; i < numSamples; ++i)
  21409. {
  21410. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21411. intData += srcBytesPerSample;
  21412. }
  21413. }
  21414. else
  21415. {
  21416. intData += srcBytesPerSample * numSamples;
  21417. for (int i = numSamples; --i >= 0;)
  21418. {
  21419. intData -= srcBytesPerSample;
  21420. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21421. }
  21422. }
  21423. }
  21424. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21425. {
  21426. const float scale = 1.0f / 0x7fffffff;
  21427. const char* intData = static_cast <const char*> (source);
  21428. if (source != (void*) dest || srcBytesPerSample >= 4)
  21429. {
  21430. for (int i = 0; i < numSamples; ++i)
  21431. {
  21432. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21433. intData += srcBytesPerSample;
  21434. }
  21435. }
  21436. else
  21437. {
  21438. intData += srcBytesPerSample * numSamples;
  21439. for (int i = numSamples; --i >= 0;)
  21440. {
  21441. intData -= srcBytesPerSample;
  21442. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21443. }
  21444. }
  21445. }
  21446. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21447. {
  21448. const char* s = static_cast <const char*> (source);
  21449. for (int i = 0; i < numSamples; ++i)
  21450. {
  21451. dest[i] = *(float*)s;
  21452. #if JUCE_BIG_ENDIAN
  21453. uint32* const d = (uint32*) (dest + i);
  21454. *d = ByteOrder::swap (*d);
  21455. #endif
  21456. s += srcBytesPerSample;
  21457. }
  21458. }
  21459. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21460. {
  21461. const char* s = static_cast <const char*> (source);
  21462. for (int i = 0; i < numSamples; ++i)
  21463. {
  21464. dest[i] = *(float*)s;
  21465. #if JUCE_LITTLE_ENDIAN
  21466. uint32* const d = (uint32*) (dest + i);
  21467. *d = ByteOrder::swap (*d);
  21468. #endif
  21469. s += srcBytesPerSample;
  21470. }
  21471. }
  21472. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21473. const float* const source,
  21474. void* const dest,
  21475. const int numSamples)
  21476. {
  21477. switch (destFormat)
  21478. {
  21479. case int16LE:
  21480. convertFloatToInt16LE (source, dest, numSamples);
  21481. break;
  21482. case int16BE:
  21483. convertFloatToInt16BE (source, dest, numSamples);
  21484. break;
  21485. case int24LE:
  21486. convertFloatToInt24LE (source, dest, numSamples);
  21487. break;
  21488. case int24BE:
  21489. convertFloatToInt24BE (source, dest, numSamples);
  21490. break;
  21491. case int32LE:
  21492. convertFloatToInt32LE (source, dest, numSamples);
  21493. break;
  21494. case int32BE:
  21495. convertFloatToInt32BE (source, dest, numSamples);
  21496. break;
  21497. case float32LE:
  21498. convertFloatToFloat32LE (source, dest, numSamples);
  21499. break;
  21500. case float32BE:
  21501. convertFloatToFloat32BE (source, dest, numSamples);
  21502. break;
  21503. default:
  21504. jassertfalse;
  21505. break;
  21506. }
  21507. }
  21508. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21509. const void* const source,
  21510. float* const dest,
  21511. const int numSamples)
  21512. {
  21513. switch (sourceFormat)
  21514. {
  21515. case int16LE:
  21516. convertInt16LEToFloat (source, dest, numSamples);
  21517. break;
  21518. case int16BE:
  21519. convertInt16BEToFloat (source, dest, numSamples);
  21520. break;
  21521. case int24LE:
  21522. convertInt24LEToFloat (source, dest, numSamples);
  21523. break;
  21524. case int24BE:
  21525. convertInt24BEToFloat (source, dest, numSamples);
  21526. break;
  21527. case int32LE:
  21528. convertInt32LEToFloat (source, dest, numSamples);
  21529. break;
  21530. case int32BE:
  21531. convertInt32BEToFloat (source, dest, numSamples);
  21532. break;
  21533. case float32LE:
  21534. convertFloat32LEToFloat (source, dest, numSamples);
  21535. break;
  21536. case float32BE:
  21537. convertFloat32BEToFloat (source, dest, numSamples);
  21538. break;
  21539. default:
  21540. jassertfalse;
  21541. break;
  21542. }
  21543. }
  21544. void AudioDataConverters::interleaveSamples (const float** const source,
  21545. float* const dest,
  21546. const int numSamples,
  21547. const int numChannels)
  21548. {
  21549. for (int chan = 0; chan < numChannels; ++chan)
  21550. {
  21551. int i = chan;
  21552. const float* src = source [chan];
  21553. for (int j = 0; j < numSamples; ++j)
  21554. {
  21555. dest [i] = src [j];
  21556. i += numChannels;
  21557. }
  21558. }
  21559. }
  21560. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21561. float** const dest,
  21562. const int numSamples,
  21563. const int numChannels)
  21564. {
  21565. for (int chan = 0; chan < numChannels; ++chan)
  21566. {
  21567. int i = chan;
  21568. float* dst = dest [chan];
  21569. for (int j = 0; j < numSamples; ++j)
  21570. {
  21571. dst [j] = source [i];
  21572. i += numChannels;
  21573. }
  21574. }
  21575. }
  21576. #if JUCE_UNIT_TESTS
  21577. class AudioConversionTests : public UnitTest
  21578. {
  21579. public:
  21580. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21581. template <class F1, class E1, class F2, class E2>
  21582. struct Test5
  21583. {
  21584. static void test (UnitTest& unitTest)
  21585. {
  21586. test (unitTest, false);
  21587. test (unitTest, true);
  21588. }
  21589. static void test (UnitTest& unitTest, bool inPlace)
  21590. {
  21591. const int numSamples = 2048;
  21592. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21593. {
  21594. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21595. bool clippingFailed = false;
  21596. for (int i = 0; i < numSamples / 2; ++i)
  21597. {
  21598. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21599. if (! d.isFloatingPoint())
  21600. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21601. ++d;
  21602. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21603. ++d;
  21604. }
  21605. unitTest.expect (! clippingFailed);
  21606. }
  21607. // convert data from the source to dest format..
  21608. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21609. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21610. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21611. // ..and back again..
  21612. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21613. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21614. if (! inPlace)
  21615. zerostruct (reversed);
  21616. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21617. {
  21618. int biggestDiff = 0;
  21619. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21620. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21621. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21622. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21623. for (int i = 0; i < numSamples; ++i)
  21624. {
  21625. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21626. ++d1;
  21627. ++d2;
  21628. }
  21629. unitTest.expect (biggestDiff <= errorMargin);
  21630. }
  21631. }
  21632. };
  21633. template <class F1, class E1, class FormatType>
  21634. struct Test3
  21635. {
  21636. static void test (UnitTest& unitTest)
  21637. {
  21638. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21639. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21640. }
  21641. };
  21642. template <class FormatType, class Endianness>
  21643. struct Test2
  21644. {
  21645. static void test (UnitTest& unitTest)
  21646. {
  21647. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21648. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21649. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21650. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21651. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21652. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21653. }
  21654. };
  21655. template <class FormatType>
  21656. struct Test1
  21657. {
  21658. static void test (UnitTest& unitTest)
  21659. {
  21660. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21661. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21662. }
  21663. };
  21664. void runTest()
  21665. {
  21666. beginTest ("Round-trip conversion");
  21667. Test1 <AudioData::Int8>::test (*this);
  21668. Test1 <AudioData::Int16>::test (*this);
  21669. Test1 <AudioData::Int24>::test (*this);
  21670. Test1 <AudioData::Int32>::test (*this);
  21671. Test1 <AudioData::Float32>::test (*this);
  21672. }
  21673. };
  21674. static AudioConversionTests audioConversionUnitTests;
  21675. #endif
  21676. END_JUCE_NAMESPACE
  21677. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21678. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21679. BEGIN_JUCE_NAMESPACE
  21680. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21681. const int numSamples) throw()
  21682. : numChannels (numChannels_),
  21683. size (numSamples)
  21684. {
  21685. jassert (numSamples >= 0);
  21686. jassert (numChannels_ > 0);
  21687. allocateData();
  21688. }
  21689. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21690. : numChannels (other.numChannels),
  21691. size (other.size)
  21692. {
  21693. allocateData();
  21694. const size_t numBytes = size * sizeof (float);
  21695. for (int i = 0; i < numChannels; ++i)
  21696. memcpy (channels[i], other.channels[i], numBytes);
  21697. }
  21698. void AudioSampleBuffer::allocateData()
  21699. {
  21700. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21701. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21702. allocatedData.malloc (allocatedBytes);
  21703. channels = reinterpret_cast <float**> (allocatedData.getData());
  21704. float* chan = (float*) (allocatedData + channelListSize);
  21705. for (int i = 0; i < numChannels; ++i)
  21706. {
  21707. channels[i] = chan;
  21708. chan += size;
  21709. }
  21710. channels [numChannels] = 0;
  21711. }
  21712. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21713. const int numChannels_,
  21714. const int numSamples) throw()
  21715. : numChannels (numChannels_),
  21716. size (numSamples),
  21717. allocatedBytes (0)
  21718. {
  21719. jassert (numChannels_ > 0);
  21720. allocateChannels (dataToReferTo);
  21721. }
  21722. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21723. const int newNumChannels,
  21724. const int newNumSamples) throw()
  21725. {
  21726. jassert (newNumChannels > 0);
  21727. allocatedBytes = 0;
  21728. allocatedData.free();
  21729. numChannels = newNumChannels;
  21730. size = newNumSamples;
  21731. allocateChannels (dataToReferTo);
  21732. }
  21733. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21734. {
  21735. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21736. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21737. {
  21738. channels = static_cast <float**> (preallocatedChannelSpace);
  21739. }
  21740. else
  21741. {
  21742. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21743. channels = reinterpret_cast <float**> (allocatedData.getData());
  21744. }
  21745. for (int i = 0; i < numChannels; ++i)
  21746. {
  21747. // you have to pass in the same number of valid pointers as numChannels
  21748. jassert (dataToReferTo[i] != 0);
  21749. channels[i] = dataToReferTo[i];
  21750. }
  21751. channels [numChannels] = 0;
  21752. }
  21753. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21754. {
  21755. if (this != &other)
  21756. {
  21757. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21758. const size_t numBytes = size * sizeof (float);
  21759. for (int i = 0; i < numChannels; ++i)
  21760. memcpy (channels[i], other.channels[i], numBytes);
  21761. }
  21762. return *this;
  21763. }
  21764. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21765. {
  21766. }
  21767. void AudioSampleBuffer::setSize (const int newNumChannels,
  21768. const int newNumSamples,
  21769. const bool keepExistingContent,
  21770. const bool clearExtraSpace,
  21771. const bool avoidReallocating) throw()
  21772. {
  21773. jassert (newNumChannels > 0);
  21774. if (newNumSamples != size || newNumChannels != numChannels)
  21775. {
  21776. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21777. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21778. if (keepExistingContent)
  21779. {
  21780. HeapBlock <char> newData;
  21781. newData.allocate (newTotalBytes, clearExtraSpace);
  21782. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21783. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21784. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21785. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21786. for (int i = 0; i < numChansToCopy; ++i)
  21787. {
  21788. memcpy (newChan, channels[i], numBytesToCopy);
  21789. newChannels[i] = newChan;
  21790. newChan += newNumSamples;
  21791. }
  21792. allocatedData.swapWith (newData);
  21793. allocatedBytes = (int) newTotalBytes;
  21794. channels = newChannels;
  21795. }
  21796. else
  21797. {
  21798. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21799. {
  21800. if (clearExtraSpace)
  21801. zeromem (allocatedData, newTotalBytes);
  21802. }
  21803. else
  21804. {
  21805. allocatedBytes = newTotalBytes;
  21806. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21807. channels = reinterpret_cast <float**> (allocatedData.getData());
  21808. }
  21809. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21810. for (int i = 0; i < newNumChannels; ++i)
  21811. {
  21812. channels[i] = chan;
  21813. chan += newNumSamples;
  21814. }
  21815. }
  21816. channels [newNumChannels] = 0;
  21817. size = newNumSamples;
  21818. numChannels = newNumChannels;
  21819. }
  21820. }
  21821. void AudioSampleBuffer::clear() throw()
  21822. {
  21823. for (int i = 0; i < numChannels; ++i)
  21824. zeromem (channels[i], size * sizeof (float));
  21825. }
  21826. void AudioSampleBuffer::clear (const int startSample,
  21827. const int numSamples) throw()
  21828. {
  21829. jassert (startSample >= 0 && startSample + numSamples <= size);
  21830. for (int i = 0; i < numChannels; ++i)
  21831. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21832. }
  21833. void AudioSampleBuffer::clear (const int channel,
  21834. const int startSample,
  21835. const int numSamples) throw()
  21836. {
  21837. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21838. jassert (startSample >= 0 && startSample + numSamples <= size);
  21839. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21840. }
  21841. void AudioSampleBuffer::applyGain (const int channel,
  21842. const int startSample,
  21843. int numSamples,
  21844. const float gain) throw()
  21845. {
  21846. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21847. jassert (startSample >= 0 && startSample + numSamples <= size);
  21848. if (gain != 1.0f)
  21849. {
  21850. float* d = channels [channel] + startSample;
  21851. if (gain == 0.0f)
  21852. {
  21853. zeromem (d, sizeof (float) * numSamples);
  21854. }
  21855. else
  21856. {
  21857. while (--numSamples >= 0)
  21858. *d++ *= gain;
  21859. }
  21860. }
  21861. }
  21862. void AudioSampleBuffer::applyGainRamp (const int channel,
  21863. const int startSample,
  21864. int numSamples,
  21865. float startGain,
  21866. float endGain) throw()
  21867. {
  21868. if (startGain == endGain)
  21869. {
  21870. applyGain (channel, startSample, numSamples, startGain);
  21871. }
  21872. else
  21873. {
  21874. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21875. jassert (startSample >= 0 && startSample + numSamples <= size);
  21876. const float increment = (endGain - startGain) / numSamples;
  21877. float* d = channels [channel] + startSample;
  21878. while (--numSamples >= 0)
  21879. {
  21880. *d++ *= startGain;
  21881. startGain += increment;
  21882. }
  21883. }
  21884. }
  21885. void AudioSampleBuffer::applyGain (const int startSample,
  21886. const int numSamples,
  21887. const float gain) throw()
  21888. {
  21889. for (int i = 0; i < numChannels; ++i)
  21890. applyGain (i, startSample, numSamples, gain);
  21891. }
  21892. void AudioSampleBuffer::addFrom (const int destChannel,
  21893. const int destStartSample,
  21894. const AudioSampleBuffer& source,
  21895. const int sourceChannel,
  21896. const int sourceStartSample,
  21897. int numSamples,
  21898. const float gain) throw()
  21899. {
  21900. jassert (&source != this || sourceChannel != destChannel);
  21901. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21902. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21903. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21904. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21905. if (gain != 0.0f && numSamples > 0)
  21906. {
  21907. float* d = channels [destChannel] + destStartSample;
  21908. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21909. if (gain != 1.0f)
  21910. {
  21911. while (--numSamples >= 0)
  21912. *d++ += gain * *s++;
  21913. }
  21914. else
  21915. {
  21916. while (--numSamples >= 0)
  21917. *d++ += *s++;
  21918. }
  21919. }
  21920. }
  21921. void AudioSampleBuffer::addFrom (const int destChannel,
  21922. const int destStartSample,
  21923. const float* source,
  21924. int numSamples,
  21925. const float gain) throw()
  21926. {
  21927. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21928. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21929. jassert (source != 0);
  21930. if (gain != 0.0f && numSamples > 0)
  21931. {
  21932. float* d = channels [destChannel] + destStartSample;
  21933. if (gain != 1.0f)
  21934. {
  21935. while (--numSamples >= 0)
  21936. *d++ += gain * *source++;
  21937. }
  21938. else
  21939. {
  21940. while (--numSamples >= 0)
  21941. *d++ += *source++;
  21942. }
  21943. }
  21944. }
  21945. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21946. const int destStartSample,
  21947. const float* source,
  21948. int numSamples,
  21949. float startGain,
  21950. const float endGain) throw()
  21951. {
  21952. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21953. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21954. jassert (source != 0);
  21955. if (startGain == endGain)
  21956. {
  21957. addFrom (destChannel,
  21958. destStartSample,
  21959. source,
  21960. numSamples,
  21961. startGain);
  21962. }
  21963. else
  21964. {
  21965. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21966. {
  21967. const float increment = (endGain - startGain) / numSamples;
  21968. float* d = channels [destChannel] + destStartSample;
  21969. while (--numSamples >= 0)
  21970. {
  21971. *d++ += startGain * *source++;
  21972. startGain += increment;
  21973. }
  21974. }
  21975. }
  21976. }
  21977. void AudioSampleBuffer::copyFrom (const int destChannel,
  21978. const int destStartSample,
  21979. const AudioSampleBuffer& source,
  21980. const int sourceChannel,
  21981. const int sourceStartSample,
  21982. int numSamples) throw()
  21983. {
  21984. jassert (&source != this || sourceChannel != destChannel);
  21985. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21986. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21987. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21988. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21989. if (numSamples > 0)
  21990. {
  21991. memcpy (channels [destChannel] + destStartSample,
  21992. source.channels [sourceChannel] + sourceStartSample,
  21993. sizeof (float) * numSamples);
  21994. }
  21995. }
  21996. void AudioSampleBuffer::copyFrom (const int destChannel,
  21997. const int destStartSample,
  21998. const float* source,
  21999. int numSamples) throw()
  22000. {
  22001. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22002. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22003. jassert (source != 0);
  22004. if (numSamples > 0)
  22005. {
  22006. memcpy (channels [destChannel] + destStartSample,
  22007. source,
  22008. sizeof (float) * numSamples);
  22009. }
  22010. }
  22011. void AudioSampleBuffer::copyFrom (const int destChannel,
  22012. const int destStartSample,
  22013. const float* source,
  22014. int numSamples,
  22015. const float gain) throw()
  22016. {
  22017. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22018. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22019. jassert (source != 0);
  22020. if (numSamples > 0)
  22021. {
  22022. float* d = channels [destChannel] + destStartSample;
  22023. if (gain != 1.0f)
  22024. {
  22025. if (gain == 0)
  22026. {
  22027. zeromem (d, sizeof (float) * numSamples);
  22028. }
  22029. else
  22030. {
  22031. while (--numSamples >= 0)
  22032. *d++ = gain * *source++;
  22033. }
  22034. }
  22035. else
  22036. {
  22037. memcpy (d, source, sizeof (float) * numSamples);
  22038. }
  22039. }
  22040. }
  22041. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  22042. const int destStartSample,
  22043. const float* source,
  22044. int numSamples,
  22045. float startGain,
  22046. float endGain) throw()
  22047. {
  22048. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22049. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22050. jassert (source != 0);
  22051. if (startGain == endGain)
  22052. {
  22053. copyFrom (destChannel,
  22054. destStartSample,
  22055. source,
  22056. numSamples,
  22057. startGain);
  22058. }
  22059. else
  22060. {
  22061. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22062. {
  22063. const float increment = (endGain - startGain) / numSamples;
  22064. float* d = channels [destChannel] + destStartSample;
  22065. while (--numSamples >= 0)
  22066. {
  22067. *d++ = startGain * *source++;
  22068. startGain += increment;
  22069. }
  22070. }
  22071. }
  22072. }
  22073. void AudioSampleBuffer::findMinMax (const int channel,
  22074. const int startSample,
  22075. int numSamples,
  22076. float& minVal,
  22077. float& maxVal) const throw()
  22078. {
  22079. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22080. jassert (startSample >= 0 && startSample + numSamples <= size);
  22081. if (numSamples <= 0)
  22082. {
  22083. minVal = 0.0f;
  22084. maxVal = 0.0f;
  22085. }
  22086. else
  22087. {
  22088. const float* d = channels [channel] + startSample;
  22089. float mn = *d++;
  22090. float mx = mn;
  22091. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  22092. {
  22093. const float samp = *d++;
  22094. if (samp > mx)
  22095. mx = samp;
  22096. if (samp < mn)
  22097. mn = samp;
  22098. }
  22099. maxVal = mx;
  22100. minVal = mn;
  22101. }
  22102. }
  22103. float AudioSampleBuffer::getMagnitude (const int channel,
  22104. const int startSample,
  22105. const int numSamples) const throw()
  22106. {
  22107. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22108. jassert (startSample >= 0 && startSample + numSamples <= size);
  22109. float mn, mx;
  22110. findMinMax (channel, startSample, numSamples, mn, mx);
  22111. return jmax (mn, -mn, mx, -mx);
  22112. }
  22113. float AudioSampleBuffer::getMagnitude (const int startSample,
  22114. const int numSamples) const throw()
  22115. {
  22116. float mag = 0.0f;
  22117. for (int i = 0; i < numChannels; ++i)
  22118. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22119. return mag;
  22120. }
  22121. float AudioSampleBuffer::getRMSLevel (const int channel,
  22122. const int startSample,
  22123. const int numSamples) const throw()
  22124. {
  22125. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22126. jassert (startSample >= 0 && startSample + numSamples <= size);
  22127. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22128. return 0.0f;
  22129. const float* const data = channels [channel] + startSample;
  22130. double sum = 0.0;
  22131. for (int i = 0; i < numSamples; ++i)
  22132. {
  22133. const float sample = data [i];
  22134. sum += sample * sample;
  22135. }
  22136. return (float) std::sqrt (sum / numSamples);
  22137. }
  22138. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22139. const int startSample,
  22140. const int numSamples,
  22141. const int readerStartSample,
  22142. const bool useLeftChan,
  22143. const bool useRightChan)
  22144. {
  22145. jassert (reader != 0);
  22146. jassert (startSample >= 0 && startSample + numSamples <= size);
  22147. if (numSamples > 0)
  22148. {
  22149. int* chans[3];
  22150. if (useLeftChan == useRightChan)
  22151. {
  22152. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22153. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22154. }
  22155. else if (useLeftChan || (reader->numChannels == 1))
  22156. {
  22157. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22158. chans[1] = 0;
  22159. }
  22160. else if (useRightChan)
  22161. {
  22162. chans[0] = 0;
  22163. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22164. }
  22165. chans[2] = 0;
  22166. reader->read (chans, 2, readerStartSample, numSamples, true);
  22167. if (! reader->usesFloatingPointData)
  22168. {
  22169. for (int j = 0; j < 2; ++j)
  22170. {
  22171. float* const d = reinterpret_cast <float*> (chans[j]);
  22172. if (d != 0)
  22173. {
  22174. const float multiplier = 1.0f / 0x7fffffff;
  22175. for (int i = 0; i < numSamples; ++i)
  22176. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22177. }
  22178. }
  22179. }
  22180. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22181. {
  22182. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22183. memcpy (getSampleData (1, startSample),
  22184. getSampleData (0, startSample),
  22185. sizeof (float) * numSamples);
  22186. }
  22187. }
  22188. }
  22189. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22190. const int startSample,
  22191. const int numSamples) const
  22192. {
  22193. jassert (writer != 0);
  22194. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22195. }
  22196. END_JUCE_NAMESPACE
  22197. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22198. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22199. BEGIN_JUCE_NAMESPACE
  22200. IIRFilter::IIRFilter()
  22201. : active (false)
  22202. {
  22203. reset();
  22204. }
  22205. IIRFilter::IIRFilter (const IIRFilter& other)
  22206. : active (other.active)
  22207. {
  22208. const ScopedLock sl (other.processLock);
  22209. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22210. reset();
  22211. }
  22212. IIRFilter::~IIRFilter()
  22213. {
  22214. }
  22215. void IIRFilter::reset() throw()
  22216. {
  22217. const ScopedLock sl (processLock);
  22218. x1 = 0;
  22219. x2 = 0;
  22220. y1 = 0;
  22221. y2 = 0;
  22222. }
  22223. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22224. {
  22225. float out = coefficients[0] * in
  22226. + coefficients[1] * x1
  22227. + coefficients[2] * x2
  22228. - coefficients[4] * y1
  22229. - coefficients[5] * y2;
  22230. #if JUCE_INTEL
  22231. if (! (out < -1.0e-8 || out > 1.0e-8))
  22232. out = 0;
  22233. #endif
  22234. x2 = x1;
  22235. x1 = in;
  22236. y2 = y1;
  22237. y1 = out;
  22238. return out;
  22239. }
  22240. void IIRFilter::processSamples (float* const samples,
  22241. const int numSamples) throw()
  22242. {
  22243. const ScopedLock sl (processLock);
  22244. if (active)
  22245. {
  22246. for (int i = 0; i < numSamples; ++i)
  22247. {
  22248. const float in = samples[i];
  22249. float out = coefficients[0] * in
  22250. + coefficients[1] * x1
  22251. + coefficients[2] * x2
  22252. - coefficients[4] * y1
  22253. - coefficients[5] * y2;
  22254. #if JUCE_INTEL
  22255. if (! (out < -1.0e-8 || out > 1.0e-8))
  22256. out = 0;
  22257. #endif
  22258. x2 = x1;
  22259. x1 = in;
  22260. y2 = y1;
  22261. y1 = out;
  22262. samples[i] = out;
  22263. }
  22264. }
  22265. }
  22266. void IIRFilter::makeLowPass (const double sampleRate,
  22267. const double frequency) throw()
  22268. {
  22269. jassert (sampleRate > 0);
  22270. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22271. const double nSquared = n * n;
  22272. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22273. setCoefficients (c1,
  22274. c1 * 2.0f,
  22275. c1,
  22276. 1.0,
  22277. c1 * 2.0 * (1.0 - nSquared),
  22278. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22279. }
  22280. void IIRFilter::makeHighPass (const double sampleRate,
  22281. const double frequency) throw()
  22282. {
  22283. const double n = tan (double_Pi * frequency / sampleRate);
  22284. const double nSquared = n * n;
  22285. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22286. setCoefficients (c1,
  22287. c1 * -2.0f,
  22288. c1,
  22289. 1.0,
  22290. c1 * 2.0 * (nSquared - 1.0),
  22291. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22292. }
  22293. void IIRFilter::makeLowShelf (const double sampleRate,
  22294. const double cutOffFrequency,
  22295. const double Q,
  22296. const float gainFactor) throw()
  22297. {
  22298. jassert (sampleRate > 0);
  22299. jassert (Q > 0);
  22300. const double A = jmax (0.0f, gainFactor);
  22301. const double aminus1 = A - 1.0;
  22302. const double aplus1 = A + 1.0;
  22303. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22304. const double coso = std::cos (omega);
  22305. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22306. const double aminus1TimesCoso = aminus1 * coso;
  22307. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22308. A * 2.0 * (aminus1 - aplus1 * coso),
  22309. A * (aplus1 - aminus1TimesCoso - beta),
  22310. aplus1 + aminus1TimesCoso + beta,
  22311. -2.0 * (aminus1 + aplus1 * coso),
  22312. aplus1 + aminus1TimesCoso - beta);
  22313. }
  22314. void IIRFilter::makeHighShelf (const double sampleRate,
  22315. const double cutOffFrequency,
  22316. const double Q,
  22317. const float gainFactor) throw()
  22318. {
  22319. jassert (sampleRate > 0);
  22320. jassert (Q > 0);
  22321. const double A = jmax (0.0f, gainFactor);
  22322. const double aminus1 = A - 1.0;
  22323. const double aplus1 = A + 1.0;
  22324. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22325. const double coso = std::cos (omega);
  22326. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22327. const double aminus1TimesCoso = aminus1 * coso;
  22328. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22329. A * -2.0 * (aminus1 + aplus1 * coso),
  22330. A * (aplus1 + aminus1TimesCoso - beta),
  22331. aplus1 - aminus1TimesCoso + beta,
  22332. 2.0 * (aminus1 - aplus1 * coso),
  22333. aplus1 - aminus1TimesCoso - beta);
  22334. }
  22335. void IIRFilter::makeBandPass (const double sampleRate,
  22336. const double centreFrequency,
  22337. const double Q,
  22338. const float gainFactor) throw()
  22339. {
  22340. jassert (sampleRate > 0);
  22341. jassert (Q > 0);
  22342. const double A = jmax (0.0f, gainFactor);
  22343. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22344. const double alpha = 0.5 * std::sin (omega) / Q;
  22345. const double c2 = -2.0 * std::cos (omega);
  22346. const double alphaTimesA = alpha * A;
  22347. const double alphaOverA = alpha / A;
  22348. setCoefficients (1.0 + alphaTimesA,
  22349. c2,
  22350. 1.0 - alphaTimesA,
  22351. 1.0 + alphaOverA,
  22352. c2,
  22353. 1.0 - alphaOverA);
  22354. }
  22355. void IIRFilter::makeInactive() throw()
  22356. {
  22357. const ScopedLock sl (processLock);
  22358. active = false;
  22359. }
  22360. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22361. {
  22362. const ScopedLock sl (processLock);
  22363. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22364. active = other.active;
  22365. }
  22366. void IIRFilter::setCoefficients (double c1,
  22367. double c2,
  22368. double c3,
  22369. double c4,
  22370. double c5,
  22371. double c6) throw()
  22372. {
  22373. const double a = 1.0 / c4;
  22374. c1 *= a;
  22375. c2 *= a;
  22376. c3 *= a;
  22377. c5 *= a;
  22378. c6 *= a;
  22379. const ScopedLock sl (processLock);
  22380. coefficients[0] = (float) c1;
  22381. coefficients[1] = (float) c2;
  22382. coefficients[2] = (float) c3;
  22383. coefficients[3] = (float) c4;
  22384. coefficients[4] = (float) c5;
  22385. coefficients[5] = (float) c6;
  22386. active = true;
  22387. }
  22388. END_JUCE_NAMESPACE
  22389. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22390. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22391. BEGIN_JUCE_NAMESPACE
  22392. MidiBuffer::MidiBuffer() throw()
  22393. : bytesUsed (0)
  22394. {
  22395. }
  22396. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22397. : bytesUsed (0)
  22398. {
  22399. addEvent (message, 0);
  22400. }
  22401. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22402. : data (other.data),
  22403. bytesUsed (other.bytesUsed)
  22404. {
  22405. }
  22406. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22407. {
  22408. bytesUsed = other.bytesUsed;
  22409. data = other.data;
  22410. return *this;
  22411. }
  22412. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22413. {
  22414. data.swapWith (other.data);
  22415. swapVariables <int> (bytesUsed, other.bytesUsed);
  22416. }
  22417. MidiBuffer::~MidiBuffer()
  22418. {
  22419. }
  22420. inline uint8* MidiBuffer::getData() const throw()
  22421. {
  22422. return static_cast <uint8*> (data.getData());
  22423. }
  22424. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22425. {
  22426. return *static_cast <const int*> (d);
  22427. }
  22428. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22429. {
  22430. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22431. }
  22432. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22433. {
  22434. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22435. }
  22436. void MidiBuffer::clear() throw()
  22437. {
  22438. bytesUsed = 0;
  22439. }
  22440. void MidiBuffer::clear (const int startSample, const int numSamples)
  22441. {
  22442. uint8* const start = findEventAfter (getData(), startSample - 1);
  22443. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22444. if (end > start)
  22445. {
  22446. const int bytesToMove = bytesUsed - (int) (end - getData());
  22447. if (bytesToMove > 0)
  22448. memmove (start, end, bytesToMove);
  22449. bytesUsed -= (int) (end - start);
  22450. }
  22451. }
  22452. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22453. {
  22454. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22455. }
  22456. namespace MidiBufferHelpers
  22457. {
  22458. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22459. {
  22460. unsigned int byte = (unsigned int) *data;
  22461. int size = 0;
  22462. if (byte == 0xf0 || byte == 0xf7)
  22463. {
  22464. const uint8* d = data + 1;
  22465. while (d < data + maxBytes)
  22466. if (*d++ == 0xf7)
  22467. break;
  22468. size = (int) (d - data);
  22469. }
  22470. else if (byte == 0xff)
  22471. {
  22472. int n;
  22473. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22474. size = jmin (maxBytes, n + 2 + bytesLeft);
  22475. }
  22476. else if (byte >= 0x80)
  22477. {
  22478. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22479. }
  22480. return size;
  22481. }
  22482. }
  22483. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22484. {
  22485. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22486. if (numBytes > 0)
  22487. {
  22488. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22489. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22490. uint8* d = findEventAfter (getData(), sampleNumber);
  22491. const int bytesToMove = bytesUsed - (int) (d - getData());
  22492. if (bytesToMove > 0)
  22493. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22494. *reinterpret_cast <int*> (d) = sampleNumber;
  22495. d += sizeof (int);
  22496. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22497. d += sizeof (uint16);
  22498. memcpy (d, newData, numBytes);
  22499. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22500. }
  22501. }
  22502. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22503. const int startSample,
  22504. const int numSamples,
  22505. const int sampleDeltaToAdd)
  22506. {
  22507. Iterator i (otherBuffer);
  22508. i.setNextSamplePosition (startSample);
  22509. const uint8* eventData;
  22510. int eventSize, position;
  22511. while (i.getNextEvent (eventData, eventSize, position)
  22512. && (position < startSample + numSamples || numSamples < 0))
  22513. {
  22514. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22515. }
  22516. }
  22517. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22518. {
  22519. data.ensureSize (minimumNumBytes);
  22520. }
  22521. bool MidiBuffer::isEmpty() const throw()
  22522. {
  22523. return bytesUsed == 0;
  22524. }
  22525. int MidiBuffer::getNumEvents() const throw()
  22526. {
  22527. int n = 0;
  22528. const uint8* d = getData();
  22529. const uint8* const end = d + bytesUsed;
  22530. while (d < end)
  22531. {
  22532. d += getEventTotalSize (d);
  22533. ++n;
  22534. }
  22535. return n;
  22536. }
  22537. int MidiBuffer::getFirstEventTime() const throw()
  22538. {
  22539. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22540. }
  22541. int MidiBuffer::getLastEventTime() const throw()
  22542. {
  22543. if (bytesUsed == 0)
  22544. return 0;
  22545. const uint8* d = getData();
  22546. const uint8* const endData = d + bytesUsed;
  22547. for (;;)
  22548. {
  22549. const uint8* const nextOne = d + getEventTotalSize (d);
  22550. if (nextOne >= endData)
  22551. return getEventTime (d);
  22552. d = nextOne;
  22553. }
  22554. }
  22555. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22556. {
  22557. const uint8* const endData = getData() + bytesUsed;
  22558. while (d < endData && getEventTime (d) <= samplePosition)
  22559. d += getEventTotalSize (d);
  22560. return d;
  22561. }
  22562. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22563. : buffer (buffer_),
  22564. data (buffer_.getData())
  22565. {
  22566. }
  22567. MidiBuffer::Iterator::~Iterator() throw()
  22568. {
  22569. }
  22570. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22571. {
  22572. data = buffer.getData();
  22573. const uint8* dataEnd = data + buffer.bytesUsed;
  22574. while (data < dataEnd && getEventTime (data) < samplePosition)
  22575. data += getEventTotalSize (data);
  22576. }
  22577. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22578. {
  22579. if (data >= buffer.getData() + buffer.bytesUsed)
  22580. return false;
  22581. samplePosition = getEventTime (data);
  22582. numBytes = getEventDataSize (data);
  22583. data += sizeof (int) + sizeof (uint16);
  22584. midiData = data;
  22585. data += numBytes;
  22586. return true;
  22587. }
  22588. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22589. {
  22590. if (data >= buffer.getData() + buffer.bytesUsed)
  22591. return false;
  22592. samplePosition = getEventTime (data);
  22593. const int numBytes = getEventDataSize (data);
  22594. data += sizeof (int) + sizeof (uint16);
  22595. result = MidiMessage (data, numBytes, samplePosition);
  22596. data += numBytes;
  22597. return true;
  22598. }
  22599. END_JUCE_NAMESPACE
  22600. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22601. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22602. BEGIN_JUCE_NAMESPACE
  22603. namespace MidiFileHelpers
  22604. {
  22605. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22606. {
  22607. unsigned int buffer = v & 0x7F;
  22608. while ((v >>= 7) != 0)
  22609. {
  22610. buffer <<= 8;
  22611. buffer |= ((v & 0x7F) | 0x80);
  22612. }
  22613. for (;;)
  22614. {
  22615. out.writeByte ((char) buffer);
  22616. if (buffer & 0x80)
  22617. buffer >>= 8;
  22618. else
  22619. break;
  22620. }
  22621. }
  22622. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22623. {
  22624. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22625. data += 4;
  22626. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22627. {
  22628. bool ok = false;
  22629. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22630. {
  22631. for (int i = 0; i < 8; ++i)
  22632. {
  22633. ch = ByteOrder::bigEndianInt (data);
  22634. data += 4;
  22635. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22636. {
  22637. ok = true;
  22638. break;
  22639. }
  22640. }
  22641. }
  22642. if (! ok)
  22643. return false;
  22644. }
  22645. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22646. data += 4;
  22647. fileType = (short) ByteOrder::bigEndianShort (data);
  22648. data += 2;
  22649. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22650. data += 2;
  22651. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22652. data += 2;
  22653. bytesRemaining -= 6;
  22654. data += bytesRemaining;
  22655. return true;
  22656. }
  22657. double convertTicksToSeconds (const double time,
  22658. const MidiMessageSequence& tempoEvents,
  22659. const int timeFormat)
  22660. {
  22661. if (timeFormat > 0)
  22662. {
  22663. int numer = 4, denom = 4;
  22664. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22665. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22666. double secsPerTick = 0.5 * tickLen;
  22667. const int numEvents = tempoEvents.getNumEvents();
  22668. for (int i = 0; i < numEvents; ++i)
  22669. {
  22670. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22671. if (time <= m.getTimeStamp())
  22672. break;
  22673. if (timeFormat > 0)
  22674. {
  22675. correctedTempoTime = correctedTempoTime
  22676. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22677. }
  22678. else
  22679. {
  22680. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22681. }
  22682. tempoTime = m.getTimeStamp();
  22683. if (m.isTempoMetaEvent())
  22684. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22685. else if (m.isTimeSignatureMetaEvent())
  22686. m.getTimeSignatureInfo (numer, denom);
  22687. while (i + 1 < numEvents)
  22688. {
  22689. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22690. if (m2.getTimeStamp() == tempoTime)
  22691. {
  22692. ++i;
  22693. if (m2.isTempoMetaEvent())
  22694. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22695. else if (m2.isTimeSignatureMetaEvent())
  22696. m2.getTimeSignatureInfo (numer, denom);
  22697. }
  22698. else
  22699. {
  22700. break;
  22701. }
  22702. }
  22703. }
  22704. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22705. }
  22706. else
  22707. {
  22708. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22709. }
  22710. }
  22711. // a comparator that puts all the note-offs before note-ons that have the same time
  22712. struct Sorter
  22713. {
  22714. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22715. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22716. {
  22717. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22718. if (diff == 0)
  22719. {
  22720. if (first->message.isNoteOff() && second->message.isNoteOn())
  22721. return -1;
  22722. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22723. return 1;
  22724. else
  22725. return 0;
  22726. }
  22727. else
  22728. {
  22729. return (diff > 0) ? 1 : -1;
  22730. }
  22731. }
  22732. };
  22733. }
  22734. MidiFile::MidiFile()
  22735. : timeFormat ((short) (unsigned short) 0xe728)
  22736. {
  22737. }
  22738. MidiFile::~MidiFile()
  22739. {
  22740. clear();
  22741. }
  22742. void MidiFile::clear()
  22743. {
  22744. tracks.clear();
  22745. }
  22746. int MidiFile::getNumTracks() const throw()
  22747. {
  22748. return tracks.size();
  22749. }
  22750. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22751. {
  22752. return tracks [index];
  22753. }
  22754. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22755. {
  22756. tracks.add (new MidiMessageSequence (trackSequence));
  22757. }
  22758. short MidiFile::getTimeFormat() const throw()
  22759. {
  22760. return timeFormat;
  22761. }
  22762. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22763. {
  22764. timeFormat = (short) ticks;
  22765. }
  22766. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22767. const int subframeResolution) throw()
  22768. {
  22769. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22770. }
  22771. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22772. {
  22773. for (int i = tracks.size(); --i >= 0;)
  22774. {
  22775. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22776. for (int j = 0; j < numEvents; ++j)
  22777. {
  22778. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22779. if (m.isTempoMetaEvent())
  22780. tempoChangeEvents.addEvent (m);
  22781. }
  22782. }
  22783. }
  22784. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22785. {
  22786. for (int i = tracks.size(); --i >= 0;)
  22787. {
  22788. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22789. for (int j = 0; j < numEvents; ++j)
  22790. {
  22791. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22792. if (m.isTimeSignatureMetaEvent())
  22793. timeSigEvents.addEvent (m);
  22794. }
  22795. }
  22796. }
  22797. double MidiFile::getLastTimestamp() const
  22798. {
  22799. double t = 0.0;
  22800. for (int i = tracks.size(); --i >= 0;)
  22801. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22802. return t;
  22803. }
  22804. bool MidiFile::readFrom (InputStream& sourceStream)
  22805. {
  22806. clear();
  22807. MemoryBlock data;
  22808. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22809. // (put a sanity-check on the file size, as midi files are generally small)
  22810. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22811. {
  22812. size_t size = data.getSize();
  22813. const uint8* d = static_cast <const uint8*> (data.getData());
  22814. short fileType, expectedTracks;
  22815. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22816. {
  22817. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22818. int track = 0;
  22819. while (size > 0 && track < expectedTracks)
  22820. {
  22821. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22822. d += 4;
  22823. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22824. d += 4;
  22825. if (chunkSize <= 0)
  22826. break;
  22827. if (size < 0)
  22828. return false;
  22829. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22830. {
  22831. readNextTrack (d, chunkSize);
  22832. }
  22833. size -= chunkSize + 8;
  22834. d += chunkSize;
  22835. ++track;
  22836. }
  22837. return true;
  22838. }
  22839. }
  22840. return false;
  22841. }
  22842. void MidiFile::readNextTrack (const uint8* data, int size)
  22843. {
  22844. double time = 0;
  22845. char lastStatusByte = 0;
  22846. MidiMessageSequence result;
  22847. while (size > 0)
  22848. {
  22849. int bytesUsed;
  22850. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22851. data += bytesUsed;
  22852. size -= bytesUsed;
  22853. time += delay;
  22854. int messSize = 0;
  22855. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22856. if (messSize <= 0)
  22857. break;
  22858. size -= messSize;
  22859. data += messSize;
  22860. result.addEvent (mm);
  22861. const char firstByte = *(mm.getRawData());
  22862. if ((firstByte & 0xf0) != 0xf0)
  22863. lastStatusByte = firstByte;
  22864. }
  22865. // use a sort that puts all the note-offs before note-ons that have the same time
  22866. MidiFileHelpers::Sorter sorter;
  22867. result.list.sort (sorter, true);
  22868. result.updateMatchedPairs();
  22869. addTrack (result);
  22870. }
  22871. void MidiFile::convertTimestampTicksToSeconds()
  22872. {
  22873. MidiMessageSequence tempoEvents;
  22874. findAllTempoEvents (tempoEvents);
  22875. findAllTimeSigEvents (tempoEvents);
  22876. for (int i = 0; i < tracks.size(); ++i)
  22877. {
  22878. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22879. for (int j = ms.getNumEvents(); --j >= 0;)
  22880. {
  22881. MidiMessage& m = ms.getEventPointer(j)->message;
  22882. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22883. tempoEvents,
  22884. timeFormat));
  22885. }
  22886. }
  22887. }
  22888. bool MidiFile::writeTo (OutputStream& out)
  22889. {
  22890. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22891. out.writeIntBigEndian (6);
  22892. out.writeShortBigEndian (1); // type
  22893. out.writeShortBigEndian ((short) tracks.size());
  22894. out.writeShortBigEndian (timeFormat);
  22895. for (int i = 0; i < tracks.size(); ++i)
  22896. writeTrack (out, i);
  22897. out.flush();
  22898. return true;
  22899. }
  22900. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22901. {
  22902. MemoryOutputStream out;
  22903. const MidiMessageSequence& ms = *tracks[trackNum];
  22904. int lastTick = 0;
  22905. char lastStatusByte = 0;
  22906. for (int i = 0; i < ms.getNumEvents(); ++i)
  22907. {
  22908. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22909. const int tick = roundToInt (mm.getTimeStamp());
  22910. const int delta = jmax (0, tick - lastTick);
  22911. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22912. lastTick = tick;
  22913. const char statusByte = *(mm.getRawData());
  22914. if ((statusByte == lastStatusByte)
  22915. && ((statusByte & 0xf0) != 0xf0)
  22916. && i > 0
  22917. && mm.getRawDataSize() > 1)
  22918. {
  22919. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22920. }
  22921. else
  22922. {
  22923. out.write (mm.getRawData(), mm.getRawDataSize());
  22924. }
  22925. lastStatusByte = statusByte;
  22926. }
  22927. out.writeByte (0);
  22928. const MidiMessage m (MidiMessage::endOfTrack());
  22929. out.write (m.getRawData(),
  22930. m.getRawDataSize());
  22931. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22932. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22933. mainOut.write (out.getData(), (int) out.getDataSize());
  22934. }
  22935. END_JUCE_NAMESPACE
  22936. /*** End of inlined file: juce_MidiFile.cpp ***/
  22937. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22938. BEGIN_JUCE_NAMESPACE
  22939. MidiKeyboardState::MidiKeyboardState()
  22940. {
  22941. zerostruct (noteStates);
  22942. }
  22943. MidiKeyboardState::~MidiKeyboardState()
  22944. {
  22945. }
  22946. void MidiKeyboardState::reset()
  22947. {
  22948. const ScopedLock sl (lock);
  22949. zerostruct (noteStates);
  22950. eventsToAdd.clear();
  22951. }
  22952. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22953. {
  22954. jassert (midiChannel >= 0 && midiChannel <= 16);
  22955. return ((unsigned int) n) < 128
  22956. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22957. }
  22958. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22959. {
  22960. return ((unsigned int) n) < 128
  22961. && (noteStates[n] & midiChannelMask) != 0;
  22962. }
  22963. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22964. {
  22965. jassert (midiChannel >= 0 && midiChannel <= 16);
  22966. jassert (((unsigned int) midiNoteNumber) < 128);
  22967. const ScopedLock sl (lock);
  22968. if (((unsigned int) midiNoteNumber) < 128)
  22969. {
  22970. const int timeNow = (int) Time::getMillisecondCounter();
  22971. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22972. eventsToAdd.clear (0, timeNow - 500);
  22973. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22974. }
  22975. }
  22976. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22977. {
  22978. if (((unsigned int) midiNoteNumber) < 128)
  22979. {
  22980. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22981. for (int i = listeners.size(); --i >= 0;)
  22982. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22983. }
  22984. }
  22985. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22986. {
  22987. const ScopedLock sl (lock);
  22988. if (isNoteOn (midiChannel, midiNoteNumber))
  22989. {
  22990. const int timeNow = (int) Time::getMillisecondCounter();
  22991. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22992. eventsToAdd.clear (0, timeNow - 500);
  22993. noteOffInternal (midiChannel, midiNoteNumber);
  22994. }
  22995. }
  22996. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22997. {
  22998. if (isNoteOn (midiChannel, midiNoteNumber))
  22999. {
  23000. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  23001. for (int i = listeners.size(); --i >= 0;)
  23002. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  23003. }
  23004. }
  23005. void MidiKeyboardState::allNotesOff (const int midiChannel)
  23006. {
  23007. const ScopedLock sl (lock);
  23008. if (midiChannel <= 0)
  23009. {
  23010. for (int i = 1; i <= 16; ++i)
  23011. allNotesOff (i);
  23012. }
  23013. else
  23014. {
  23015. for (int i = 0; i < 128; ++i)
  23016. noteOff (midiChannel, i);
  23017. }
  23018. }
  23019. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  23020. {
  23021. if (message.isNoteOn())
  23022. {
  23023. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  23024. }
  23025. else if (message.isNoteOff())
  23026. {
  23027. noteOffInternal (message.getChannel(), message.getNoteNumber());
  23028. }
  23029. else if (message.isAllNotesOff())
  23030. {
  23031. for (int i = 0; i < 128; ++i)
  23032. noteOffInternal (message.getChannel(), i);
  23033. }
  23034. }
  23035. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  23036. const int startSample,
  23037. const int numSamples,
  23038. const bool injectIndirectEvents)
  23039. {
  23040. MidiBuffer::Iterator i (buffer);
  23041. MidiMessage message (0xf4, 0.0);
  23042. int time;
  23043. const ScopedLock sl (lock);
  23044. while (i.getNextEvent (message, time))
  23045. processNextMidiEvent (message);
  23046. if (injectIndirectEvents)
  23047. {
  23048. MidiBuffer::Iterator i2 (eventsToAdd);
  23049. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  23050. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  23051. while (i2.getNextEvent (message, time))
  23052. {
  23053. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  23054. buffer.addEvent (message, startSample + pos);
  23055. }
  23056. }
  23057. eventsToAdd.clear();
  23058. }
  23059. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  23060. {
  23061. const ScopedLock sl (lock);
  23062. listeners.addIfNotAlreadyThere (listener);
  23063. }
  23064. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  23065. {
  23066. const ScopedLock sl (lock);
  23067. listeners.removeValue (listener);
  23068. }
  23069. END_JUCE_NAMESPACE
  23070. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  23071. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  23072. BEGIN_JUCE_NAMESPACE
  23073. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  23074. {
  23075. numBytesUsed = 0;
  23076. int v = 0;
  23077. int i;
  23078. do
  23079. {
  23080. i = (int) *data++;
  23081. if (++numBytesUsed > 6)
  23082. break;
  23083. v = (v << 7) + (i & 0x7f);
  23084. } while (i & 0x80);
  23085. return v;
  23086. }
  23087. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  23088. {
  23089. // this method only works for valid starting bytes of a short midi message
  23090. jassert (firstByte >= 0x80
  23091. && firstByte != 0xf0
  23092. && firstByte != 0xf7);
  23093. static const char messageLengths[] =
  23094. {
  23095. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23096. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23097. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23098. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23099. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23100. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23101. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23102. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  23103. };
  23104. return messageLengths [firstByte & 0x7f];
  23105. }
  23106. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  23107. : timeStamp (t),
  23108. size (dataSize)
  23109. {
  23110. jassert (dataSize > 0);
  23111. if (dataSize <= 4)
  23112. data = static_cast<uint8*> (preallocatedData.asBytes);
  23113. else
  23114. data = new uint8 [dataSize];
  23115. memcpy (data, d, dataSize);
  23116. // check that the length matches the data..
  23117. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23118. }
  23119. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23120. : timeStamp (t),
  23121. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23122. size (1)
  23123. {
  23124. data[0] = (uint8) byte1;
  23125. // check that the length matches the data..
  23126. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23127. }
  23128. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23129. : timeStamp (t),
  23130. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23131. size (2)
  23132. {
  23133. data[0] = (uint8) byte1;
  23134. data[1] = (uint8) byte2;
  23135. // check that the length matches the data..
  23136. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23137. }
  23138. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23139. : timeStamp (t),
  23140. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23141. size (3)
  23142. {
  23143. data[0] = (uint8) byte1;
  23144. data[1] = (uint8) byte2;
  23145. data[2] = (uint8) byte3;
  23146. // check that the length matches the data..
  23147. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23148. }
  23149. MidiMessage::MidiMessage (const MidiMessage& other)
  23150. : timeStamp (other.timeStamp),
  23151. size (other.size)
  23152. {
  23153. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23154. {
  23155. data = new uint8 [size];
  23156. memcpy (data, other.data, size);
  23157. }
  23158. else
  23159. {
  23160. data = static_cast<uint8*> (preallocatedData.asBytes);
  23161. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23162. }
  23163. }
  23164. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23165. : timeStamp (newTimeStamp),
  23166. size (other.size)
  23167. {
  23168. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23169. {
  23170. data = new uint8 [size];
  23171. memcpy (data, other.data, size);
  23172. }
  23173. else
  23174. {
  23175. data = static_cast<uint8*> (preallocatedData.asBytes);
  23176. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23177. }
  23178. }
  23179. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23180. : timeStamp (t),
  23181. data (static_cast<uint8*> (preallocatedData.asBytes))
  23182. {
  23183. const uint8* src = static_cast <const uint8*> (src_);
  23184. unsigned int byte = (unsigned int) *src;
  23185. if (byte < 0x80)
  23186. {
  23187. byte = (unsigned int) (uint8) lastStatusByte;
  23188. numBytesUsed = -1;
  23189. }
  23190. else
  23191. {
  23192. numBytesUsed = 0;
  23193. --sz;
  23194. ++src;
  23195. }
  23196. if (byte >= 0x80)
  23197. {
  23198. if (byte == 0xf0)
  23199. {
  23200. const uint8* d = src;
  23201. bool haveReadAllLengthBytes = false;
  23202. while (d < src + sz)
  23203. {
  23204. if (*d >= 0x80)
  23205. {
  23206. if (*d == 0xf7)
  23207. {
  23208. ++d; // include the trailing 0xf7 when we hit it
  23209. break;
  23210. }
  23211. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  23212. break; // bytes, assume it's the end of the sysex
  23213. ++d;
  23214. continue;
  23215. }
  23216. haveReadAllLengthBytes = true;
  23217. ++d;
  23218. }
  23219. size = 1 + (int) (d - src);
  23220. data = new uint8 [size];
  23221. *data = (uint8) byte;
  23222. memcpy (data + 1, src, size - 1);
  23223. }
  23224. else if (byte == 0xff)
  23225. {
  23226. int n;
  23227. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23228. size = jmin (sz + 1, n + 2 + bytesLeft);
  23229. data = new uint8 [size];
  23230. *data = (uint8) byte;
  23231. memcpy (data + 1, src, size - 1);
  23232. }
  23233. else
  23234. {
  23235. preallocatedData.asInt32 = 0;
  23236. size = getMessageLengthFromFirstByte ((uint8) byte);
  23237. data[0] = (uint8) byte;
  23238. if (size > 1)
  23239. {
  23240. data[1] = src[0];
  23241. if (size > 2)
  23242. data[2] = src[1];
  23243. }
  23244. }
  23245. numBytesUsed += size;
  23246. }
  23247. else
  23248. {
  23249. preallocatedData.asInt32 = 0;
  23250. size = 0;
  23251. }
  23252. }
  23253. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23254. {
  23255. if (this != &other)
  23256. {
  23257. timeStamp = other.timeStamp;
  23258. size = other.size;
  23259. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23260. delete[] data;
  23261. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23262. {
  23263. data = new uint8 [size];
  23264. memcpy (data, other.data, size);
  23265. }
  23266. else
  23267. {
  23268. data = static_cast<uint8*> (preallocatedData.asBytes);
  23269. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23270. }
  23271. }
  23272. return *this;
  23273. }
  23274. MidiMessage::~MidiMessage()
  23275. {
  23276. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23277. delete[] data;
  23278. }
  23279. int MidiMessage::getChannel() const throw()
  23280. {
  23281. if ((data[0] & 0xf0) != 0xf0)
  23282. return (data[0] & 0xf) + 1;
  23283. else
  23284. return 0;
  23285. }
  23286. bool MidiMessage::isForChannel (const int channel) const throw()
  23287. {
  23288. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23289. return ((data[0] & 0xf) == channel - 1)
  23290. && ((data[0] & 0xf0) != 0xf0);
  23291. }
  23292. void MidiMessage::setChannel (const int channel) throw()
  23293. {
  23294. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23295. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23296. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23297. | (uint8)(channel - 1));
  23298. }
  23299. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23300. {
  23301. return ((data[0] & 0xf0) == 0x90)
  23302. && (returnTrueForVelocity0 || data[2] != 0);
  23303. }
  23304. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23305. {
  23306. return ((data[0] & 0xf0) == 0x80)
  23307. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23308. }
  23309. bool MidiMessage::isNoteOnOrOff() const throw()
  23310. {
  23311. const int d = data[0] & 0xf0;
  23312. return (d == 0x90) || (d == 0x80);
  23313. }
  23314. int MidiMessage::getNoteNumber() const throw()
  23315. {
  23316. return data[1];
  23317. }
  23318. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23319. {
  23320. if (isNoteOnOrOff())
  23321. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23322. }
  23323. uint8 MidiMessage::getVelocity() const throw()
  23324. {
  23325. if (isNoteOnOrOff())
  23326. return data[2];
  23327. else
  23328. return 0;
  23329. }
  23330. float MidiMessage::getFloatVelocity() const throw()
  23331. {
  23332. return getVelocity() * (1.0f / 127.0f);
  23333. }
  23334. void MidiMessage::setVelocity (const float newVelocity) throw()
  23335. {
  23336. if (isNoteOnOrOff())
  23337. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23338. }
  23339. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23340. {
  23341. if (isNoteOnOrOff())
  23342. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23343. }
  23344. bool MidiMessage::isAftertouch() const throw()
  23345. {
  23346. return (data[0] & 0xf0) == 0xa0;
  23347. }
  23348. int MidiMessage::getAfterTouchValue() const throw()
  23349. {
  23350. return data[2];
  23351. }
  23352. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23353. const int noteNum,
  23354. const int aftertouchValue) throw()
  23355. {
  23356. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23357. jassert (((unsigned int) noteNum) <= 127);
  23358. jassert (((unsigned int) aftertouchValue) <= 127);
  23359. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23360. noteNum & 0x7f,
  23361. aftertouchValue & 0x7f);
  23362. }
  23363. bool MidiMessage::isChannelPressure() const throw()
  23364. {
  23365. return (data[0] & 0xf0) == 0xd0;
  23366. }
  23367. int MidiMessage::getChannelPressureValue() const throw()
  23368. {
  23369. jassert (isChannelPressure());
  23370. return data[1];
  23371. }
  23372. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23373. const int pressure) throw()
  23374. {
  23375. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23376. jassert (((unsigned int) pressure) <= 127);
  23377. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23378. pressure & 0x7f);
  23379. }
  23380. bool MidiMessage::isProgramChange() const throw()
  23381. {
  23382. return (data[0] & 0xf0) == 0xc0;
  23383. }
  23384. int MidiMessage::getProgramChangeNumber() const throw()
  23385. {
  23386. return data[1];
  23387. }
  23388. const MidiMessage MidiMessage::programChange (const int channel,
  23389. const int programNumber) throw()
  23390. {
  23391. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23392. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23393. programNumber & 0x7f);
  23394. }
  23395. bool MidiMessage::isPitchWheel() const throw()
  23396. {
  23397. return (data[0] & 0xf0) == 0xe0;
  23398. }
  23399. int MidiMessage::getPitchWheelValue() const throw()
  23400. {
  23401. return data[1] | (data[2] << 7);
  23402. }
  23403. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23404. const int position) throw()
  23405. {
  23406. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23407. jassert (((unsigned int) position) <= 0x3fff);
  23408. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23409. position & 127,
  23410. (position >> 7) & 127);
  23411. }
  23412. bool MidiMessage::isController() const throw()
  23413. {
  23414. return (data[0] & 0xf0) == 0xb0;
  23415. }
  23416. int MidiMessage::getControllerNumber() const throw()
  23417. {
  23418. jassert (isController());
  23419. return data[1];
  23420. }
  23421. int MidiMessage::getControllerValue() const throw()
  23422. {
  23423. jassert (isController());
  23424. return data[2];
  23425. }
  23426. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23427. const int controllerType,
  23428. const int value) throw()
  23429. {
  23430. // the channel must be between 1 and 16 inclusive
  23431. jassert (channel > 0 && channel <= 16);
  23432. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23433. controllerType & 127,
  23434. value & 127);
  23435. }
  23436. const MidiMessage MidiMessage::noteOn (const int channel,
  23437. const int noteNumber,
  23438. const float velocity) throw()
  23439. {
  23440. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23441. }
  23442. const MidiMessage MidiMessage::noteOn (const int channel,
  23443. const int noteNumber,
  23444. const uint8 velocity) throw()
  23445. {
  23446. jassert (channel > 0 && channel <= 16);
  23447. jassert (((unsigned int) noteNumber) <= 127);
  23448. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23449. noteNumber & 127,
  23450. jlimit (0, 127, roundToInt (velocity)));
  23451. }
  23452. const MidiMessage MidiMessage::noteOff (const int channel,
  23453. const int noteNumber) throw()
  23454. {
  23455. jassert (channel > 0 && channel <= 16);
  23456. jassert (((unsigned int) noteNumber) <= 127);
  23457. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23458. }
  23459. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23460. {
  23461. return controllerEvent (channel, 123, 0);
  23462. }
  23463. bool MidiMessage::isAllNotesOff() const throw()
  23464. {
  23465. return (data[0] & 0xf0) == 0xb0
  23466. && data[1] == 123;
  23467. }
  23468. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23469. {
  23470. return controllerEvent (channel, 120, 0);
  23471. }
  23472. bool MidiMessage::isAllSoundOff() const throw()
  23473. {
  23474. return (data[0] & 0xf0) == 0xb0
  23475. && data[1] == 120;
  23476. }
  23477. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23478. {
  23479. return controllerEvent (channel, 121, 0);
  23480. }
  23481. const MidiMessage MidiMessage::masterVolume (const float volume)
  23482. {
  23483. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23484. uint8 buf[8];
  23485. buf[0] = 0xf0;
  23486. buf[1] = 0x7f;
  23487. buf[2] = 0x7f;
  23488. buf[3] = 0x04;
  23489. buf[4] = 0x01;
  23490. buf[5] = (uint8) (vol & 0x7f);
  23491. buf[6] = (uint8) (vol >> 7);
  23492. buf[7] = 0xf7;
  23493. return MidiMessage (buf, 8);
  23494. }
  23495. bool MidiMessage::isSysEx() const throw()
  23496. {
  23497. return *data == 0xf0;
  23498. }
  23499. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23500. {
  23501. MemoryBlock mm (dataSize + 2);
  23502. uint8* const m = static_cast <uint8*> (mm.getData());
  23503. m[0] = 0xf0;
  23504. memcpy (m + 1, sysexData, dataSize);
  23505. m[dataSize + 1] = 0xf7;
  23506. return MidiMessage (m, dataSize + 2);
  23507. }
  23508. const uint8* MidiMessage::getSysExData() const throw()
  23509. {
  23510. return (isSysEx()) ? getRawData() + 1 : 0;
  23511. }
  23512. int MidiMessage::getSysExDataSize() const throw()
  23513. {
  23514. return (isSysEx()) ? size - 2 : 0;
  23515. }
  23516. bool MidiMessage::isMetaEvent() const throw()
  23517. {
  23518. return *data == 0xff;
  23519. }
  23520. bool MidiMessage::isActiveSense() const throw()
  23521. {
  23522. return *data == 0xfe;
  23523. }
  23524. int MidiMessage::getMetaEventType() const throw()
  23525. {
  23526. if (*data != 0xff)
  23527. return -1;
  23528. else
  23529. return data[1];
  23530. }
  23531. int MidiMessage::getMetaEventLength() const throw()
  23532. {
  23533. if (*data == 0xff)
  23534. {
  23535. int n;
  23536. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23537. }
  23538. return 0;
  23539. }
  23540. const uint8* MidiMessage::getMetaEventData() const throw()
  23541. {
  23542. int n;
  23543. const uint8* d = data + 2;
  23544. readVariableLengthVal (d, n);
  23545. return d + n;
  23546. }
  23547. bool MidiMessage::isTrackMetaEvent() const throw()
  23548. {
  23549. return getMetaEventType() == 0;
  23550. }
  23551. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23552. {
  23553. return getMetaEventType() == 47;
  23554. }
  23555. bool MidiMessage::isTextMetaEvent() const throw()
  23556. {
  23557. const int t = getMetaEventType();
  23558. return t > 0 && t < 16;
  23559. }
  23560. const String MidiMessage::getTextFromTextMetaEvent() const
  23561. {
  23562. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23563. }
  23564. bool MidiMessage::isTrackNameEvent() const throw()
  23565. {
  23566. return (data[1] == 3)
  23567. && (*data == 0xff);
  23568. }
  23569. bool MidiMessage::isTempoMetaEvent() const throw()
  23570. {
  23571. return (data[1] == 81)
  23572. && (*data == 0xff);
  23573. }
  23574. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23575. {
  23576. return (data[1] == 0x20)
  23577. && (*data == 0xff)
  23578. && (data[2] == 1);
  23579. }
  23580. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23581. {
  23582. return data[3] + 1;
  23583. }
  23584. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23585. {
  23586. if (! isTempoMetaEvent())
  23587. return 0.0;
  23588. const uint8* const d = getMetaEventData();
  23589. return (((unsigned int) d[0] << 16)
  23590. | ((unsigned int) d[1] << 8)
  23591. | d[2])
  23592. / 1000000.0;
  23593. }
  23594. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23595. {
  23596. if (timeFormat > 0)
  23597. {
  23598. if (! isTempoMetaEvent())
  23599. return 0.5 / timeFormat;
  23600. return getTempoSecondsPerQuarterNote() / timeFormat;
  23601. }
  23602. else
  23603. {
  23604. const int frameCode = (-timeFormat) >> 8;
  23605. double framesPerSecond;
  23606. switch (frameCode)
  23607. {
  23608. case 24: framesPerSecond = 24.0; break;
  23609. case 25: framesPerSecond = 25.0; break;
  23610. case 29: framesPerSecond = 29.97; break;
  23611. case 30: framesPerSecond = 30.0; break;
  23612. default: framesPerSecond = 30.0; break;
  23613. }
  23614. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23615. }
  23616. }
  23617. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23618. {
  23619. uint8 d[8];
  23620. d[0] = 0xff;
  23621. d[1] = 81;
  23622. d[2] = 3;
  23623. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23624. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23625. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23626. return MidiMessage (d, 6, 0.0);
  23627. }
  23628. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23629. {
  23630. return (data[1] == 0x58)
  23631. && (*data == (uint8) 0xff);
  23632. }
  23633. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23634. {
  23635. if (isTimeSignatureMetaEvent())
  23636. {
  23637. const uint8* const d = getMetaEventData();
  23638. numerator = d[0];
  23639. denominator = 1 << d[1];
  23640. }
  23641. else
  23642. {
  23643. numerator = 4;
  23644. denominator = 4;
  23645. }
  23646. }
  23647. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23648. {
  23649. uint8 d[8];
  23650. d[0] = 0xff;
  23651. d[1] = 0x58;
  23652. d[2] = 0x04;
  23653. d[3] = (uint8) numerator;
  23654. int n = 1;
  23655. int powerOfTwo = 0;
  23656. while (n < denominator)
  23657. {
  23658. n <<= 1;
  23659. ++powerOfTwo;
  23660. }
  23661. d[4] = (uint8) powerOfTwo;
  23662. d[5] = 0x01;
  23663. d[6] = 96;
  23664. return MidiMessage (d, 7, 0.0);
  23665. }
  23666. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23667. {
  23668. uint8 d[8];
  23669. d[0] = 0xff;
  23670. d[1] = 0x20;
  23671. d[2] = 0x01;
  23672. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23673. return MidiMessage (d, 4, 0.0);
  23674. }
  23675. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23676. {
  23677. return getMetaEventType() == 89;
  23678. }
  23679. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23680. {
  23681. return (int) *getMetaEventData();
  23682. }
  23683. const MidiMessage MidiMessage::endOfTrack() throw()
  23684. {
  23685. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23686. }
  23687. bool MidiMessage::isSongPositionPointer() const throw()
  23688. {
  23689. return *data == 0xf2;
  23690. }
  23691. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23692. {
  23693. return data[1] | (data[2] << 7);
  23694. }
  23695. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23696. {
  23697. return MidiMessage (0xf2,
  23698. positionInMidiBeats & 127,
  23699. (positionInMidiBeats >> 7) & 127);
  23700. }
  23701. bool MidiMessage::isMidiStart() const throw()
  23702. {
  23703. return *data == 0xfa;
  23704. }
  23705. const MidiMessage MidiMessage::midiStart() throw()
  23706. {
  23707. return MidiMessage (0xfa);
  23708. }
  23709. bool MidiMessage::isMidiContinue() const throw()
  23710. {
  23711. return *data == 0xfb;
  23712. }
  23713. const MidiMessage MidiMessage::midiContinue() throw()
  23714. {
  23715. return MidiMessage (0xfb);
  23716. }
  23717. bool MidiMessage::isMidiStop() const throw()
  23718. {
  23719. return *data == 0xfc;
  23720. }
  23721. const MidiMessage MidiMessage::midiStop() throw()
  23722. {
  23723. return MidiMessage (0xfc);
  23724. }
  23725. bool MidiMessage::isMidiClock() const throw()
  23726. {
  23727. return *data == 0xf8;
  23728. }
  23729. const MidiMessage MidiMessage::midiClock() throw()
  23730. {
  23731. return MidiMessage (0xf8);
  23732. }
  23733. bool MidiMessage::isQuarterFrame() const throw()
  23734. {
  23735. return *data == 0xf1;
  23736. }
  23737. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23738. {
  23739. return ((int) data[1]) >> 4;
  23740. }
  23741. int MidiMessage::getQuarterFrameValue() const throw()
  23742. {
  23743. return ((int) data[1]) & 0x0f;
  23744. }
  23745. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23746. const int value) throw()
  23747. {
  23748. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23749. }
  23750. bool MidiMessage::isFullFrame() const throw()
  23751. {
  23752. return data[0] == 0xf0
  23753. && data[1] == 0x7f
  23754. && size >= 10
  23755. && data[3] == 0x01
  23756. && data[4] == 0x01;
  23757. }
  23758. void MidiMessage::getFullFrameParameters (int& hours,
  23759. int& minutes,
  23760. int& seconds,
  23761. int& frames,
  23762. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23763. {
  23764. jassert (isFullFrame());
  23765. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23766. hours = data[5] & 0x1f;
  23767. minutes = data[6];
  23768. seconds = data[7];
  23769. frames = data[8];
  23770. }
  23771. const MidiMessage MidiMessage::fullFrame (const int hours,
  23772. const int minutes,
  23773. const int seconds,
  23774. const int frames,
  23775. MidiMessage::SmpteTimecodeType timecodeType)
  23776. {
  23777. uint8 d[10];
  23778. d[0] = 0xf0;
  23779. d[1] = 0x7f;
  23780. d[2] = 0x7f;
  23781. d[3] = 0x01;
  23782. d[4] = 0x01;
  23783. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23784. d[6] = (uint8) minutes;
  23785. d[7] = (uint8) seconds;
  23786. d[8] = (uint8) frames;
  23787. d[9] = 0xf7;
  23788. return MidiMessage (d, 10, 0.0);
  23789. }
  23790. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23791. {
  23792. return data[0] == 0xf0
  23793. && data[1] == 0x7f
  23794. && data[3] == 0x06
  23795. && size > 5;
  23796. }
  23797. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23798. {
  23799. jassert (isMidiMachineControlMessage());
  23800. return (MidiMachineControlCommand) data[4];
  23801. }
  23802. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23803. {
  23804. uint8 d[6];
  23805. d[0] = 0xf0;
  23806. d[1] = 0x7f;
  23807. d[2] = 0x00;
  23808. d[3] = 0x06;
  23809. d[4] = (uint8) command;
  23810. d[5] = 0xf7;
  23811. return MidiMessage (d, 6, 0.0);
  23812. }
  23813. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23814. int& minutes,
  23815. int& seconds,
  23816. int& frames) const throw()
  23817. {
  23818. if (size >= 12
  23819. && data[0] == 0xf0
  23820. && data[1] == 0x7f
  23821. && data[3] == 0x06
  23822. && data[4] == 0x44
  23823. && data[5] == 0x06
  23824. && data[6] == 0x01)
  23825. {
  23826. hours = data[7] % 24; // (that some machines send out hours > 24)
  23827. minutes = data[8];
  23828. seconds = data[9];
  23829. frames = data[10];
  23830. return true;
  23831. }
  23832. return false;
  23833. }
  23834. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23835. int minutes,
  23836. int seconds,
  23837. int frames)
  23838. {
  23839. uint8 d[12];
  23840. d[0] = 0xf0;
  23841. d[1] = 0x7f;
  23842. d[2] = 0x00;
  23843. d[3] = 0x06;
  23844. d[4] = 0x44;
  23845. d[5] = 0x06;
  23846. d[6] = 0x01;
  23847. d[7] = (uint8) hours;
  23848. d[8] = (uint8) minutes;
  23849. d[9] = (uint8) seconds;
  23850. d[10] = (uint8) frames;
  23851. d[11] = 0xf7;
  23852. return MidiMessage (d, 12, 0.0);
  23853. }
  23854. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23855. {
  23856. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23857. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23858. if (((unsigned int) note) < 128)
  23859. {
  23860. String s (useSharps ? sharpNoteNames [note % 12]
  23861. : flatNoteNames [note % 12]);
  23862. if (includeOctaveNumber)
  23863. s << (note / 12 + (octaveNumForMiddleC - 5));
  23864. return s;
  23865. }
  23866. return String::empty;
  23867. }
  23868. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23869. {
  23870. noteNumber -= 12 * 6 + 9; // now 0 = A
  23871. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23872. }
  23873. const String MidiMessage::getGMInstrumentName (const int n)
  23874. {
  23875. const char* names[] =
  23876. {
  23877. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23878. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23879. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23880. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23881. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23882. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23883. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23884. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23885. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23886. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23887. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23888. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23889. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23890. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23891. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23892. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23893. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23894. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23895. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23896. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23897. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23898. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23899. "Applause", "Gunshot"
  23900. };
  23901. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23902. }
  23903. const String MidiMessage::getGMInstrumentBankName (const int n)
  23904. {
  23905. const char* names[] =
  23906. {
  23907. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23908. "Bass", "Strings", "Ensemble", "Brass",
  23909. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23910. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23911. };
  23912. return (((unsigned int) n) <= 15) ? names[n] : (const char*) 0;
  23913. }
  23914. const String MidiMessage::getRhythmInstrumentName (const int n)
  23915. {
  23916. const char* names[] =
  23917. {
  23918. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23919. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23920. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23921. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23922. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23923. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23924. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23925. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23926. "Mute Triangle", "Open Triangle"
  23927. };
  23928. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23929. }
  23930. const String MidiMessage::getControllerName (const int n)
  23931. {
  23932. const char* names[] =
  23933. {
  23934. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23935. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23936. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23937. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23938. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23939. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23940. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23941. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23942. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23943. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23944. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23945. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23946. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23947. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23948. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23949. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23950. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23951. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23952. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23954. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23955. "Poly Operation"
  23956. };
  23957. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23958. }
  23959. END_JUCE_NAMESPACE
  23960. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23961. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23962. BEGIN_JUCE_NAMESPACE
  23963. MidiMessageCollector::MidiMessageCollector()
  23964. : lastCallbackTime (0),
  23965. sampleRate (44100.0001)
  23966. {
  23967. }
  23968. MidiMessageCollector::~MidiMessageCollector()
  23969. {
  23970. }
  23971. void MidiMessageCollector::reset (const double sampleRate_)
  23972. {
  23973. jassert (sampleRate_ > 0);
  23974. const ScopedLock sl (midiCallbackLock);
  23975. sampleRate = sampleRate_;
  23976. incomingMessages.clear();
  23977. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23978. }
  23979. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23980. {
  23981. // you need to call reset() to set the correct sample rate before using this object
  23982. jassert (sampleRate != 44100.0001);
  23983. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23984. // for details of what the number should be.
  23985. jassert (message.getTimeStamp() != 0);
  23986. const ScopedLock sl (midiCallbackLock);
  23987. const int sampleNumber
  23988. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23989. incomingMessages.addEvent (message, sampleNumber);
  23990. // if the messages don't get used for over a second, we'd better
  23991. // get rid of any old ones to avoid the queue getting too big
  23992. if (sampleNumber > sampleRate)
  23993. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23994. }
  23995. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23996. const int numSamples)
  23997. {
  23998. // you need to call reset() to set the correct sample rate before using this object
  23999. jassert (sampleRate != 44100.0001);
  24000. const double timeNow = Time::getMillisecondCounterHiRes();
  24001. const double msElapsed = timeNow - lastCallbackTime;
  24002. const ScopedLock sl (midiCallbackLock);
  24003. lastCallbackTime = timeNow;
  24004. if (! incomingMessages.isEmpty())
  24005. {
  24006. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  24007. int startSample = 0;
  24008. int scale = 1 << 16;
  24009. const uint8* midiData;
  24010. int numBytes, samplePosition;
  24011. MidiBuffer::Iterator iter (incomingMessages);
  24012. if (numSourceSamples > numSamples)
  24013. {
  24014. // if our list of events is longer than the buffer we're being
  24015. // asked for, scale them down to squeeze them all in..
  24016. const int maxBlockLengthToUse = numSamples << 5;
  24017. if (numSourceSamples > maxBlockLengthToUse)
  24018. {
  24019. startSample = numSourceSamples - maxBlockLengthToUse;
  24020. numSourceSamples = maxBlockLengthToUse;
  24021. iter.setNextSamplePosition (startSample);
  24022. }
  24023. scale = (numSamples << 10) / numSourceSamples;
  24024. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24025. {
  24026. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  24027. destBuffer.addEvent (midiData, numBytes,
  24028. jlimit (0, numSamples - 1, samplePosition));
  24029. }
  24030. }
  24031. else
  24032. {
  24033. // if our event list is shorter than the number we need, put them
  24034. // towards the end of the buffer
  24035. startSample = numSamples - numSourceSamples;
  24036. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24037. {
  24038. destBuffer.addEvent (midiData, numBytes,
  24039. jlimit (0, numSamples - 1, samplePosition + startSample));
  24040. }
  24041. }
  24042. incomingMessages.clear();
  24043. }
  24044. }
  24045. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  24046. {
  24047. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  24048. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24049. addMessageToQueue (m);
  24050. }
  24051. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  24052. {
  24053. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  24054. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24055. addMessageToQueue (m);
  24056. }
  24057. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  24058. {
  24059. addMessageToQueue (message);
  24060. }
  24061. END_JUCE_NAMESPACE
  24062. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  24063. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  24064. BEGIN_JUCE_NAMESPACE
  24065. MidiMessageSequence::MidiMessageSequence()
  24066. {
  24067. }
  24068. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  24069. {
  24070. list.ensureStorageAllocated (other.list.size());
  24071. for (int i = 0; i < other.list.size(); ++i)
  24072. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  24073. }
  24074. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  24075. {
  24076. MidiMessageSequence otherCopy (other);
  24077. swapWith (otherCopy);
  24078. return *this;
  24079. }
  24080. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  24081. {
  24082. list.swapWithArray (other.list);
  24083. }
  24084. MidiMessageSequence::~MidiMessageSequence()
  24085. {
  24086. }
  24087. void MidiMessageSequence::clear()
  24088. {
  24089. list.clear();
  24090. }
  24091. int MidiMessageSequence::getNumEvents() const
  24092. {
  24093. return list.size();
  24094. }
  24095. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  24096. {
  24097. return list [index];
  24098. }
  24099. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  24100. {
  24101. const MidiEventHolder* const meh = list [index];
  24102. if (meh != 0 && meh->noteOffObject != 0)
  24103. return meh->noteOffObject->message.getTimeStamp();
  24104. else
  24105. return 0.0;
  24106. }
  24107. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  24108. {
  24109. const MidiEventHolder* const meh = list [index];
  24110. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  24111. }
  24112. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  24113. {
  24114. return list.indexOf (event);
  24115. }
  24116. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24117. {
  24118. const int numEvents = list.size();
  24119. int i;
  24120. for (i = 0; i < numEvents; ++i)
  24121. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24122. break;
  24123. return i;
  24124. }
  24125. double MidiMessageSequence::getStartTime() const
  24126. {
  24127. if (list.size() > 0)
  24128. return list.getUnchecked(0)->message.getTimeStamp();
  24129. else
  24130. return 0;
  24131. }
  24132. double MidiMessageSequence::getEndTime() const
  24133. {
  24134. if (list.size() > 0)
  24135. return list.getLast()->message.getTimeStamp();
  24136. else
  24137. return 0;
  24138. }
  24139. double MidiMessageSequence::getEventTime (const int index) const
  24140. {
  24141. if (((unsigned int) index) < (unsigned int) list.size())
  24142. return list.getUnchecked (index)->message.getTimeStamp();
  24143. return 0.0;
  24144. }
  24145. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24146. double timeAdjustment)
  24147. {
  24148. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24149. timeAdjustment += newMessage.getTimeStamp();
  24150. newOne->message.setTimeStamp (timeAdjustment);
  24151. int i;
  24152. for (i = list.size(); --i >= 0;)
  24153. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24154. break;
  24155. list.insert (i + 1, newOne);
  24156. }
  24157. void MidiMessageSequence::deleteEvent (const int index,
  24158. const bool deleteMatchingNoteUp)
  24159. {
  24160. if (((unsigned int) index) < (unsigned int) list.size())
  24161. {
  24162. if (deleteMatchingNoteUp)
  24163. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24164. list.remove (index);
  24165. }
  24166. }
  24167. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24168. double timeAdjustment,
  24169. double firstAllowableTime,
  24170. double endOfAllowableDestTimes)
  24171. {
  24172. firstAllowableTime -= timeAdjustment;
  24173. endOfAllowableDestTimes -= timeAdjustment;
  24174. for (int i = 0; i < other.list.size(); ++i)
  24175. {
  24176. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24177. const double t = m.getTimeStamp();
  24178. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24179. {
  24180. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24181. newOne->message.setTimeStamp (timeAdjustment + t);
  24182. list.add (newOne);
  24183. }
  24184. }
  24185. sort();
  24186. }
  24187. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24188. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24189. {
  24190. const double diff = first->message.getTimeStamp()
  24191. - second->message.getTimeStamp();
  24192. return (diff > 0) - (diff < 0);
  24193. }
  24194. void MidiMessageSequence::sort()
  24195. {
  24196. list.sort (*this, true);
  24197. }
  24198. void MidiMessageSequence::updateMatchedPairs()
  24199. {
  24200. for (int i = 0; i < list.size(); ++i)
  24201. {
  24202. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24203. if (m1.isNoteOn())
  24204. {
  24205. list.getUnchecked(i)->noteOffObject = 0;
  24206. const int note = m1.getNoteNumber();
  24207. const int chan = m1.getChannel();
  24208. const int len = list.size();
  24209. for (int j = i + 1; j < len; ++j)
  24210. {
  24211. const MidiMessage& m = list.getUnchecked(j)->message;
  24212. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24213. {
  24214. if (m.isNoteOff())
  24215. {
  24216. list.getUnchecked(i)->noteOffObject = list[j];
  24217. break;
  24218. }
  24219. else if (m.isNoteOn())
  24220. {
  24221. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24222. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24223. list.getUnchecked(i)->noteOffObject = list[j];
  24224. break;
  24225. }
  24226. }
  24227. }
  24228. }
  24229. }
  24230. }
  24231. void MidiMessageSequence::addTimeToMessages (const double delta)
  24232. {
  24233. for (int i = list.size(); --i >= 0;)
  24234. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24235. + delta);
  24236. }
  24237. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24238. MidiMessageSequence& destSequence,
  24239. const bool alsoIncludeMetaEvents) const
  24240. {
  24241. for (int i = 0; i < list.size(); ++i)
  24242. {
  24243. const MidiMessage& mm = list.getUnchecked(i)->message;
  24244. if (mm.isForChannel (channelNumberToExtract)
  24245. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24246. {
  24247. destSequence.addEvent (mm);
  24248. }
  24249. }
  24250. }
  24251. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24252. {
  24253. for (int i = 0; i < list.size(); ++i)
  24254. {
  24255. const MidiMessage& mm = list.getUnchecked(i)->message;
  24256. if (mm.isSysEx())
  24257. destSequence.addEvent (mm);
  24258. }
  24259. }
  24260. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24261. {
  24262. for (int i = list.size(); --i >= 0;)
  24263. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24264. list.remove(i);
  24265. }
  24266. void MidiMessageSequence::deleteSysExMessages()
  24267. {
  24268. for (int i = list.size(); --i >= 0;)
  24269. if (list.getUnchecked(i)->message.isSysEx())
  24270. list.remove(i);
  24271. }
  24272. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24273. const double time,
  24274. OwnedArray<MidiMessage>& dest)
  24275. {
  24276. bool doneProg = false;
  24277. bool donePitchWheel = false;
  24278. Array <int> doneControllers;
  24279. doneControllers.ensureStorageAllocated (32);
  24280. for (int i = list.size(); --i >= 0;)
  24281. {
  24282. const MidiMessage& mm = list.getUnchecked(i)->message;
  24283. if (mm.isForChannel (channelNumber)
  24284. && mm.getTimeStamp() <= time)
  24285. {
  24286. if (mm.isProgramChange())
  24287. {
  24288. if (! doneProg)
  24289. {
  24290. dest.add (new MidiMessage (mm, 0.0));
  24291. doneProg = true;
  24292. }
  24293. }
  24294. else if (mm.isController())
  24295. {
  24296. if (! doneControllers.contains (mm.getControllerNumber()))
  24297. {
  24298. dest.add (new MidiMessage (mm, 0.0));
  24299. doneControllers.add (mm.getControllerNumber());
  24300. }
  24301. }
  24302. else if (mm.isPitchWheel())
  24303. {
  24304. if (! donePitchWheel)
  24305. {
  24306. dest.add (new MidiMessage (mm, 0.0));
  24307. donePitchWheel = true;
  24308. }
  24309. }
  24310. }
  24311. }
  24312. }
  24313. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24314. : message (message_),
  24315. noteOffObject (0)
  24316. {
  24317. }
  24318. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24319. {
  24320. }
  24321. END_JUCE_NAMESPACE
  24322. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24323. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24324. BEGIN_JUCE_NAMESPACE
  24325. AudioPluginFormat::AudioPluginFormat() throw()
  24326. {
  24327. }
  24328. AudioPluginFormat::~AudioPluginFormat()
  24329. {
  24330. }
  24331. END_JUCE_NAMESPACE
  24332. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24333. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24334. BEGIN_JUCE_NAMESPACE
  24335. AudioPluginFormatManager::AudioPluginFormatManager()
  24336. {
  24337. }
  24338. AudioPluginFormatManager::~AudioPluginFormatManager()
  24339. {
  24340. clearSingletonInstance();
  24341. }
  24342. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24343. void AudioPluginFormatManager::addDefaultFormats()
  24344. {
  24345. #if JUCE_DEBUG
  24346. // you should only call this method once!
  24347. for (int i = formats.size(); --i >= 0;)
  24348. {
  24349. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24350. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24351. #endif
  24352. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24353. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24354. #endif
  24355. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24356. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24357. #endif
  24358. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24359. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24360. #endif
  24361. }
  24362. #endif
  24363. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24364. formats.add (new AudioUnitPluginFormat());
  24365. #endif
  24366. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24367. formats.add (new VSTPluginFormat());
  24368. #endif
  24369. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24370. formats.add (new DirectXPluginFormat());
  24371. #endif
  24372. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24373. formats.add (new LADSPAPluginFormat());
  24374. #endif
  24375. }
  24376. int AudioPluginFormatManager::getNumFormats()
  24377. {
  24378. return formats.size();
  24379. }
  24380. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24381. {
  24382. return formats [index];
  24383. }
  24384. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24385. {
  24386. formats.add (format);
  24387. }
  24388. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24389. String& errorMessage) const
  24390. {
  24391. AudioPluginInstance* result = 0;
  24392. for (int i = 0; i < formats.size(); ++i)
  24393. {
  24394. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24395. if (result != 0)
  24396. break;
  24397. }
  24398. if (result == 0)
  24399. {
  24400. if (! doesPluginStillExist (description))
  24401. errorMessage = TRANS ("This plug-in file no longer exists");
  24402. else
  24403. errorMessage = TRANS ("This plug-in failed to load correctly");
  24404. }
  24405. return result;
  24406. }
  24407. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24408. {
  24409. for (int i = 0; i < formats.size(); ++i)
  24410. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24411. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24412. return false;
  24413. }
  24414. END_JUCE_NAMESPACE
  24415. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24416. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24417. #define JUCE_PLUGIN_HOST 1
  24418. BEGIN_JUCE_NAMESPACE
  24419. AudioPluginInstance::AudioPluginInstance()
  24420. {
  24421. }
  24422. AudioPluginInstance::~AudioPluginInstance()
  24423. {
  24424. }
  24425. void* AudioPluginInstance::getPlatformSpecificData()
  24426. {
  24427. return 0;
  24428. }
  24429. END_JUCE_NAMESPACE
  24430. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24431. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24432. BEGIN_JUCE_NAMESPACE
  24433. KnownPluginList::KnownPluginList()
  24434. {
  24435. }
  24436. KnownPluginList::~KnownPluginList()
  24437. {
  24438. }
  24439. void KnownPluginList::clear()
  24440. {
  24441. if (types.size() > 0)
  24442. {
  24443. types.clear();
  24444. sendChangeMessage();
  24445. }
  24446. }
  24447. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24448. {
  24449. for (int i = 0; i < types.size(); ++i)
  24450. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24451. return types.getUnchecked(i);
  24452. return 0;
  24453. }
  24454. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24455. {
  24456. for (int i = 0; i < types.size(); ++i)
  24457. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24458. return types.getUnchecked(i);
  24459. return 0;
  24460. }
  24461. bool KnownPluginList::addType (const PluginDescription& type)
  24462. {
  24463. for (int i = types.size(); --i >= 0;)
  24464. {
  24465. if (types.getUnchecked(i)->isDuplicateOf (type))
  24466. {
  24467. // strange - found a duplicate plugin with different info..
  24468. jassert (types.getUnchecked(i)->name == type.name);
  24469. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24470. *types.getUnchecked(i) = type;
  24471. return false;
  24472. }
  24473. }
  24474. types.add (new PluginDescription (type));
  24475. sendChangeMessage();
  24476. return true;
  24477. }
  24478. void KnownPluginList::removeType (const int index)
  24479. {
  24480. types.remove (index);
  24481. sendChangeMessage();
  24482. }
  24483. namespace
  24484. {
  24485. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24486. {
  24487. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24488. return File (fileOrIdentifier).getLastModificationTime();
  24489. return Time (0);
  24490. }
  24491. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24492. {
  24493. return t1 != t2 || t1 == Time (0);
  24494. }
  24495. }
  24496. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24497. {
  24498. if (getTypeForFile (fileOrIdentifier) == 0)
  24499. return false;
  24500. for (int i = types.size(); --i >= 0;)
  24501. {
  24502. const PluginDescription* const d = types.getUnchecked(i);
  24503. if (d->fileOrIdentifier == fileOrIdentifier
  24504. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24505. {
  24506. return false;
  24507. }
  24508. }
  24509. return true;
  24510. }
  24511. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24512. const bool dontRescanIfAlreadyInList,
  24513. OwnedArray <PluginDescription>& typesFound,
  24514. AudioPluginFormat& format)
  24515. {
  24516. bool addedOne = false;
  24517. if (dontRescanIfAlreadyInList
  24518. && getTypeForFile (fileOrIdentifier) != 0)
  24519. {
  24520. bool needsRescanning = false;
  24521. for (int i = types.size(); --i >= 0;)
  24522. {
  24523. const PluginDescription* const d = types.getUnchecked(i);
  24524. if (d->fileOrIdentifier == fileOrIdentifier)
  24525. {
  24526. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24527. needsRescanning = true;
  24528. else
  24529. typesFound.add (new PluginDescription (*d));
  24530. }
  24531. }
  24532. if (! needsRescanning)
  24533. return false;
  24534. }
  24535. OwnedArray <PluginDescription> found;
  24536. format.findAllTypesForFile (found, fileOrIdentifier);
  24537. for (int i = 0; i < found.size(); ++i)
  24538. {
  24539. PluginDescription* const desc = found.getUnchecked(i);
  24540. jassert (desc != 0);
  24541. if (addType (*desc))
  24542. addedOne = true;
  24543. typesFound.add (new PluginDescription (*desc));
  24544. }
  24545. return addedOne;
  24546. }
  24547. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24548. OwnedArray <PluginDescription>& typesFound)
  24549. {
  24550. for (int i = 0; i < files.size(); ++i)
  24551. {
  24552. bool loaded = false;
  24553. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24554. {
  24555. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24556. if (scanAndAddFile (files[i], true, typesFound, *format))
  24557. loaded = true;
  24558. }
  24559. if (! loaded)
  24560. {
  24561. const File f (files[i]);
  24562. if (f.isDirectory())
  24563. {
  24564. StringArray s;
  24565. {
  24566. Array<File> subFiles;
  24567. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24568. for (int j = 0; j < subFiles.size(); ++j)
  24569. s.add (subFiles.getReference(j).getFullPathName());
  24570. }
  24571. scanAndAddDragAndDroppedFiles (s, typesFound);
  24572. }
  24573. }
  24574. }
  24575. }
  24576. class PluginSorter
  24577. {
  24578. public:
  24579. KnownPluginList::SortMethod method;
  24580. PluginSorter() throw() {}
  24581. int compareElements (const PluginDescription* const first,
  24582. const PluginDescription* const second) const
  24583. {
  24584. int diff = 0;
  24585. if (method == KnownPluginList::sortByCategory)
  24586. diff = first->category.compareLexicographically (second->category);
  24587. else if (method == KnownPluginList::sortByManufacturer)
  24588. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24589. else if (method == KnownPluginList::sortByFileSystemLocation)
  24590. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24591. .upToLastOccurrenceOf ("/", false, false)
  24592. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24593. .upToLastOccurrenceOf ("/", false, false));
  24594. if (diff == 0)
  24595. diff = first->name.compareLexicographically (second->name);
  24596. return diff;
  24597. }
  24598. };
  24599. void KnownPluginList::sort (const SortMethod method)
  24600. {
  24601. if (method != defaultOrder)
  24602. {
  24603. PluginSorter sorter;
  24604. sorter.method = method;
  24605. types.sort (sorter, true);
  24606. sendChangeMessage();
  24607. }
  24608. }
  24609. XmlElement* KnownPluginList::createXml() const
  24610. {
  24611. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24612. for (int i = 0; i < types.size(); ++i)
  24613. e->addChildElement (types.getUnchecked(i)->createXml());
  24614. return e;
  24615. }
  24616. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24617. {
  24618. clear();
  24619. if (xml.hasTagName ("KNOWNPLUGINS"))
  24620. {
  24621. forEachXmlChildElement (xml, e)
  24622. {
  24623. PluginDescription info;
  24624. if (info.loadFromXml (*e))
  24625. addType (info);
  24626. }
  24627. }
  24628. }
  24629. const int menuIdBase = 0x324503f4;
  24630. // This is used to turn a bunch of paths into a nested menu structure.
  24631. struct PluginFilesystemTree
  24632. {
  24633. private:
  24634. String folder;
  24635. OwnedArray <PluginFilesystemTree> subFolders;
  24636. Array <PluginDescription*> plugins;
  24637. void addPlugin (PluginDescription* const pd, const String& path)
  24638. {
  24639. if (path.isEmpty())
  24640. {
  24641. plugins.add (pd);
  24642. }
  24643. else
  24644. {
  24645. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24646. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24647. for (int i = subFolders.size(); --i >= 0;)
  24648. {
  24649. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24650. {
  24651. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24652. return;
  24653. }
  24654. }
  24655. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24656. newFolder->folder = firstSubFolder;
  24657. subFolders.add (newFolder);
  24658. newFolder->addPlugin (pd, remainingPath);
  24659. }
  24660. }
  24661. // removes any deeply nested folders that don't contain any actual plugins
  24662. void optimise()
  24663. {
  24664. for (int i = subFolders.size(); --i >= 0;)
  24665. {
  24666. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24667. sub->optimise();
  24668. if (sub->plugins.size() == 0)
  24669. {
  24670. for (int j = 0; j < sub->subFolders.size(); ++j)
  24671. subFolders.add (sub->subFolders.getUnchecked(j));
  24672. sub->subFolders.clear (false);
  24673. subFolders.remove (i);
  24674. }
  24675. }
  24676. }
  24677. public:
  24678. void buildTree (const Array <PluginDescription*>& allPlugins)
  24679. {
  24680. for (int i = 0; i < allPlugins.size(); ++i)
  24681. {
  24682. String path (allPlugins.getUnchecked(i)
  24683. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24684. .upToLastOccurrenceOf ("/", false, false));
  24685. if (path.substring (1, 2) == ":")
  24686. path = path.substring (2);
  24687. addPlugin (allPlugins.getUnchecked(i), path);
  24688. }
  24689. optimise();
  24690. }
  24691. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24692. {
  24693. int i;
  24694. for (i = 0; i < subFolders.size(); ++i)
  24695. {
  24696. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24697. PopupMenu subMenu;
  24698. sub->addToMenu (subMenu, allPlugins);
  24699. #if JUCE_MAC
  24700. // avoid the special AU formatting nonsense on Mac..
  24701. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24702. #else
  24703. m.addSubMenu (sub->folder, subMenu);
  24704. #endif
  24705. }
  24706. for (i = 0; i < plugins.size(); ++i)
  24707. {
  24708. PluginDescription* const plugin = plugins.getUnchecked(i);
  24709. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24710. plugin->name, true, false);
  24711. }
  24712. }
  24713. };
  24714. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24715. {
  24716. Array <PluginDescription*> sorted;
  24717. {
  24718. PluginSorter sorter;
  24719. sorter.method = sortMethod;
  24720. for (int i = 0; i < types.size(); ++i)
  24721. sorted.addSorted (sorter, types.getUnchecked(i));
  24722. }
  24723. if (sortMethod == sortByCategory
  24724. || sortMethod == sortByManufacturer)
  24725. {
  24726. String lastSubMenuName;
  24727. PopupMenu sub;
  24728. for (int i = 0; i < sorted.size(); ++i)
  24729. {
  24730. const PluginDescription* const pd = sorted.getUnchecked(i);
  24731. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24732. : pd->manufacturerName);
  24733. if (! thisSubMenuName.containsNonWhitespaceChars())
  24734. thisSubMenuName = "Other";
  24735. if (thisSubMenuName != lastSubMenuName)
  24736. {
  24737. if (sub.getNumItems() > 0)
  24738. {
  24739. menu.addSubMenu (lastSubMenuName, sub);
  24740. sub.clear();
  24741. }
  24742. lastSubMenuName = thisSubMenuName;
  24743. }
  24744. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24745. }
  24746. if (sub.getNumItems() > 0)
  24747. menu.addSubMenu (lastSubMenuName, sub);
  24748. }
  24749. else if (sortMethod == sortByFileSystemLocation)
  24750. {
  24751. PluginFilesystemTree root;
  24752. root.buildTree (sorted);
  24753. root.addToMenu (menu, types);
  24754. }
  24755. else
  24756. {
  24757. for (int i = 0; i < sorted.size(); ++i)
  24758. {
  24759. const PluginDescription* const pd = sorted.getUnchecked(i);
  24760. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24761. }
  24762. }
  24763. }
  24764. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24765. {
  24766. const int i = menuResultCode - menuIdBase;
  24767. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24768. }
  24769. END_JUCE_NAMESPACE
  24770. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24771. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24772. BEGIN_JUCE_NAMESPACE
  24773. PluginDescription::PluginDescription()
  24774. : uid (0),
  24775. isInstrument (false),
  24776. numInputChannels (0),
  24777. numOutputChannels (0)
  24778. {
  24779. }
  24780. PluginDescription::~PluginDescription()
  24781. {
  24782. }
  24783. PluginDescription::PluginDescription (const PluginDescription& other)
  24784. : name (other.name),
  24785. pluginFormatName (other.pluginFormatName),
  24786. category (other.category),
  24787. manufacturerName (other.manufacturerName),
  24788. version (other.version),
  24789. fileOrIdentifier (other.fileOrIdentifier),
  24790. lastFileModTime (other.lastFileModTime),
  24791. uid (other.uid),
  24792. isInstrument (other.isInstrument),
  24793. numInputChannels (other.numInputChannels),
  24794. numOutputChannels (other.numOutputChannels)
  24795. {
  24796. }
  24797. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24798. {
  24799. name = other.name;
  24800. pluginFormatName = other.pluginFormatName;
  24801. category = other.category;
  24802. manufacturerName = other.manufacturerName;
  24803. version = other.version;
  24804. fileOrIdentifier = other.fileOrIdentifier;
  24805. uid = other.uid;
  24806. isInstrument = other.isInstrument;
  24807. lastFileModTime = other.lastFileModTime;
  24808. numInputChannels = other.numInputChannels;
  24809. numOutputChannels = other.numOutputChannels;
  24810. return *this;
  24811. }
  24812. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24813. {
  24814. return fileOrIdentifier == other.fileOrIdentifier
  24815. && uid == other.uid;
  24816. }
  24817. const String PluginDescription::createIdentifierString() const
  24818. {
  24819. return pluginFormatName
  24820. + "-" + name
  24821. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24822. + "-" + String::toHexString (uid);
  24823. }
  24824. XmlElement* PluginDescription::createXml() const
  24825. {
  24826. XmlElement* const e = new XmlElement ("PLUGIN");
  24827. e->setAttribute ("name", name);
  24828. e->setAttribute ("format", pluginFormatName);
  24829. e->setAttribute ("category", category);
  24830. e->setAttribute ("manufacturer", manufacturerName);
  24831. e->setAttribute ("version", version);
  24832. e->setAttribute ("file", fileOrIdentifier);
  24833. e->setAttribute ("uid", String::toHexString (uid));
  24834. e->setAttribute ("isInstrument", isInstrument);
  24835. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24836. e->setAttribute ("numInputs", numInputChannels);
  24837. e->setAttribute ("numOutputs", numOutputChannels);
  24838. return e;
  24839. }
  24840. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24841. {
  24842. if (xml.hasTagName ("PLUGIN"))
  24843. {
  24844. name = xml.getStringAttribute ("name");
  24845. pluginFormatName = xml.getStringAttribute ("format");
  24846. category = xml.getStringAttribute ("category");
  24847. manufacturerName = xml.getStringAttribute ("manufacturer");
  24848. version = xml.getStringAttribute ("version");
  24849. fileOrIdentifier = xml.getStringAttribute ("file");
  24850. uid = xml.getStringAttribute ("uid").getHexValue32();
  24851. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24852. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24853. numInputChannels = xml.getIntAttribute ("numInputs");
  24854. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24855. return true;
  24856. }
  24857. return false;
  24858. }
  24859. END_JUCE_NAMESPACE
  24860. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24861. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24862. BEGIN_JUCE_NAMESPACE
  24863. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24864. AudioPluginFormat& formatToLookFor,
  24865. FileSearchPath directoriesToSearch,
  24866. const bool recursive,
  24867. const File& deadMansPedalFile_)
  24868. : list (listToAddTo),
  24869. format (formatToLookFor),
  24870. deadMansPedalFile (deadMansPedalFile_),
  24871. nextIndex (0),
  24872. progress (0)
  24873. {
  24874. directoriesToSearch.removeRedundantPaths();
  24875. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24876. // If any plugins have crashed recently when being loaded, move them to the
  24877. // end of the list to give the others a chance to load correctly..
  24878. const StringArray crashedPlugins (getDeadMansPedalFile());
  24879. for (int i = 0; i < crashedPlugins.size(); ++i)
  24880. {
  24881. const String f = crashedPlugins[i];
  24882. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24883. if (f == filesOrIdentifiersToScan[j])
  24884. filesOrIdentifiersToScan.move (j, -1);
  24885. }
  24886. }
  24887. PluginDirectoryScanner::~PluginDirectoryScanner()
  24888. {
  24889. }
  24890. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24891. {
  24892. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24893. }
  24894. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24895. {
  24896. String file (filesOrIdentifiersToScan [nextIndex]);
  24897. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24898. {
  24899. OwnedArray <PluginDescription> typesFound;
  24900. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24901. StringArray crashedPlugins (getDeadMansPedalFile());
  24902. crashedPlugins.removeString (file);
  24903. crashedPlugins.add (file);
  24904. setDeadMansPedalFile (crashedPlugins);
  24905. list.scanAndAddFile (file,
  24906. dontRescanIfAlreadyInList,
  24907. typesFound,
  24908. format);
  24909. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24910. crashedPlugins.removeString (file);
  24911. setDeadMansPedalFile (crashedPlugins);
  24912. if (typesFound.size() == 0)
  24913. failedFiles.add (file);
  24914. }
  24915. return skipNextFile();
  24916. }
  24917. bool PluginDirectoryScanner::skipNextFile()
  24918. {
  24919. if (nextIndex >= filesOrIdentifiersToScan.size())
  24920. return false;
  24921. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24922. return nextIndex < filesOrIdentifiersToScan.size();
  24923. }
  24924. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24925. {
  24926. StringArray lines;
  24927. if (deadMansPedalFile != File::nonexistent)
  24928. {
  24929. lines.addLines (deadMansPedalFile.loadFileAsString());
  24930. lines.removeEmptyStrings();
  24931. }
  24932. return lines;
  24933. }
  24934. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24935. {
  24936. if (deadMansPedalFile != File::nonexistent)
  24937. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24938. }
  24939. END_JUCE_NAMESPACE
  24940. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24941. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24942. BEGIN_JUCE_NAMESPACE
  24943. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24944. const File& deadMansPedalFile_,
  24945. PropertiesFile* const propertiesToUse_)
  24946. : list (listToEdit),
  24947. deadMansPedalFile (deadMansPedalFile_),
  24948. optionsButton ("Options..."),
  24949. propertiesToUse (propertiesToUse_)
  24950. {
  24951. listBox.setModel (this);
  24952. addAndMakeVisible (&listBox);
  24953. addAndMakeVisible (&optionsButton);
  24954. optionsButton.addButtonListener (this);
  24955. optionsButton.setTriggeredOnMouseDown (true);
  24956. setSize (400, 600);
  24957. list.addChangeListener (this);
  24958. changeListenerCallback (0);
  24959. }
  24960. PluginListComponent::~PluginListComponent()
  24961. {
  24962. list.removeChangeListener (this);
  24963. }
  24964. void PluginListComponent::resized()
  24965. {
  24966. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24967. optionsButton.changeWidthToFitText (24);
  24968. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24969. }
  24970. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24971. {
  24972. listBox.updateContent();
  24973. listBox.repaint();
  24974. }
  24975. int PluginListComponent::getNumRows()
  24976. {
  24977. return list.getNumTypes();
  24978. }
  24979. void PluginListComponent::paintListBoxItem (int row,
  24980. Graphics& g,
  24981. int width, int height,
  24982. bool rowIsSelected)
  24983. {
  24984. if (rowIsSelected)
  24985. g.fillAll (findColour (TextEditor::highlightColourId));
  24986. const PluginDescription* const pd = list.getType (row);
  24987. if (pd != 0)
  24988. {
  24989. GlyphArrangement ga;
  24990. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24991. g.setColour (Colours::black);
  24992. ga.draw (g);
  24993. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24994. String desc;
  24995. desc << pd->pluginFormatName
  24996. << (pd->isInstrument ? " instrument" : " effect")
  24997. << " - "
  24998. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24999. << " / "
  25000. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  25001. if (pd->manufacturerName.isNotEmpty())
  25002. desc << " - " << pd->manufacturerName;
  25003. if (pd->version.isNotEmpty())
  25004. desc << " - " << pd->version;
  25005. if (pd->category.isNotEmpty())
  25006. desc << " - category: '" << pd->category << '\'';
  25007. g.setColour (Colours::grey);
  25008. ga.clear();
  25009. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  25010. ga.draw (g);
  25011. }
  25012. }
  25013. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  25014. {
  25015. list.removeType (lastRowSelected);
  25016. }
  25017. void PluginListComponent::buttonClicked (Button* button)
  25018. {
  25019. if (button == &optionsButton)
  25020. {
  25021. PopupMenu menu;
  25022. menu.addItem (1, TRANS("Clear list"));
  25023. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  25024. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  25025. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  25026. menu.addSeparator();
  25027. menu.addItem (2, TRANS("Sort alphabetically"));
  25028. menu.addItem (3, TRANS("Sort by category"));
  25029. menu.addItem (4, TRANS("Sort by manufacturer"));
  25030. menu.addSeparator();
  25031. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  25032. {
  25033. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  25034. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  25035. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  25036. }
  25037. const int r = menu.showAt (&optionsButton);
  25038. if (r == 1)
  25039. {
  25040. list.clear();
  25041. }
  25042. else if (r == 2)
  25043. {
  25044. list.sort (KnownPluginList::sortAlphabetically);
  25045. }
  25046. else if (r == 3)
  25047. {
  25048. list.sort (KnownPluginList::sortByCategory);
  25049. }
  25050. else if (r == 4)
  25051. {
  25052. list.sort (KnownPluginList::sortByManufacturer);
  25053. }
  25054. else if (r == 5)
  25055. {
  25056. const SparseSet <int> selected (listBox.getSelectedRows());
  25057. for (int i = list.getNumTypes(); --i >= 0;)
  25058. if (selected.contains (i))
  25059. list.removeType (i);
  25060. }
  25061. else if (r == 6)
  25062. {
  25063. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  25064. if (desc != 0)
  25065. {
  25066. if (File (desc->fileOrIdentifier).existsAsFile())
  25067. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  25068. }
  25069. }
  25070. else if (r == 7)
  25071. {
  25072. for (int i = list.getNumTypes(); --i >= 0;)
  25073. {
  25074. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  25075. {
  25076. list.removeType (i);
  25077. }
  25078. }
  25079. }
  25080. else if (r != 0)
  25081. {
  25082. typeToScan = r - 10;
  25083. startTimer (1);
  25084. }
  25085. }
  25086. }
  25087. void PluginListComponent::timerCallback()
  25088. {
  25089. stopTimer();
  25090. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  25091. }
  25092. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  25093. {
  25094. return true;
  25095. }
  25096. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  25097. {
  25098. OwnedArray <PluginDescription> typesFound;
  25099. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  25100. }
  25101. void PluginListComponent::scanFor (AudioPluginFormat* format)
  25102. {
  25103. if (format == 0)
  25104. return;
  25105. FileSearchPath path (format->getDefaultLocationsToSearch());
  25106. if (propertiesToUse != 0)
  25107. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25108. {
  25109. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  25110. FileSearchPathListComponent pathList;
  25111. pathList.setSize (500, 300);
  25112. pathList.setPath (path);
  25113. aw.addCustomComponent (&pathList);
  25114. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  25115. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25116. if (aw.runModalLoop() == 0)
  25117. return;
  25118. path = pathList.getPath();
  25119. }
  25120. if (propertiesToUse != 0)
  25121. {
  25122. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25123. propertiesToUse->saveIfNeeded();
  25124. }
  25125. double progress = 0.0;
  25126. AlertWindow aw (TRANS("Scanning for plugins..."),
  25127. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25128. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25129. aw.addProgressBarComponent (progress);
  25130. aw.enterModalState();
  25131. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25132. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25133. for (;;)
  25134. {
  25135. aw.setMessage (TRANS("Testing:\n\n")
  25136. + scanner.getNextPluginFileThatWillBeScanned());
  25137. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25138. if (! scanner.scanNextFile (true))
  25139. break;
  25140. if (! aw.isCurrentlyModal())
  25141. break;
  25142. progress = scanner.getProgress();
  25143. }
  25144. if (scanner.getFailedFiles().size() > 0)
  25145. {
  25146. StringArray shortNames;
  25147. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25148. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25149. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25150. TRANS("Scan complete"),
  25151. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25152. + shortNames.joinIntoString (", "));
  25153. }
  25154. }
  25155. END_JUCE_NAMESPACE
  25156. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25157. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25158. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25159. #include <AudioUnit/AudioUnit.h>
  25160. #include <AudioUnit/AUCocoaUIView.h>
  25161. #include <CoreAudioKit/AUGenericView.h>
  25162. #if JUCE_SUPPORT_CARBON
  25163. #include <AudioToolbox/AudioUnitUtilities.h>
  25164. #include <AudioUnit/AudioUnitCarbonView.h>
  25165. #endif
  25166. BEGIN_JUCE_NAMESPACE
  25167. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25168. #endif
  25169. #if JUCE_MAC
  25170. // Change this to disable logging of various activities
  25171. #ifndef AU_LOGGING
  25172. #define AU_LOGGING 1
  25173. #endif
  25174. #if AU_LOGGING
  25175. #define log(a) Logger::writeToLog(a);
  25176. #else
  25177. #define log(a)
  25178. #endif
  25179. namespace AudioUnitFormatHelpers
  25180. {
  25181. static int insideCallback = 0;
  25182. static const String osTypeToString (OSType type)
  25183. {
  25184. char s[4];
  25185. s[0] = (char) (((uint32) type) >> 24);
  25186. s[1] = (char) (((uint32) type) >> 16);
  25187. s[2] = (char) (((uint32) type) >> 8);
  25188. s[3] = (char) ((uint32) type);
  25189. return String (s, 4);
  25190. }
  25191. static OSType stringToOSType (const String& s1)
  25192. {
  25193. const String s (s1 + " ");
  25194. return (((OSType) (unsigned char) s[0]) << 24)
  25195. | (((OSType) (unsigned char) s[1]) << 16)
  25196. | (((OSType) (unsigned char) s[2]) << 8)
  25197. | ((OSType) (unsigned char) s[3]);
  25198. }
  25199. static const char* auIdentifierPrefix = "AudioUnit:";
  25200. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  25201. {
  25202. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25203. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25204. String s (auIdentifierPrefix);
  25205. if (desc.componentType == kAudioUnitType_MusicDevice)
  25206. s << "Synths/";
  25207. else if (desc.componentType == kAudioUnitType_MusicEffect
  25208. || desc.componentType == kAudioUnitType_Effect)
  25209. s << "Effects/";
  25210. else if (desc.componentType == kAudioUnitType_Generator)
  25211. s << "Generators/";
  25212. else if (desc.componentType == kAudioUnitType_Panner)
  25213. s << "Panners/";
  25214. s << osTypeToString (desc.componentType) << ","
  25215. << osTypeToString (desc.componentSubType) << ","
  25216. << osTypeToString (desc.componentManufacturer);
  25217. return s;
  25218. }
  25219. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25220. {
  25221. Handle componentNameHandle = NewHandle (sizeof (void*));
  25222. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25223. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25224. {
  25225. ComponentDescription desc;
  25226. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25227. {
  25228. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25229. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25230. if (nameString != 0 && nameString[0] != 0)
  25231. {
  25232. const String all ((const char*) nameString + 1, nameString[0]);
  25233. DBG ("name: "+ all);
  25234. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25235. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25236. }
  25237. if (infoString != 0 && infoString[0] != 0)
  25238. {
  25239. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25240. }
  25241. if (name.isEmpty())
  25242. name = "<Unknown>";
  25243. }
  25244. DisposeHandle (componentNameHandle);
  25245. DisposeHandle (componentInfoHandle);
  25246. }
  25247. }
  25248. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25249. String& name, String& version, String& manufacturer)
  25250. {
  25251. zerostruct (desc);
  25252. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25253. {
  25254. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25255. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25256. StringArray tokens;
  25257. tokens.addTokens (s, ",", String::empty);
  25258. tokens.trim();
  25259. tokens.removeEmptyStrings();
  25260. if (tokens.size() == 3)
  25261. {
  25262. desc.componentType = stringToOSType (tokens[0]);
  25263. desc.componentSubType = stringToOSType (tokens[1]);
  25264. desc.componentManufacturer = stringToOSType (tokens[2]);
  25265. ComponentRecord* comp = FindNextComponent (0, &desc);
  25266. if (comp != 0)
  25267. {
  25268. getAUDetails (comp, name, manufacturer);
  25269. return true;
  25270. }
  25271. }
  25272. }
  25273. return false;
  25274. }
  25275. }
  25276. class AudioUnitPluginWindowCarbon;
  25277. class AudioUnitPluginWindowCocoa;
  25278. class AudioUnitPluginInstance : public AudioPluginInstance
  25279. {
  25280. public:
  25281. ~AudioUnitPluginInstance();
  25282. void initialise();
  25283. // AudioPluginInstance methods:
  25284. void fillInPluginDescription (PluginDescription& desc) const
  25285. {
  25286. desc.name = pluginName;
  25287. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25288. desc.uid = ((int) componentDesc.componentType)
  25289. ^ ((int) componentDesc.componentSubType)
  25290. ^ ((int) componentDesc.componentManufacturer);
  25291. desc.lastFileModTime = 0;
  25292. desc.pluginFormatName = "AudioUnit";
  25293. desc.category = getCategory();
  25294. desc.manufacturerName = manufacturer;
  25295. desc.version = version;
  25296. desc.numInputChannels = getNumInputChannels();
  25297. desc.numOutputChannels = getNumOutputChannels();
  25298. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25299. }
  25300. void* getPlatformSpecificData() { return audioUnit; }
  25301. const String getName() const { return pluginName; }
  25302. bool acceptsMidi() const { return wantsMidiMessages; }
  25303. bool producesMidi() const { return false; }
  25304. // AudioProcessor methods:
  25305. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25306. void releaseResources();
  25307. void processBlock (AudioSampleBuffer& buffer,
  25308. MidiBuffer& midiMessages);
  25309. bool hasEditor() const;
  25310. AudioProcessorEditor* createEditor();
  25311. const String getInputChannelName (int index) const;
  25312. bool isInputChannelStereoPair (int index) const;
  25313. const String getOutputChannelName (int index) const;
  25314. bool isOutputChannelStereoPair (int index) const;
  25315. int getNumParameters();
  25316. float getParameter (int index);
  25317. void setParameter (int index, float newValue);
  25318. const String getParameterName (int index);
  25319. const String getParameterText (int index);
  25320. bool isParameterAutomatable (int index) const;
  25321. int getNumPrograms();
  25322. int getCurrentProgram();
  25323. void setCurrentProgram (int index);
  25324. const String getProgramName (int index);
  25325. void changeProgramName (int index, const String& newName);
  25326. void getStateInformation (MemoryBlock& destData);
  25327. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25328. void setStateInformation (const void* data, int sizeInBytes);
  25329. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25330. juce_UseDebuggingNewOperator
  25331. private:
  25332. friend class AudioUnitPluginWindowCarbon;
  25333. friend class AudioUnitPluginWindowCocoa;
  25334. friend class AudioUnitPluginFormat;
  25335. ComponentDescription componentDesc;
  25336. String pluginName, manufacturer, version;
  25337. String fileOrIdentifier;
  25338. CriticalSection lock;
  25339. bool wantsMidiMessages, wasPlaying, prepared;
  25340. HeapBlock <AudioBufferList> outputBufferList;
  25341. AudioTimeStamp timeStamp;
  25342. AudioSampleBuffer* currentBuffer;
  25343. AudioUnit audioUnit;
  25344. Array <int> parameterIds;
  25345. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25346. void setPluginCallbacks();
  25347. void getParameterListFromPlugin();
  25348. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25349. const AudioTimeStamp* inTimeStamp,
  25350. UInt32 inBusNumber,
  25351. UInt32 inNumberFrames,
  25352. AudioBufferList* ioData) const;
  25353. static OSStatus renderGetInputCallback (void* inRefCon,
  25354. AudioUnitRenderActionFlags* ioActionFlags,
  25355. const AudioTimeStamp* inTimeStamp,
  25356. UInt32 inBusNumber,
  25357. UInt32 inNumberFrames,
  25358. AudioBufferList* ioData)
  25359. {
  25360. return ((AudioUnitPluginInstance*) inRefCon)
  25361. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25362. }
  25363. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25364. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25365. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25366. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25367. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25368. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25369. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25370. {
  25371. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25372. }
  25373. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25374. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25375. Float64* outCurrentMeasureDownBeat)
  25376. {
  25377. return ((AudioUnitPluginInstance*) inHostUserData)
  25378. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25379. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25380. }
  25381. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25382. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25383. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25384. {
  25385. return ((AudioUnitPluginInstance*) inHostUserData)
  25386. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25387. outCurrentSampleInTimeLine, outIsCycling,
  25388. outCycleStartBeat, outCycleEndBeat);
  25389. }
  25390. void getNumChannels (int& numIns, int& numOuts)
  25391. {
  25392. numIns = 0;
  25393. numOuts = 0;
  25394. AUChannelInfo supportedChannels [128];
  25395. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25396. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25397. 0, supportedChannels, &supportedChannelsSize) == noErr
  25398. && supportedChannelsSize > 0)
  25399. {
  25400. int explicitNumIns = 0;
  25401. int explicitNumOuts = 0;
  25402. int maximumNumIns = 0;
  25403. int maximumNumOuts = 0;
  25404. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25405. {
  25406. const int inChannels = (int) supportedChannels[i].inChannels;
  25407. const int outChannels = (int) supportedChannels[i].outChannels;
  25408. if (inChannels < 0)
  25409. maximumNumIns = jmin (maximumNumIns, inChannels);
  25410. else
  25411. explicitNumIns = jmax (explicitNumIns, inChannels);
  25412. if (outChannels < 0)
  25413. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25414. else
  25415. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25416. }
  25417. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25418. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25419. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25420. {
  25421. numIns = numOuts = 2;
  25422. }
  25423. else
  25424. {
  25425. numIns = explicitNumIns;
  25426. numOuts = explicitNumOuts;
  25427. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25428. numIns = 2;
  25429. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25430. numOuts = 2;
  25431. }
  25432. }
  25433. else
  25434. {
  25435. // (this really means the plugin will take any number of ins/outs as long
  25436. // as they are the same)
  25437. numIns = numOuts = 2;
  25438. }
  25439. }
  25440. const String getCategory() const;
  25441. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25442. };
  25443. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25444. : fileOrIdentifier (fileOrIdentifier),
  25445. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25446. audioUnit (0),
  25447. currentBuffer (0)
  25448. {
  25449. using namespace AudioUnitFormatHelpers;
  25450. try
  25451. {
  25452. ++insideCallback;
  25453. log ("Opening AU: " + fileOrIdentifier);
  25454. if (getComponentDescFromFile (fileOrIdentifier))
  25455. {
  25456. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25457. if (comp != 0)
  25458. {
  25459. audioUnit = (AudioUnit) OpenComponent (comp);
  25460. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25461. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25462. }
  25463. }
  25464. --insideCallback;
  25465. }
  25466. catch (...)
  25467. {
  25468. --insideCallback;
  25469. }
  25470. }
  25471. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25472. {
  25473. const ScopedLock sl (lock);
  25474. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25475. if (audioUnit != 0)
  25476. {
  25477. AudioUnitUninitialize (audioUnit);
  25478. CloseComponent (audioUnit);
  25479. audioUnit = 0;
  25480. }
  25481. }
  25482. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25483. {
  25484. zerostruct (componentDesc);
  25485. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25486. return true;
  25487. const File file (fileOrIdentifier);
  25488. if (! file.hasFileExtension (".component"))
  25489. return false;
  25490. const char* const utf8 = fileOrIdentifier.toUTF8();
  25491. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25492. strlen (utf8), file.isDirectory());
  25493. if (url != 0)
  25494. {
  25495. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25496. CFRelease (url);
  25497. if (bundleRef != 0)
  25498. {
  25499. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25500. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25501. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25502. if (pluginName.isEmpty())
  25503. pluginName = file.getFileNameWithoutExtension();
  25504. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25505. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25506. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25507. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25508. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25509. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25510. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25511. UseResFile (resFileId);
  25512. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25513. {
  25514. Handle h = Get1IndResource ('thng', i);
  25515. if (h != 0)
  25516. {
  25517. HLock (h);
  25518. const uint32* const types = (const uint32*) *h;
  25519. if (types[0] == kAudioUnitType_MusicDevice
  25520. || types[0] == kAudioUnitType_MusicEffect
  25521. || types[0] == kAudioUnitType_Effect
  25522. || types[0] == kAudioUnitType_Generator
  25523. || types[0] == kAudioUnitType_Panner)
  25524. {
  25525. componentDesc.componentType = types[0];
  25526. componentDesc.componentSubType = types[1];
  25527. componentDesc.componentManufacturer = types[2];
  25528. break;
  25529. }
  25530. HUnlock (h);
  25531. ReleaseResource (h);
  25532. }
  25533. }
  25534. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25535. CFRelease (bundleRef);
  25536. }
  25537. }
  25538. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25539. }
  25540. void AudioUnitPluginInstance::initialise()
  25541. {
  25542. getParameterListFromPlugin();
  25543. setPluginCallbacks();
  25544. int numIns, numOuts;
  25545. getNumChannels (numIns, numOuts);
  25546. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25547. setLatencySamples (0);
  25548. }
  25549. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25550. {
  25551. parameterIds.clear();
  25552. if (audioUnit != 0)
  25553. {
  25554. UInt32 paramListSize = 0;
  25555. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25556. 0, 0, &paramListSize);
  25557. if (paramListSize > 0)
  25558. {
  25559. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25560. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25561. 0, &parameterIds.getReference(0), &paramListSize);
  25562. }
  25563. }
  25564. }
  25565. void AudioUnitPluginInstance::setPluginCallbacks()
  25566. {
  25567. if (audioUnit != 0)
  25568. {
  25569. {
  25570. AURenderCallbackStruct info;
  25571. zerostruct (info);
  25572. info.inputProcRefCon = this;
  25573. info.inputProc = renderGetInputCallback;
  25574. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25575. 0, &info, sizeof (info));
  25576. }
  25577. {
  25578. HostCallbackInfo info;
  25579. zerostruct (info);
  25580. info.hostUserData = this;
  25581. info.beatAndTempoProc = getBeatAndTempoCallback;
  25582. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25583. info.transportStateProc = getTransportStateCallback;
  25584. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25585. 0, &info, sizeof (info));
  25586. }
  25587. }
  25588. }
  25589. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25590. int samplesPerBlockExpected)
  25591. {
  25592. if (audioUnit != 0)
  25593. {
  25594. releaseResources();
  25595. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25596. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25597. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25598. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25599. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25600. {
  25601. Float64 sr = sampleRate_;
  25602. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25603. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25604. }
  25605. int numIns, numOuts;
  25606. getNumChannels (numIns, numOuts);
  25607. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25608. Float64 latencySecs = 0.0;
  25609. UInt32 latencySize = sizeof (latencySecs);
  25610. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25611. 0, &latencySecs, &latencySize);
  25612. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25613. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25614. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25615. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25616. {
  25617. AudioStreamBasicDescription stream;
  25618. zerostruct (stream);
  25619. stream.mSampleRate = sampleRate_;
  25620. stream.mFormatID = kAudioFormatLinearPCM;
  25621. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25622. stream.mFramesPerPacket = 1;
  25623. stream.mBytesPerPacket = 4;
  25624. stream.mBytesPerFrame = 4;
  25625. stream.mBitsPerChannel = 32;
  25626. stream.mChannelsPerFrame = numIns;
  25627. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25628. 0, &stream, sizeof (stream));
  25629. stream.mChannelsPerFrame = numOuts;
  25630. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25631. 0, &stream, sizeof (stream));
  25632. }
  25633. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25634. outputBufferList->mNumberBuffers = numOuts;
  25635. for (int i = numOuts; --i >= 0;)
  25636. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25637. zerostruct (timeStamp);
  25638. timeStamp.mSampleTime = 0;
  25639. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25640. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25641. currentBuffer = 0;
  25642. wasPlaying = false;
  25643. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25644. }
  25645. }
  25646. void AudioUnitPluginInstance::releaseResources()
  25647. {
  25648. if (prepared)
  25649. {
  25650. AudioUnitUninitialize (audioUnit);
  25651. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25652. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25653. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25654. outputBufferList.free();
  25655. currentBuffer = 0;
  25656. prepared = false;
  25657. }
  25658. }
  25659. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25660. const AudioTimeStamp* inTimeStamp,
  25661. UInt32 inBusNumber,
  25662. UInt32 inNumberFrames,
  25663. AudioBufferList* ioData) const
  25664. {
  25665. if (inBusNumber == 0
  25666. && currentBuffer != 0)
  25667. {
  25668. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25669. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25670. {
  25671. if (i < currentBuffer->getNumChannels())
  25672. {
  25673. memcpy (ioData->mBuffers[i].mData,
  25674. currentBuffer->getSampleData (i, 0),
  25675. sizeof (float) * inNumberFrames);
  25676. }
  25677. else
  25678. {
  25679. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25680. }
  25681. }
  25682. }
  25683. return noErr;
  25684. }
  25685. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25686. MidiBuffer& midiMessages)
  25687. {
  25688. const int numSamples = buffer.getNumSamples();
  25689. if (prepared)
  25690. {
  25691. AudioUnitRenderActionFlags flags = 0;
  25692. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25693. for (int i = getNumOutputChannels(); --i >= 0;)
  25694. {
  25695. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25696. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25697. }
  25698. currentBuffer = &buffer;
  25699. if (wantsMidiMessages)
  25700. {
  25701. const uint8* midiEventData;
  25702. int midiEventSize, midiEventPosition;
  25703. MidiBuffer::Iterator i (midiMessages);
  25704. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25705. {
  25706. if (midiEventSize <= 3)
  25707. MusicDeviceMIDIEvent (audioUnit,
  25708. midiEventData[0], midiEventData[1], midiEventData[2],
  25709. midiEventPosition);
  25710. else
  25711. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25712. }
  25713. midiMessages.clear();
  25714. }
  25715. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25716. 0, numSamples, outputBufferList);
  25717. timeStamp.mSampleTime += numSamples;
  25718. }
  25719. else
  25720. {
  25721. // Plugin not working correctly, so just bypass..
  25722. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25723. buffer.clear (i, 0, buffer.getNumSamples());
  25724. }
  25725. }
  25726. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25727. {
  25728. AudioPlayHead* const ph = getPlayHead();
  25729. AudioPlayHead::CurrentPositionInfo result;
  25730. if (ph != 0 && ph->getCurrentPosition (result))
  25731. {
  25732. if (outCurrentBeat != 0)
  25733. *outCurrentBeat = result.ppqPosition;
  25734. if (outCurrentTempo != 0)
  25735. *outCurrentTempo = result.bpm;
  25736. }
  25737. else
  25738. {
  25739. if (outCurrentBeat != 0)
  25740. *outCurrentBeat = 0;
  25741. if (outCurrentTempo != 0)
  25742. *outCurrentTempo = 120.0;
  25743. }
  25744. return noErr;
  25745. }
  25746. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25747. Float32* outTimeSig_Numerator,
  25748. UInt32* outTimeSig_Denominator,
  25749. Float64* outCurrentMeasureDownBeat) const
  25750. {
  25751. AudioPlayHead* const ph = getPlayHead();
  25752. AudioPlayHead::CurrentPositionInfo result;
  25753. if (ph != 0 && ph->getCurrentPosition (result))
  25754. {
  25755. if (outTimeSig_Numerator != 0)
  25756. *outTimeSig_Numerator = result.timeSigNumerator;
  25757. if (outTimeSig_Denominator != 0)
  25758. *outTimeSig_Denominator = result.timeSigDenominator;
  25759. if (outDeltaSampleOffsetToNextBeat != 0)
  25760. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25761. if (outCurrentMeasureDownBeat != 0)
  25762. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25763. }
  25764. else
  25765. {
  25766. if (outDeltaSampleOffsetToNextBeat != 0)
  25767. *outDeltaSampleOffsetToNextBeat = 0;
  25768. if (outTimeSig_Numerator != 0)
  25769. *outTimeSig_Numerator = 4;
  25770. if (outTimeSig_Denominator != 0)
  25771. *outTimeSig_Denominator = 4;
  25772. if (outCurrentMeasureDownBeat != 0)
  25773. *outCurrentMeasureDownBeat = 0;
  25774. }
  25775. return noErr;
  25776. }
  25777. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25778. Boolean* outTransportStateChanged,
  25779. Float64* outCurrentSampleInTimeLine,
  25780. Boolean* outIsCycling,
  25781. Float64* outCycleStartBeat,
  25782. Float64* outCycleEndBeat)
  25783. {
  25784. AudioPlayHead* const ph = getPlayHead();
  25785. AudioPlayHead::CurrentPositionInfo result;
  25786. if (ph != 0 && ph->getCurrentPosition (result))
  25787. {
  25788. if (outIsPlaying != 0)
  25789. *outIsPlaying = result.isPlaying;
  25790. if (outTransportStateChanged != 0)
  25791. {
  25792. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25793. wasPlaying = result.isPlaying;
  25794. }
  25795. if (outCurrentSampleInTimeLine != 0)
  25796. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25797. if (outIsCycling != 0)
  25798. *outIsCycling = false;
  25799. if (outCycleStartBeat != 0)
  25800. *outCycleStartBeat = 0;
  25801. if (outCycleEndBeat != 0)
  25802. *outCycleEndBeat = 0;
  25803. }
  25804. else
  25805. {
  25806. if (outIsPlaying != 0)
  25807. *outIsPlaying = false;
  25808. if (outTransportStateChanged != 0)
  25809. *outTransportStateChanged = false;
  25810. if (outCurrentSampleInTimeLine != 0)
  25811. *outCurrentSampleInTimeLine = 0;
  25812. if (outIsCycling != 0)
  25813. *outIsCycling = false;
  25814. if (outCycleStartBeat != 0)
  25815. *outCycleStartBeat = 0;
  25816. if (outCycleEndBeat != 0)
  25817. *outCycleEndBeat = 0;
  25818. }
  25819. return noErr;
  25820. }
  25821. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25822. public Timer
  25823. {
  25824. public:
  25825. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25826. : AudioProcessorEditor (&plugin_),
  25827. plugin (plugin_)
  25828. {
  25829. addAndMakeVisible (&wrapper);
  25830. setOpaque (true);
  25831. setVisible (true);
  25832. setSize (100, 100);
  25833. createView (createGenericViewIfNeeded);
  25834. }
  25835. ~AudioUnitPluginWindowCocoa()
  25836. {
  25837. const bool wasValid = isValid();
  25838. wrapper.setView (0);
  25839. if (wasValid)
  25840. plugin.editorBeingDeleted (this);
  25841. }
  25842. bool isValid() const { return wrapper.getView() != 0; }
  25843. void paint (Graphics& g)
  25844. {
  25845. g.fillAll (Colours::white);
  25846. }
  25847. void resized()
  25848. {
  25849. wrapper.setSize (getWidth(), getHeight());
  25850. }
  25851. void timerCallback()
  25852. {
  25853. wrapper.resizeToFitView();
  25854. startTimer (jmin (713, getTimerInterval() + 51));
  25855. }
  25856. void childBoundsChanged (Component* child)
  25857. {
  25858. setSize (wrapper.getWidth(), wrapper.getHeight());
  25859. startTimer (70);
  25860. }
  25861. private:
  25862. AudioUnitPluginInstance& plugin;
  25863. NSViewComponent wrapper;
  25864. bool createView (const bool createGenericViewIfNeeded)
  25865. {
  25866. NSView* pluginView = 0;
  25867. UInt32 dataSize = 0;
  25868. Boolean isWritable = false;
  25869. AudioUnitInitialize (plugin.audioUnit);
  25870. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25871. 0, &dataSize, &isWritable) == noErr
  25872. && dataSize != 0
  25873. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25874. 0, &dataSize, &isWritable) == noErr)
  25875. {
  25876. HeapBlock <AudioUnitCocoaViewInfo> info;
  25877. info.calloc (dataSize, 1);
  25878. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25879. 0, info, &dataSize) == noErr)
  25880. {
  25881. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25882. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25883. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25884. Class viewClass = [viewBundle classNamed: viewClassName];
  25885. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25886. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25887. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25888. {
  25889. id factory = [[[viewClass alloc] init] autorelease];
  25890. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25891. withSize: NSMakeSize (getWidth(), getHeight())];
  25892. }
  25893. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25894. CFRelease (info->mCocoaAUViewClass[i]);
  25895. CFRelease (info->mCocoaAUViewBundleLocation);
  25896. }
  25897. }
  25898. if (createGenericViewIfNeeded && (pluginView == 0))
  25899. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25900. wrapper.setView (pluginView);
  25901. if (pluginView != 0)
  25902. {
  25903. timerCallback();
  25904. startTimer (70);
  25905. }
  25906. return pluginView != 0;
  25907. }
  25908. };
  25909. #if JUCE_SUPPORT_CARBON
  25910. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25911. {
  25912. public:
  25913. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25914. : AudioProcessorEditor (&plugin_),
  25915. plugin (plugin_),
  25916. viewComponent (0)
  25917. {
  25918. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25919. setOpaque (true);
  25920. setVisible (true);
  25921. setSize (400, 300);
  25922. ComponentDescription viewList [16];
  25923. UInt32 viewListSize = sizeof (viewList);
  25924. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25925. 0, &viewList, &viewListSize);
  25926. componentRecord = FindNextComponent (0, &viewList[0]);
  25927. }
  25928. ~AudioUnitPluginWindowCarbon()
  25929. {
  25930. innerWrapper = 0;
  25931. if (isValid())
  25932. plugin.editorBeingDeleted (this);
  25933. }
  25934. bool isValid() const throw() { return componentRecord != 0; }
  25935. void paint (Graphics& g)
  25936. {
  25937. g.fillAll (Colours::black);
  25938. }
  25939. void resized()
  25940. {
  25941. innerWrapper->setSize (getWidth(), getHeight());
  25942. }
  25943. bool keyStateChanged (bool)
  25944. {
  25945. return false;
  25946. }
  25947. bool keyPressed (const KeyPress&)
  25948. {
  25949. return false;
  25950. }
  25951. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25952. AudioUnitCarbonView getViewComponent()
  25953. {
  25954. if (viewComponent == 0 && componentRecord != 0)
  25955. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25956. return viewComponent;
  25957. }
  25958. void closeViewComponent()
  25959. {
  25960. if (viewComponent != 0)
  25961. {
  25962. log ("Closing AU GUI: " + plugin.getName());
  25963. CloseComponent (viewComponent);
  25964. viewComponent = 0;
  25965. }
  25966. }
  25967. juce_UseDebuggingNewOperator
  25968. private:
  25969. AudioUnitPluginInstance& plugin;
  25970. ComponentRecord* componentRecord;
  25971. AudioUnitCarbonView viewComponent;
  25972. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25973. {
  25974. public:
  25975. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25976. : owner (owner_)
  25977. {
  25978. }
  25979. ~InnerWrapperComponent()
  25980. {
  25981. deleteWindow();
  25982. }
  25983. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25984. {
  25985. log ("Opening AU GUI: " + owner->plugin.getName());
  25986. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25987. if (viewComponent == 0)
  25988. return 0;
  25989. Float32Point pos = { 0, 0 };
  25990. Float32Point size = { 250, 200 };
  25991. HIViewRef pluginView = 0;
  25992. AudioUnitCarbonViewCreate (viewComponent,
  25993. owner->getAudioUnit(),
  25994. windowRef,
  25995. rootView,
  25996. &pos,
  25997. &size,
  25998. (ControlRef*) &pluginView);
  25999. return pluginView;
  26000. }
  26001. void removeView (HIViewRef)
  26002. {
  26003. owner->closeViewComponent();
  26004. }
  26005. private:
  26006. AudioUnitPluginWindowCarbon* const owner;
  26007. };
  26008. friend class InnerWrapperComponent;
  26009. ScopedPointer<InnerWrapperComponent> innerWrapper;
  26010. };
  26011. #endif
  26012. bool AudioUnitPluginInstance::hasEditor() const
  26013. {
  26014. return true;
  26015. }
  26016. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  26017. {
  26018. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  26019. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26020. w = 0;
  26021. #if JUCE_SUPPORT_CARBON
  26022. if (w == 0)
  26023. {
  26024. w = new AudioUnitPluginWindowCarbon (*this);
  26025. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26026. w = 0;
  26027. }
  26028. #endif
  26029. if (w == 0)
  26030. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  26031. return w.release();
  26032. }
  26033. const String AudioUnitPluginInstance::getCategory() const
  26034. {
  26035. const char* result = 0;
  26036. switch (componentDesc.componentType)
  26037. {
  26038. case kAudioUnitType_Effect:
  26039. case kAudioUnitType_MusicEffect:
  26040. result = "Effect";
  26041. break;
  26042. case kAudioUnitType_MusicDevice:
  26043. result = "Synth";
  26044. break;
  26045. case kAudioUnitType_Generator:
  26046. result = "Generator";
  26047. break;
  26048. case kAudioUnitType_Panner:
  26049. result = "Panner";
  26050. break;
  26051. default:
  26052. break;
  26053. }
  26054. return result;
  26055. }
  26056. int AudioUnitPluginInstance::getNumParameters()
  26057. {
  26058. return parameterIds.size();
  26059. }
  26060. float AudioUnitPluginInstance::getParameter (int index)
  26061. {
  26062. const ScopedLock sl (lock);
  26063. Float32 value = 0.0f;
  26064. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26065. {
  26066. AudioUnitGetParameter (audioUnit,
  26067. (UInt32) parameterIds.getUnchecked (index),
  26068. kAudioUnitScope_Global, 0,
  26069. &value);
  26070. }
  26071. return value;
  26072. }
  26073. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  26074. {
  26075. const ScopedLock sl (lock);
  26076. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26077. {
  26078. AudioUnitSetParameter (audioUnit,
  26079. (UInt32) parameterIds.getUnchecked (index),
  26080. kAudioUnitScope_Global, 0,
  26081. newValue, 0);
  26082. }
  26083. }
  26084. const String AudioUnitPluginInstance::getParameterName (int index)
  26085. {
  26086. AudioUnitParameterInfo info;
  26087. zerostruct (info);
  26088. UInt32 sz = sizeof (info);
  26089. String name;
  26090. if (AudioUnitGetProperty (audioUnit,
  26091. kAudioUnitProperty_ParameterInfo,
  26092. kAudioUnitScope_Global,
  26093. parameterIds [index], &info, &sz) == noErr)
  26094. {
  26095. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  26096. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  26097. else
  26098. name = String (info.name, sizeof (info.name));
  26099. }
  26100. return name;
  26101. }
  26102. const String AudioUnitPluginInstance::getParameterText (int index)
  26103. {
  26104. return String (getParameter (index));
  26105. }
  26106. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  26107. {
  26108. AudioUnitParameterInfo info;
  26109. UInt32 sz = sizeof (info);
  26110. if (AudioUnitGetProperty (audioUnit,
  26111. kAudioUnitProperty_ParameterInfo,
  26112. kAudioUnitScope_Global,
  26113. parameterIds [index], &info, &sz) == noErr)
  26114. {
  26115. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  26116. }
  26117. return true;
  26118. }
  26119. int AudioUnitPluginInstance::getNumPrograms()
  26120. {
  26121. CFArrayRef presets;
  26122. UInt32 sz = sizeof (CFArrayRef);
  26123. int num = 0;
  26124. if (AudioUnitGetProperty (audioUnit,
  26125. kAudioUnitProperty_FactoryPresets,
  26126. kAudioUnitScope_Global,
  26127. 0, &presets, &sz) == noErr)
  26128. {
  26129. num = (int) CFArrayGetCount (presets);
  26130. CFRelease (presets);
  26131. }
  26132. return num;
  26133. }
  26134. int AudioUnitPluginInstance::getCurrentProgram()
  26135. {
  26136. AUPreset current;
  26137. current.presetNumber = 0;
  26138. UInt32 sz = sizeof (AUPreset);
  26139. AudioUnitGetProperty (audioUnit,
  26140. kAudioUnitProperty_FactoryPresets,
  26141. kAudioUnitScope_Global,
  26142. 0, &current, &sz);
  26143. return current.presetNumber;
  26144. }
  26145. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26146. {
  26147. AUPreset current;
  26148. current.presetNumber = newIndex;
  26149. current.presetName = 0;
  26150. AudioUnitSetProperty (audioUnit,
  26151. kAudioUnitProperty_FactoryPresets,
  26152. kAudioUnitScope_Global,
  26153. 0, &current, sizeof (AUPreset));
  26154. }
  26155. const String AudioUnitPluginInstance::getProgramName (int index)
  26156. {
  26157. String s;
  26158. CFArrayRef presets;
  26159. UInt32 sz = sizeof (CFArrayRef);
  26160. if (AudioUnitGetProperty (audioUnit,
  26161. kAudioUnitProperty_FactoryPresets,
  26162. kAudioUnitScope_Global,
  26163. 0, &presets, &sz) == noErr)
  26164. {
  26165. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26166. {
  26167. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26168. if (p != 0 && p->presetNumber == index)
  26169. {
  26170. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26171. break;
  26172. }
  26173. }
  26174. CFRelease (presets);
  26175. }
  26176. return s;
  26177. }
  26178. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26179. {
  26180. jassertfalse; // xxx not implemented!
  26181. }
  26182. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26183. {
  26184. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  26185. return "Input " + String (index + 1);
  26186. return String::empty;
  26187. }
  26188. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26189. {
  26190. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  26191. return false;
  26192. return true;
  26193. }
  26194. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26195. {
  26196. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  26197. return "Output " + String (index + 1);
  26198. return String::empty;
  26199. }
  26200. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26201. {
  26202. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  26203. return false;
  26204. return true;
  26205. }
  26206. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26207. {
  26208. getCurrentProgramStateInformation (destData);
  26209. }
  26210. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26211. {
  26212. CFPropertyListRef propertyList = 0;
  26213. UInt32 sz = sizeof (CFPropertyListRef);
  26214. if (AudioUnitGetProperty (audioUnit,
  26215. kAudioUnitProperty_ClassInfo,
  26216. kAudioUnitScope_Global,
  26217. 0, &propertyList, &sz) == noErr)
  26218. {
  26219. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26220. CFWriteStreamOpen (stream);
  26221. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26222. CFWriteStreamClose (stream);
  26223. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26224. destData.setSize (bytesWritten);
  26225. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26226. CFRelease (data);
  26227. CFRelease (stream);
  26228. CFRelease (propertyList);
  26229. }
  26230. }
  26231. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26232. {
  26233. setCurrentProgramStateInformation (data, sizeInBytes);
  26234. }
  26235. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26236. {
  26237. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26238. (const UInt8*) data,
  26239. sizeInBytes,
  26240. kCFAllocatorNull);
  26241. CFReadStreamOpen (stream);
  26242. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26243. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26244. stream,
  26245. 0,
  26246. kCFPropertyListImmutable,
  26247. &format,
  26248. 0);
  26249. CFRelease (stream);
  26250. if (propertyList != 0)
  26251. AudioUnitSetProperty (audioUnit,
  26252. kAudioUnitProperty_ClassInfo,
  26253. kAudioUnitScope_Global,
  26254. 0, &propertyList, sizeof (propertyList));
  26255. }
  26256. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26257. {
  26258. }
  26259. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26260. {
  26261. }
  26262. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26263. const String& fileOrIdentifier)
  26264. {
  26265. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26266. return;
  26267. PluginDescription desc;
  26268. desc.fileOrIdentifier = fileOrIdentifier;
  26269. desc.uid = 0;
  26270. try
  26271. {
  26272. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26273. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26274. if (auInstance != 0)
  26275. {
  26276. auInstance->fillInPluginDescription (desc);
  26277. results.add (new PluginDescription (desc));
  26278. }
  26279. }
  26280. catch (...)
  26281. {
  26282. // crashed while loading...
  26283. }
  26284. }
  26285. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26286. {
  26287. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26288. {
  26289. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26290. if (result->audioUnit != 0)
  26291. {
  26292. result->initialise();
  26293. return result.release();
  26294. }
  26295. }
  26296. return 0;
  26297. }
  26298. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26299. const bool /*recursive*/)
  26300. {
  26301. StringArray result;
  26302. ComponentRecord* comp = 0;
  26303. ComponentDescription desc;
  26304. zerostruct (desc);
  26305. for (;;)
  26306. {
  26307. zerostruct (desc);
  26308. comp = FindNextComponent (comp, &desc);
  26309. if (comp == 0)
  26310. break;
  26311. GetComponentInfo (comp, &desc, 0, 0, 0);
  26312. if (desc.componentType == kAudioUnitType_MusicDevice
  26313. || desc.componentType == kAudioUnitType_MusicEffect
  26314. || desc.componentType == kAudioUnitType_Effect
  26315. || desc.componentType == kAudioUnitType_Generator
  26316. || desc.componentType == kAudioUnitType_Panner)
  26317. {
  26318. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26319. DBG (s);
  26320. result.add (s);
  26321. }
  26322. }
  26323. return result;
  26324. }
  26325. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26326. {
  26327. ComponentDescription desc;
  26328. String name, version, manufacturer;
  26329. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26330. return FindNextComponent (0, &desc) != 0;
  26331. const File f (fileOrIdentifier);
  26332. return f.hasFileExtension (".component")
  26333. && f.isDirectory();
  26334. }
  26335. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26336. {
  26337. ComponentDescription desc;
  26338. String name, version, manufacturer;
  26339. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26340. if (name.isEmpty())
  26341. name = fileOrIdentifier;
  26342. return name;
  26343. }
  26344. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26345. {
  26346. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26347. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26348. else
  26349. return File (desc.fileOrIdentifier).exists();
  26350. }
  26351. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26352. {
  26353. return FileSearchPath ("/(Default AudioUnit locations)");
  26354. }
  26355. #endif
  26356. END_JUCE_NAMESPACE
  26357. #undef log
  26358. #endif
  26359. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26360. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26361. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26362. #define JUCE_MAC_VST_INCLUDED 1
  26363. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26364. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26365. #if JUCE_WINDOWS
  26366. #undef _WIN32_WINNT
  26367. #define _WIN32_WINNT 0x500
  26368. #undef STRICT
  26369. #define STRICT
  26370. #include <windows.h>
  26371. #include <float.h>
  26372. #pragma warning (disable : 4312 4355)
  26373. #elif JUCE_LINUX
  26374. #include <float.h>
  26375. #include <sys/time.h>
  26376. #include <X11/Xlib.h>
  26377. #include <X11/Xutil.h>
  26378. #include <X11/Xatom.h>
  26379. #undef Font
  26380. #undef KeyPress
  26381. #undef Drawable
  26382. #undef Time
  26383. #else
  26384. #include <Cocoa/Cocoa.h>
  26385. #include <Carbon/Carbon.h>
  26386. #endif
  26387. #if ! (JUCE_MAC && JUCE_64BIT)
  26388. BEGIN_JUCE_NAMESPACE
  26389. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26390. #endif
  26391. #undef PRAGMA_ALIGN_SUPPORTED
  26392. #define VST_FORCE_DEPRECATED 0
  26393. #if JUCE_MSVC
  26394. #pragma warning (push)
  26395. #pragma warning (disable: 4996)
  26396. #endif
  26397. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26398. your include path if you want to add VST support.
  26399. If you're not interested in VSTs, you can disable them by changing the
  26400. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26401. */
  26402. #include "pluginterfaces/vst2.x/aeffectx.h"
  26403. #if JUCE_MSVC
  26404. #pragma warning (pop)
  26405. #endif
  26406. #if JUCE_LINUX
  26407. #define Font JUCE_NAMESPACE::Font
  26408. #define KeyPress JUCE_NAMESPACE::KeyPress
  26409. #define Drawable JUCE_NAMESPACE::Drawable
  26410. #define Time JUCE_NAMESPACE::Time
  26411. #endif
  26412. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26413. #ifdef __aeffect__
  26414. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26415. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26416. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26417. events to the list.
  26418. This is used by both the VST hosting code and the plugin wrapper.
  26419. */
  26420. class VSTMidiEventList
  26421. {
  26422. public:
  26423. VSTMidiEventList()
  26424. : numEventsUsed (0), numEventsAllocated (0)
  26425. {
  26426. }
  26427. ~VSTMidiEventList()
  26428. {
  26429. freeEvents();
  26430. }
  26431. void clear()
  26432. {
  26433. numEventsUsed = 0;
  26434. if (events != 0)
  26435. events->numEvents = 0;
  26436. }
  26437. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26438. {
  26439. ensureSize (numEventsUsed + 1);
  26440. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26441. events->numEvents = ++numEventsUsed;
  26442. if (numBytes <= 4)
  26443. {
  26444. if (e->type == kVstSysExType)
  26445. {
  26446. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26447. e->type = kVstMidiType;
  26448. e->byteSize = sizeof (VstMidiEvent);
  26449. e->noteLength = 0;
  26450. e->noteOffset = 0;
  26451. e->detune = 0;
  26452. e->noteOffVelocity = 0;
  26453. }
  26454. e->deltaFrames = frameOffset;
  26455. memcpy (e->midiData, midiData, numBytes);
  26456. }
  26457. else
  26458. {
  26459. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26460. if (se->type == kVstSysExType)
  26461. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26462. else
  26463. se->sysexDump = (char*) juce_malloc (numBytes);
  26464. memcpy (se->sysexDump, midiData, numBytes);
  26465. se->type = kVstSysExType;
  26466. se->byteSize = sizeof (VstMidiSysexEvent);
  26467. se->deltaFrames = frameOffset;
  26468. se->flags = 0;
  26469. se->dumpBytes = numBytes;
  26470. se->resvd1 = 0;
  26471. se->resvd2 = 0;
  26472. }
  26473. }
  26474. // Handy method to pull the events out of an event buffer supplied by the host
  26475. // or plugin.
  26476. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26477. {
  26478. for (int i = 0; i < events->numEvents; ++i)
  26479. {
  26480. const VstEvent* const e = events->events[i];
  26481. if (e != 0)
  26482. {
  26483. if (e->type == kVstMidiType)
  26484. {
  26485. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26486. 4, e->deltaFrames);
  26487. }
  26488. else if (e->type == kVstSysExType)
  26489. {
  26490. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26491. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26492. e->deltaFrames);
  26493. }
  26494. }
  26495. }
  26496. }
  26497. void ensureSize (int numEventsNeeded)
  26498. {
  26499. if (numEventsNeeded > numEventsAllocated)
  26500. {
  26501. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26502. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26503. if (events == 0)
  26504. events.calloc (size, 1);
  26505. else
  26506. events.realloc (size, 1);
  26507. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26508. {
  26509. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26510. (int) sizeof (VstMidiSysexEvent)));
  26511. e->type = kVstMidiType;
  26512. e->byteSize = sizeof (VstMidiEvent);
  26513. events->events[i] = (VstEvent*) e;
  26514. }
  26515. numEventsAllocated = numEventsNeeded;
  26516. }
  26517. }
  26518. void freeEvents()
  26519. {
  26520. if (events != 0)
  26521. {
  26522. for (int i = numEventsAllocated; --i >= 0;)
  26523. {
  26524. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26525. if (e->type == kVstSysExType)
  26526. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26527. juce_free (e);
  26528. }
  26529. events.free();
  26530. numEventsUsed = 0;
  26531. numEventsAllocated = 0;
  26532. }
  26533. }
  26534. HeapBlock <VstEvents> events;
  26535. private:
  26536. int numEventsUsed, numEventsAllocated;
  26537. };
  26538. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26539. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26540. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26541. #if ! JUCE_WINDOWS
  26542. static void _fpreset() {}
  26543. static void _clearfp() {}
  26544. #endif
  26545. extern void juce_callAnyTimersSynchronously();
  26546. const int fxbVersionNum = 1;
  26547. struct fxProgram
  26548. {
  26549. long chunkMagic; // 'CcnK'
  26550. long byteSize; // of this chunk, excl. magic + byteSize
  26551. long fxMagic; // 'FxCk'
  26552. long version;
  26553. long fxID; // fx unique id
  26554. long fxVersion;
  26555. long numParams;
  26556. char prgName[28];
  26557. float params[1]; // variable no. of parameters
  26558. };
  26559. struct fxSet
  26560. {
  26561. long chunkMagic; // 'CcnK'
  26562. long byteSize; // of this chunk, excl. magic + byteSize
  26563. long fxMagic; // 'FxBk'
  26564. long version;
  26565. long fxID; // fx unique id
  26566. long fxVersion;
  26567. long numPrograms;
  26568. char future[128];
  26569. fxProgram programs[1]; // variable no. of programs
  26570. };
  26571. struct fxChunkSet
  26572. {
  26573. long chunkMagic; // 'CcnK'
  26574. long byteSize; // of this chunk, excl. magic + byteSize
  26575. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26576. long version;
  26577. long fxID; // fx unique id
  26578. long fxVersion;
  26579. long numPrograms;
  26580. char future[128];
  26581. long chunkSize;
  26582. char chunk[8]; // variable
  26583. };
  26584. struct fxProgramSet
  26585. {
  26586. long chunkMagic; // 'CcnK'
  26587. long byteSize; // of this chunk, excl. magic + byteSize
  26588. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26589. long version;
  26590. long fxID; // fx unique id
  26591. long fxVersion;
  26592. long numPrograms;
  26593. char name[28];
  26594. long chunkSize;
  26595. char chunk[8]; // variable
  26596. };
  26597. namespace
  26598. {
  26599. long vst_swap (const long x) throw()
  26600. {
  26601. #ifdef JUCE_LITTLE_ENDIAN
  26602. return (long) ByteOrder::swap ((uint32) x);
  26603. #else
  26604. return x;
  26605. #endif
  26606. }
  26607. float vst_swapFloat (const float x) throw()
  26608. {
  26609. #ifdef JUCE_LITTLE_ENDIAN
  26610. union { uint32 asInt; float asFloat; } n;
  26611. n.asFloat = x;
  26612. n.asInt = ByteOrder::swap (n.asInt);
  26613. return n.asFloat;
  26614. #else
  26615. return x;
  26616. #endif
  26617. }
  26618. double getVSTHostTimeNanoseconds()
  26619. {
  26620. #if JUCE_WINDOWS
  26621. return timeGetTime() * 1000000.0;
  26622. #elif JUCE_LINUX
  26623. timeval micro;
  26624. gettimeofday (&micro, 0);
  26625. return micro.tv_usec * 1000.0;
  26626. #elif JUCE_MAC
  26627. UnsignedWide micro;
  26628. Microseconds (&micro);
  26629. return micro.lo * 1000.0;
  26630. #endif
  26631. }
  26632. }
  26633. typedef AEffect* (*MainCall) (audioMasterCallback);
  26634. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26635. static int shellUIDToCreate = 0;
  26636. static int insideVSTCallback = 0;
  26637. class VSTPluginWindow;
  26638. // Change this to disable logging of various VST activities
  26639. #ifndef VST_LOGGING
  26640. #define VST_LOGGING 1
  26641. #endif
  26642. #if VST_LOGGING
  26643. #define log(a) Logger::writeToLog(a);
  26644. #else
  26645. #define log(a)
  26646. #endif
  26647. #if JUCE_MAC && JUCE_PPC
  26648. static void* NewCFMFromMachO (void* const machofp) throw()
  26649. {
  26650. void* result = juce_malloc (8);
  26651. ((void**) result)[0] = machofp;
  26652. ((void**) result)[1] = result;
  26653. return result;
  26654. }
  26655. #endif
  26656. #if JUCE_LINUX
  26657. extern Display* display;
  26658. extern XContext windowHandleXContext;
  26659. typedef void (*EventProcPtr) (XEvent* ev);
  26660. static bool xErrorTriggered;
  26661. namespace
  26662. {
  26663. int temporaryErrorHandler (Display*, XErrorEvent*)
  26664. {
  26665. xErrorTriggered = true;
  26666. return 0;
  26667. }
  26668. int getPropertyFromXWindow (Window handle, Atom atom)
  26669. {
  26670. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26671. xErrorTriggered = false;
  26672. int userSize;
  26673. unsigned long bytes, userCount;
  26674. unsigned char* data;
  26675. Atom userType;
  26676. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26677. &userType, &userSize, &userCount, &bytes, &data);
  26678. XSetErrorHandler (oldErrorHandler);
  26679. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26680. : 0;
  26681. }
  26682. Window getChildWindow (Window windowToCheck)
  26683. {
  26684. Window rootWindow, parentWindow;
  26685. Window* childWindows;
  26686. unsigned int numChildren;
  26687. XQueryTree (display,
  26688. windowToCheck,
  26689. &rootWindow,
  26690. &parentWindow,
  26691. &childWindows,
  26692. &numChildren);
  26693. if (numChildren > 0)
  26694. return childWindows [0];
  26695. return 0;
  26696. }
  26697. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26698. {
  26699. if (e.mods.isLeftButtonDown())
  26700. {
  26701. ev.xbutton.button = Button1;
  26702. ev.xbutton.state |= Button1Mask;
  26703. }
  26704. else if (e.mods.isRightButtonDown())
  26705. {
  26706. ev.xbutton.button = Button3;
  26707. ev.xbutton.state |= Button3Mask;
  26708. }
  26709. else if (e.mods.isMiddleButtonDown())
  26710. {
  26711. ev.xbutton.button = Button2;
  26712. ev.xbutton.state |= Button2Mask;
  26713. }
  26714. }
  26715. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26716. {
  26717. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26718. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26719. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26720. }
  26721. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26722. {
  26723. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26724. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26725. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26726. }
  26727. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26728. {
  26729. if (increment < 0)
  26730. {
  26731. ev.xbutton.button = Button5;
  26732. ev.xbutton.state |= Button5Mask;
  26733. }
  26734. else if (increment > 0)
  26735. {
  26736. ev.xbutton.button = Button4;
  26737. ev.xbutton.state |= Button4Mask;
  26738. }
  26739. }
  26740. }
  26741. #endif
  26742. class ModuleHandle : public ReferenceCountedObject
  26743. {
  26744. public:
  26745. File file;
  26746. MainCall moduleMain;
  26747. String pluginName;
  26748. static Array <ModuleHandle*>& getActiveModules()
  26749. {
  26750. static Array <ModuleHandle*> activeModules;
  26751. return activeModules;
  26752. }
  26753. static ModuleHandle* findOrCreateModule (const File& file)
  26754. {
  26755. for (int i = getActiveModules().size(); --i >= 0;)
  26756. {
  26757. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26758. if (module->file == file)
  26759. return module;
  26760. }
  26761. _fpreset(); // (doesn't do any harm)
  26762. ++insideVSTCallback;
  26763. shellUIDToCreate = 0;
  26764. log ("Attempting to load VST: " + file.getFullPathName());
  26765. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26766. if (! m->open())
  26767. m = 0;
  26768. --insideVSTCallback;
  26769. _fpreset(); // (doesn't do any harm)
  26770. return m.release();
  26771. }
  26772. ModuleHandle (const File& file_)
  26773. : file (file_),
  26774. moduleMain (0),
  26775. #if JUCE_WINDOWS || JUCE_LINUX
  26776. hModule (0)
  26777. #elif JUCE_MAC
  26778. fragId (0),
  26779. resHandle (0),
  26780. bundleRef (0),
  26781. resFileId (0)
  26782. #endif
  26783. {
  26784. getActiveModules().add (this);
  26785. #if JUCE_WINDOWS || JUCE_LINUX
  26786. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26787. #elif JUCE_MAC
  26788. FSRef ref;
  26789. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26790. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26791. #endif
  26792. }
  26793. ~ModuleHandle()
  26794. {
  26795. getActiveModules().removeValue (this);
  26796. close();
  26797. }
  26798. juce_UseDebuggingNewOperator
  26799. #if JUCE_WINDOWS || JUCE_LINUX
  26800. void* hModule;
  26801. String fullParentDirectoryPathName;
  26802. bool open()
  26803. {
  26804. #if JUCE_WINDOWS
  26805. static bool timePeriodSet = false;
  26806. if (! timePeriodSet)
  26807. {
  26808. timePeriodSet = true;
  26809. timeBeginPeriod (2);
  26810. }
  26811. #endif
  26812. pluginName = file.getFileNameWithoutExtension();
  26813. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26814. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26815. if (moduleMain == 0)
  26816. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26817. return moduleMain != 0;
  26818. }
  26819. void close()
  26820. {
  26821. _fpreset(); // (doesn't do any harm)
  26822. PlatformUtilities::freeDynamicLibrary (hModule);
  26823. }
  26824. void closeEffect (AEffect* eff)
  26825. {
  26826. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26827. }
  26828. #else
  26829. CFragConnectionID fragId;
  26830. Handle resHandle;
  26831. CFBundleRef bundleRef;
  26832. FSSpec parentDirFSSpec;
  26833. short resFileId;
  26834. bool open()
  26835. {
  26836. bool ok = false;
  26837. const String filename (file.getFullPathName());
  26838. if (file.hasFileExtension (".vst"))
  26839. {
  26840. const char* const utf8 = filename.toUTF8();
  26841. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26842. strlen (utf8), file.isDirectory());
  26843. if (url != 0)
  26844. {
  26845. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26846. CFRelease (url);
  26847. if (bundleRef != 0)
  26848. {
  26849. if (CFBundleLoadExecutable (bundleRef))
  26850. {
  26851. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26852. if (moduleMain == 0)
  26853. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26854. if (moduleMain != 0)
  26855. {
  26856. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26857. if (name != 0)
  26858. {
  26859. if (CFGetTypeID (name) == CFStringGetTypeID())
  26860. {
  26861. char buffer[1024];
  26862. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26863. pluginName = buffer;
  26864. }
  26865. }
  26866. if (pluginName.isEmpty())
  26867. pluginName = file.getFileNameWithoutExtension();
  26868. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26869. ok = true;
  26870. }
  26871. }
  26872. if (! ok)
  26873. {
  26874. CFBundleUnloadExecutable (bundleRef);
  26875. CFRelease (bundleRef);
  26876. bundleRef = 0;
  26877. }
  26878. }
  26879. }
  26880. }
  26881. #if JUCE_PPC
  26882. else
  26883. {
  26884. FSRef fn;
  26885. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26886. {
  26887. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26888. if (resFileId != -1)
  26889. {
  26890. const int numEffs = Count1Resources ('aEff');
  26891. for (int i = 0; i < numEffs; ++i)
  26892. {
  26893. resHandle = Get1IndResource ('aEff', i + 1);
  26894. if (resHandle != 0)
  26895. {
  26896. OSType type;
  26897. Str255 name;
  26898. SInt16 id;
  26899. GetResInfo (resHandle, &id, &type, name);
  26900. pluginName = String ((const char*) name + 1, name[0]);
  26901. DetachResource (resHandle);
  26902. HLock (resHandle);
  26903. Ptr ptr;
  26904. Str255 errorText;
  26905. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26906. name, kPrivateCFragCopy,
  26907. &fragId, &ptr, errorText);
  26908. if (err == noErr)
  26909. {
  26910. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26911. ok = true;
  26912. }
  26913. else
  26914. {
  26915. HUnlock (resHandle);
  26916. }
  26917. break;
  26918. }
  26919. }
  26920. if (! ok)
  26921. CloseResFile (resFileId);
  26922. }
  26923. }
  26924. }
  26925. #endif
  26926. return ok;
  26927. }
  26928. void close()
  26929. {
  26930. #if JUCE_PPC
  26931. if (fragId != 0)
  26932. {
  26933. if (moduleMain != 0)
  26934. disposeMachOFromCFM ((void*) moduleMain);
  26935. CloseConnection (&fragId);
  26936. HUnlock (resHandle);
  26937. if (resFileId != 0)
  26938. CloseResFile (resFileId);
  26939. }
  26940. else
  26941. #endif
  26942. if (bundleRef != 0)
  26943. {
  26944. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26945. if (CFGetRetainCount (bundleRef) == 1)
  26946. CFBundleUnloadExecutable (bundleRef);
  26947. if (CFGetRetainCount (bundleRef) > 0)
  26948. CFRelease (bundleRef);
  26949. }
  26950. }
  26951. void closeEffect (AEffect* eff)
  26952. {
  26953. #if JUCE_PPC
  26954. if (fragId != 0)
  26955. {
  26956. Array<void*> thingsToDelete;
  26957. thingsToDelete.add ((void*) eff->dispatcher);
  26958. thingsToDelete.add ((void*) eff->process);
  26959. thingsToDelete.add ((void*) eff->setParameter);
  26960. thingsToDelete.add ((void*) eff->getParameter);
  26961. thingsToDelete.add ((void*) eff->processReplacing);
  26962. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26963. for (int i = thingsToDelete.size(); --i >= 0;)
  26964. disposeMachOFromCFM (thingsToDelete[i]);
  26965. }
  26966. else
  26967. #endif
  26968. {
  26969. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26970. }
  26971. }
  26972. #if JUCE_PPC
  26973. static void* newMachOFromCFM (void* cfmfp)
  26974. {
  26975. if (cfmfp == 0)
  26976. return 0;
  26977. UInt32* const mfp = new UInt32[6];
  26978. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26979. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26980. mfp[2] = 0x800c0000;
  26981. mfp[3] = 0x804c0004;
  26982. mfp[4] = 0x7c0903a6;
  26983. mfp[5] = 0x4e800420;
  26984. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26985. return mfp;
  26986. }
  26987. static void disposeMachOFromCFM (void* ptr)
  26988. {
  26989. delete[] static_cast <UInt32*> (ptr);
  26990. }
  26991. void coerceAEffectFunctionCalls (AEffect* eff)
  26992. {
  26993. if (fragId != 0)
  26994. {
  26995. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26996. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26997. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26998. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26999. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  27000. }
  27001. }
  27002. #endif
  27003. #endif
  27004. };
  27005. /**
  27006. An instance of a plugin, created by a VSTPluginFormat.
  27007. */
  27008. class VSTPluginInstance : public AudioPluginInstance,
  27009. private Timer,
  27010. private AsyncUpdater
  27011. {
  27012. public:
  27013. ~VSTPluginInstance();
  27014. // AudioPluginInstance methods:
  27015. void fillInPluginDescription (PluginDescription& desc) const
  27016. {
  27017. desc.name = name;
  27018. desc.fileOrIdentifier = module->file.getFullPathName();
  27019. desc.uid = getUID();
  27020. desc.lastFileModTime = module->file.getLastModificationTime();
  27021. desc.pluginFormatName = "VST";
  27022. desc.category = getCategory();
  27023. {
  27024. char buffer [kVstMaxVendorStrLen + 8];
  27025. zerostruct (buffer);
  27026. dispatch (effGetVendorString, 0, 0, buffer, 0);
  27027. desc.manufacturerName = buffer;
  27028. }
  27029. desc.version = getVersion();
  27030. desc.numInputChannels = getNumInputChannels();
  27031. desc.numOutputChannels = getNumOutputChannels();
  27032. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  27033. }
  27034. void* getPlatformSpecificData() { return effect; }
  27035. const String getName() const { return name; }
  27036. int getUID() const;
  27037. bool acceptsMidi() const { return wantsMidiMessages; }
  27038. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  27039. // AudioProcessor methods:
  27040. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  27041. void releaseResources();
  27042. void processBlock (AudioSampleBuffer& buffer,
  27043. MidiBuffer& midiMessages);
  27044. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  27045. AudioProcessorEditor* createEditor();
  27046. const String getInputChannelName (int index) const;
  27047. bool isInputChannelStereoPair (int index) const;
  27048. const String getOutputChannelName (int index) const;
  27049. bool isOutputChannelStereoPair (int index) const;
  27050. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  27051. float getParameter (int index);
  27052. void setParameter (int index, float newValue);
  27053. const String getParameterName (int index);
  27054. const String getParameterText (int index);
  27055. bool isParameterAutomatable (int index) const;
  27056. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  27057. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  27058. void setCurrentProgram (int index);
  27059. const String getProgramName (int index);
  27060. void changeProgramName (int index, const String& newName);
  27061. void getStateInformation (MemoryBlock& destData);
  27062. void getCurrentProgramStateInformation (MemoryBlock& destData);
  27063. void setStateInformation (const void* data, int sizeInBytes);
  27064. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  27065. void timerCallback();
  27066. void handleAsyncUpdate();
  27067. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  27068. juce_UseDebuggingNewOperator
  27069. private:
  27070. friend class VSTPluginWindow;
  27071. friend class VSTPluginFormat;
  27072. AEffect* effect;
  27073. String name;
  27074. CriticalSection lock;
  27075. bool wantsMidiMessages, initialised, isPowerOn;
  27076. mutable StringArray programNames;
  27077. AudioSampleBuffer tempBuffer;
  27078. CriticalSection midiInLock;
  27079. MidiBuffer incomingMidi;
  27080. VSTMidiEventList midiEventsToSend;
  27081. VstTimeInfo vstHostTime;
  27082. ReferenceCountedObjectPtr <ModuleHandle> module;
  27083. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  27084. bool restoreProgramSettings (const fxProgram* const prog);
  27085. const String getCurrentProgramName();
  27086. void setParamsInProgramBlock (fxProgram* const prog);
  27087. void updateStoredProgramNames();
  27088. void initialise();
  27089. void handleMidiFromPlugin (const VstEvents* const events);
  27090. void createTempParameterStore (MemoryBlock& dest);
  27091. void restoreFromTempParameterStore (const MemoryBlock& mb);
  27092. const String getParameterLabel (int index) const;
  27093. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  27094. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  27095. void setChunkData (const char* data, int size, bool isPreset);
  27096. bool loadFromFXBFile (const void* data, int numBytes);
  27097. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  27098. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  27099. const String getVersion() const;
  27100. const String getCategory() const;
  27101. void setPower (const bool on);
  27102. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  27103. };
  27104. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  27105. : effect (0),
  27106. wantsMidiMessages (false),
  27107. initialised (false),
  27108. isPowerOn (false),
  27109. tempBuffer (1, 1),
  27110. module (module_)
  27111. {
  27112. try
  27113. {
  27114. _fpreset();
  27115. ++insideVSTCallback;
  27116. name = module->pluginName;
  27117. log ("Creating VST instance: " + name);
  27118. #if JUCE_MAC
  27119. if (module->resFileId != 0)
  27120. UseResFile (module->resFileId);
  27121. #if JUCE_PPC
  27122. if (module->fragId != 0)
  27123. {
  27124. static void* audioMasterCoerced = 0;
  27125. if (audioMasterCoerced == 0)
  27126. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  27127. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  27128. }
  27129. else
  27130. #endif
  27131. #endif
  27132. {
  27133. effect = module->moduleMain (&audioMaster);
  27134. }
  27135. --insideVSTCallback;
  27136. if (effect != 0 && effect->magic == kEffectMagic)
  27137. {
  27138. #if JUCE_PPC
  27139. module->coerceAEffectFunctionCalls (effect);
  27140. #endif
  27141. jassert (effect->resvd2 == 0);
  27142. jassert (effect->object != 0);
  27143. _fpreset(); // some dodgy plugs fuck around with this
  27144. }
  27145. else
  27146. {
  27147. effect = 0;
  27148. }
  27149. }
  27150. catch (...)
  27151. {
  27152. --insideVSTCallback;
  27153. }
  27154. }
  27155. VSTPluginInstance::~VSTPluginInstance()
  27156. {
  27157. const ScopedLock sl (lock);
  27158. jassert (insideVSTCallback == 0);
  27159. if (effect != 0 && effect->magic == kEffectMagic)
  27160. {
  27161. try
  27162. {
  27163. #if JUCE_MAC
  27164. if (module->resFileId != 0)
  27165. UseResFile (module->resFileId);
  27166. #endif
  27167. // Must delete any editors before deleting the plugin instance!
  27168. jassert (getActiveEditor() == 0);
  27169. _fpreset(); // some dodgy plugs fuck around with this
  27170. module->closeEffect (effect);
  27171. }
  27172. catch (...)
  27173. {}
  27174. }
  27175. module = 0;
  27176. effect = 0;
  27177. }
  27178. void VSTPluginInstance::initialise()
  27179. {
  27180. if (initialised || effect == 0)
  27181. return;
  27182. log ("Initialising VST: " + module->pluginName);
  27183. initialised = true;
  27184. dispatch (effIdentify, 0, 0, 0, 0);
  27185. // this code would ask the plugin for its name, but so few plugins
  27186. // actually bother implementing this correctly, that it's better to
  27187. // just ignore it and use the file name instead.
  27188. /* {
  27189. char buffer [256];
  27190. zerostruct (buffer);
  27191. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27192. name = String (buffer).trim();
  27193. if (name.isEmpty())
  27194. name = module->pluginName;
  27195. }
  27196. */
  27197. if (getSampleRate() > 0)
  27198. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27199. if (getBlockSize() > 0)
  27200. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27201. dispatch (effOpen, 0, 0, 0, 0);
  27202. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27203. getSampleRate(), getBlockSize());
  27204. if (getNumPrograms() > 1)
  27205. setCurrentProgram (0);
  27206. else
  27207. dispatch (effSetProgram, 0, 0, 0, 0);
  27208. int i;
  27209. for (i = effect->numInputs; --i >= 0;)
  27210. dispatch (effConnectInput, i, 1, 0, 0);
  27211. for (i = effect->numOutputs; --i >= 0;)
  27212. dispatch (effConnectOutput, i, 1, 0, 0);
  27213. updateStoredProgramNames();
  27214. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27215. setLatencySamples (effect->initialDelay);
  27216. }
  27217. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27218. int samplesPerBlockExpected)
  27219. {
  27220. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27221. sampleRate_, samplesPerBlockExpected);
  27222. setLatencySamples (effect->initialDelay);
  27223. vstHostTime.tempo = 120.0;
  27224. vstHostTime.timeSigNumerator = 4;
  27225. vstHostTime.timeSigDenominator = 4;
  27226. vstHostTime.sampleRate = sampleRate_;
  27227. vstHostTime.samplePos = 0;
  27228. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27229. initialise();
  27230. if (initialised)
  27231. {
  27232. wantsMidiMessages = wantsMidiMessages
  27233. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27234. if (wantsMidiMessages)
  27235. midiEventsToSend.ensureSize (256);
  27236. else
  27237. midiEventsToSend.freeEvents();
  27238. incomingMidi.clear();
  27239. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27240. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27241. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27242. if (! isPowerOn)
  27243. setPower (true);
  27244. // dodgy hack to force some plugins to initialise the sample rate..
  27245. if ((! hasEditor()) && getNumParameters() > 0)
  27246. {
  27247. const float old = getParameter (0);
  27248. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27249. setParameter (0, old);
  27250. }
  27251. dispatch (effStartProcess, 0, 0, 0, 0);
  27252. }
  27253. }
  27254. void VSTPluginInstance::releaseResources()
  27255. {
  27256. if (initialised)
  27257. {
  27258. dispatch (effStopProcess, 0, 0, 0, 0);
  27259. setPower (false);
  27260. }
  27261. tempBuffer.setSize (1, 1);
  27262. incomingMidi.clear();
  27263. midiEventsToSend.freeEvents();
  27264. }
  27265. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27266. MidiBuffer& midiMessages)
  27267. {
  27268. const int numSamples = buffer.getNumSamples();
  27269. if (initialised)
  27270. {
  27271. AudioPlayHead* playHead = getPlayHead();
  27272. if (playHead != 0)
  27273. {
  27274. AudioPlayHead::CurrentPositionInfo position;
  27275. playHead->getCurrentPosition (position);
  27276. vstHostTime.tempo = position.bpm;
  27277. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27278. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27279. vstHostTime.ppqPos = position.ppqPosition;
  27280. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27281. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27282. if (position.isPlaying)
  27283. vstHostTime.flags |= kVstTransportPlaying;
  27284. else
  27285. vstHostTime.flags &= ~kVstTransportPlaying;
  27286. }
  27287. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27288. if (wantsMidiMessages)
  27289. {
  27290. midiEventsToSend.clear();
  27291. midiEventsToSend.ensureSize (1);
  27292. MidiBuffer::Iterator iter (midiMessages);
  27293. const uint8* midiData;
  27294. int numBytesOfMidiData, samplePosition;
  27295. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27296. {
  27297. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27298. jlimit (0, numSamples - 1, samplePosition));
  27299. }
  27300. try
  27301. {
  27302. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27303. }
  27304. catch (...)
  27305. {}
  27306. }
  27307. _clearfp();
  27308. if ((effect->flags & effFlagsCanReplacing) != 0)
  27309. {
  27310. try
  27311. {
  27312. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27313. }
  27314. catch (...)
  27315. {}
  27316. }
  27317. else
  27318. {
  27319. tempBuffer.setSize (effect->numOutputs, numSamples);
  27320. tempBuffer.clear();
  27321. try
  27322. {
  27323. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27324. }
  27325. catch (...)
  27326. {}
  27327. for (int i = effect->numOutputs; --i >= 0;)
  27328. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27329. }
  27330. }
  27331. else
  27332. {
  27333. // Not initialised, so just bypass..
  27334. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27335. buffer.clear (i, 0, buffer.getNumSamples());
  27336. }
  27337. {
  27338. // copy any incoming midi..
  27339. const ScopedLock sl (midiInLock);
  27340. midiMessages.swapWith (incomingMidi);
  27341. incomingMidi.clear();
  27342. }
  27343. }
  27344. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27345. {
  27346. if (events != 0)
  27347. {
  27348. const ScopedLock sl (midiInLock);
  27349. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27350. }
  27351. }
  27352. static Array <VSTPluginWindow*> activeVSTWindows;
  27353. class VSTPluginWindow : public AudioProcessorEditor,
  27354. #if ! JUCE_MAC
  27355. public ComponentMovementWatcher,
  27356. #endif
  27357. public Timer
  27358. {
  27359. public:
  27360. VSTPluginWindow (VSTPluginInstance& plugin_)
  27361. : AudioProcessorEditor (&plugin_),
  27362. #if ! JUCE_MAC
  27363. ComponentMovementWatcher (this),
  27364. #endif
  27365. plugin (plugin_),
  27366. isOpen (false),
  27367. wasShowing (false),
  27368. pluginRefusesToResize (false),
  27369. pluginWantsKeys (false),
  27370. alreadyInside (false),
  27371. recursiveResize (false)
  27372. {
  27373. #if JUCE_WINDOWS
  27374. sizeCheckCount = 0;
  27375. pluginHWND = 0;
  27376. #elif JUCE_LINUX
  27377. pluginWindow = None;
  27378. pluginProc = None;
  27379. #else
  27380. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27381. #endif
  27382. activeVSTWindows.add (this);
  27383. setSize (1, 1);
  27384. setOpaque (true);
  27385. setVisible (true);
  27386. }
  27387. ~VSTPluginWindow()
  27388. {
  27389. #if JUCE_MAC
  27390. innerWrapper = 0;
  27391. #else
  27392. closePluginWindow();
  27393. #endif
  27394. activeVSTWindows.removeValue (this);
  27395. plugin.editorBeingDeleted (this);
  27396. }
  27397. #if ! JUCE_MAC
  27398. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27399. {
  27400. if (recursiveResize)
  27401. return;
  27402. Component* const topComp = getTopLevelComponent();
  27403. if (topComp->getPeer() != 0)
  27404. {
  27405. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27406. recursiveResize = true;
  27407. #if JUCE_WINDOWS
  27408. if (pluginHWND != 0)
  27409. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27410. #elif JUCE_LINUX
  27411. if (pluginWindow != 0)
  27412. {
  27413. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27414. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27415. XMapRaised (display, pluginWindow);
  27416. }
  27417. #endif
  27418. recursiveResize = false;
  27419. }
  27420. }
  27421. void componentVisibilityChanged (Component&)
  27422. {
  27423. const bool isShowingNow = isShowing();
  27424. if (wasShowing != isShowingNow)
  27425. {
  27426. wasShowing = isShowingNow;
  27427. if (isShowingNow)
  27428. openPluginWindow();
  27429. else
  27430. closePluginWindow();
  27431. }
  27432. componentMovedOrResized (true, true);
  27433. }
  27434. void componentPeerChanged()
  27435. {
  27436. closePluginWindow();
  27437. openPluginWindow();
  27438. }
  27439. #endif
  27440. bool keyStateChanged (bool)
  27441. {
  27442. return pluginWantsKeys;
  27443. }
  27444. bool keyPressed (const KeyPress&)
  27445. {
  27446. return pluginWantsKeys;
  27447. }
  27448. #if JUCE_MAC
  27449. void paint (Graphics& g)
  27450. {
  27451. g.fillAll (Colours::black);
  27452. }
  27453. #else
  27454. void paint (Graphics& g)
  27455. {
  27456. if (isOpen)
  27457. {
  27458. ComponentPeer* const peer = getPeer();
  27459. if (peer != 0)
  27460. {
  27461. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27462. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27463. #if JUCE_LINUX
  27464. if (pluginWindow != 0)
  27465. {
  27466. const Rectangle<int> clip (g.getClipBounds());
  27467. XEvent ev;
  27468. zerostruct (ev);
  27469. ev.xexpose.type = Expose;
  27470. ev.xexpose.display = display;
  27471. ev.xexpose.window = pluginWindow;
  27472. ev.xexpose.x = clip.getX();
  27473. ev.xexpose.y = clip.getY();
  27474. ev.xexpose.width = clip.getWidth();
  27475. ev.xexpose.height = clip.getHeight();
  27476. sendEventToChild (&ev);
  27477. }
  27478. #endif
  27479. }
  27480. }
  27481. else
  27482. {
  27483. g.fillAll (Colours::black);
  27484. }
  27485. }
  27486. #endif
  27487. void timerCallback()
  27488. {
  27489. #if JUCE_WINDOWS
  27490. if (--sizeCheckCount <= 0)
  27491. {
  27492. sizeCheckCount = 10;
  27493. checkPluginWindowSize();
  27494. }
  27495. #endif
  27496. try
  27497. {
  27498. static bool reentrant = false;
  27499. if (! reentrant)
  27500. {
  27501. reentrant = true;
  27502. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27503. reentrant = false;
  27504. }
  27505. }
  27506. catch (...)
  27507. {}
  27508. }
  27509. void mouseDown (const MouseEvent& e)
  27510. {
  27511. #if JUCE_LINUX
  27512. if (pluginWindow == 0)
  27513. return;
  27514. toFront (true);
  27515. XEvent ev;
  27516. zerostruct (ev);
  27517. ev.xbutton.display = display;
  27518. ev.xbutton.type = ButtonPress;
  27519. ev.xbutton.window = pluginWindow;
  27520. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27521. ev.xbutton.time = CurrentTime;
  27522. ev.xbutton.x = e.x;
  27523. ev.xbutton.y = e.y;
  27524. ev.xbutton.x_root = e.getScreenX();
  27525. ev.xbutton.y_root = e.getScreenY();
  27526. translateJuceToXButtonModifiers (e, ev);
  27527. sendEventToChild (&ev);
  27528. #elif JUCE_WINDOWS
  27529. (void) e;
  27530. toFront (true);
  27531. #endif
  27532. }
  27533. void broughtToFront()
  27534. {
  27535. activeVSTWindows.removeValue (this);
  27536. activeVSTWindows.add (this);
  27537. #if JUCE_MAC
  27538. dispatch (effEditTop, 0, 0, 0, 0);
  27539. #endif
  27540. }
  27541. juce_UseDebuggingNewOperator
  27542. private:
  27543. VSTPluginInstance& plugin;
  27544. bool isOpen, wasShowing, recursiveResize;
  27545. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27546. #if JUCE_WINDOWS
  27547. HWND pluginHWND;
  27548. void* originalWndProc;
  27549. int sizeCheckCount;
  27550. #elif JUCE_LINUX
  27551. Window pluginWindow;
  27552. EventProcPtr pluginProc;
  27553. #endif
  27554. #if JUCE_MAC
  27555. void openPluginWindow (WindowRef parentWindow)
  27556. {
  27557. if (isOpen || parentWindow == 0)
  27558. return;
  27559. isOpen = true;
  27560. ERect* rect = 0;
  27561. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27562. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27563. // do this before and after like in the steinberg example
  27564. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27565. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27566. // Install keyboard hooks
  27567. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27568. // double-check it's not too tiny
  27569. int w = 250, h = 150;
  27570. if (rect != 0)
  27571. {
  27572. w = rect->right - rect->left;
  27573. h = rect->bottom - rect->top;
  27574. if (w == 0 || h == 0)
  27575. {
  27576. w = 250;
  27577. h = 150;
  27578. }
  27579. }
  27580. w = jmax (w, 32);
  27581. h = jmax (h, 32);
  27582. setSize (w, h);
  27583. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27584. repaint();
  27585. }
  27586. #else
  27587. void openPluginWindow()
  27588. {
  27589. if (isOpen || getWindowHandle() == 0)
  27590. return;
  27591. log ("Opening VST UI: " + plugin.name);
  27592. isOpen = true;
  27593. ERect* rect = 0;
  27594. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27595. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27596. // do this before and after like in the steinberg example
  27597. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27598. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27599. // Install keyboard hooks
  27600. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27601. #if JUCE_WINDOWS
  27602. originalWndProc = 0;
  27603. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27604. if (pluginHWND == 0)
  27605. {
  27606. isOpen = false;
  27607. setSize (300, 150);
  27608. return;
  27609. }
  27610. #pragma warning (push)
  27611. #pragma warning (disable: 4244)
  27612. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27613. if (! pluginWantsKeys)
  27614. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27615. #pragma warning (pop)
  27616. int w, h;
  27617. RECT r;
  27618. GetWindowRect (pluginHWND, &r);
  27619. w = r.right - r.left;
  27620. h = r.bottom - r.top;
  27621. if (rect != 0)
  27622. {
  27623. const int rw = rect->right - rect->left;
  27624. const int rh = rect->bottom - rect->top;
  27625. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27626. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27627. {
  27628. // very dodgy logic to decide which size is right.
  27629. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27630. {
  27631. SetWindowPos (pluginHWND, 0,
  27632. 0, 0, rw, rh,
  27633. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27634. GetWindowRect (pluginHWND, &r);
  27635. w = r.right - r.left;
  27636. h = r.bottom - r.top;
  27637. pluginRefusesToResize = (w != rw) || (h != rh);
  27638. w = rw;
  27639. h = rh;
  27640. }
  27641. }
  27642. }
  27643. #elif JUCE_LINUX
  27644. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27645. if (pluginWindow != 0)
  27646. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27647. XInternAtom (display, "_XEventProc", False));
  27648. int w = 250, h = 150;
  27649. if (rect != 0)
  27650. {
  27651. w = rect->right - rect->left;
  27652. h = rect->bottom - rect->top;
  27653. if (w == 0 || h == 0)
  27654. {
  27655. w = 250;
  27656. h = 150;
  27657. }
  27658. }
  27659. if (pluginWindow != 0)
  27660. XMapRaised (display, pluginWindow);
  27661. #endif
  27662. // double-check it's not too tiny
  27663. w = jmax (w, 32);
  27664. h = jmax (h, 32);
  27665. setSize (w, h);
  27666. #if JUCE_WINDOWS
  27667. checkPluginWindowSize();
  27668. #endif
  27669. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27670. repaint();
  27671. }
  27672. #endif
  27673. #if ! JUCE_MAC
  27674. void closePluginWindow()
  27675. {
  27676. if (isOpen)
  27677. {
  27678. log ("Closing VST UI: " + plugin.getName());
  27679. isOpen = false;
  27680. dispatch (effEditClose, 0, 0, 0, 0);
  27681. #if JUCE_WINDOWS
  27682. #pragma warning (push)
  27683. #pragma warning (disable: 4244)
  27684. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27685. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27686. #pragma warning (pop)
  27687. stopTimer();
  27688. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27689. DestroyWindow (pluginHWND);
  27690. pluginHWND = 0;
  27691. #elif JUCE_LINUX
  27692. stopTimer();
  27693. pluginWindow = 0;
  27694. pluginProc = 0;
  27695. #endif
  27696. }
  27697. }
  27698. #endif
  27699. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27700. {
  27701. return plugin.dispatch (opcode, index, value, ptr, opt);
  27702. }
  27703. #if JUCE_WINDOWS
  27704. void checkPluginWindowSize()
  27705. {
  27706. RECT r;
  27707. GetWindowRect (pluginHWND, &r);
  27708. const int w = r.right - r.left;
  27709. const int h = r.bottom - r.top;
  27710. if (isShowing() && w > 0 && h > 0
  27711. && (w != getWidth() || h != getHeight())
  27712. && ! pluginRefusesToResize)
  27713. {
  27714. setSize (w, h);
  27715. sizeCheckCount = 0;
  27716. }
  27717. }
  27718. // hooks to get keyboard events from VST windows..
  27719. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27720. {
  27721. for (int i = activeVSTWindows.size(); --i >= 0;)
  27722. {
  27723. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27724. if (w->pluginHWND == hW)
  27725. {
  27726. if (message == WM_CHAR
  27727. || message == WM_KEYDOWN
  27728. || message == WM_SYSKEYDOWN
  27729. || message == WM_KEYUP
  27730. || message == WM_SYSKEYUP
  27731. || message == WM_APPCOMMAND)
  27732. {
  27733. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27734. message, wParam, lParam);
  27735. }
  27736. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27737. (HWND) w->pluginHWND,
  27738. message,
  27739. wParam,
  27740. lParam);
  27741. }
  27742. }
  27743. return DefWindowProc (hW, message, wParam, lParam);
  27744. }
  27745. #endif
  27746. #if JUCE_LINUX
  27747. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27748. void sendEventToChild (XEvent* event)
  27749. {
  27750. if (pluginProc != 0)
  27751. {
  27752. // if the plugin publishes an event procedure, pass the event directly..
  27753. pluginProc (event);
  27754. }
  27755. else if (pluginWindow != 0)
  27756. {
  27757. // if the plugin has a window, then send the event to the window so that
  27758. // its message thread will pick it up..
  27759. XSendEvent (display, pluginWindow, False, 0L, event);
  27760. XFlush (display);
  27761. }
  27762. }
  27763. void mouseEnter (const MouseEvent& e)
  27764. {
  27765. if (pluginWindow != 0)
  27766. {
  27767. XEvent ev;
  27768. zerostruct (ev);
  27769. ev.xcrossing.display = display;
  27770. ev.xcrossing.type = EnterNotify;
  27771. ev.xcrossing.window = pluginWindow;
  27772. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27773. ev.xcrossing.time = CurrentTime;
  27774. ev.xcrossing.x = e.x;
  27775. ev.xcrossing.y = e.y;
  27776. ev.xcrossing.x_root = e.getScreenX();
  27777. ev.xcrossing.y_root = e.getScreenY();
  27778. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27779. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27780. translateJuceToXCrossingModifiers (e, ev);
  27781. sendEventToChild (&ev);
  27782. }
  27783. }
  27784. void mouseExit (const MouseEvent& e)
  27785. {
  27786. if (pluginWindow != 0)
  27787. {
  27788. XEvent ev;
  27789. zerostruct (ev);
  27790. ev.xcrossing.display = display;
  27791. ev.xcrossing.type = LeaveNotify;
  27792. ev.xcrossing.window = pluginWindow;
  27793. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27794. ev.xcrossing.time = CurrentTime;
  27795. ev.xcrossing.x = e.x;
  27796. ev.xcrossing.y = e.y;
  27797. ev.xcrossing.x_root = e.getScreenX();
  27798. ev.xcrossing.y_root = e.getScreenY();
  27799. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27800. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27801. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27802. translateJuceToXCrossingModifiers (e, ev);
  27803. sendEventToChild (&ev);
  27804. }
  27805. }
  27806. void mouseMove (const MouseEvent& e)
  27807. {
  27808. if (pluginWindow != 0)
  27809. {
  27810. XEvent ev;
  27811. zerostruct (ev);
  27812. ev.xmotion.display = display;
  27813. ev.xmotion.type = MotionNotify;
  27814. ev.xmotion.window = pluginWindow;
  27815. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27816. ev.xmotion.time = CurrentTime;
  27817. ev.xmotion.is_hint = NotifyNormal;
  27818. ev.xmotion.x = e.x;
  27819. ev.xmotion.y = e.y;
  27820. ev.xmotion.x_root = e.getScreenX();
  27821. ev.xmotion.y_root = e.getScreenY();
  27822. sendEventToChild (&ev);
  27823. }
  27824. }
  27825. void mouseDrag (const MouseEvent& e)
  27826. {
  27827. if (pluginWindow != 0)
  27828. {
  27829. XEvent ev;
  27830. zerostruct (ev);
  27831. ev.xmotion.display = display;
  27832. ev.xmotion.type = MotionNotify;
  27833. ev.xmotion.window = pluginWindow;
  27834. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27835. ev.xmotion.time = CurrentTime;
  27836. ev.xmotion.x = e.x ;
  27837. ev.xmotion.y = e.y;
  27838. ev.xmotion.x_root = e.getScreenX();
  27839. ev.xmotion.y_root = e.getScreenY();
  27840. ev.xmotion.is_hint = NotifyNormal;
  27841. translateJuceToXMotionModifiers (e, ev);
  27842. sendEventToChild (&ev);
  27843. }
  27844. }
  27845. void mouseUp (const MouseEvent& e)
  27846. {
  27847. if (pluginWindow != 0)
  27848. {
  27849. XEvent ev;
  27850. zerostruct (ev);
  27851. ev.xbutton.display = display;
  27852. ev.xbutton.type = ButtonRelease;
  27853. ev.xbutton.window = pluginWindow;
  27854. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27855. ev.xbutton.time = CurrentTime;
  27856. ev.xbutton.x = e.x;
  27857. ev.xbutton.y = e.y;
  27858. ev.xbutton.x_root = e.getScreenX();
  27859. ev.xbutton.y_root = e.getScreenY();
  27860. translateJuceToXButtonModifiers (e, ev);
  27861. sendEventToChild (&ev);
  27862. }
  27863. }
  27864. void mouseWheelMove (const MouseEvent& e,
  27865. float incrementX,
  27866. float incrementY)
  27867. {
  27868. if (pluginWindow != 0)
  27869. {
  27870. XEvent ev;
  27871. zerostruct (ev);
  27872. ev.xbutton.display = display;
  27873. ev.xbutton.type = ButtonPress;
  27874. ev.xbutton.window = pluginWindow;
  27875. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27876. ev.xbutton.time = CurrentTime;
  27877. ev.xbutton.x = e.x;
  27878. ev.xbutton.y = e.y;
  27879. ev.xbutton.x_root = e.getScreenX();
  27880. ev.xbutton.y_root = e.getScreenY();
  27881. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27882. sendEventToChild (&ev);
  27883. // TODO - put a usleep here ?
  27884. ev.xbutton.type = ButtonRelease;
  27885. sendEventToChild (&ev);
  27886. }
  27887. }
  27888. #endif
  27889. #if JUCE_MAC
  27890. #if ! JUCE_SUPPORT_CARBON
  27891. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27892. #endif
  27893. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27894. {
  27895. public:
  27896. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27897. : owner (owner_),
  27898. alreadyInside (false)
  27899. {
  27900. }
  27901. ~InnerWrapperComponent()
  27902. {
  27903. deleteWindow();
  27904. }
  27905. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27906. {
  27907. owner->openPluginWindow (windowRef);
  27908. return 0;
  27909. }
  27910. void removeView (HIViewRef)
  27911. {
  27912. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27913. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27914. }
  27915. bool getEmbeddedViewSize (int& w, int& h)
  27916. {
  27917. ERect* rect = 0;
  27918. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27919. w = rect->right - rect->left;
  27920. h = rect->bottom - rect->top;
  27921. return true;
  27922. }
  27923. void mouseDown (int x, int y)
  27924. {
  27925. if (! alreadyInside)
  27926. {
  27927. alreadyInside = true;
  27928. getTopLevelComponent()->toFront (true);
  27929. owner->dispatch (effEditMouse, x, y, 0, 0);
  27930. alreadyInside = false;
  27931. }
  27932. else
  27933. {
  27934. PostEvent (::mouseDown, 0);
  27935. }
  27936. }
  27937. void paint()
  27938. {
  27939. ComponentPeer* const peer = getPeer();
  27940. if (peer != 0)
  27941. {
  27942. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27943. ERect r;
  27944. r.left = pos.getX();
  27945. r.right = r.left + getWidth();
  27946. r.top = pos.getY();
  27947. r.bottom = r.top + getHeight();
  27948. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27949. }
  27950. }
  27951. private:
  27952. VSTPluginWindow* const owner;
  27953. bool alreadyInside;
  27954. };
  27955. friend class InnerWrapperComponent;
  27956. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27957. void resized()
  27958. {
  27959. innerWrapper->setSize (getWidth(), getHeight());
  27960. }
  27961. #endif
  27962. };
  27963. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27964. {
  27965. if (hasEditor())
  27966. return new VSTPluginWindow (*this);
  27967. return 0;
  27968. }
  27969. void VSTPluginInstance::handleAsyncUpdate()
  27970. {
  27971. // indicates that something about the plugin has changed..
  27972. updateHostDisplay();
  27973. }
  27974. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27975. {
  27976. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27977. {
  27978. changeProgramName (getCurrentProgram(), prog->prgName);
  27979. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27980. setParameter (i, vst_swapFloat (prog->params[i]));
  27981. return true;
  27982. }
  27983. return false;
  27984. }
  27985. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27986. const int dataSize)
  27987. {
  27988. if (dataSize < 28)
  27989. return false;
  27990. const fxSet* const set = (const fxSet*) data;
  27991. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27992. || vst_swap (set->version) > fxbVersionNum)
  27993. return false;
  27994. if (vst_swap (set->fxMagic) == 'FxBk')
  27995. {
  27996. // bank of programs
  27997. if (vst_swap (set->numPrograms) >= 0)
  27998. {
  27999. const int oldProg = getCurrentProgram();
  28000. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  28001. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28002. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  28003. {
  28004. if (i != oldProg)
  28005. {
  28006. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  28007. if (((const char*) prog) - ((const char*) set) >= dataSize)
  28008. return false;
  28009. if (vst_swap (set->numPrograms) > 0)
  28010. setCurrentProgram (i);
  28011. if (! restoreProgramSettings (prog))
  28012. return false;
  28013. }
  28014. }
  28015. if (vst_swap (set->numPrograms) > 0)
  28016. setCurrentProgram (oldProg);
  28017. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  28018. if (((const char*) prog) - ((const char*) set) >= dataSize)
  28019. return false;
  28020. if (! restoreProgramSettings (prog))
  28021. return false;
  28022. }
  28023. }
  28024. else if (vst_swap (set->fxMagic) == 'FxCk')
  28025. {
  28026. // single program
  28027. const fxProgram* const prog = (const fxProgram*) data;
  28028. if (vst_swap (prog->chunkMagic) != 'CcnK')
  28029. return false;
  28030. changeProgramName (getCurrentProgram(), prog->prgName);
  28031. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  28032. setParameter (i, vst_swapFloat (prog->params[i]));
  28033. }
  28034. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  28035. {
  28036. // non-preset chunk
  28037. const fxChunkSet* const cset = (const fxChunkSet*) data;
  28038. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  28039. return false;
  28040. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  28041. }
  28042. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  28043. {
  28044. // preset chunk
  28045. const fxProgramSet* const cset = (const fxProgramSet*) data;
  28046. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  28047. return false;
  28048. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  28049. changeProgramName (getCurrentProgram(), cset->name);
  28050. }
  28051. else
  28052. {
  28053. return false;
  28054. }
  28055. return true;
  28056. }
  28057. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  28058. {
  28059. const int numParams = getNumParameters();
  28060. prog->chunkMagic = vst_swap ('CcnK');
  28061. prog->byteSize = 0;
  28062. prog->fxMagic = vst_swap ('FxCk');
  28063. prog->version = vst_swap (fxbVersionNum);
  28064. prog->fxID = vst_swap (getUID());
  28065. prog->fxVersion = vst_swap (getVersionNumber());
  28066. prog->numParams = vst_swap (numParams);
  28067. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  28068. for (int i = 0; i < numParams; ++i)
  28069. prog->params[i] = vst_swapFloat (getParameter (i));
  28070. }
  28071. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  28072. {
  28073. const int numPrograms = getNumPrograms();
  28074. const int numParams = getNumParameters();
  28075. if (usesChunks())
  28076. {
  28077. if (isFXB)
  28078. {
  28079. MemoryBlock chunk;
  28080. getChunkData (chunk, false, maxSizeMB);
  28081. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  28082. dest.setSize (totalLen, true);
  28083. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  28084. set->chunkMagic = vst_swap ('CcnK');
  28085. set->byteSize = 0;
  28086. set->fxMagic = vst_swap ('FBCh');
  28087. set->version = vst_swap (fxbVersionNum);
  28088. set->fxID = vst_swap (getUID());
  28089. set->fxVersion = vst_swap (getVersionNumber());
  28090. set->numPrograms = vst_swap (numPrograms);
  28091. set->chunkSize = vst_swap ((long) chunk.getSize());
  28092. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28093. }
  28094. else
  28095. {
  28096. MemoryBlock chunk;
  28097. getChunkData (chunk, true, maxSizeMB);
  28098. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  28099. dest.setSize (totalLen, true);
  28100. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  28101. set->chunkMagic = vst_swap ('CcnK');
  28102. set->byteSize = 0;
  28103. set->fxMagic = vst_swap ('FPCh');
  28104. set->version = vst_swap (fxbVersionNum);
  28105. set->fxID = vst_swap (getUID());
  28106. set->fxVersion = vst_swap (getVersionNumber());
  28107. set->numPrograms = vst_swap (numPrograms);
  28108. set->chunkSize = vst_swap ((long) chunk.getSize());
  28109. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  28110. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28111. }
  28112. }
  28113. else
  28114. {
  28115. if (isFXB)
  28116. {
  28117. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28118. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  28119. dest.setSize (len, true);
  28120. fxSet* const set = (fxSet*) dest.getData();
  28121. set->chunkMagic = vst_swap ('CcnK');
  28122. set->byteSize = 0;
  28123. set->fxMagic = vst_swap ('FxBk');
  28124. set->version = vst_swap (fxbVersionNum);
  28125. set->fxID = vst_swap (getUID());
  28126. set->fxVersion = vst_swap (getVersionNumber());
  28127. set->numPrograms = vst_swap (numPrograms);
  28128. const int oldProgram = getCurrentProgram();
  28129. MemoryBlock oldSettings;
  28130. createTempParameterStore (oldSettings);
  28131. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  28132. for (int i = 0; i < numPrograms; ++i)
  28133. {
  28134. if (i != oldProgram)
  28135. {
  28136. setCurrentProgram (i);
  28137. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  28138. }
  28139. }
  28140. setCurrentProgram (oldProgram);
  28141. restoreFromTempParameterStore (oldSettings);
  28142. }
  28143. else
  28144. {
  28145. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28146. dest.setSize (totalLen, true);
  28147. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28148. }
  28149. }
  28150. return true;
  28151. }
  28152. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28153. {
  28154. if (usesChunks())
  28155. {
  28156. void* data = 0;
  28157. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28158. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28159. {
  28160. mb.setSize (bytes);
  28161. mb.copyFrom (data, 0, bytes);
  28162. }
  28163. }
  28164. }
  28165. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28166. {
  28167. if (size > 0 && usesChunks())
  28168. {
  28169. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28170. if (! isPreset)
  28171. updateStoredProgramNames();
  28172. }
  28173. }
  28174. void VSTPluginInstance::timerCallback()
  28175. {
  28176. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28177. stopTimer();
  28178. }
  28179. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28180. {
  28181. const ScopedLock sl (lock);
  28182. ++insideVSTCallback;
  28183. int result = 0;
  28184. try
  28185. {
  28186. if (effect != 0)
  28187. {
  28188. #if JUCE_MAC
  28189. if (module->resFileId != 0)
  28190. UseResFile (module->resFileId);
  28191. #endif
  28192. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28193. #if JUCE_MAC
  28194. module->resFileId = CurResFile();
  28195. #endif
  28196. --insideVSTCallback;
  28197. return result;
  28198. }
  28199. }
  28200. catch (...)
  28201. {
  28202. }
  28203. --insideVSTCallback;
  28204. return result;
  28205. }
  28206. namespace
  28207. {
  28208. static const int defaultVSTSampleRateValue = 16384;
  28209. static const int defaultVSTBlockSizeValue = 512;
  28210. // handles non plugin-specific callbacks..
  28211. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28212. {
  28213. (void) index;
  28214. (void) value;
  28215. (void) opt;
  28216. switch (opcode)
  28217. {
  28218. case audioMasterCanDo:
  28219. {
  28220. static const char* canDos[] = { "supplyIdle",
  28221. "sendVstEvents",
  28222. "sendVstMidiEvent",
  28223. "sendVstTimeInfo",
  28224. "receiveVstEvents",
  28225. "receiveVstMidiEvent",
  28226. "supportShell",
  28227. "shellCategory" };
  28228. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28229. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28230. return 1;
  28231. return 0;
  28232. }
  28233. case audioMasterVersion: return 0x2400;
  28234. case audioMasterCurrentId: return shellUIDToCreate;
  28235. case audioMasterGetNumAutomatableParameters: return 0;
  28236. case audioMasterGetAutomationState: return 1;
  28237. case audioMasterGetVendorVersion: return 0x0101;
  28238. case audioMasterGetVendorString:
  28239. case audioMasterGetProductString:
  28240. {
  28241. String hostName ("Juce VST Host");
  28242. if (JUCEApplication::getInstance() != 0)
  28243. hostName = JUCEApplication::getInstance()->getApplicationName();
  28244. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28245. break;
  28246. }
  28247. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28248. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28249. case audioMasterSetOutputSampleRate: return 0;
  28250. default:
  28251. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28252. break;
  28253. }
  28254. return 0;
  28255. }
  28256. }
  28257. // handles callbacks for a specific plugin
  28258. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28259. {
  28260. switch (opcode)
  28261. {
  28262. case audioMasterAutomate:
  28263. sendParamChangeMessageToListeners (index, opt);
  28264. break;
  28265. case audioMasterProcessEvents:
  28266. handleMidiFromPlugin ((const VstEvents*) ptr);
  28267. break;
  28268. case audioMasterGetTime:
  28269. #if JUCE_MSVC
  28270. #pragma warning (push)
  28271. #pragma warning (disable: 4311)
  28272. #endif
  28273. return (VstIntPtr) &vstHostTime;
  28274. #if JUCE_MSVC
  28275. #pragma warning (pop)
  28276. #endif
  28277. break;
  28278. case audioMasterIdle:
  28279. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28280. {
  28281. ++insideVSTCallback;
  28282. #if JUCE_MAC
  28283. if (getActiveEditor() != 0)
  28284. dispatch (effEditIdle, 0, 0, 0, 0);
  28285. #endif
  28286. juce_callAnyTimersSynchronously();
  28287. handleUpdateNowIfNeeded();
  28288. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28289. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28290. --insideVSTCallback;
  28291. }
  28292. break;
  28293. case audioMasterUpdateDisplay:
  28294. triggerAsyncUpdate();
  28295. break;
  28296. case audioMasterTempoAt:
  28297. // returns (10000 * bpm)
  28298. break;
  28299. case audioMasterNeedIdle:
  28300. startTimer (50);
  28301. break;
  28302. case audioMasterSizeWindow:
  28303. if (getActiveEditor() != 0)
  28304. getActiveEditor()->setSize (index, value);
  28305. return 1;
  28306. case audioMasterGetSampleRate:
  28307. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28308. case audioMasterGetBlockSize:
  28309. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28310. case audioMasterWantMidi:
  28311. wantsMidiMessages = true;
  28312. break;
  28313. case audioMasterGetDirectory:
  28314. #if JUCE_MAC
  28315. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28316. #else
  28317. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28318. #endif
  28319. case audioMasterGetAutomationState:
  28320. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28321. break;
  28322. // none of these are handled (yet)..
  28323. case audioMasterBeginEdit:
  28324. case audioMasterEndEdit:
  28325. case audioMasterSetTime:
  28326. case audioMasterPinConnected:
  28327. case audioMasterGetParameterQuantization:
  28328. case audioMasterIOChanged:
  28329. case audioMasterGetInputLatency:
  28330. case audioMasterGetOutputLatency:
  28331. case audioMasterGetPreviousPlug:
  28332. case audioMasterGetNextPlug:
  28333. case audioMasterWillReplaceOrAccumulate:
  28334. case audioMasterGetCurrentProcessLevel:
  28335. case audioMasterOfflineStart:
  28336. case audioMasterOfflineRead:
  28337. case audioMasterOfflineWrite:
  28338. case audioMasterOfflineGetCurrentPass:
  28339. case audioMasterOfflineGetCurrentMetaPass:
  28340. case audioMasterVendorSpecific:
  28341. case audioMasterSetIcon:
  28342. case audioMasterGetLanguage:
  28343. case audioMasterOpenWindow:
  28344. case audioMasterCloseWindow:
  28345. break;
  28346. default:
  28347. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28348. }
  28349. return 0;
  28350. }
  28351. // entry point for all callbacks from the plugin
  28352. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28353. {
  28354. try
  28355. {
  28356. if (effect != 0 && effect->resvd2 != 0)
  28357. {
  28358. return ((VSTPluginInstance*)(effect->resvd2))
  28359. ->handleCallback (opcode, index, value, ptr, opt);
  28360. }
  28361. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28362. }
  28363. catch (...)
  28364. {
  28365. return 0;
  28366. }
  28367. }
  28368. const String VSTPluginInstance::getVersion() const
  28369. {
  28370. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28371. String s;
  28372. if (v == 0 || v == -1)
  28373. v = getVersionNumber();
  28374. if (v != 0)
  28375. {
  28376. int versionBits[4];
  28377. int n = 0;
  28378. while (v != 0)
  28379. {
  28380. versionBits [n++] = (v & 0xff);
  28381. v >>= 8;
  28382. }
  28383. s << 'V';
  28384. while (n > 0)
  28385. {
  28386. s << versionBits [--n];
  28387. if (n > 0)
  28388. s << '.';
  28389. }
  28390. }
  28391. return s;
  28392. }
  28393. int VSTPluginInstance::getUID() const
  28394. {
  28395. int uid = effect != 0 ? effect->uniqueID : 0;
  28396. if (uid == 0)
  28397. uid = module->file.hashCode();
  28398. return uid;
  28399. }
  28400. const String VSTPluginInstance::getCategory() const
  28401. {
  28402. const char* result = 0;
  28403. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28404. {
  28405. case kPlugCategEffect: result = "Effect"; break;
  28406. case kPlugCategSynth: result = "Synth"; break;
  28407. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28408. case kPlugCategMastering: result = "Mastering"; break;
  28409. case kPlugCategSpacializer: result = "Spacial"; break;
  28410. case kPlugCategRoomFx: result = "Reverb"; break;
  28411. case kPlugSurroundFx: result = "Surround"; break;
  28412. case kPlugCategRestoration: result = "Restoration"; break;
  28413. case kPlugCategGenerator: result = "Tone generation"; break;
  28414. default: break;
  28415. }
  28416. return result;
  28417. }
  28418. float VSTPluginInstance::getParameter (int index)
  28419. {
  28420. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28421. {
  28422. try
  28423. {
  28424. const ScopedLock sl (lock);
  28425. return effect->getParameter (effect, index);
  28426. }
  28427. catch (...)
  28428. {
  28429. }
  28430. }
  28431. return 0.0f;
  28432. }
  28433. void VSTPluginInstance::setParameter (int index, float newValue)
  28434. {
  28435. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28436. {
  28437. try
  28438. {
  28439. const ScopedLock sl (lock);
  28440. if (effect->getParameter (effect, index) != newValue)
  28441. effect->setParameter (effect, index, newValue);
  28442. }
  28443. catch (...)
  28444. {
  28445. }
  28446. }
  28447. }
  28448. const String VSTPluginInstance::getParameterName (int index)
  28449. {
  28450. if (effect != 0)
  28451. {
  28452. jassert (index >= 0 && index < effect->numParams);
  28453. char nm [256];
  28454. zerostruct (nm);
  28455. dispatch (effGetParamName, index, 0, nm, 0);
  28456. return String (nm).trim();
  28457. }
  28458. return String::empty;
  28459. }
  28460. const String VSTPluginInstance::getParameterLabel (int index) const
  28461. {
  28462. if (effect != 0)
  28463. {
  28464. jassert (index >= 0 && index < effect->numParams);
  28465. char nm [256];
  28466. zerostruct (nm);
  28467. dispatch (effGetParamLabel, index, 0, nm, 0);
  28468. return String (nm).trim();
  28469. }
  28470. return String::empty;
  28471. }
  28472. const String VSTPluginInstance::getParameterText (int index)
  28473. {
  28474. if (effect != 0)
  28475. {
  28476. jassert (index >= 0 && index < effect->numParams);
  28477. char nm [256];
  28478. zerostruct (nm);
  28479. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28480. return String (nm).trim();
  28481. }
  28482. return String::empty;
  28483. }
  28484. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28485. {
  28486. if (effect != 0)
  28487. {
  28488. jassert (index >= 0 && index < effect->numParams);
  28489. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28490. }
  28491. return false;
  28492. }
  28493. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28494. {
  28495. dest.setSize (64 + 4 * getNumParameters());
  28496. dest.fillWith (0);
  28497. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28498. float* const p = (float*) (((char*) dest.getData()) + 64);
  28499. for (int i = 0; i < getNumParameters(); ++i)
  28500. p[i] = getParameter(i);
  28501. }
  28502. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28503. {
  28504. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28505. float* p = (float*) (((char*) m.getData()) + 64);
  28506. for (int i = 0; i < getNumParameters(); ++i)
  28507. setParameter (i, p[i]);
  28508. }
  28509. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28510. {
  28511. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28512. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28513. }
  28514. const String VSTPluginInstance::getProgramName (int index)
  28515. {
  28516. if (index == getCurrentProgram())
  28517. {
  28518. return getCurrentProgramName();
  28519. }
  28520. else if (effect != 0)
  28521. {
  28522. char nm [256];
  28523. zerostruct (nm);
  28524. if (dispatch (effGetProgramNameIndexed,
  28525. jlimit (0, getNumPrograms(), index),
  28526. -1, nm, 0) != 0)
  28527. {
  28528. return String (nm).trim();
  28529. }
  28530. }
  28531. return programNames [index];
  28532. }
  28533. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28534. {
  28535. if (index == getCurrentProgram())
  28536. {
  28537. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28538. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28539. }
  28540. else
  28541. {
  28542. jassertfalse; // xxx not implemented!
  28543. }
  28544. }
  28545. void VSTPluginInstance::updateStoredProgramNames()
  28546. {
  28547. if (effect != 0 && getNumPrograms() > 0)
  28548. {
  28549. char nm [256];
  28550. zerostruct (nm);
  28551. // only do this if the plugin can't use indexed names..
  28552. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28553. {
  28554. const int oldProgram = getCurrentProgram();
  28555. MemoryBlock oldSettings;
  28556. createTempParameterStore (oldSettings);
  28557. for (int i = 0; i < getNumPrograms(); ++i)
  28558. {
  28559. setCurrentProgram (i);
  28560. getCurrentProgramName(); // (this updates the list)
  28561. }
  28562. setCurrentProgram (oldProgram);
  28563. restoreFromTempParameterStore (oldSettings);
  28564. }
  28565. }
  28566. }
  28567. const String VSTPluginInstance::getCurrentProgramName()
  28568. {
  28569. if (effect != 0)
  28570. {
  28571. char nm [256];
  28572. zerostruct (nm);
  28573. dispatch (effGetProgramName, 0, 0, nm, 0);
  28574. const int index = getCurrentProgram();
  28575. if (programNames[index].isEmpty())
  28576. {
  28577. while (programNames.size() < index)
  28578. programNames.add (String::empty);
  28579. programNames.set (index, String (nm).trim());
  28580. }
  28581. return String (nm).trim();
  28582. }
  28583. return String::empty;
  28584. }
  28585. const String VSTPluginInstance::getInputChannelName (int index) const
  28586. {
  28587. if (index >= 0 && index < getNumInputChannels())
  28588. {
  28589. VstPinProperties pinProps;
  28590. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28591. return String (pinProps.label, sizeof (pinProps.label));
  28592. }
  28593. return String::empty;
  28594. }
  28595. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28596. {
  28597. if (index < 0 || index >= getNumInputChannels())
  28598. return false;
  28599. VstPinProperties pinProps;
  28600. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28601. return (pinProps.flags & kVstPinIsStereo) != 0;
  28602. return true;
  28603. }
  28604. const String VSTPluginInstance::getOutputChannelName (int index) const
  28605. {
  28606. if (index >= 0 && index < getNumOutputChannels())
  28607. {
  28608. VstPinProperties pinProps;
  28609. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28610. return String (pinProps.label, sizeof (pinProps.label));
  28611. }
  28612. return String::empty;
  28613. }
  28614. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28615. {
  28616. if (index < 0 || index >= getNumOutputChannels())
  28617. return false;
  28618. VstPinProperties pinProps;
  28619. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28620. return (pinProps.flags & kVstPinIsStereo) != 0;
  28621. return true;
  28622. }
  28623. void VSTPluginInstance::setPower (const bool on)
  28624. {
  28625. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28626. isPowerOn = on;
  28627. }
  28628. const int defaultMaxSizeMB = 64;
  28629. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28630. {
  28631. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28632. }
  28633. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28634. {
  28635. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28636. }
  28637. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28638. {
  28639. loadFromFXBFile (data, sizeInBytes);
  28640. }
  28641. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28642. {
  28643. loadFromFXBFile (data, sizeInBytes);
  28644. }
  28645. VSTPluginFormat::VSTPluginFormat()
  28646. {
  28647. }
  28648. VSTPluginFormat::~VSTPluginFormat()
  28649. {
  28650. }
  28651. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28652. const String& fileOrIdentifier)
  28653. {
  28654. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28655. return;
  28656. PluginDescription desc;
  28657. desc.fileOrIdentifier = fileOrIdentifier;
  28658. desc.uid = 0;
  28659. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28660. if (instance == 0)
  28661. return;
  28662. try
  28663. {
  28664. #if JUCE_MAC
  28665. if (instance->module->resFileId != 0)
  28666. UseResFile (instance->module->resFileId);
  28667. #endif
  28668. instance->fillInPluginDescription (desc);
  28669. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28670. if (category != kPlugCategShell)
  28671. {
  28672. // Normal plugin...
  28673. results.add (new PluginDescription (desc));
  28674. ++insideVSTCallback;
  28675. instance->dispatch (effOpen, 0, 0, 0, 0);
  28676. --insideVSTCallback;
  28677. }
  28678. else
  28679. {
  28680. // It's a shell plugin, so iterate all the subtypes...
  28681. char shellEffectName [64];
  28682. for (;;)
  28683. {
  28684. zerostruct (shellEffectName);
  28685. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28686. if (uid == 0)
  28687. {
  28688. break;
  28689. }
  28690. else
  28691. {
  28692. desc.uid = uid;
  28693. desc.name = shellEffectName;
  28694. bool alreadyThere = false;
  28695. for (int i = results.size(); --i >= 0;)
  28696. {
  28697. PluginDescription* const d = results.getUnchecked(i);
  28698. if (d->isDuplicateOf (desc))
  28699. {
  28700. alreadyThere = true;
  28701. break;
  28702. }
  28703. }
  28704. if (! alreadyThere)
  28705. results.add (new PluginDescription (desc));
  28706. }
  28707. }
  28708. }
  28709. }
  28710. catch (...)
  28711. {
  28712. // crashed while loading...
  28713. }
  28714. }
  28715. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28716. {
  28717. ScopedPointer <VSTPluginInstance> result;
  28718. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28719. {
  28720. File file (desc.fileOrIdentifier);
  28721. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28722. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28723. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28724. if (module != 0)
  28725. {
  28726. shellUIDToCreate = desc.uid;
  28727. result = new VSTPluginInstance (module);
  28728. if (result->effect != 0)
  28729. {
  28730. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28731. result->initialise();
  28732. }
  28733. else
  28734. {
  28735. result = 0;
  28736. }
  28737. }
  28738. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28739. }
  28740. return result.release();
  28741. }
  28742. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28743. {
  28744. const File f (fileOrIdentifier);
  28745. #if JUCE_MAC
  28746. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28747. return true;
  28748. #if JUCE_PPC
  28749. FSRef fileRef;
  28750. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28751. {
  28752. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28753. if (resFileId != -1)
  28754. {
  28755. const int numEffects = Count1Resources ('aEff');
  28756. CloseResFile (resFileId);
  28757. if (numEffects > 0)
  28758. return true;
  28759. }
  28760. }
  28761. #endif
  28762. return false;
  28763. #elif JUCE_WINDOWS
  28764. return f.existsAsFile() && f.hasFileExtension (".dll");
  28765. #elif JUCE_LINUX
  28766. return f.existsAsFile() && f.hasFileExtension (".so");
  28767. #endif
  28768. }
  28769. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28770. {
  28771. return fileOrIdentifier;
  28772. }
  28773. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28774. {
  28775. return File (desc.fileOrIdentifier).exists();
  28776. }
  28777. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28778. {
  28779. StringArray results;
  28780. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28781. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28782. return results;
  28783. }
  28784. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28785. {
  28786. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28787. // .component or .vst directories.
  28788. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28789. while (iter.next())
  28790. {
  28791. const File f (iter.getFile());
  28792. bool isPlugin = false;
  28793. if (fileMightContainThisPluginType (f.getFullPathName()))
  28794. {
  28795. isPlugin = true;
  28796. results.add (f.getFullPathName());
  28797. }
  28798. if (recursive && (! isPlugin) && f.isDirectory())
  28799. recursiveFileSearch (results, f, true);
  28800. }
  28801. }
  28802. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28803. {
  28804. #if JUCE_MAC
  28805. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28806. #elif JUCE_WINDOWS
  28807. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28808. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28809. #elif JUCE_LINUX
  28810. return FileSearchPath ("/usr/lib/vst");
  28811. #endif
  28812. }
  28813. END_JUCE_NAMESPACE
  28814. #endif
  28815. #undef log
  28816. #endif
  28817. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28818. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28819. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28820. BEGIN_JUCE_NAMESPACE
  28821. AudioProcessor::AudioProcessor()
  28822. : playHead (0),
  28823. activeEditor (0),
  28824. sampleRate (0),
  28825. blockSize (0),
  28826. numInputChannels (0),
  28827. numOutputChannels (0),
  28828. latencySamples (0),
  28829. suspended (false),
  28830. nonRealtime (false)
  28831. {
  28832. }
  28833. AudioProcessor::~AudioProcessor()
  28834. {
  28835. // ooh, nasty - the editor should have been deleted before the filter
  28836. // that it refers to is deleted..
  28837. jassert (activeEditor == 0);
  28838. #if JUCE_DEBUG
  28839. // This will fail if you've called beginParameterChangeGesture() for one
  28840. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28841. jassert (changingParams.countNumberOfSetBits() == 0);
  28842. #endif
  28843. }
  28844. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28845. {
  28846. playHead = newPlayHead;
  28847. }
  28848. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28849. {
  28850. const ScopedLock sl (listenerLock);
  28851. listeners.addIfNotAlreadyThere (newListener);
  28852. }
  28853. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28854. {
  28855. const ScopedLock sl (listenerLock);
  28856. listeners.removeValue (listenerToRemove);
  28857. }
  28858. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28859. const int numOuts,
  28860. const double sampleRate_,
  28861. const int blockSize_) throw()
  28862. {
  28863. numInputChannels = numIns;
  28864. numOutputChannels = numOuts;
  28865. sampleRate = sampleRate_;
  28866. blockSize = blockSize_;
  28867. }
  28868. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28869. {
  28870. nonRealtime = nonRealtime_;
  28871. }
  28872. void AudioProcessor::setLatencySamples (const int newLatency)
  28873. {
  28874. if (latencySamples != newLatency)
  28875. {
  28876. latencySamples = newLatency;
  28877. updateHostDisplay();
  28878. }
  28879. }
  28880. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28881. const float newValue)
  28882. {
  28883. setParameter (parameterIndex, newValue);
  28884. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28885. }
  28886. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28887. {
  28888. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28889. for (int i = listeners.size(); --i >= 0;)
  28890. {
  28891. AudioProcessorListener* l;
  28892. {
  28893. const ScopedLock sl (listenerLock);
  28894. l = listeners [i];
  28895. }
  28896. if (l != 0)
  28897. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28898. }
  28899. }
  28900. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28901. {
  28902. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28903. #if JUCE_DEBUG
  28904. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28905. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28906. jassert (! changingParams [parameterIndex]);
  28907. changingParams.setBit (parameterIndex);
  28908. #endif
  28909. for (int i = listeners.size(); --i >= 0;)
  28910. {
  28911. AudioProcessorListener* l;
  28912. {
  28913. const ScopedLock sl (listenerLock);
  28914. l = listeners [i];
  28915. }
  28916. if (l != 0)
  28917. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28918. }
  28919. }
  28920. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28921. {
  28922. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28923. #if JUCE_DEBUG
  28924. // This means you've called endParameterChangeGesture without having previously called
  28925. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28926. // calls matched correctly.
  28927. jassert (changingParams [parameterIndex]);
  28928. changingParams.clearBit (parameterIndex);
  28929. #endif
  28930. for (int i = listeners.size(); --i >= 0;)
  28931. {
  28932. AudioProcessorListener* l;
  28933. {
  28934. const ScopedLock sl (listenerLock);
  28935. l = listeners [i];
  28936. }
  28937. if (l != 0)
  28938. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28939. }
  28940. }
  28941. void AudioProcessor::updateHostDisplay()
  28942. {
  28943. for (int i = listeners.size(); --i >= 0;)
  28944. {
  28945. AudioProcessorListener* l;
  28946. {
  28947. const ScopedLock sl (listenerLock);
  28948. l = listeners [i];
  28949. }
  28950. if (l != 0)
  28951. l->audioProcessorChanged (this);
  28952. }
  28953. }
  28954. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28955. {
  28956. return true;
  28957. }
  28958. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28959. {
  28960. return false;
  28961. }
  28962. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28963. {
  28964. const ScopedLock sl (callbackLock);
  28965. suspended = shouldBeSuspended;
  28966. }
  28967. void AudioProcessor::reset()
  28968. {
  28969. }
  28970. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28971. {
  28972. const ScopedLock sl (callbackLock);
  28973. jassert (activeEditor == editor);
  28974. if (activeEditor == editor)
  28975. activeEditor = 0;
  28976. }
  28977. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28978. {
  28979. if (activeEditor != 0)
  28980. return activeEditor;
  28981. AudioProcessorEditor* const ed = createEditor();
  28982. // You must make your hasEditor() method return a consistent result!
  28983. jassert (hasEditor() == (ed != 0));
  28984. if (ed != 0)
  28985. {
  28986. // you must give your editor comp a size before returning it..
  28987. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28988. const ScopedLock sl (callbackLock);
  28989. activeEditor = ed;
  28990. }
  28991. return ed;
  28992. }
  28993. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28994. {
  28995. getStateInformation (destData);
  28996. }
  28997. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28998. {
  28999. setStateInformation (data, sizeInBytes);
  29000. }
  29001. // magic number to identify memory blocks that we've stored as XML
  29002. const uint32 magicXmlNumber = 0x21324356;
  29003. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  29004. JUCE_NAMESPACE::MemoryBlock& destData)
  29005. {
  29006. const String xmlString (xml.createDocument (String::empty, true, false));
  29007. const int stringLength = xmlString.getNumBytesAsUTF8();
  29008. destData.setSize (stringLength + 10);
  29009. char* const d = static_cast<char*> (destData.getData());
  29010. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  29011. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  29012. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  29013. }
  29014. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  29015. const int sizeInBytes)
  29016. {
  29017. if (sizeInBytes > 8
  29018. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  29019. {
  29020. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  29021. if (stringLength > 0)
  29022. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  29023. jmin ((sizeInBytes - 8), stringLength)));
  29024. }
  29025. return 0;
  29026. }
  29027. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  29028. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  29029. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  29030. {
  29031. return timeInSeconds == other.timeInSeconds
  29032. && ppqPosition == other.ppqPosition
  29033. && editOriginTime == other.editOriginTime
  29034. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  29035. && frameRate == other.frameRate
  29036. && isPlaying == other.isPlaying
  29037. && isRecording == other.isRecording
  29038. && bpm == other.bpm
  29039. && timeSigNumerator == other.timeSigNumerator
  29040. && timeSigDenominator == other.timeSigDenominator;
  29041. }
  29042. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  29043. {
  29044. return ! operator== (other);
  29045. }
  29046. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  29047. {
  29048. zerostruct (*this);
  29049. timeSigNumerator = 4;
  29050. timeSigDenominator = 4;
  29051. bpm = 120;
  29052. }
  29053. END_JUCE_NAMESPACE
  29054. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  29055. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  29056. BEGIN_JUCE_NAMESPACE
  29057. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  29058. : owner (owner_)
  29059. {
  29060. // the filter must be valid..
  29061. jassert (owner != 0);
  29062. }
  29063. AudioProcessorEditor::~AudioProcessorEditor()
  29064. {
  29065. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  29066. // filter for some reason..
  29067. jassert (owner->getActiveEditor() != this);
  29068. }
  29069. END_JUCE_NAMESPACE
  29070. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  29071. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  29072. BEGIN_JUCE_NAMESPACE
  29073. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  29074. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  29075. : id (id_),
  29076. processor (processor_),
  29077. isPrepared (false)
  29078. {
  29079. jassert (processor_ != 0);
  29080. }
  29081. AudioProcessorGraph::Node::~Node()
  29082. {
  29083. }
  29084. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  29085. AudioProcessorGraph* const graph)
  29086. {
  29087. if (! isPrepared)
  29088. {
  29089. isPrepared = true;
  29090. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29091. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  29092. if (ioProc != 0)
  29093. ioProc->setParentGraph (graph);
  29094. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  29095. processor->getNumOutputChannels(),
  29096. sampleRate, blockSize);
  29097. processor->prepareToPlay (sampleRate, blockSize);
  29098. }
  29099. }
  29100. void AudioProcessorGraph::Node::unprepare()
  29101. {
  29102. if (isPrepared)
  29103. {
  29104. isPrepared = false;
  29105. processor->releaseResources();
  29106. }
  29107. }
  29108. AudioProcessorGraph::AudioProcessorGraph()
  29109. : lastNodeId (0),
  29110. renderingBuffers (1, 1),
  29111. currentAudioOutputBuffer (1, 1)
  29112. {
  29113. }
  29114. AudioProcessorGraph::~AudioProcessorGraph()
  29115. {
  29116. clearRenderingSequence();
  29117. clear();
  29118. }
  29119. const String AudioProcessorGraph::getName() const
  29120. {
  29121. return "Audio Graph";
  29122. }
  29123. void AudioProcessorGraph::clear()
  29124. {
  29125. nodes.clear();
  29126. connections.clear();
  29127. triggerAsyncUpdate();
  29128. }
  29129. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  29130. {
  29131. for (int i = nodes.size(); --i >= 0;)
  29132. if (nodes.getUnchecked(i)->id == nodeId)
  29133. return nodes.getUnchecked(i);
  29134. return 0;
  29135. }
  29136. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  29137. uint32 nodeId)
  29138. {
  29139. if (newProcessor == 0)
  29140. {
  29141. jassertfalse;
  29142. return 0;
  29143. }
  29144. if (nodeId == 0)
  29145. {
  29146. nodeId = ++lastNodeId;
  29147. }
  29148. else
  29149. {
  29150. // you can't add a node with an id that already exists in the graph..
  29151. jassert (getNodeForId (nodeId) == 0);
  29152. removeNode (nodeId);
  29153. }
  29154. lastNodeId = nodeId;
  29155. Node* const n = new Node (nodeId, newProcessor);
  29156. nodes.add (n);
  29157. triggerAsyncUpdate();
  29158. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29159. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29160. if (ioProc != 0)
  29161. ioProc->setParentGraph (this);
  29162. return n;
  29163. }
  29164. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29165. {
  29166. disconnectNode (nodeId);
  29167. for (int i = nodes.size(); --i >= 0;)
  29168. {
  29169. if (nodes.getUnchecked(i)->id == nodeId)
  29170. {
  29171. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29172. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29173. if (ioProc != 0)
  29174. ioProc->setParentGraph (0);
  29175. nodes.remove (i);
  29176. triggerAsyncUpdate();
  29177. return true;
  29178. }
  29179. }
  29180. return false;
  29181. }
  29182. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29183. const int sourceChannelIndex,
  29184. const uint32 destNodeId,
  29185. const int destChannelIndex) const
  29186. {
  29187. for (int i = connections.size(); --i >= 0;)
  29188. {
  29189. const Connection* const c = connections.getUnchecked(i);
  29190. if (c->sourceNodeId == sourceNodeId
  29191. && c->destNodeId == destNodeId
  29192. && c->sourceChannelIndex == sourceChannelIndex
  29193. && c->destChannelIndex == destChannelIndex)
  29194. {
  29195. return c;
  29196. }
  29197. }
  29198. return 0;
  29199. }
  29200. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29201. const uint32 possibleDestNodeId) const
  29202. {
  29203. for (int i = connections.size(); --i >= 0;)
  29204. {
  29205. const Connection* const c = connections.getUnchecked(i);
  29206. if (c->sourceNodeId == possibleSourceNodeId
  29207. && c->destNodeId == possibleDestNodeId)
  29208. {
  29209. return true;
  29210. }
  29211. }
  29212. return false;
  29213. }
  29214. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29215. const int sourceChannelIndex,
  29216. const uint32 destNodeId,
  29217. const int destChannelIndex) const
  29218. {
  29219. if (sourceChannelIndex < 0
  29220. || destChannelIndex < 0
  29221. || sourceNodeId == destNodeId
  29222. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29223. return false;
  29224. const Node* const source = getNodeForId (sourceNodeId);
  29225. if (source == 0
  29226. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29227. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29228. return false;
  29229. const Node* const dest = getNodeForId (destNodeId);
  29230. if (dest == 0
  29231. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29232. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29233. return false;
  29234. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29235. destNodeId, destChannelIndex) == 0;
  29236. }
  29237. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29238. const int sourceChannelIndex,
  29239. const uint32 destNodeId,
  29240. const int destChannelIndex)
  29241. {
  29242. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29243. return false;
  29244. Connection* const c = new Connection();
  29245. c->sourceNodeId = sourceNodeId;
  29246. c->sourceChannelIndex = sourceChannelIndex;
  29247. c->destNodeId = destNodeId;
  29248. c->destChannelIndex = destChannelIndex;
  29249. connections.add (c);
  29250. triggerAsyncUpdate();
  29251. return true;
  29252. }
  29253. void AudioProcessorGraph::removeConnection (const int index)
  29254. {
  29255. connections.remove (index);
  29256. triggerAsyncUpdate();
  29257. }
  29258. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29259. const uint32 destNodeId, const int destChannelIndex)
  29260. {
  29261. bool doneAnything = false;
  29262. for (int i = connections.size(); --i >= 0;)
  29263. {
  29264. const Connection* const c = connections.getUnchecked(i);
  29265. if (c->sourceNodeId == sourceNodeId
  29266. && c->destNodeId == destNodeId
  29267. && c->sourceChannelIndex == sourceChannelIndex
  29268. && c->destChannelIndex == destChannelIndex)
  29269. {
  29270. removeConnection (i);
  29271. doneAnything = true;
  29272. triggerAsyncUpdate();
  29273. }
  29274. }
  29275. return doneAnything;
  29276. }
  29277. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29278. {
  29279. bool doneAnything = false;
  29280. for (int i = connections.size(); --i >= 0;)
  29281. {
  29282. const Connection* const c = connections.getUnchecked(i);
  29283. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29284. {
  29285. removeConnection (i);
  29286. doneAnything = true;
  29287. triggerAsyncUpdate();
  29288. }
  29289. }
  29290. return doneAnything;
  29291. }
  29292. bool AudioProcessorGraph::removeIllegalConnections()
  29293. {
  29294. bool doneAnything = false;
  29295. for (int i = connections.size(); --i >= 0;)
  29296. {
  29297. const Connection* const c = connections.getUnchecked(i);
  29298. const Node* const source = getNodeForId (c->sourceNodeId);
  29299. const Node* const dest = getNodeForId (c->destNodeId);
  29300. if (source == 0 || dest == 0
  29301. || (c->sourceChannelIndex != midiChannelIndex
  29302. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29303. || (c->sourceChannelIndex == midiChannelIndex
  29304. && ! source->processor->producesMidi())
  29305. || (c->destChannelIndex != midiChannelIndex
  29306. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29307. || (c->destChannelIndex == midiChannelIndex
  29308. && ! dest->processor->acceptsMidi()))
  29309. {
  29310. removeConnection (i);
  29311. doneAnything = true;
  29312. triggerAsyncUpdate();
  29313. }
  29314. }
  29315. return doneAnything;
  29316. }
  29317. namespace GraphRenderingOps
  29318. {
  29319. class AudioGraphRenderingOp
  29320. {
  29321. public:
  29322. AudioGraphRenderingOp() {}
  29323. virtual ~AudioGraphRenderingOp() {}
  29324. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29325. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29326. const int numSamples) = 0;
  29327. juce_UseDebuggingNewOperator
  29328. };
  29329. class ClearChannelOp : public AudioGraphRenderingOp
  29330. {
  29331. public:
  29332. ClearChannelOp (const int channelNum_)
  29333. : channelNum (channelNum_)
  29334. {}
  29335. ~ClearChannelOp() {}
  29336. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29337. {
  29338. sharedBufferChans.clear (channelNum, 0, numSamples);
  29339. }
  29340. private:
  29341. const int channelNum;
  29342. ClearChannelOp (const ClearChannelOp&);
  29343. ClearChannelOp& operator= (const ClearChannelOp&);
  29344. };
  29345. class CopyChannelOp : public AudioGraphRenderingOp
  29346. {
  29347. public:
  29348. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29349. : srcChannelNum (srcChannelNum_),
  29350. dstChannelNum (dstChannelNum_)
  29351. {}
  29352. ~CopyChannelOp() {}
  29353. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29354. {
  29355. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29356. }
  29357. private:
  29358. const int srcChannelNum, dstChannelNum;
  29359. CopyChannelOp (const CopyChannelOp&);
  29360. CopyChannelOp& operator= (const CopyChannelOp&);
  29361. };
  29362. class AddChannelOp : public AudioGraphRenderingOp
  29363. {
  29364. public:
  29365. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29366. : srcChannelNum (srcChannelNum_),
  29367. dstChannelNum (dstChannelNum_)
  29368. {}
  29369. ~AddChannelOp() {}
  29370. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29371. {
  29372. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29373. }
  29374. private:
  29375. const int srcChannelNum, dstChannelNum;
  29376. AddChannelOp (const AddChannelOp&);
  29377. AddChannelOp& operator= (const AddChannelOp&);
  29378. };
  29379. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29380. {
  29381. public:
  29382. ClearMidiBufferOp (const int bufferNum_)
  29383. : bufferNum (bufferNum_)
  29384. {}
  29385. ~ClearMidiBufferOp() {}
  29386. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29387. {
  29388. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29389. }
  29390. private:
  29391. const int bufferNum;
  29392. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29393. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29394. };
  29395. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29396. {
  29397. public:
  29398. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29399. : srcBufferNum (srcBufferNum_),
  29400. dstBufferNum (dstBufferNum_)
  29401. {}
  29402. ~CopyMidiBufferOp() {}
  29403. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29404. {
  29405. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29406. }
  29407. private:
  29408. const int srcBufferNum, dstBufferNum;
  29409. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29410. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29411. };
  29412. class AddMidiBufferOp : public AudioGraphRenderingOp
  29413. {
  29414. public:
  29415. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29416. : srcBufferNum (srcBufferNum_),
  29417. dstBufferNum (dstBufferNum_)
  29418. {}
  29419. ~AddMidiBufferOp() {}
  29420. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29421. {
  29422. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29423. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29424. }
  29425. private:
  29426. const int srcBufferNum, dstBufferNum;
  29427. AddMidiBufferOp (const AddMidiBufferOp&);
  29428. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29429. };
  29430. class ProcessBufferOp : public AudioGraphRenderingOp
  29431. {
  29432. public:
  29433. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29434. const Array <int>& audioChannelsToUse_,
  29435. const int totalChans_,
  29436. const int midiBufferToUse_)
  29437. : node (node_),
  29438. processor (node_->getProcessor()),
  29439. audioChannelsToUse (audioChannelsToUse_),
  29440. totalChans (jmax (1, totalChans_)),
  29441. midiBufferToUse (midiBufferToUse_)
  29442. {
  29443. channels.calloc (totalChans);
  29444. while (audioChannelsToUse.size() < totalChans)
  29445. audioChannelsToUse.add (0);
  29446. }
  29447. ~ProcessBufferOp()
  29448. {
  29449. }
  29450. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29451. {
  29452. for (int i = totalChans; --i >= 0;)
  29453. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29454. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29455. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29456. }
  29457. const AudioProcessorGraph::Node::Ptr node;
  29458. AudioProcessor* const processor;
  29459. private:
  29460. Array <int> audioChannelsToUse;
  29461. HeapBlock <float*> channels;
  29462. int totalChans;
  29463. int midiBufferToUse;
  29464. ProcessBufferOp (const ProcessBufferOp&);
  29465. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29466. };
  29467. /** Used to calculate the correct sequence of rendering ops needed, based on
  29468. the best re-use of shared buffers at each stage.
  29469. */
  29470. class RenderingOpSequenceCalculator
  29471. {
  29472. public:
  29473. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29474. const Array<void*>& orderedNodes_,
  29475. Array<void*>& renderingOps)
  29476. : graph (graph_),
  29477. orderedNodes (orderedNodes_)
  29478. {
  29479. nodeIds.add (-2); // first buffer is read-only zeros
  29480. channels.add (0);
  29481. midiNodeIds.add (-2);
  29482. for (int i = 0; i < orderedNodes.size(); ++i)
  29483. {
  29484. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29485. renderingOps, i);
  29486. markAnyUnusedBuffersAsFree (i);
  29487. }
  29488. }
  29489. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29490. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29491. juce_UseDebuggingNewOperator
  29492. private:
  29493. AudioProcessorGraph& graph;
  29494. const Array<void*>& orderedNodes;
  29495. Array <int> nodeIds, channels, midiNodeIds;
  29496. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29497. Array<void*>& renderingOps,
  29498. const int ourRenderingIndex)
  29499. {
  29500. const int numIns = node->getProcessor()->getNumInputChannels();
  29501. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29502. const int totalChans = jmax (numIns, numOuts);
  29503. Array <int> audioChannelsToUse;
  29504. int midiBufferToUse = -1;
  29505. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29506. {
  29507. // get a list of all the inputs to this node
  29508. Array <int> sourceNodes, sourceOutputChans;
  29509. for (int i = graph.getNumConnections(); --i >= 0;)
  29510. {
  29511. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29512. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29513. {
  29514. sourceNodes.add (c->sourceNodeId);
  29515. sourceOutputChans.add (c->sourceChannelIndex);
  29516. }
  29517. }
  29518. int bufIndex = -1;
  29519. if (sourceNodes.size() == 0)
  29520. {
  29521. // unconnected input channel
  29522. if (inputChan >= numOuts)
  29523. {
  29524. bufIndex = getReadOnlyEmptyBuffer();
  29525. jassert (bufIndex >= 0);
  29526. }
  29527. else
  29528. {
  29529. bufIndex = getFreeBuffer (false);
  29530. renderingOps.add (new ClearChannelOp (bufIndex));
  29531. }
  29532. }
  29533. else if (sourceNodes.size() == 1)
  29534. {
  29535. // channel with a straightforward single input..
  29536. const int srcNode = sourceNodes.getUnchecked(0);
  29537. const int srcChan = sourceOutputChans.getUnchecked(0);
  29538. bufIndex = getBufferContaining (srcNode, srcChan);
  29539. if (bufIndex < 0)
  29540. {
  29541. // if not found, this is probably a feedback loop
  29542. bufIndex = getReadOnlyEmptyBuffer();
  29543. jassert (bufIndex >= 0);
  29544. }
  29545. if (inputChan < numOuts
  29546. && isBufferNeededLater (ourRenderingIndex,
  29547. inputChan,
  29548. srcNode, srcChan))
  29549. {
  29550. // can't mess up this channel because it's needed later by another node, so we
  29551. // need to use a copy of it..
  29552. const int newFreeBuffer = getFreeBuffer (false);
  29553. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29554. bufIndex = newFreeBuffer;
  29555. }
  29556. }
  29557. else
  29558. {
  29559. // channel with a mix of several inputs..
  29560. // try to find a re-usable channel from our inputs..
  29561. int reusableInputIndex = -1;
  29562. for (int i = 0; i < sourceNodes.size(); ++i)
  29563. {
  29564. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29565. sourceOutputChans.getUnchecked(i));
  29566. if (sourceBufIndex >= 0
  29567. && ! isBufferNeededLater (ourRenderingIndex,
  29568. inputChan,
  29569. sourceNodes.getUnchecked(i),
  29570. sourceOutputChans.getUnchecked(i)))
  29571. {
  29572. // we've found one of our input chans that can be re-used..
  29573. reusableInputIndex = i;
  29574. bufIndex = sourceBufIndex;
  29575. break;
  29576. }
  29577. }
  29578. if (reusableInputIndex < 0)
  29579. {
  29580. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29581. bufIndex = getFreeBuffer (false);
  29582. jassert (bufIndex != 0);
  29583. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29584. sourceOutputChans.getUnchecked (0));
  29585. if (srcIndex < 0)
  29586. {
  29587. // if not found, this is probably a feedback loop
  29588. renderingOps.add (new ClearChannelOp (bufIndex));
  29589. }
  29590. else
  29591. {
  29592. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29593. }
  29594. reusableInputIndex = 0;
  29595. }
  29596. for (int j = 0; j < sourceNodes.size(); ++j)
  29597. {
  29598. if (j != reusableInputIndex)
  29599. {
  29600. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29601. sourceOutputChans.getUnchecked(j));
  29602. if (srcIndex >= 0)
  29603. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29604. }
  29605. }
  29606. }
  29607. jassert (bufIndex >= 0);
  29608. audioChannelsToUse.add (bufIndex);
  29609. if (inputChan < numOuts)
  29610. markBufferAsContaining (bufIndex, node->id, inputChan);
  29611. }
  29612. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29613. {
  29614. const int bufIndex = getFreeBuffer (false);
  29615. jassert (bufIndex != 0);
  29616. audioChannelsToUse.add (bufIndex);
  29617. markBufferAsContaining (bufIndex, node->id, outputChan);
  29618. }
  29619. // Now the same thing for midi..
  29620. Array <int> midiSourceNodes;
  29621. for (int i = graph.getNumConnections(); --i >= 0;)
  29622. {
  29623. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29624. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29625. midiSourceNodes.add (c->sourceNodeId);
  29626. }
  29627. if (midiSourceNodes.size() == 0)
  29628. {
  29629. // No midi inputs..
  29630. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29631. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29632. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29633. }
  29634. else if (midiSourceNodes.size() == 1)
  29635. {
  29636. // One midi input..
  29637. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29638. AudioProcessorGraph::midiChannelIndex);
  29639. if (midiBufferToUse >= 0)
  29640. {
  29641. if (isBufferNeededLater (ourRenderingIndex,
  29642. AudioProcessorGraph::midiChannelIndex,
  29643. midiSourceNodes.getUnchecked(0),
  29644. AudioProcessorGraph::midiChannelIndex))
  29645. {
  29646. // can't mess up this channel because it's needed later by another node, so we
  29647. // need to use a copy of it..
  29648. const int newFreeBuffer = getFreeBuffer (true);
  29649. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29650. midiBufferToUse = newFreeBuffer;
  29651. }
  29652. }
  29653. else
  29654. {
  29655. // probably a feedback loop, so just use an empty one..
  29656. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29657. }
  29658. }
  29659. else
  29660. {
  29661. // More than one midi input being mixed..
  29662. int reusableInputIndex = -1;
  29663. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29664. {
  29665. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29666. AudioProcessorGraph::midiChannelIndex);
  29667. if (sourceBufIndex >= 0
  29668. && ! isBufferNeededLater (ourRenderingIndex,
  29669. AudioProcessorGraph::midiChannelIndex,
  29670. midiSourceNodes.getUnchecked(i),
  29671. AudioProcessorGraph::midiChannelIndex))
  29672. {
  29673. // we've found one of our input buffers that can be re-used..
  29674. reusableInputIndex = i;
  29675. midiBufferToUse = sourceBufIndex;
  29676. break;
  29677. }
  29678. }
  29679. if (reusableInputIndex < 0)
  29680. {
  29681. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29682. midiBufferToUse = getFreeBuffer (true);
  29683. jassert (midiBufferToUse >= 0);
  29684. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29685. AudioProcessorGraph::midiChannelIndex);
  29686. if (srcIndex >= 0)
  29687. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29688. else
  29689. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29690. reusableInputIndex = 0;
  29691. }
  29692. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29693. {
  29694. if (j != reusableInputIndex)
  29695. {
  29696. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29697. AudioProcessorGraph::midiChannelIndex);
  29698. if (srcIndex >= 0)
  29699. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29700. }
  29701. }
  29702. }
  29703. if (node->getProcessor()->producesMidi())
  29704. markBufferAsContaining (midiBufferToUse, node->id,
  29705. AudioProcessorGraph::midiChannelIndex);
  29706. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29707. totalChans, midiBufferToUse));
  29708. }
  29709. int getFreeBuffer (const bool forMidi)
  29710. {
  29711. if (forMidi)
  29712. {
  29713. for (int i = 1; i < midiNodeIds.size(); ++i)
  29714. if (midiNodeIds.getUnchecked(i) < 0)
  29715. return i;
  29716. midiNodeIds.add (-1);
  29717. return midiNodeIds.size() - 1;
  29718. }
  29719. else
  29720. {
  29721. for (int i = 1; i < nodeIds.size(); ++i)
  29722. if (nodeIds.getUnchecked(i) < 0)
  29723. return i;
  29724. nodeIds.add (-1);
  29725. channels.add (0);
  29726. return nodeIds.size() - 1;
  29727. }
  29728. }
  29729. int getReadOnlyEmptyBuffer() const
  29730. {
  29731. return 0;
  29732. }
  29733. int getBufferContaining (const int nodeId, const int outputChannel) const
  29734. {
  29735. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29736. {
  29737. for (int i = midiNodeIds.size(); --i >= 0;)
  29738. if (midiNodeIds.getUnchecked(i) == nodeId)
  29739. return i;
  29740. }
  29741. else
  29742. {
  29743. for (int i = nodeIds.size(); --i >= 0;)
  29744. if (nodeIds.getUnchecked(i) == nodeId
  29745. && channels.getUnchecked(i) == outputChannel)
  29746. return i;
  29747. }
  29748. return -1;
  29749. }
  29750. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29751. {
  29752. int i;
  29753. for (i = 0; i < nodeIds.size(); ++i)
  29754. {
  29755. if (nodeIds.getUnchecked(i) >= 0
  29756. && ! isBufferNeededLater (stepIndex, -1,
  29757. nodeIds.getUnchecked(i),
  29758. channels.getUnchecked(i)))
  29759. {
  29760. nodeIds.set (i, -1);
  29761. }
  29762. }
  29763. for (i = 0; i < midiNodeIds.size(); ++i)
  29764. {
  29765. if (midiNodeIds.getUnchecked(i) >= 0
  29766. && ! isBufferNeededLater (stepIndex, -1,
  29767. midiNodeIds.getUnchecked(i),
  29768. AudioProcessorGraph::midiChannelIndex))
  29769. {
  29770. midiNodeIds.set (i, -1);
  29771. }
  29772. }
  29773. }
  29774. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29775. int inputChannelOfIndexToIgnore,
  29776. const int nodeId,
  29777. const int outputChanIndex) const
  29778. {
  29779. while (stepIndexToSearchFrom < orderedNodes.size())
  29780. {
  29781. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29782. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29783. {
  29784. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29785. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29786. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29787. return true;
  29788. }
  29789. else
  29790. {
  29791. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29792. if (i != inputChannelOfIndexToIgnore
  29793. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29794. node->id, i) != 0)
  29795. return true;
  29796. }
  29797. inputChannelOfIndexToIgnore = -1;
  29798. ++stepIndexToSearchFrom;
  29799. }
  29800. return false;
  29801. }
  29802. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29803. {
  29804. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29805. {
  29806. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29807. midiNodeIds.set (bufferNum, nodeId);
  29808. }
  29809. else
  29810. {
  29811. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29812. nodeIds.set (bufferNum, nodeId);
  29813. channels.set (bufferNum, outputIndex);
  29814. }
  29815. }
  29816. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29817. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29818. };
  29819. }
  29820. void AudioProcessorGraph::clearRenderingSequence()
  29821. {
  29822. const ScopedLock sl (renderLock);
  29823. for (int i = renderingOps.size(); --i >= 0;)
  29824. {
  29825. GraphRenderingOps::AudioGraphRenderingOp* const r
  29826. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29827. renderingOps.remove (i);
  29828. delete r;
  29829. }
  29830. }
  29831. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29832. const uint32 possibleDestinationId,
  29833. const int recursionCheck) const
  29834. {
  29835. if (recursionCheck > 0)
  29836. {
  29837. for (int i = connections.size(); --i >= 0;)
  29838. {
  29839. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29840. if (c->destNodeId == possibleDestinationId
  29841. && (c->sourceNodeId == possibleInputId
  29842. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29843. return true;
  29844. }
  29845. }
  29846. return false;
  29847. }
  29848. void AudioProcessorGraph::buildRenderingSequence()
  29849. {
  29850. Array<void*> newRenderingOps;
  29851. int numRenderingBuffersNeeded = 2;
  29852. int numMidiBuffersNeeded = 1;
  29853. {
  29854. MessageManagerLock mml;
  29855. Array<void*> orderedNodes;
  29856. int i;
  29857. for (i = 0; i < nodes.size(); ++i)
  29858. {
  29859. Node* const node = nodes.getUnchecked(i);
  29860. node->prepare (getSampleRate(), getBlockSize(), this);
  29861. int j = 0;
  29862. for (; j < orderedNodes.size(); ++j)
  29863. if (isAnInputTo (node->id,
  29864. ((Node*) orderedNodes.getUnchecked (j))->id,
  29865. nodes.size() + 1))
  29866. break;
  29867. orderedNodes.insert (j, node);
  29868. }
  29869. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29870. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29871. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29872. }
  29873. Array<void*> oldRenderingOps (renderingOps);
  29874. {
  29875. // swap over to the new rendering sequence..
  29876. const ScopedLock sl (renderLock);
  29877. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29878. renderingBuffers.clear();
  29879. for (int i = midiBuffers.size(); --i >= 0;)
  29880. midiBuffers.getUnchecked(i)->clear();
  29881. while (midiBuffers.size() < numMidiBuffersNeeded)
  29882. midiBuffers.add (new MidiBuffer());
  29883. renderingOps = newRenderingOps;
  29884. }
  29885. for (int i = oldRenderingOps.size(); --i >= 0;)
  29886. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29887. }
  29888. void AudioProcessorGraph::handleAsyncUpdate()
  29889. {
  29890. buildRenderingSequence();
  29891. }
  29892. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29893. {
  29894. currentAudioInputBuffer = 0;
  29895. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29896. currentMidiInputBuffer = 0;
  29897. currentMidiOutputBuffer.clear();
  29898. clearRenderingSequence();
  29899. buildRenderingSequence();
  29900. }
  29901. void AudioProcessorGraph::releaseResources()
  29902. {
  29903. for (int i = 0; i < nodes.size(); ++i)
  29904. nodes.getUnchecked(i)->unprepare();
  29905. renderingBuffers.setSize (1, 1);
  29906. midiBuffers.clear();
  29907. currentAudioInputBuffer = 0;
  29908. currentAudioOutputBuffer.setSize (1, 1);
  29909. currentMidiInputBuffer = 0;
  29910. currentMidiOutputBuffer.clear();
  29911. }
  29912. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29913. {
  29914. const int numSamples = buffer.getNumSamples();
  29915. const ScopedLock sl (renderLock);
  29916. currentAudioInputBuffer = &buffer;
  29917. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29918. currentAudioOutputBuffer.clear();
  29919. currentMidiInputBuffer = &midiMessages;
  29920. currentMidiOutputBuffer.clear();
  29921. int i;
  29922. for (i = 0; i < renderingOps.size(); ++i)
  29923. {
  29924. GraphRenderingOps::AudioGraphRenderingOp* const op
  29925. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29926. op->perform (renderingBuffers, midiBuffers, numSamples);
  29927. }
  29928. for (i = 0; i < buffer.getNumChannels(); ++i)
  29929. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29930. midiMessages.clear();
  29931. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29932. }
  29933. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29934. {
  29935. return "Input " + String (channelIndex + 1);
  29936. }
  29937. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29938. {
  29939. return "Output " + String (channelIndex + 1);
  29940. }
  29941. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29942. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29943. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29944. bool AudioProcessorGraph::producesMidi() const { return true; }
  29945. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29946. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29947. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29948. : type (type_),
  29949. graph (0)
  29950. {
  29951. }
  29952. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29953. {
  29954. }
  29955. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29956. {
  29957. switch (type)
  29958. {
  29959. case audioOutputNode: return "Audio Output";
  29960. case audioInputNode: return "Audio Input";
  29961. case midiOutputNode: return "Midi Output";
  29962. case midiInputNode: return "Midi Input";
  29963. default: break;
  29964. }
  29965. return String::empty;
  29966. }
  29967. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29968. {
  29969. d.name = getName();
  29970. d.uid = d.name.hashCode();
  29971. d.category = "I/O devices";
  29972. d.pluginFormatName = "Internal";
  29973. d.manufacturerName = "Raw Material Software";
  29974. d.version = "1.0";
  29975. d.isInstrument = false;
  29976. d.numInputChannels = getNumInputChannels();
  29977. if (type == audioOutputNode && graph != 0)
  29978. d.numInputChannels = graph->getNumInputChannels();
  29979. d.numOutputChannels = getNumOutputChannels();
  29980. if (type == audioInputNode && graph != 0)
  29981. d.numOutputChannels = graph->getNumOutputChannels();
  29982. }
  29983. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29984. {
  29985. jassert (graph != 0);
  29986. }
  29987. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29988. {
  29989. }
  29990. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29991. MidiBuffer& midiMessages)
  29992. {
  29993. jassert (graph != 0);
  29994. switch (type)
  29995. {
  29996. case audioOutputNode:
  29997. {
  29998. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29999. buffer.getNumChannels()); --i >= 0;)
  30000. {
  30001. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  30002. }
  30003. break;
  30004. }
  30005. case audioInputNode:
  30006. {
  30007. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  30008. buffer.getNumChannels()); --i >= 0;)
  30009. {
  30010. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  30011. }
  30012. break;
  30013. }
  30014. case midiOutputNode:
  30015. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  30016. break;
  30017. case midiInputNode:
  30018. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  30019. break;
  30020. default:
  30021. break;
  30022. }
  30023. }
  30024. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  30025. {
  30026. return type == midiOutputNode;
  30027. }
  30028. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  30029. {
  30030. return type == midiInputNode;
  30031. }
  30032. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  30033. {
  30034. switch (type)
  30035. {
  30036. case audioOutputNode: return "Output " + String (channelIndex + 1);
  30037. case midiOutputNode: return "Midi Output";
  30038. default: break;
  30039. }
  30040. return String::empty;
  30041. }
  30042. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  30043. {
  30044. switch (type)
  30045. {
  30046. case audioInputNode: return "Input " + String (channelIndex + 1);
  30047. case midiInputNode: return "Midi Input";
  30048. default: break;
  30049. }
  30050. return String::empty;
  30051. }
  30052. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  30053. {
  30054. return type == audioInputNode || type == audioOutputNode;
  30055. }
  30056. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  30057. {
  30058. return isInputChannelStereoPair (index);
  30059. }
  30060. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  30061. {
  30062. return type == audioInputNode || type == midiInputNode;
  30063. }
  30064. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  30065. {
  30066. return type == audioOutputNode || type == midiOutputNode;
  30067. }
  30068. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  30069. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  30070. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  30071. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  30072. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  30073. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  30074. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  30075. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  30076. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  30077. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  30078. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  30079. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  30080. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  30081. {
  30082. }
  30083. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  30084. {
  30085. }
  30086. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  30087. {
  30088. graph = newGraph;
  30089. if (graph != 0)
  30090. {
  30091. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  30092. type == audioInputNode ? graph->getNumInputChannels() : 0,
  30093. getSampleRate(),
  30094. getBlockSize());
  30095. updateHostDisplay();
  30096. }
  30097. }
  30098. END_JUCE_NAMESPACE
  30099. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  30100. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30101. BEGIN_JUCE_NAMESPACE
  30102. AudioProcessorPlayer::AudioProcessorPlayer()
  30103. : processor (0),
  30104. sampleRate (0),
  30105. blockSize (0),
  30106. isPrepared (false),
  30107. numInputChans (0),
  30108. numOutputChans (0),
  30109. tempBuffer (1, 1)
  30110. {
  30111. }
  30112. AudioProcessorPlayer::~AudioProcessorPlayer()
  30113. {
  30114. setProcessor (0);
  30115. }
  30116. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  30117. {
  30118. if (processor != processorToPlay)
  30119. {
  30120. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  30121. {
  30122. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  30123. sampleRate, blockSize);
  30124. processorToPlay->prepareToPlay (sampleRate, blockSize);
  30125. }
  30126. AudioProcessor* oldOne;
  30127. {
  30128. const ScopedLock sl (lock);
  30129. oldOne = isPrepared ? processor : 0;
  30130. processor = processorToPlay;
  30131. isPrepared = true;
  30132. }
  30133. if (oldOne != 0)
  30134. oldOne->releaseResources();
  30135. }
  30136. }
  30137. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  30138. const int numInputChannels,
  30139. float** const outputChannelData,
  30140. const int numOutputChannels,
  30141. const int numSamples)
  30142. {
  30143. // these should have been prepared by audioDeviceAboutToStart()...
  30144. jassert (sampleRate > 0 && blockSize > 0);
  30145. incomingMidi.clear();
  30146. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30147. int i, totalNumChans = 0;
  30148. if (numInputChannels > numOutputChannels)
  30149. {
  30150. // if there aren't enough output channels for the number of
  30151. // inputs, we need to create some temporary extra ones (can't
  30152. // use the input data in case it gets written to)
  30153. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30154. false, false, true);
  30155. for (i = 0; i < numOutputChannels; ++i)
  30156. {
  30157. channels[totalNumChans] = outputChannelData[i];
  30158. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30159. ++totalNumChans;
  30160. }
  30161. for (i = numOutputChannels; i < numInputChannels; ++i)
  30162. {
  30163. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30164. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30165. ++totalNumChans;
  30166. }
  30167. }
  30168. else
  30169. {
  30170. for (i = 0; i < numInputChannels; ++i)
  30171. {
  30172. channels[totalNumChans] = outputChannelData[i];
  30173. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30174. ++totalNumChans;
  30175. }
  30176. for (i = numInputChannels; i < numOutputChannels; ++i)
  30177. {
  30178. channels[totalNumChans] = outputChannelData[i];
  30179. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30180. ++totalNumChans;
  30181. }
  30182. }
  30183. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30184. const ScopedLock sl (lock);
  30185. if (processor != 0)
  30186. {
  30187. const ScopedLock sl (processor->getCallbackLock());
  30188. if (processor->isSuspended())
  30189. {
  30190. for (i = 0; i < numOutputChannels; ++i)
  30191. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30192. }
  30193. else
  30194. {
  30195. processor->processBlock (buffer, incomingMidi);
  30196. }
  30197. }
  30198. }
  30199. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30200. {
  30201. const ScopedLock sl (lock);
  30202. sampleRate = device->getCurrentSampleRate();
  30203. blockSize = device->getCurrentBufferSizeSamples();
  30204. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30205. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30206. messageCollector.reset (sampleRate);
  30207. zeromem (channels, sizeof (channels));
  30208. if (processor != 0)
  30209. {
  30210. if (isPrepared)
  30211. processor->releaseResources();
  30212. AudioProcessor* const oldProcessor = processor;
  30213. setProcessor (0);
  30214. setProcessor (oldProcessor);
  30215. }
  30216. }
  30217. void AudioProcessorPlayer::audioDeviceStopped()
  30218. {
  30219. const ScopedLock sl (lock);
  30220. if (processor != 0 && isPrepared)
  30221. processor->releaseResources();
  30222. sampleRate = 0.0;
  30223. blockSize = 0;
  30224. isPrepared = false;
  30225. tempBuffer.setSize (1, 1);
  30226. }
  30227. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30228. {
  30229. messageCollector.addMessageToQueue (message);
  30230. }
  30231. END_JUCE_NAMESPACE
  30232. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30233. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30234. BEGIN_JUCE_NAMESPACE
  30235. class ProcessorParameterPropertyComp : public PropertyComponent,
  30236. public AudioProcessorListener,
  30237. public Timer
  30238. {
  30239. public:
  30240. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  30241. : PropertyComponent (name),
  30242. owner (owner_),
  30243. index (index_),
  30244. paramHasChanged (false),
  30245. slider (owner_, index_)
  30246. {
  30247. startTimer (100);
  30248. addAndMakeVisible (&slider);
  30249. owner_.addListener (this);
  30250. }
  30251. ~ProcessorParameterPropertyComp()
  30252. {
  30253. owner.removeListener (this);
  30254. }
  30255. void refresh()
  30256. {
  30257. paramHasChanged = false;
  30258. slider.setValue (owner.getParameter (index), false);
  30259. }
  30260. void audioProcessorChanged (AudioProcessor*) {}
  30261. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30262. {
  30263. if (parameterIndex == index)
  30264. paramHasChanged = true;
  30265. }
  30266. void timerCallback()
  30267. {
  30268. if (paramHasChanged)
  30269. {
  30270. refresh();
  30271. startTimer (1000 / 50);
  30272. }
  30273. else
  30274. {
  30275. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  30276. }
  30277. }
  30278. juce_UseDebuggingNewOperator
  30279. private:
  30280. class ParamSlider : public Slider
  30281. {
  30282. public:
  30283. ParamSlider (AudioProcessor& owner_, const int index_)
  30284. : owner (owner_),
  30285. index (index_)
  30286. {
  30287. setRange (0.0, 1.0, 0.0);
  30288. setSliderStyle (Slider::LinearBar);
  30289. setTextBoxIsEditable (false);
  30290. setScrollWheelEnabled (false);
  30291. }
  30292. void valueChanged()
  30293. {
  30294. const float newVal = (float) getValue();
  30295. if (owner.getParameter (index) != newVal)
  30296. owner.setParameter (index, newVal);
  30297. }
  30298. const String getTextFromValue (double /*value*/)
  30299. {
  30300. return owner.getParameterText (index);
  30301. }
  30302. juce_UseDebuggingNewOperator
  30303. private:
  30304. AudioProcessor& owner;
  30305. const int index;
  30306. ParamSlider (const ParamSlider&);
  30307. ParamSlider& operator= (const ParamSlider&);
  30308. };
  30309. AudioProcessor& owner;
  30310. const int index;
  30311. bool volatile paramHasChanged;
  30312. ParamSlider slider;
  30313. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30314. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30315. };
  30316. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30317. : AudioProcessorEditor (owner_)
  30318. {
  30319. jassert (owner_ != 0);
  30320. setOpaque (true);
  30321. addAndMakeVisible (&panel);
  30322. Array <PropertyComponent*> params;
  30323. const int numParams = owner_->getNumParameters();
  30324. int totalHeight = 0;
  30325. for (int i = 0; i < numParams; ++i)
  30326. {
  30327. String name (owner_->getParameterName (i));
  30328. if (name.trim().isEmpty())
  30329. name = "Unnamed";
  30330. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30331. params.add (pc);
  30332. totalHeight += pc->getPreferredHeight();
  30333. }
  30334. panel.addProperties (params);
  30335. setSize (400, jlimit (25, 400, totalHeight));
  30336. }
  30337. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30338. {
  30339. }
  30340. void GenericAudioProcessorEditor::paint (Graphics& g)
  30341. {
  30342. g.fillAll (Colours::white);
  30343. }
  30344. void GenericAudioProcessorEditor::resized()
  30345. {
  30346. panel.setBounds (getLocalBounds());
  30347. }
  30348. END_JUCE_NAMESPACE
  30349. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30350. /*** Start of inlined file: juce_Sampler.cpp ***/
  30351. BEGIN_JUCE_NAMESPACE
  30352. SamplerSound::SamplerSound (const String& name_,
  30353. AudioFormatReader& source,
  30354. const BigInteger& midiNotes_,
  30355. const int midiNoteForNormalPitch,
  30356. const double attackTimeSecs,
  30357. const double releaseTimeSecs,
  30358. const double maxSampleLengthSeconds)
  30359. : name (name_),
  30360. midiNotes (midiNotes_),
  30361. midiRootNote (midiNoteForNormalPitch)
  30362. {
  30363. sourceSampleRate = source.sampleRate;
  30364. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30365. {
  30366. length = 0;
  30367. attackSamples = 0;
  30368. releaseSamples = 0;
  30369. }
  30370. else
  30371. {
  30372. length = jmin ((int) source.lengthInSamples,
  30373. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30374. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30375. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30376. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30377. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30378. }
  30379. }
  30380. SamplerSound::~SamplerSound()
  30381. {
  30382. }
  30383. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30384. {
  30385. return midiNotes [midiNoteNumber];
  30386. }
  30387. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30388. {
  30389. return true;
  30390. }
  30391. SamplerVoice::SamplerVoice()
  30392. : pitchRatio (0.0),
  30393. sourceSamplePosition (0.0),
  30394. lgain (0.0f),
  30395. rgain (0.0f),
  30396. isInAttack (false),
  30397. isInRelease (false)
  30398. {
  30399. }
  30400. SamplerVoice::~SamplerVoice()
  30401. {
  30402. }
  30403. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30404. {
  30405. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30406. }
  30407. void SamplerVoice::startNote (const int midiNoteNumber,
  30408. const float velocity,
  30409. SynthesiserSound* s,
  30410. const int /*currentPitchWheelPosition*/)
  30411. {
  30412. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30413. jassert (sound != 0); // this object can only play SamplerSounds!
  30414. if (sound != 0)
  30415. {
  30416. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30417. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30418. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30419. sourceSamplePosition = 0.0;
  30420. lgain = velocity;
  30421. rgain = velocity;
  30422. isInAttack = (sound->attackSamples > 0);
  30423. isInRelease = false;
  30424. if (isInAttack)
  30425. {
  30426. attackReleaseLevel = 0.0f;
  30427. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30428. }
  30429. else
  30430. {
  30431. attackReleaseLevel = 1.0f;
  30432. attackDelta = 0.0f;
  30433. }
  30434. if (sound->releaseSamples > 0)
  30435. {
  30436. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30437. }
  30438. else
  30439. {
  30440. releaseDelta = 0.0f;
  30441. }
  30442. }
  30443. }
  30444. void SamplerVoice::stopNote (const bool allowTailOff)
  30445. {
  30446. if (allowTailOff)
  30447. {
  30448. isInAttack = false;
  30449. isInRelease = true;
  30450. }
  30451. else
  30452. {
  30453. clearCurrentNote();
  30454. }
  30455. }
  30456. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30457. {
  30458. }
  30459. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30460. const int /*newValue*/)
  30461. {
  30462. }
  30463. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30464. {
  30465. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30466. if (playingSound != 0)
  30467. {
  30468. const float* const inL = playingSound->data->getSampleData (0, 0);
  30469. const float* const inR = playingSound->data->getNumChannels() > 1
  30470. ? playingSound->data->getSampleData (1, 0) : 0;
  30471. float* outL = outputBuffer.getSampleData (0, startSample);
  30472. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30473. while (--numSamples >= 0)
  30474. {
  30475. const int pos = (int) sourceSamplePosition;
  30476. const float alpha = (float) (sourceSamplePosition - pos);
  30477. const float invAlpha = 1.0f - alpha;
  30478. // just using a very simple linear interpolation here..
  30479. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30480. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30481. : l;
  30482. l *= lgain;
  30483. r *= rgain;
  30484. if (isInAttack)
  30485. {
  30486. l *= attackReleaseLevel;
  30487. r *= attackReleaseLevel;
  30488. attackReleaseLevel += attackDelta;
  30489. if (attackReleaseLevel >= 1.0f)
  30490. {
  30491. attackReleaseLevel = 1.0f;
  30492. isInAttack = false;
  30493. }
  30494. }
  30495. else if (isInRelease)
  30496. {
  30497. l *= attackReleaseLevel;
  30498. r *= attackReleaseLevel;
  30499. attackReleaseLevel += releaseDelta;
  30500. if (attackReleaseLevel <= 0.0f)
  30501. {
  30502. stopNote (false);
  30503. break;
  30504. }
  30505. }
  30506. if (outR != 0)
  30507. {
  30508. *outL++ += l;
  30509. *outR++ += r;
  30510. }
  30511. else
  30512. {
  30513. *outL++ += (l + r) * 0.5f;
  30514. }
  30515. sourceSamplePosition += pitchRatio;
  30516. if (sourceSamplePosition > playingSound->length)
  30517. {
  30518. stopNote (false);
  30519. break;
  30520. }
  30521. }
  30522. }
  30523. }
  30524. END_JUCE_NAMESPACE
  30525. /*** End of inlined file: juce_Sampler.cpp ***/
  30526. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30527. BEGIN_JUCE_NAMESPACE
  30528. SynthesiserSound::SynthesiserSound()
  30529. {
  30530. }
  30531. SynthesiserSound::~SynthesiserSound()
  30532. {
  30533. }
  30534. SynthesiserVoice::SynthesiserVoice()
  30535. : currentSampleRate (44100.0),
  30536. currentlyPlayingNote (-1),
  30537. noteOnTime (0),
  30538. currentlyPlayingSound (0)
  30539. {
  30540. }
  30541. SynthesiserVoice::~SynthesiserVoice()
  30542. {
  30543. }
  30544. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30545. {
  30546. return currentlyPlayingSound != 0
  30547. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30548. }
  30549. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30550. {
  30551. currentSampleRate = newRate;
  30552. }
  30553. void SynthesiserVoice::clearCurrentNote()
  30554. {
  30555. currentlyPlayingNote = -1;
  30556. currentlyPlayingSound = 0;
  30557. }
  30558. Synthesiser::Synthesiser()
  30559. : sampleRate (0),
  30560. lastNoteOnCounter (0),
  30561. shouldStealNotes (true)
  30562. {
  30563. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30564. lastPitchWheelValues[i] = 0x2000;
  30565. }
  30566. Synthesiser::~Synthesiser()
  30567. {
  30568. }
  30569. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30570. {
  30571. const ScopedLock sl (lock);
  30572. return voices [index];
  30573. }
  30574. void Synthesiser::clearVoices()
  30575. {
  30576. const ScopedLock sl (lock);
  30577. voices.clear();
  30578. }
  30579. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30580. {
  30581. const ScopedLock sl (lock);
  30582. voices.add (newVoice);
  30583. }
  30584. void Synthesiser::removeVoice (const int index)
  30585. {
  30586. const ScopedLock sl (lock);
  30587. voices.remove (index);
  30588. }
  30589. void Synthesiser::clearSounds()
  30590. {
  30591. const ScopedLock sl (lock);
  30592. sounds.clear();
  30593. }
  30594. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30595. {
  30596. const ScopedLock sl (lock);
  30597. sounds.add (newSound);
  30598. }
  30599. void Synthesiser::removeSound (const int index)
  30600. {
  30601. const ScopedLock sl (lock);
  30602. sounds.remove (index);
  30603. }
  30604. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30605. {
  30606. shouldStealNotes = shouldStealNotes_;
  30607. }
  30608. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30609. {
  30610. if (sampleRate != newRate)
  30611. {
  30612. const ScopedLock sl (lock);
  30613. allNotesOff (0, false);
  30614. sampleRate = newRate;
  30615. for (int i = voices.size(); --i >= 0;)
  30616. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30617. }
  30618. }
  30619. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30620. const MidiBuffer& midiData,
  30621. int startSample,
  30622. int numSamples)
  30623. {
  30624. // must set the sample rate before using this!
  30625. jassert (sampleRate != 0);
  30626. const ScopedLock sl (lock);
  30627. MidiBuffer::Iterator midiIterator (midiData);
  30628. midiIterator.setNextSamplePosition (startSample);
  30629. MidiMessage m (0xf4, 0.0);
  30630. while (numSamples > 0)
  30631. {
  30632. int midiEventPos;
  30633. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30634. && midiEventPos < startSample + numSamples;
  30635. const int numThisTime = useEvent ? midiEventPos - startSample
  30636. : numSamples;
  30637. if (numThisTime > 0)
  30638. {
  30639. for (int i = voices.size(); --i >= 0;)
  30640. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30641. }
  30642. if (useEvent)
  30643. {
  30644. if (m.isNoteOn())
  30645. {
  30646. const int channel = m.getChannel();
  30647. noteOn (channel,
  30648. m.getNoteNumber(),
  30649. m.getFloatVelocity());
  30650. }
  30651. else if (m.isNoteOff())
  30652. {
  30653. noteOff (m.getChannel(),
  30654. m.getNoteNumber(),
  30655. true);
  30656. }
  30657. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30658. {
  30659. allNotesOff (m.getChannel(), true);
  30660. }
  30661. else if (m.isPitchWheel())
  30662. {
  30663. const int channel = m.getChannel();
  30664. const int wheelPos = m.getPitchWheelValue();
  30665. lastPitchWheelValues [channel - 1] = wheelPos;
  30666. handlePitchWheel (channel, wheelPos);
  30667. }
  30668. else if (m.isController())
  30669. {
  30670. handleController (m.getChannel(),
  30671. m.getControllerNumber(),
  30672. m.getControllerValue());
  30673. }
  30674. }
  30675. startSample += numThisTime;
  30676. numSamples -= numThisTime;
  30677. }
  30678. }
  30679. void Synthesiser::noteOn (const int midiChannel,
  30680. const int midiNoteNumber,
  30681. const float velocity)
  30682. {
  30683. const ScopedLock sl (lock);
  30684. for (int i = sounds.size(); --i >= 0;)
  30685. {
  30686. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30687. if (sound->appliesToNote (midiNoteNumber)
  30688. && sound->appliesToChannel (midiChannel))
  30689. {
  30690. startVoice (findFreeVoice (sound, shouldStealNotes),
  30691. sound, midiChannel, midiNoteNumber, velocity);
  30692. }
  30693. }
  30694. }
  30695. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30696. SynthesiserSound* const sound,
  30697. const int midiChannel,
  30698. const int midiNoteNumber,
  30699. const float velocity)
  30700. {
  30701. if (voice != 0 && sound != 0)
  30702. {
  30703. if (voice->currentlyPlayingSound != 0)
  30704. voice->stopNote (false);
  30705. voice->startNote (midiNoteNumber,
  30706. velocity,
  30707. sound,
  30708. lastPitchWheelValues [midiChannel - 1]);
  30709. voice->currentlyPlayingNote = midiNoteNumber;
  30710. voice->noteOnTime = ++lastNoteOnCounter;
  30711. voice->currentlyPlayingSound = sound;
  30712. }
  30713. }
  30714. void Synthesiser::noteOff (const int midiChannel,
  30715. const int midiNoteNumber,
  30716. const bool allowTailOff)
  30717. {
  30718. const ScopedLock sl (lock);
  30719. for (int i = voices.size(); --i >= 0;)
  30720. {
  30721. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30722. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30723. {
  30724. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30725. if (sound != 0
  30726. && sound->appliesToNote (midiNoteNumber)
  30727. && sound->appliesToChannel (midiChannel))
  30728. {
  30729. voice->stopNote (allowTailOff);
  30730. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30731. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30732. }
  30733. }
  30734. }
  30735. }
  30736. void Synthesiser::allNotesOff (const int midiChannel,
  30737. const bool allowTailOff)
  30738. {
  30739. const ScopedLock sl (lock);
  30740. for (int i = voices.size(); --i >= 0;)
  30741. {
  30742. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30743. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30744. voice->stopNote (allowTailOff);
  30745. }
  30746. }
  30747. void Synthesiser::handlePitchWheel (const int midiChannel,
  30748. const int wheelValue)
  30749. {
  30750. const ScopedLock sl (lock);
  30751. for (int i = voices.size(); --i >= 0;)
  30752. {
  30753. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30754. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30755. {
  30756. voice->pitchWheelMoved (wheelValue);
  30757. }
  30758. }
  30759. }
  30760. void Synthesiser::handleController (const int midiChannel,
  30761. const int controllerNumber,
  30762. const int controllerValue)
  30763. {
  30764. const ScopedLock sl (lock);
  30765. for (int i = voices.size(); --i >= 0;)
  30766. {
  30767. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30768. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30769. voice->controllerMoved (controllerNumber, controllerValue);
  30770. }
  30771. }
  30772. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30773. const bool stealIfNoneAvailable) const
  30774. {
  30775. const ScopedLock sl (lock);
  30776. for (int i = voices.size(); --i >= 0;)
  30777. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30778. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30779. return voices.getUnchecked (i);
  30780. if (stealIfNoneAvailable)
  30781. {
  30782. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30783. SynthesiserVoice* oldest = 0;
  30784. for (int i = voices.size(); --i >= 0;)
  30785. {
  30786. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30787. if (voice->canPlaySound (soundToPlay)
  30788. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30789. oldest = voice;
  30790. }
  30791. jassert (oldest != 0);
  30792. return oldest;
  30793. }
  30794. return 0;
  30795. }
  30796. END_JUCE_NAMESPACE
  30797. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30798. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30799. BEGIN_JUCE_NAMESPACE
  30800. // special message of our own with a string in it
  30801. class ActionMessage : public Message
  30802. {
  30803. public:
  30804. const String message;
  30805. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30806. : message (messageText)
  30807. {
  30808. pointerParameter = listener_;
  30809. }
  30810. private:
  30811. ActionMessage (const ActionMessage&);
  30812. ActionMessage& operator= (const ActionMessage&);
  30813. };
  30814. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30815. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30816. {
  30817. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30818. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30819. if (owner->actionListeners.contains (target))
  30820. target->actionListenerCallback (am.message);
  30821. }
  30822. ActionBroadcaster::ActionBroadcaster()
  30823. {
  30824. // are you trying to create this object before or after juce has been intialised??
  30825. jassert (MessageManager::instance != 0);
  30826. callback.owner = this;
  30827. }
  30828. ActionBroadcaster::~ActionBroadcaster()
  30829. {
  30830. // all event-based objects must be deleted BEFORE juce is shut down!
  30831. jassert (MessageManager::instance != 0);
  30832. }
  30833. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30834. {
  30835. const ScopedLock sl (actionListenerLock);
  30836. if (listener != 0)
  30837. actionListeners.add (listener);
  30838. }
  30839. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30840. {
  30841. const ScopedLock sl (actionListenerLock);
  30842. actionListeners.removeValue (listener);
  30843. }
  30844. void ActionBroadcaster::removeAllActionListeners()
  30845. {
  30846. const ScopedLock sl (actionListenerLock);
  30847. actionListeners.clear();
  30848. }
  30849. void ActionBroadcaster::sendActionMessage (const String& message) const
  30850. {
  30851. const ScopedLock sl (actionListenerLock);
  30852. for (int i = actionListeners.size(); --i >= 0;)
  30853. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30854. }
  30855. END_JUCE_NAMESPACE
  30856. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30857. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30858. BEGIN_JUCE_NAMESPACE
  30859. class AsyncUpdater::AsyncUpdaterMessage : public CallbackMessage
  30860. {
  30861. public:
  30862. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30863. : owner (owner_)
  30864. {
  30865. }
  30866. void messageCallback()
  30867. {
  30868. if (owner.pendingMessage.compareAndSetBool (0, this))
  30869. owner.handleAsyncUpdate();
  30870. }
  30871. AsyncUpdater& owner;
  30872. };
  30873. AsyncUpdater::AsyncUpdater() throw()
  30874. {
  30875. }
  30876. AsyncUpdater::~AsyncUpdater()
  30877. {
  30878. // You're deleting this object with a background thread while there's an update
  30879. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30880. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30881. // deleting this object, or find some other way to avoid such a race condition.
  30882. jassert (/*(! isUpdatePending()) ||*/ MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30883. pendingMessage = 0;
  30884. }
  30885. void AsyncUpdater::triggerAsyncUpdate()
  30886. {
  30887. if (pendingMessage.value == 0)
  30888. {
  30889. ScopedPointer<AsyncUpdaterMessage> pending (new AsyncUpdaterMessage (*this));
  30890. if (pendingMessage.compareAndSetBool (pending, 0))
  30891. pending.release()->post();
  30892. }
  30893. }
  30894. void AsyncUpdater::cancelPendingUpdate() throw()
  30895. {
  30896. pendingMessage = 0;
  30897. }
  30898. void AsyncUpdater::handleUpdateNowIfNeeded()
  30899. {
  30900. // This can only be called by the event thread.
  30901. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30902. if (pendingMessage.exchange (0) != 0)
  30903. handleAsyncUpdate();
  30904. }
  30905. bool AsyncUpdater::isUpdatePending() const throw()
  30906. {
  30907. return pendingMessage.value != 0;
  30908. }
  30909. END_JUCE_NAMESPACE
  30910. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30911. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30912. BEGIN_JUCE_NAMESPACE
  30913. ChangeBroadcaster::ChangeBroadcaster() throw()
  30914. {
  30915. // are you trying to create this object before or after juce has been intialised??
  30916. jassert (MessageManager::instance != 0);
  30917. callback.owner = this;
  30918. }
  30919. ChangeBroadcaster::~ChangeBroadcaster()
  30920. {
  30921. // all event-based objects must be deleted BEFORE juce is shut down!
  30922. jassert (MessageManager::instance != 0);
  30923. }
  30924. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30925. {
  30926. // Listeners can only be safely added when the event thread is locked
  30927. // You can use a MessageManagerLock if you need to call this from another thread.
  30928. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30929. changeListeners.add (listener);
  30930. }
  30931. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30932. {
  30933. // Listeners can only be safely added when the event thread is locked
  30934. // You can use a MessageManagerLock if you need to call this from another thread.
  30935. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30936. changeListeners.remove (listener);
  30937. }
  30938. void ChangeBroadcaster::removeAllChangeListeners()
  30939. {
  30940. // Listeners can only be safely added when the event thread is locked
  30941. // You can use a MessageManagerLock if you need to call this from another thread.
  30942. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30943. changeListeners.clear();
  30944. }
  30945. void ChangeBroadcaster::sendChangeMessage()
  30946. {
  30947. if (changeListeners.size() > 0)
  30948. callback.triggerAsyncUpdate();
  30949. }
  30950. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30951. {
  30952. // This can only be called by the event thread.
  30953. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30954. callback.cancelPendingUpdate();
  30955. callListeners();
  30956. }
  30957. void ChangeBroadcaster::dispatchPendingMessages()
  30958. {
  30959. callback.handleUpdateNowIfNeeded();
  30960. }
  30961. void ChangeBroadcaster::callListeners()
  30962. {
  30963. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30964. }
  30965. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30966. : owner (0)
  30967. {
  30968. }
  30969. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30970. {
  30971. jassert (owner != 0);
  30972. owner->callListeners();
  30973. }
  30974. END_JUCE_NAMESPACE
  30975. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30976. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30977. BEGIN_JUCE_NAMESPACE
  30978. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30979. const uint32 magicMessageHeaderNumber)
  30980. : Thread ("Juce IPC connection"),
  30981. callbackConnectionState (false),
  30982. useMessageThread (callbacksOnMessageThread),
  30983. magicMessageHeader (magicMessageHeaderNumber),
  30984. pipeReceiveMessageTimeout (-1)
  30985. {
  30986. }
  30987. InterprocessConnection::~InterprocessConnection()
  30988. {
  30989. callbackConnectionState = false;
  30990. disconnect();
  30991. }
  30992. bool InterprocessConnection::connectToSocket (const String& hostName,
  30993. const int portNumber,
  30994. const int timeOutMillisecs)
  30995. {
  30996. disconnect();
  30997. const ScopedLock sl (pipeAndSocketLock);
  30998. socket = new StreamingSocket();
  30999. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  31000. {
  31001. connectionMadeInt();
  31002. startThread();
  31003. return true;
  31004. }
  31005. else
  31006. {
  31007. socket = 0;
  31008. return false;
  31009. }
  31010. }
  31011. bool InterprocessConnection::connectToPipe (const String& pipeName,
  31012. const int pipeReceiveMessageTimeoutMs)
  31013. {
  31014. disconnect();
  31015. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31016. if (newPipe->openExisting (pipeName))
  31017. {
  31018. const ScopedLock sl (pipeAndSocketLock);
  31019. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31020. initialiseWithPipe (newPipe.release());
  31021. return true;
  31022. }
  31023. return false;
  31024. }
  31025. bool InterprocessConnection::createPipe (const String& pipeName,
  31026. const int pipeReceiveMessageTimeoutMs)
  31027. {
  31028. disconnect();
  31029. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31030. if (newPipe->createNewPipe (pipeName))
  31031. {
  31032. const ScopedLock sl (pipeAndSocketLock);
  31033. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31034. initialiseWithPipe (newPipe.release());
  31035. return true;
  31036. }
  31037. return false;
  31038. }
  31039. void InterprocessConnection::disconnect()
  31040. {
  31041. if (socket != 0)
  31042. socket->close();
  31043. if (pipe != 0)
  31044. {
  31045. pipe->cancelPendingReads();
  31046. pipe->close();
  31047. }
  31048. stopThread (4000);
  31049. {
  31050. const ScopedLock sl (pipeAndSocketLock);
  31051. socket = 0;
  31052. pipe = 0;
  31053. }
  31054. connectionLostInt();
  31055. }
  31056. bool InterprocessConnection::isConnected() const
  31057. {
  31058. const ScopedLock sl (pipeAndSocketLock);
  31059. return ((socket != 0 && socket->isConnected())
  31060. || (pipe != 0 && pipe->isOpen()))
  31061. && isThreadRunning();
  31062. }
  31063. const String InterprocessConnection::getConnectedHostName() const
  31064. {
  31065. if (pipe != 0)
  31066. {
  31067. return "localhost";
  31068. }
  31069. else if (socket != 0)
  31070. {
  31071. if (! socket->isLocal())
  31072. return socket->getHostName();
  31073. return "localhost";
  31074. }
  31075. return String::empty;
  31076. }
  31077. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  31078. {
  31079. uint32 messageHeader[2];
  31080. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  31081. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  31082. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  31083. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  31084. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  31085. size_t bytesWritten = 0;
  31086. const ScopedLock sl (pipeAndSocketLock);
  31087. if (socket != 0)
  31088. {
  31089. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  31090. }
  31091. else if (pipe != 0)
  31092. {
  31093. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  31094. }
  31095. if (bytesWritten < 0)
  31096. {
  31097. // error..
  31098. return false;
  31099. }
  31100. return (bytesWritten == messageData.getSize());
  31101. }
  31102. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31103. {
  31104. jassert (socket == 0);
  31105. socket = socket_;
  31106. connectionMadeInt();
  31107. startThread();
  31108. }
  31109. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31110. {
  31111. jassert (pipe == 0);
  31112. pipe = pipe_;
  31113. connectionMadeInt();
  31114. startThread();
  31115. }
  31116. const int messageMagicNumber = 0xb734128b;
  31117. void InterprocessConnection::handleMessage (const Message& message)
  31118. {
  31119. if (message.intParameter1 == messageMagicNumber)
  31120. {
  31121. switch (message.intParameter2)
  31122. {
  31123. case 0:
  31124. {
  31125. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31126. messageReceived (*data);
  31127. break;
  31128. }
  31129. case 1:
  31130. connectionMade();
  31131. break;
  31132. case 2:
  31133. connectionLost();
  31134. break;
  31135. }
  31136. }
  31137. }
  31138. void InterprocessConnection::connectionMadeInt()
  31139. {
  31140. if (! callbackConnectionState)
  31141. {
  31142. callbackConnectionState = true;
  31143. if (useMessageThread)
  31144. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31145. else
  31146. connectionMade();
  31147. }
  31148. }
  31149. void InterprocessConnection::connectionLostInt()
  31150. {
  31151. if (callbackConnectionState)
  31152. {
  31153. callbackConnectionState = false;
  31154. if (useMessageThread)
  31155. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31156. else
  31157. connectionLost();
  31158. }
  31159. }
  31160. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31161. {
  31162. jassert (callbackConnectionState);
  31163. if (useMessageThread)
  31164. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31165. else
  31166. messageReceived (data);
  31167. }
  31168. bool InterprocessConnection::readNextMessageInt()
  31169. {
  31170. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31171. uint32 messageHeader[2];
  31172. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31173. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31174. if (bytes == sizeof (messageHeader)
  31175. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31176. {
  31177. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31178. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31179. {
  31180. MemoryBlock messageData (bytesInMessage, true);
  31181. int bytesRead = 0;
  31182. while (bytesInMessage > 0)
  31183. {
  31184. if (threadShouldExit())
  31185. return false;
  31186. const int numThisTime = jmin (bytesInMessage, 65536);
  31187. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31188. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31189. if (bytesIn <= 0)
  31190. break;
  31191. bytesRead += bytesIn;
  31192. bytesInMessage -= bytesIn;
  31193. }
  31194. if (bytesRead >= 0)
  31195. deliverDataInt (messageData);
  31196. }
  31197. }
  31198. else if (bytes < 0)
  31199. {
  31200. {
  31201. const ScopedLock sl (pipeAndSocketLock);
  31202. socket = 0;
  31203. }
  31204. connectionLostInt();
  31205. return false;
  31206. }
  31207. return true;
  31208. }
  31209. void InterprocessConnection::run()
  31210. {
  31211. while (! threadShouldExit())
  31212. {
  31213. if (socket != 0)
  31214. {
  31215. const int ready = socket->waitUntilReady (true, 0);
  31216. if (ready < 0)
  31217. {
  31218. {
  31219. const ScopedLock sl (pipeAndSocketLock);
  31220. socket = 0;
  31221. }
  31222. connectionLostInt();
  31223. break;
  31224. }
  31225. else if (ready > 0)
  31226. {
  31227. if (! readNextMessageInt())
  31228. break;
  31229. }
  31230. else
  31231. {
  31232. Thread::sleep (2);
  31233. }
  31234. }
  31235. else if (pipe != 0)
  31236. {
  31237. if (! pipe->isOpen())
  31238. {
  31239. {
  31240. const ScopedLock sl (pipeAndSocketLock);
  31241. pipe = 0;
  31242. }
  31243. connectionLostInt();
  31244. break;
  31245. }
  31246. else
  31247. {
  31248. if (! readNextMessageInt())
  31249. break;
  31250. }
  31251. }
  31252. else
  31253. {
  31254. break;
  31255. }
  31256. }
  31257. }
  31258. END_JUCE_NAMESPACE
  31259. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31260. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31261. BEGIN_JUCE_NAMESPACE
  31262. InterprocessConnectionServer::InterprocessConnectionServer()
  31263. : Thread ("Juce IPC server")
  31264. {
  31265. }
  31266. InterprocessConnectionServer::~InterprocessConnectionServer()
  31267. {
  31268. stop();
  31269. }
  31270. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31271. {
  31272. stop();
  31273. socket = new StreamingSocket();
  31274. if (socket->createListener (portNumber))
  31275. {
  31276. startThread();
  31277. return true;
  31278. }
  31279. socket = 0;
  31280. return false;
  31281. }
  31282. void InterprocessConnectionServer::stop()
  31283. {
  31284. signalThreadShouldExit();
  31285. if (socket != 0)
  31286. socket->close();
  31287. stopThread (4000);
  31288. socket = 0;
  31289. }
  31290. void InterprocessConnectionServer::run()
  31291. {
  31292. while ((! threadShouldExit()) && socket != 0)
  31293. {
  31294. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31295. if (clientSocket != 0)
  31296. {
  31297. InterprocessConnection* newConnection = createConnectionObject();
  31298. if (newConnection != 0)
  31299. newConnection->initialiseWithSocket (clientSocket.release());
  31300. }
  31301. }
  31302. }
  31303. END_JUCE_NAMESPACE
  31304. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31305. /*** Start of inlined file: juce_Message.cpp ***/
  31306. BEGIN_JUCE_NAMESPACE
  31307. Message::Message() throw()
  31308. : intParameter1 (0),
  31309. intParameter2 (0),
  31310. intParameter3 (0),
  31311. pointerParameter (0),
  31312. messageRecipient (0)
  31313. {
  31314. }
  31315. Message::Message (const int intParameter1_,
  31316. const int intParameter2_,
  31317. const int intParameter3_,
  31318. void* const pointerParameter_) throw()
  31319. : intParameter1 (intParameter1_),
  31320. intParameter2 (intParameter2_),
  31321. intParameter3 (intParameter3_),
  31322. pointerParameter (pointerParameter_),
  31323. messageRecipient (0)
  31324. {
  31325. }
  31326. Message::~Message()
  31327. {
  31328. }
  31329. END_JUCE_NAMESPACE
  31330. /*** End of inlined file: juce_Message.cpp ***/
  31331. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31332. BEGIN_JUCE_NAMESPACE
  31333. MessageListener::MessageListener() throw()
  31334. {
  31335. // are you trying to create a messagelistener before or after juce has been intialised??
  31336. jassert (MessageManager::instance != 0);
  31337. if (MessageManager::instance != 0)
  31338. MessageManager::instance->messageListeners.add (this);
  31339. }
  31340. MessageListener::~MessageListener()
  31341. {
  31342. if (MessageManager::instance != 0)
  31343. MessageManager::instance->messageListeners.removeValue (this);
  31344. }
  31345. void MessageListener::postMessage (Message* const message) const throw()
  31346. {
  31347. message->messageRecipient = const_cast <MessageListener*> (this);
  31348. if (MessageManager::instance == 0)
  31349. MessageManager::getInstance();
  31350. MessageManager::instance->postMessageToQueue (message);
  31351. }
  31352. bool MessageListener::isValidMessageListener() const throw()
  31353. {
  31354. return (MessageManager::instance != 0)
  31355. && MessageManager::instance->messageListeners.contains (this);
  31356. }
  31357. END_JUCE_NAMESPACE
  31358. /*** End of inlined file: juce_MessageListener.cpp ***/
  31359. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31360. BEGIN_JUCE_NAMESPACE
  31361. // platform-specific functions..
  31362. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31363. bool juce_postMessageToSystemQueue (Message* message);
  31364. MessageManager* MessageManager::instance = 0;
  31365. static const int quitMessageId = 0xfffff321;
  31366. MessageManager::MessageManager() throw()
  31367. : quitMessagePosted (false),
  31368. quitMessageReceived (false),
  31369. threadWithLock (0)
  31370. {
  31371. messageThreadId = Thread::getCurrentThreadId();
  31372. }
  31373. MessageManager::~MessageManager() throw()
  31374. {
  31375. broadcaster = 0;
  31376. doPlatformSpecificShutdown();
  31377. /* If you hit this assertion, then you've probably leaked some kind of MessageListener object.
  31378. This could also be caused by leaking AsyncUpdaters, ChangeBroadcasters, and various other types
  31379. of event class.
  31380. */
  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() {}
  31401. void CallbackMessage::post()
  31402. {
  31403. if (MessageManager::instance != 0)
  31404. MessageManager::instance->postMessageToQueue (this);
  31405. }
  31406. // not for public use..
  31407. void MessageManager::deliverMessage (Message* const message)
  31408. {
  31409. JUCE_TRY
  31410. {
  31411. const ScopedPointer <Message> messageDeleter (message);
  31412. MessageListener* const recipient = message->messageRecipient;
  31413. if (recipient == 0)
  31414. {
  31415. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31416. if (callbackMessage != 0)
  31417. {
  31418. callbackMessage->messageCallback();
  31419. }
  31420. else if (message->intParameter1 == quitMessageId)
  31421. {
  31422. quitMessageReceived = true;
  31423. }
  31424. }
  31425. else if (messageListeners.contains (recipient))
  31426. {
  31427. recipient->handleMessage (*message);
  31428. }
  31429. }
  31430. JUCE_CATCH_EXCEPTION
  31431. }
  31432. #if ! (JUCE_MAC || JUCE_IOS)
  31433. void MessageManager::runDispatchLoop()
  31434. {
  31435. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31436. runDispatchLoopUntil (-1);
  31437. }
  31438. void MessageManager::stopDispatchLoop()
  31439. {
  31440. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31441. quitMessagePosted = true;
  31442. }
  31443. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31444. {
  31445. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31446. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31447. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31448. && ! quitMessageReceived)
  31449. {
  31450. JUCE_TRY
  31451. {
  31452. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31453. {
  31454. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31455. if (msToWait > 0)
  31456. Thread::sleep (jmin (5, msToWait));
  31457. }
  31458. }
  31459. JUCE_CATCH_EXCEPTION
  31460. }
  31461. return ! quitMessageReceived;
  31462. }
  31463. #endif
  31464. void MessageManager::deliverBroadcastMessage (const String& value)
  31465. {
  31466. if (broadcaster != 0)
  31467. broadcaster->sendActionMessage (value);
  31468. }
  31469. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31470. {
  31471. if (broadcaster == 0)
  31472. broadcaster = new ActionBroadcaster();
  31473. broadcaster->addActionListener (listener);
  31474. }
  31475. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31476. {
  31477. if (broadcaster != 0)
  31478. broadcaster->removeActionListener (listener);
  31479. }
  31480. bool MessageManager::isThisTheMessageThread() const throw()
  31481. {
  31482. return Thread::getCurrentThreadId() == messageThreadId;
  31483. }
  31484. void MessageManager::setCurrentThreadAsMessageThread()
  31485. {
  31486. if (messageThreadId != Thread::getCurrentThreadId())
  31487. {
  31488. messageThreadId = Thread::getCurrentThreadId();
  31489. // This is needed on windows to make sure the message window is created by this thread
  31490. doPlatformSpecificShutdown();
  31491. doPlatformSpecificInitialisation();
  31492. }
  31493. }
  31494. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31495. {
  31496. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31497. return thisThread == messageThreadId || thisThread == threadWithLock;
  31498. }
  31499. /* The only safe way to lock the message thread while another thread does
  31500. some work is by posting a special message, whose purpose is to tie up the event
  31501. loop until the other thread has finished its business.
  31502. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31503. get locked before making an event callback, because if the same OS lock gets indirectly
  31504. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31505. in Cocoa).
  31506. */
  31507. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31508. {
  31509. public:
  31510. SharedEvents() {}
  31511. /* This class just holds a couple of events to communicate between the BlockingMessage
  31512. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31513. this shared data must be kept in a separate, ref-counted container. */
  31514. WaitableEvent lockedEvent, releaseEvent;
  31515. private:
  31516. SharedEvents (const SharedEvents&);
  31517. SharedEvents& operator= (const SharedEvents&);
  31518. };
  31519. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31520. {
  31521. public:
  31522. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31523. void messageCallback()
  31524. {
  31525. events->lockedEvent.signal();
  31526. events->releaseEvent.wait();
  31527. }
  31528. juce_UseDebuggingNewOperator
  31529. private:
  31530. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31531. BlockingMessage (const BlockingMessage&);
  31532. BlockingMessage& operator= (const BlockingMessage&);
  31533. };
  31534. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31535. : sharedEvents (0),
  31536. locked (false)
  31537. {
  31538. init (threadToCheck, 0);
  31539. }
  31540. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31541. : sharedEvents (0),
  31542. locked (false)
  31543. {
  31544. init (0, jobToCheckForExitSignal);
  31545. }
  31546. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31547. {
  31548. if (MessageManager::instance != 0)
  31549. {
  31550. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31551. {
  31552. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31553. }
  31554. else
  31555. {
  31556. if (threadToCheck == 0 && job == 0)
  31557. {
  31558. MessageManager::instance->lockingLock.enter();
  31559. }
  31560. else
  31561. {
  31562. while (! MessageManager::instance->lockingLock.tryEnter())
  31563. {
  31564. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31565. || (job != 0 && job->shouldExit()))
  31566. return;
  31567. Thread::sleep (1);
  31568. }
  31569. }
  31570. sharedEvents = new SharedEvents();
  31571. sharedEvents->incReferenceCount();
  31572. (new BlockingMessage (sharedEvents))->post();
  31573. while (! sharedEvents->lockedEvent.wait (50))
  31574. {
  31575. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31576. || (job != 0 && job->shouldExit()))
  31577. {
  31578. sharedEvents->releaseEvent.signal();
  31579. sharedEvents->decReferenceCount();
  31580. sharedEvents = 0;
  31581. MessageManager::instance->lockingLock.exit();
  31582. return;
  31583. }
  31584. }
  31585. jassert (MessageManager::instance->threadWithLock == 0);
  31586. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31587. locked = true;
  31588. }
  31589. }
  31590. }
  31591. MessageManagerLock::~MessageManagerLock() throw()
  31592. {
  31593. if (sharedEvents != 0)
  31594. {
  31595. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31596. sharedEvents->releaseEvent.signal();
  31597. sharedEvents->decReferenceCount();
  31598. if (MessageManager::instance != 0)
  31599. {
  31600. MessageManager::instance->threadWithLock = 0;
  31601. MessageManager::instance->lockingLock.exit();
  31602. }
  31603. }
  31604. }
  31605. END_JUCE_NAMESPACE
  31606. /*** End of inlined file: juce_MessageManager.cpp ***/
  31607. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31608. BEGIN_JUCE_NAMESPACE
  31609. class MultiTimer::MultiTimerCallback : public Timer
  31610. {
  31611. public:
  31612. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31613. : timerId (timerId_),
  31614. owner (owner_)
  31615. {
  31616. }
  31617. ~MultiTimerCallback()
  31618. {
  31619. }
  31620. void timerCallback()
  31621. {
  31622. owner.timerCallback (timerId);
  31623. }
  31624. const int timerId;
  31625. private:
  31626. MultiTimer& owner;
  31627. };
  31628. MultiTimer::MultiTimer() throw()
  31629. {
  31630. }
  31631. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31632. {
  31633. }
  31634. MultiTimer::~MultiTimer()
  31635. {
  31636. const ScopedLock sl (timerListLock);
  31637. timers.clear();
  31638. }
  31639. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31640. {
  31641. const ScopedLock sl (timerListLock);
  31642. for (int i = timers.size(); --i >= 0;)
  31643. {
  31644. MultiTimerCallback* const t = timers.getUnchecked(i);
  31645. if (t->timerId == timerId)
  31646. {
  31647. t->startTimer (intervalInMilliseconds);
  31648. return;
  31649. }
  31650. }
  31651. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31652. timers.add (newTimer);
  31653. newTimer->startTimer (intervalInMilliseconds);
  31654. }
  31655. void MultiTimer::stopTimer (const int timerId) throw()
  31656. {
  31657. const ScopedLock sl (timerListLock);
  31658. for (int i = timers.size(); --i >= 0;)
  31659. {
  31660. MultiTimerCallback* const t = timers.getUnchecked(i);
  31661. if (t->timerId == timerId)
  31662. t->stopTimer();
  31663. }
  31664. }
  31665. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31666. {
  31667. const ScopedLock sl (timerListLock);
  31668. for (int i = timers.size(); --i >= 0;)
  31669. {
  31670. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31671. if (t->timerId == timerId)
  31672. return t->isTimerRunning();
  31673. }
  31674. return false;
  31675. }
  31676. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31677. {
  31678. const ScopedLock sl (timerListLock);
  31679. for (int i = timers.size(); --i >= 0;)
  31680. {
  31681. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31682. if (t->timerId == timerId)
  31683. return t->getTimerInterval();
  31684. }
  31685. return 0;
  31686. }
  31687. END_JUCE_NAMESPACE
  31688. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31689. /*** Start of inlined file: juce_Timer.cpp ***/
  31690. BEGIN_JUCE_NAMESPACE
  31691. class InternalTimerThread : private Thread,
  31692. private MessageListener,
  31693. private DeletedAtShutdown,
  31694. private AsyncUpdater
  31695. {
  31696. public:
  31697. InternalTimerThread()
  31698. : Thread ("Juce Timer"),
  31699. firstTimer (0),
  31700. callbackNeeded (0)
  31701. {
  31702. triggerAsyncUpdate();
  31703. }
  31704. ~InternalTimerThread() throw()
  31705. {
  31706. stopThread (4000);
  31707. jassert (instance == this || instance == 0);
  31708. if (instance == this)
  31709. instance = 0;
  31710. }
  31711. void run()
  31712. {
  31713. uint32 lastTime = Time::getMillisecondCounter();
  31714. while (! threadShouldExit())
  31715. {
  31716. const uint32 now = Time::getMillisecondCounter();
  31717. if (now <= lastTime)
  31718. {
  31719. wait (2);
  31720. continue;
  31721. }
  31722. const int elapsed = now - lastTime;
  31723. lastTime = now;
  31724. int timeUntilFirstTimer = 1000;
  31725. {
  31726. const ScopedLock sl (lock);
  31727. decrementAllCounters (elapsed);
  31728. if (firstTimer != 0)
  31729. timeUntilFirstTimer = firstTimer->countdownMs;
  31730. }
  31731. if (timeUntilFirstTimer <= 0)
  31732. {
  31733. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31734. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31735. but if it fails it means the message-thread changed the value from under us so at least
  31736. some processing is happenening and we can just loop around and try again
  31737. */
  31738. if (callbackNeeded.compareAndSetBool (1, 0))
  31739. {
  31740. postMessage (new Message());
  31741. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31742. when the app has a modal loop), so this is how long to wait before assuming the
  31743. message has been lost and trying again.
  31744. */
  31745. const uint32 messageDeliveryTimeout = now + 2000;
  31746. while (callbackNeeded.get() != 0)
  31747. {
  31748. wait (4);
  31749. if (threadShouldExit())
  31750. return;
  31751. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31752. break;
  31753. }
  31754. }
  31755. }
  31756. else
  31757. {
  31758. // don't wait for too long because running this loop also helps keep the
  31759. // Time::getApproximateMillisecondTimer value stay up-to-date
  31760. wait (jlimit (1, 50, timeUntilFirstTimer));
  31761. }
  31762. }
  31763. }
  31764. void callTimers()
  31765. {
  31766. const ScopedLock sl (lock);
  31767. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31768. {
  31769. Timer* const t = firstTimer;
  31770. t->countdownMs = t->periodMs;
  31771. removeTimer (t);
  31772. addTimer (t);
  31773. const ScopedUnlock ul (lock);
  31774. JUCE_TRY
  31775. {
  31776. t->timerCallback();
  31777. }
  31778. JUCE_CATCH_EXCEPTION
  31779. }
  31780. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31781. before the boolean is set. This set should never fail since if it was false in the first place,
  31782. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31783. get a message then the value is true and the other thread can only set it to true again and
  31784. we will get another callback to set it to false.
  31785. */
  31786. callbackNeeded.set (0);
  31787. }
  31788. void handleMessage (const Message&)
  31789. {
  31790. callTimers();
  31791. }
  31792. void callTimersSynchronously()
  31793. {
  31794. if (! isThreadRunning())
  31795. {
  31796. // (This is relied on by some plugins in cases where the MM has
  31797. // had to restart and the async callback never started)
  31798. cancelPendingUpdate();
  31799. triggerAsyncUpdate();
  31800. }
  31801. callTimers();
  31802. }
  31803. static void callAnyTimersSynchronously()
  31804. {
  31805. if (InternalTimerThread::instance != 0)
  31806. InternalTimerThread::instance->callTimersSynchronously();
  31807. }
  31808. static inline void add (Timer* const tim) throw()
  31809. {
  31810. if (instance == 0)
  31811. instance = new InternalTimerThread();
  31812. const ScopedLock sl (instance->lock);
  31813. instance->addTimer (tim);
  31814. }
  31815. static inline void remove (Timer* const tim) throw()
  31816. {
  31817. if (instance != 0)
  31818. {
  31819. const ScopedLock sl (instance->lock);
  31820. instance->removeTimer (tim);
  31821. }
  31822. }
  31823. static inline void resetCounter (Timer* const tim,
  31824. const int newCounter) throw()
  31825. {
  31826. if (instance != 0)
  31827. {
  31828. tim->countdownMs = newCounter;
  31829. tim->periodMs = newCounter;
  31830. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31831. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31832. {
  31833. const ScopedLock sl (instance->lock);
  31834. instance->removeTimer (tim);
  31835. instance->addTimer (tim);
  31836. }
  31837. }
  31838. }
  31839. private:
  31840. friend class Timer;
  31841. static InternalTimerThread* instance;
  31842. static CriticalSection lock;
  31843. Timer* volatile firstTimer;
  31844. Atomic <int> callbackNeeded;
  31845. void addTimer (Timer* const t) throw()
  31846. {
  31847. #if JUCE_DEBUG
  31848. Timer* tt = firstTimer;
  31849. while (tt != 0)
  31850. {
  31851. // trying to add a timer that's already here - shouldn't get to this point,
  31852. // so if you get this assertion, let me know!
  31853. jassert (tt != t);
  31854. tt = tt->next;
  31855. }
  31856. jassert (t->previous == 0 && t->next == 0);
  31857. #endif
  31858. Timer* i = firstTimer;
  31859. if (i == 0 || i->countdownMs > t->countdownMs)
  31860. {
  31861. t->next = firstTimer;
  31862. firstTimer = t;
  31863. }
  31864. else
  31865. {
  31866. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31867. i = i->next;
  31868. jassert (i != 0);
  31869. t->next = i->next;
  31870. t->previous = i;
  31871. i->next = t;
  31872. }
  31873. if (t->next != 0)
  31874. t->next->previous = t;
  31875. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31876. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31877. notify();
  31878. }
  31879. void removeTimer (Timer* const t) throw()
  31880. {
  31881. #if JUCE_DEBUG
  31882. Timer* tt = firstTimer;
  31883. bool found = false;
  31884. while (tt != 0)
  31885. {
  31886. if (tt == t)
  31887. {
  31888. found = true;
  31889. break;
  31890. }
  31891. tt = tt->next;
  31892. }
  31893. // trying to remove a timer that's not here - shouldn't get to this point,
  31894. // so if you get this assertion, let me know!
  31895. jassert (found);
  31896. #endif
  31897. if (t->previous != 0)
  31898. {
  31899. jassert (firstTimer != t);
  31900. t->previous->next = t->next;
  31901. }
  31902. else
  31903. {
  31904. jassert (firstTimer == t);
  31905. firstTimer = t->next;
  31906. }
  31907. if (t->next != 0)
  31908. t->next->previous = t->previous;
  31909. t->next = 0;
  31910. t->previous = 0;
  31911. }
  31912. void decrementAllCounters (const int numMillisecs) const
  31913. {
  31914. Timer* t = firstTimer;
  31915. while (t != 0)
  31916. {
  31917. t->countdownMs -= numMillisecs;
  31918. t = t->next;
  31919. }
  31920. }
  31921. void handleAsyncUpdate()
  31922. {
  31923. startThread (7);
  31924. }
  31925. InternalTimerThread (const InternalTimerThread&);
  31926. InternalTimerThread& operator= (const InternalTimerThread&);
  31927. };
  31928. InternalTimerThread* InternalTimerThread::instance = 0;
  31929. CriticalSection InternalTimerThread::lock;
  31930. void juce_callAnyTimersSynchronously()
  31931. {
  31932. InternalTimerThread::callAnyTimersSynchronously();
  31933. }
  31934. #if JUCE_DEBUG
  31935. static SortedSet <Timer*> activeTimers;
  31936. #endif
  31937. Timer::Timer() throw()
  31938. : countdownMs (0),
  31939. periodMs (0),
  31940. previous (0),
  31941. next (0)
  31942. {
  31943. #if JUCE_DEBUG
  31944. activeTimers.add (this);
  31945. #endif
  31946. }
  31947. Timer::Timer (const 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()
  31958. {
  31959. stopTimer();
  31960. #if JUCE_DEBUG
  31961. activeTimers.removeValue (this);
  31962. #endif
  31963. }
  31964. void Timer::startTimer (const int interval) throw()
  31965. {
  31966. const ScopedLock sl (InternalTimerThread::lock);
  31967. #if JUCE_DEBUG
  31968. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31969. jassert (activeTimers.contains (this));
  31970. #endif
  31971. if (periodMs == 0)
  31972. {
  31973. countdownMs = interval;
  31974. periodMs = jmax (1, interval);
  31975. InternalTimerThread::add (this);
  31976. }
  31977. else
  31978. {
  31979. InternalTimerThread::resetCounter (this, interval);
  31980. }
  31981. }
  31982. void Timer::stopTimer() throw()
  31983. {
  31984. const ScopedLock sl (InternalTimerThread::lock);
  31985. #if JUCE_DEBUG
  31986. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31987. jassert (activeTimers.contains (this));
  31988. #endif
  31989. if (periodMs > 0)
  31990. {
  31991. InternalTimerThread::remove (this);
  31992. periodMs = 0;
  31993. }
  31994. }
  31995. END_JUCE_NAMESPACE
  31996. /*** End of inlined file: juce_Timer.cpp ***/
  31997. #endif
  31998. #if JUCE_BUILD_GUI
  31999. /*** Start of inlined file: juce_Component.cpp ***/
  32000. BEGIN_JUCE_NAMESPACE
  32001. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  32002. Component* Component::currentlyFocusedComponent = 0;
  32003. class Component::MouseListenerList
  32004. {
  32005. public:
  32006. MouseListenerList()
  32007. : numDeepMouseListeners (0)
  32008. {
  32009. }
  32010. ~MouseListenerList()
  32011. {
  32012. }
  32013. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  32014. {
  32015. if (! listeners.contains (newListener))
  32016. {
  32017. if (wantsEventsForAllNestedChildComponents)
  32018. {
  32019. listeners.insert (0, newListener);
  32020. ++numDeepMouseListeners;
  32021. }
  32022. else
  32023. {
  32024. listeners.add (newListener);
  32025. }
  32026. }
  32027. }
  32028. void removeListener (MouseListener* const listenerToRemove)
  32029. {
  32030. const int index = listeners.indexOf (listenerToRemove);
  32031. if (index >= 0)
  32032. {
  32033. if (index < numDeepMouseListeners)
  32034. --numDeepMouseListeners;
  32035. listeners.remove (index);
  32036. }
  32037. }
  32038. static void sendMouseEvent (Component* comp, BailOutChecker& checker,
  32039. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  32040. {
  32041. if (checker.shouldBailOut())
  32042. return;
  32043. {
  32044. MouseListenerList* const list = comp->mouseListeners_;
  32045. if (list != 0)
  32046. {
  32047. for (int i = list->listeners.size(); --i >= 0;)
  32048. {
  32049. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  32050. if (checker.shouldBailOut())
  32051. return;
  32052. i = jmin (i, list->listeners.size());
  32053. }
  32054. }
  32055. }
  32056. Component* p = comp->parentComponent_;
  32057. while (p != 0)
  32058. {
  32059. MouseListenerList* const list = p->mouseListeners_;
  32060. if (list != 0 && list->numDeepMouseListeners > 0)
  32061. {
  32062. BailOutChecker checker2 (comp, p);
  32063. for (int i = list->numDeepMouseListeners; --i >= 0;)
  32064. {
  32065. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  32066. if (checker2.shouldBailOut())
  32067. return;
  32068. i = jmin (i, list->numDeepMouseListeners);
  32069. }
  32070. }
  32071. p = p->parentComponent_;
  32072. }
  32073. }
  32074. static void sendWheelEvent (Component* comp, BailOutChecker& checker, const MouseEvent& e,
  32075. const float wheelIncrementX, const float wheelIncrementY)
  32076. {
  32077. if (checker.shouldBailOut())
  32078. return;
  32079. {
  32080. MouseListenerList* const list = comp->mouseListeners_;
  32081. if (list != 0)
  32082. {
  32083. for (int i = list->listeners.size(); --i >= 0;)
  32084. {
  32085. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  32086. if (checker.shouldBailOut())
  32087. return;
  32088. i = jmin (i, list->listeners.size());
  32089. }
  32090. }
  32091. }
  32092. Component* p = comp->parentComponent_;
  32093. while (p != 0)
  32094. {
  32095. MouseListenerList* const list = p->mouseListeners_;
  32096. if (list != 0 && list->numDeepMouseListeners > 0)
  32097. {
  32098. BailOutChecker checker2 (comp, p);
  32099. for (int i = list->numDeepMouseListeners; --i >= 0;)
  32100. {
  32101. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  32102. if (checker2.shouldBailOut())
  32103. return;
  32104. i = jmin (i, list->numDeepMouseListeners);
  32105. }
  32106. }
  32107. p = p->parentComponent_;
  32108. }
  32109. }
  32110. private:
  32111. Array <MouseListener*> listeners;
  32112. int numDeepMouseListeners;
  32113. MouseListenerList (const MouseListenerList&);
  32114. MouseListenerList& operator= (const MouseListenerList&);
  32115. };
  32116. #if JUCE_DEBUG
  32117. namespace
  32118. {
  32119. class ComponentLeakDetector
  32120. {
  32121. public:
  32122. ComponentLeakDetector() : componentCount (0) {}
  32123. ~ComponentLeakDetector()
  32124. {
  32125. /* If you hit this assertion, then you've leaked some Components.
  32126. In most cases this will be due to bad coding practices like using the manually deleting
  32127. objects rather than using ScopedPointers or embedded member objects to manage their lifetimes.
  32128. */
  32129. jassert (componentCount <= 0);
  32130. }
  32131. int componentCount;
  32132. };
  32133. ComponentLeakDetector leakDetector;
  32134. }
  32135. #endif
  32136. class Component::ComponentHelpers
  32137. {
  32138. public:
  32139. static void* runModalLoopCallback (void* userData)
  32140. {
  32141. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32142. }
  32143. static const Identifier getColourPropertyId (const int colourId)
  32144. {
  32145. String s;
  32146. s.preallocateStorage (18);
  32147. s << "jcclr_" << String::toHexString (colourId);
  32148. return s;
  32149. }
  32150. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  32151. {
  32152. return ((unsigned int) localPoint.getX()) < (unsigned int) comp.getWidth()
  32153. && ((unsigned int) localPoint.getY()) < (unsigned int) comp.getHeight()
  32154. && comp.hitTest (localPoint.getX(), localPoint.getY());
  32155. }
  32156. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  32157. {
  32158. return pointInParentSpace - comp.getPosition();
  32159. }
  32160. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  32161. {
  32162. return areaInParentSpace - comp.getPosition();
  32163. }
  32164. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  32165. {
  32166. return pointInLocalSpace + comp.getPosition();
  32167. }
  32168. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  32169. {
  32170. return areaInLocalSpace + comp.getPosition();
  32171. }
  32172. template <typename Type>
  32173. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  32174. {
  32175. const Component* const directParent = target.getParentComponent();
  32176. jassert (directParent != 0);
  32177. if (directParent == parent)
  32178. return convertFromParentSpace (target, coordInParent);
  32179. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  32180. }
  32181. template <typename Type>
  32182. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  32183. {
  32184. while (source != 0)
  32185. {
  32186. if (source == target)
  32187. return p;
  32188. if (source->isParentOf (target))
  32189. return convertFromDistantParentSpace (source, *target, p);
  32190. if (source->isOnDesktop())
  32191. {
  32192. p = source->getPeer()->localToGlobal (p);
  32193. source = 0;
  32194. }
  32195. else
  32196. {
  32197. p = convertToParentSpace (*source, p);
  32198. source = source->getParentComponent();
  32199. }
  32200. }
  32201. jassert (source == 0);
  32202. if (target == 0)
  32203. return p;
  32204. const Component* const topLevelComp = target->getTopLevelComponent();
  32205. if (topLevelComp->isOnDesktop())
  32206. p = topLevelComp->getPeer()->globalToLocal (p);
  32207. else
  32208. p = convertFromParentSpace (*topLevelComp, p);
  32209. if (topLevelComp == target)
  32210. return p;
  32211. return convertFromDistantParentSpace (topLevelComp, *target, p);
  32212. }
  32213. static const Rectangle<int> getUnclippedArea (const Component& comp)
  32214. {
  32215. Rectangle<int> r (comp.getLocalBounds());
  32216. Component* const p = comp.getParentComponent();
  32217. if (p != 0)
  32218. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  32219. return r;
  32220. }
  32221. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  32222. {
  32223. for (int i = comp.childComponentList_.size(); --i >= 0;)
  32224. {
  32225. const Component& child = *comp.childComponentList_.getUnchecked(i);
  32226. //xxx if (child.isVisible() && ! child.isTransformed())
  32227. if (child.isVisible())
  32228. {
  32229. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds_));
  32230. if (! newClip.isEmpty())
  32231. {
  32232. if (child.isOpaque())
  32233. {
  32234. g.excludeClipRegion (newClip + delta);
  32235. }
  32236. else
  32237. {
  32238. const Point<int> childPos (child.getPosition());
  32239. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  32240. }
  32241. }
  32242. }
  32243. }
  32244. }
  32245. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  32246. const Point<int>& delta,
  32247. const Rectangle<int>& clipRect,
  32248. const Component* const compToAvoid)
  32249. {
  32250. for (int i = comp.childComponentList_.size(); --i >= 0;)
  32251. {
  32252. const Component* const c = comp.childComponentList_.getUnchecked(i);
  32253. if (c != compToAvoid && c->isVisible())
  32254. {
  32255. if (c->isOpaque())
  32256. {
  32257. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  32258. childBounds.translate (delta.getX(), delta.getY());
  32259. result.subtract (childBounds);
  32260. }
  32261. else
  32262. {
  32263. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  32264. newClip.translate (-c->getX(), -c->getY());
  32265. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  32266. newClip, compToAvoid);
  32267. }
  32268. }
  32269. }
  32270. }
  32271. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  32272. {
  32273. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  32274. : Desktop::getInstance().getMainMonitorArea();
  32275. }
  32276. };
  32277. Component::Component()
  32278. : parentComponent_ (0),
  32279. lookAndFeel_ (0),
  32280. effect_ (0),
  32281. bufferedImage_ (0),
  32282. componentFlags_ (0),
  32283. componentTransparency (0)
  32284. {
  32285. #if JUCE_DEBUG
  32286. leakDetector.componentCount++;
  32287. #endif
  32288. }
  32289. Component::Component (const String& name)
  32290. : componentName_ (name),
  32291. parentComponent_ (0),
  32292. lookAndFeel_ (0),
  32293. effect_ (0),
  32294. bufferedImage_ (0),
  32295. componentFlags_ (0),
  32296. componentTransparency (0)
  32297. {
  32298. #if JUCE_DEBUG
  32299. leakDetector.componentCount++;
  32300. #endif
  32301. }
  32302. Component::~Component()
  32303. {
  32304. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  32305. static_jassert (sizeof (flags) <= sizeof (componentFlags_));
  32306. #endif
  32307. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32308. if (parentComponent_ != 0)
  32309. {
  32310. parentComponent_->removeChildComponent (this);
  32311. }
  32312. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32313. {
  32314. giveAwayFocus();
  32315. }
  32316. if (flags.hasHeavyweightPeerFlag)
  32317. removeFromDesktop();
  32318. for (int i = childComponentList_.size(); --i >= 0;)
  32319. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  32320. #if JUCE_DEBUG
  32321. leakDetector.componentCount--;
  32322. /* If you hit this assertion, then you've somehow managed to delete more components than
  32323. you have created.
  32324. In most cases this will be due to bad coding practices like manually deleting your objects
  32325. rather than using ScopedPointers or embedded member objects to manage their lifetimes.
  32326. */
  32327. jassert (leakDetector.componentCount >= 0);
  32328. #endif
  32329. }
  32330. void Component::setName (const String& name)
  32331. {
  32332. // if component methods are being called from threads other than the message
  32333. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32334. checkMessageManagerIsLocked
  32335. if (componentName_ != name)
  32336. {
  32337. componentName_ = name;
  32338. if (flags.hasHeavyweightPeerFlag)
  32339. {
  32340. ComponentPeer* const peer = getPeer();
  32341. jassert (peer != 0);
  32342. if (peer != 0)
  32343. peer->setTitle (name);
  32344. }
  32345. BailOutChecker checker (this);
  32346. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32347. }
  32348. }
  32349. void Component::setVisible (bool shouldBeVisible)
  32350. {
  32351. if (flags.visibleFlag != shouldBeVisible)
  32352. {
  32353. // if component methods are being called from threads other than the message
  32354. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32355. checkMessageManagerIsLocked
  32356. SafePointer<Component> safePointer (this);
  32357. flags.visibleFlag = shouldBeVisible;
  32358. internalRepaint (0, 0, getWidth(), getHeight());
  32359. sendFakeMouseMove();
  32360. if (! shouldBeVisible)
  32361. {
  32362. if (currentlyFocusedComponent == this
  32363. || isParentOf (currentlyFocusedComponent))
  32364. {
  32365. if (parentComponent_ != 0)
  32366. parentComponent_->grabKeyboardFocus();
  32367. else
  32368. giveAwayFocus();
  32369. }
  32370. }
  32371. if (safePointer != 0)
  32372. {
  32373. sendVisibilityChangeMessage();
  32374. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32375. {
  32376. ComponentPeer* const peer = getPeer();
  32377. jassert (peer != 0);
  32378. if (peer != 0)
  32379. {
  32380. peer->setVisible (shouldBeVisible);
  32381. internalHierarchyChanged();
  32382. }
  32383. }
  32384. }
  32385. }
  32386. }
  32387. void Component::visibilityChanged()
  32388. {
  32389. }
  32390. void Component::sendVisibilityChangeMessage()
  32391. {
  32392. BailOutChecker checker (this);
  32393. visibilityChanged();
  32394. if (! checker.shouldBailOut())
  32395. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32396. }
  32397. bool Component::isShowing() const
  32398. {
  32399. if (flags.visibleFlag)
  32400. {
  32401. if (parentComponent_ != 0)
  32402. {
  32403. return parentComponent_->isShowing();
  32404. }
  32405. else
  32406. {
  32407. const ComponentPeer* const peer = getPeer();
  32408. return peer != 0 && ! peer->isMinimised();
  32409. }
  32410. }
  32411. return false;
  32412. }
  32413. void* Component::getWindowHandle() const
  32414. {
  32415. const ComponentPeer* const peer = getPeer();
  32416. if (peer != 0)
  32417. return peer->getNativeHandle();
  32418. return 0;
  32419. }
  32420. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32421. {
  32422. // if component methods are being called from threads other than the message
  32423. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32424. checkMessageManagerIsLocked
  32425. if (isOpaque())
  32426. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32427. else
  32428. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32429. int currentStyleFlags = 0;
  32430. // don't use getPeer(), so that we only get the peer that's specifically
  32431. // for this comp, and not for one of its parents.
  32432. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32433. if (peer != 0)
  32434. currentStyleFlags = peer->getStyleFlags();
  32435. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32436. {
  32437. SafePointer<Component> safePointer (this);
  32438. #if JUCE_LINUX
  32439. // it's wise to give the component a non-zero size before
  32440. // putting it on the desktop, as X windows get confused by this, and
  32441. // a (1, 1) minimum size is enforced here.
  32442. setSize (jmax (1, getWidth()),
  32443. jmax (1, getHeight()));
  32444. #endif
  32445. const Point<int> topLeft (getScreenPosition());
  32446. bool wasFullscreen = false;
  32447. bool wasMinimised = false;
  32448. ComponentBoundsConstrainer* currentConstainer = 0;
  32449. Rectangle<int> oldNonFullScreenBounds;
  32450. if (peer != 0)
  32451. {
  32452. wasFullscreen = peer->isFullScreen();
  32453. wasMinimised = peer->isMinimised();
  32454. currentConstainer = peer->getConstrainer();
  32455. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32456. removeFromDesktop();
  32457. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32458. }
  32459. if (parentComponent_ != 0)
  32460. parentComponent_->removeChildComponent (this);
  32461. if (safePointer != 0)
  32462. {
  32463. flags.hasHeavyweightPeerFlag = true;
  32464. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32465. Desktop::getInstance().addDesktopComponent (this);
  32466. bounds_.setPosition (topLeft);
  32467. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32468. peer->setVisible (isVisible());
  32469. if (wasFullscreen)
  32470. {
  32471. peer->setFullScreen (true);
  32472. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32473. }
  32474. if (wasMinimised)
  32475. peer->setMinimised (true);
  32476. if (isAlwaysOnTop())
  32477. peer->setAlwaysOnTop (true);
  32478. peer->setConstrainer (currentConstainer);
  32479. repaint();
  32480. }
  32481. internalHierarchyChanged();
  32482. }
  32483. }
  32484. void Component::removeFromDesktop()
  32485. {
  32486. // if component methods are being called from threads other than the message
  32487. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32488. checkMessageManagerIsLocked
  32489. if (flags.hasHeavyweightPeerFlag)
  32490. {
  32491. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32492. flags.hasHeavyweightPeerFlag = false;
  32493. jassert (peer != 0);
  32494. delete peer;
  32495. Desktop::getInstance().removeDesktopComponent (this);
  32496. }
  32497. }
  32498. bool Component::isOnDesktop() const throw()
  32499. {
  32500. return flags.hasHeavyweightPeerFlag;
  32501. }
  32502. void Component::userTriedToCloseWindow()
  32503. {
  32504. /* This means that the user's trying to get rid of your window with the 'close window' system
  32505. menu option (on windows) or possibly the task manager - you should really handle this
  32506. and delete or hide your component in an appropriate way.
  32507. If you want to ignore the event and don't want to trigger this assertion, just override
  32508. this method and do nothing.
  32509. */
  32510. jassertfalse;
  32511. }
  32512. void Component::minimisationStateChanged (bool)
  32513. {
  32514. }
  32515. void Component::setOpaque (const bool shouldBeOpaque)
  32516. {
  32517. if (shouldBeOpaque != flags.opaqueFlag)
  32518. {
  32519. flags.opaqueFlag = shouldBeOpaque;
  32520. if (flags.hasHeavyweightPeerFlag)
  32521. {
  32522. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32523. if (peer != 0)
  32524. {
  32525. // to make it recreate the heavyweight window
  32526. addToDesktop (peer->getStyleFlags());
  32527. }
  32528. }
  32529. repaint();
  32530. }
  32531. }
  32532. bool Component::isOpaque() const throw()
  32533. {
  32534. return flags.opaqueFlag;
  32535. }
  32536. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32537. {
  32538. if (shouldBeBuffered != flags.bufferToImageFlag)
  32539. {
  32540. bufferedImage_ = Image::null;
  32541. flags.bufferToImageFlag = shouldBeBuffered;
  32542. }
  32543. }
  32544. void Component::toFront (const bool setAsForeground)
  32545. {
  32546. // if component methods are being called from threads other than the message
  32547. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32548. checkMessageManagerIsLocked
  32549. if (flags.hasHeavyweightPeerFlag)
  32550. {
  32551. ComponentPeer* const peer = getPeer();
  32552. if (peer != 0)
  32553. {
  32554. peer->toFront (setAsForeground);
  32555. if (setAsForeground && ! hasKeyboardFocus (true))
  32556. grabKeyboardFocus();
  32557. }
  32558. }
  32559. else if (parentComponent_ != 0)
  32560. {
  32561. Array<Component*>& childList = parentComponent_->childComponentList_;
  32562. if (childList.getLast() != this)
  32563. {
  32564. const int index = childList.indexOf (this);
  32565. if (index >= 0)
  32566. {
  32567. int insertIndex = -1;
  32568. if (! flags.alwaysOnTopFlag)
  32569. {
  32570. insertIndex = childList.size() - 1;
  32571. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32572. --insertIndex;
  32573. }
  32574. if (index != insertIndex)
  32575. {
  32576. childList.move (index, insertIndex);
  32577. sendFakeMouseMove();
  32578. repaintParent();
  32579. }
  32580. }
  32581. }
  32582. if (setAsForeground)
  32583. {
  32584. internalBroughtToFront();
  32585. grabKeyboardFocus();
  32586. }
  32587. }
  32588. }
  32589. void Component::toBehind (Component* const other)
  32590. {
  32591. if (other != 0 && other != this)
  32592. {
  32593. // the two components must belong to the same parent..
  32594. jassert (parentComponent_ == other->parentComponent_);
  32595. if (parentComponent_ != 0)
  32596. {
  32597. Array<Component*>& childList = parentComponent_->childComponentList_;
  32598. const int index = childList.indexOf (this);
  32599. if (index >= 0 && childList [index + 1] != other)
  32600. {
  32601. int otherIndex = childList.indexOf (other);
  32602. if (otherIndex >= 0)
  32603. {
  32604. if (index < otherIndex)
  32605. --otherIndex;
  32606. childList.move (index, otherIndex);
  32607. sendFakeMouseMove();
  32608. repaintParent();
  32609. }
  32610. }
  32611. }
  32612. else if (isOnDesktop())
  32613. {
  32614. jassert (other->isOnDesktop());
  32615. if (other->isOnDesktop())
  32616. {
  32617. ComponentPeer* const us = getPeer();
  32618. ComponentPeer* const them = other->getPeer();
  32619. jassert (us != 0 && them != 0);
  32620. if (us != 0 && them != 0)
  32621. us->toBehind (them);
  32622. }
  32623. }
  32624. }
  32625. }
  32626. void Component::toBack()
  32627. {
  32628. Array<Component*>& childList = parentComponent_->childComponentList_;
  32629. if (isOnDesktop())
  32630. {
  32631. jassertfalse; //xxx need to add this to native window
  32632. }
  32633. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32634. {
  32635. const int index = childList.indexOf (this);
  32636. if (index > 0)
  32637. {
  32638. int insertIndex = 0;
  32639. if (flags.alwaysOnTopFlag)
  32640. {
  32641. while (insertIndex < childList.size()
  32642. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32643. {
  32644. ++insertIndex;
  32645. }
  32646. }
  32647. if (index != insertIndex)
  32648. {
  32649. childList.move (index, insertIndex);
  32650. sendFakeMouseMove();
  32651. repaintParent();
  32652. }
  32653. }
  32654. }
  32655. }
  32656. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32657. {
  32658. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32659. {
  32660. flags.alwaysOnTopFlag = shouldStayOnTop;
  32661. if (isOnDesktop())
  32662. {
  32663. ComponentPeer* const peer = getPeer();
  32664. jassert (peer != 0);
  32665. if (peer != 0)
  32666. {
  32667. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32668. {
  32669. // some kinds of peer can't change their always-on-top status, so
  32670. // for these, we'll need to create a new window
  32671. const int oldFlags = peer->getStyleFlags();
  32672. removeFromDesktop();
  32673. addToDesktop (oldFlags);
  32674. }
  32675. }
  32676. }
  32677. if (shouldStayOnTop)
  32678. toFront (false);
  32679. internalHierarchyChanged();
  32680. }
  32681. }
  32682. bool Component::isAlwaysOnTop() const throw()
  32683. {
  32684. return flags.alwaysOnTopFlag;
  32685. }
  32686. int Component::proportionOfWidth (const float proportion) const throw()
  32687. {
  32688. return roundToInt (proportion * bounds_.getWidth());
  32689. }
  32690. int Component::proportionOfHeight (const float proportion) const throw()
  32691. {
  32692. return roundToInt (proportion * bounds_.getHeight());
  32693. }
  32694. int Component::getParentWidth() const throw()
  32695. {
  32696. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32697. : getParentMonitorArea().getWidth();
  32698. }
  32699. int Component::getParentHeight() const throw()
  32700. {
  32701. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32702. : getParentMonitorArea().getHeight();
  32703. }
  32704. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32705. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32706. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32707. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32708. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32709. {
  32710. return ComponentHelpers::convertCoordinate (this, source, point);
  32711. }
  32712. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32713. {
  32714. return ComponentHelpers::convertCoordinate (this, source, area);
  32715. }
  32716. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32717. {
  32718. return ComponentHelpers::convertCoordinate (0, this, point);
  32719. }
  32720. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32721. {
  32722. return ComponentHelpers::convertCoordinate (0, this, area);
  32723. }
  32724. /* Deprecated methods... */
  32725. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32726. {
  32727. return localPointToGlobal (relativePosition);
  32728. }
  32729. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32730. {
  32731. return getLocalPoint (0, screenPosition);
  32732. }
  32733. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32734. {
  32735. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32736. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32737. }
  32738. void Component::setBounds (const int x, const int y, int w, int h)
  32739. {
  32740. // if component methods are being called from threads other than the message
  32741. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32742. checkMessageManagerIsLocked
  32743. if (w < 0) w = 0;
  32744. if (h < 0) h = 0;
  32745. const bool wasResized = (getWidth() != w || getHeight() != h);
  32746. const bool wasMoved = (getX() != x || getY() != y);
  32747. #if JUCE_DEBUG
  32748. // It's a very bad idea to try to resize a window during its paint() method!
  32749. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32750. #endif
  32751. if (wasMoved || wasResized)
  32752. {
  32753. if (flags.visibleFlag)
  32754. {
  32755. // send a fake mouse move to trigger enter/exit messages if needed..
  32756. sendFakeMouseMove();
  32757. if (! flags.hasHeavyweightPeerFlag)
  32758. repaintParent();
  32759. }
  32760. bounds_.setBounds (x, y, w, h);
  32761. if (wasResized)
  32762. repaint();
  32763. else if (! flags.hasHeavyweightPeerFlag)
  32764. repaintParent();
  32765. if (flags.hasHeavyweightPeerFlag)
  32766. {
  32767. ComponentPeer* const peer = getPeer();
  32768. if (peer != 0)
  32769. {
  32770. if (wasMoved && wasResized)
  32771. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32772. else if (wasMoved)
  32773. peer->setPosition (getX(), getY());
  32774. else if (wasResized)
  32775. peer->setSize (getWidth(), getHeight());
  32776. }
  32777. }
  32778. sendMovedResizedMessages (wasMoved, wasResized);
  32779. }
  32780. }
  32781. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32782. {
  32783. JUCE_TRY
  32784. {
  32785. if (wasMoved)
  32786. moved();
  32787. if (wasResized)
  32788. {
  32789. resized();
  32790. for (int i = childComponentList_.size(); --i >= 0;)
  32791. {
  32792. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32793. i = jmin (i, childComponentList_.size());
  32794. }
  32795. }
  32796. BailOutChecker checker (this);
  32797. if (parentComponent_ != 0)
  32798. parentComponent_->childBoundsChanged (this);
  32799. if (! checker.shouldBailOut())
  32800. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32801. *this, wasMoved, wasResized);
  32802. }
  32803. JUCE_CATCH_EXCEPTION
  32804. }
  32805. void Component::setSize (const int w, const int h)
  32806. {
  32807. setBounds (getX(), getY(), w, h);
  32808. }
  32809. void Component::setTopLeftPosition (const int x, const int y)
  32810. {
  32811. setBounds (x, y, getWidth(), getHeight());
  32812. }
  32813. void Component::setTopRightPosition (const int x, const int y)
  32814. {
  32815. setTopLeftPosition (x - getWidth(), y);
  32816. }
  32817. void Component::setBounds (const Rectangle<int>& r)
  32818. {
  32819. setBounds (r.getX(),
  32820. r.getY(),
  32821. r.getWidth(),
  32822. r.getHeight());
  32823. }
  32824. void Component::setBoundsRelative (const float x, const float y,
  32825. const float w, const float h)
  32826. {
  32827. const int pw = getParentWidth();
  32828. const int ph = getParentHeight();
  32829. setBounds (roundToInt (x * pw),
  32830. roundToInt (y * ph),
  32831. roundToInt (w * pw),
  32832. roundToInt (h * ph));
  32833. }
  32834. void Component::setCentrePosition (const int x, const int y)
  32835. {
  32836. setTopLeftPosition (x - getWidth() / 2,
  32837. y - getHeight() / 2);
  32838. }
  32839. void Component::setCentreRelative (const float x, const float y)
  32840. {
  32841. setCentrePosition (roundToInt (getParentWidth() * x),
  32842. roundToInt (getParentHeight() * y));
  32843. }
  32844. void Component::centreWithSize (const int width, const int height)
  32845. {
  32846. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32847. setBounds (parentArea.getCentreX() - width / 2,
  32848. parentArea.getCentreY() - height / 2,
  32849. width, height);
  32850. }
  32851. void Component::setBoundsInset (const BorderSize& borders)
  32852. {
  32853. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32854. }
  32855. void Component::setBoundsToFit (int x, int y, int width, int height,
  32856. const Justification& justification,
  32857. const bool onlyReduceInSize)
  32858. {
  32859. // it's no good calling this method unless both the component and
  32860. // target rectangle have a finite size.
  32861. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32862. if (getWidth() > 0 && getHeight() > 0
  32863. && width > 0 && height > 0)
  32864. {
  32865. int newW, newH;
  32866. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32867. {
  32868. newW = getWidth();
  32869. newH = getHeight();
  32870. }
  32871. else
  32872. {
  32873. const double imageRatio = getHeight() / (double) getWidth();
  32874. const double targetRatio = height / (double) width;
  32875. if (imageRatio <= targetRatio)
  32876. {
  32877. newW = width;
  32878. newH = jmin (height, roundToInt (newW * imageRatio));
  32879. }
  32880. else
  32881. {
  32882. newH = height;
  32883. newW = jmin (width, roundToInt (newH / imageRatio));
  32884. }
  32885. }
  32886. if (newW > 0 && newH > 0)
  32887. {
  32888. int newX, newY;
  32889. justification.applyToRectangle (newX, newY, newW, newH,
  32890. x, y, width, height);
  32891. setBounds (newX, newY, newW, newH);
  32892. }
  32893. }
  32894. }
  32895. bool Component::hitTest (int x, int y)
  32896. {
  32897. if (! flags.ignoresMouseClicksFlag)
  32898. return true;
  32899. if (flags.allowChildMouseClicksFlag)
  32900. {
  32901. for (int i = getNumChildComponents(); --i >= 0;)
  32902. {
  32903. Component& child = *getChildComponent (i);
  32904. if (child.isVisible()
  32905. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32906. return true;
  32907. }
  32908. }
  32909. return false;
  32910. }
  32911. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32912. const bool allowClicksOnChildComponents) throw()
  32913. {
  32914. flags.ignoresMouseClicksFlag = ! allowClicks;
  32915. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32916. }
  32917. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32918. bool& allowsClicksOnChildComponents) const throw()
  32919. {
  32920. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32921. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32922. }
  32923. bool Component::contains (const Point<int>& point)
  32924. {
  32925. if (ComponentHelpers::hitTest (*this, point))
  32926. {
  32927. if (parentComponent_ != 0)
  32928. {
  32929. return parentComponent_->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32930. }
  32931. else if (flags.hasHeavyweightPeerFlag)
  32932. {
  32933. const ComponentPeer* const peer = getPeer();
  32934. if (peer != 0)
  32935. return peer->contains (point, true);
  32936. }
  32937. }
  32938. return false;
  32939. }
  32940. bool Component::reallyContains (const int x, const int y, const bool returnTrueIfWithinAChild)
  32941. {
  32942. const Point<int> p (x, y);
  32943. if (! contains (p))
  32944. return false;
  32945. Component* const top = getTopLevelComponent();
  32946. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, p));
  32947. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32948. }
  32949. Component* Component::getComponentAt (const Point<int>& position)
  32950. {
  32951. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32952. {
  32953. for (int i = childComponentList_.size(); --i >= 0;)
  32954. {
  32955. Component* child = childComponentList_.getUnchecked(i);
  32956. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32957. if (child != 0)
  32958. return child;
  32959. }
  32960. return this;
  32961. }
  32962. return 0;
  32963. }
  32964. Component* Component::getComponentAt (const int x, const int y)
  32965. {
  32966. return getComponentAt (Point<int> (x, y));
  32967. }
  32968. void Component::addChildComponent (Component* const child, int zOrder)
  32969. {
  32970. // if component methods are being called from threads other than the message
  32971. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32972. checkMessageManagerIsLocked
  32973. if (child != 0 && child->parentComponent_ != this)
  32974. {
  32975. if (child->parentComponent_ != 0)
  32976. child->parentComponent_->removeChildComponent (child);
  32977. else
  32978. child->removeFromDesktop();
  32979. child->parentComponent_ = this;
  32980. if (child->isVisible())
  32981. child->repaintParent();
  32982. if (! child->isAlwaysOnTop())
  32983. {
  32984. if (zOrder < 0 || zOrder > childComponentList_.size())
  32985. zOrder = childComponentList_.size();
  32986. while (zOrder > 0)
  32987. {
  32988. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32989. break;
  32990. --zOrder;
  32991. }
  32992. }
  32993. childComponentList_.insert (zOrder, child);
  32994. child->internalHierarchyChanged();
  32995. internalChildrenChanged();
  32996. }
  32997. }
  32998. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32999. {
  33000. if (child != 0)
  33001. {
  33002. child->setVisible (true);
  33003. addChildComponent (child, zOrder);
  33004. }
  33005. }
  33006. void Component::removeChildComponent (Component* const child)
  33007. {
  33008. removeChildComponent (childComponentList_.indexOf (child));
  33009. }
  33010. Component* Component::removeChildComponent (const int index)
  33011. {
  33012. // if component methods are being called from threads other than the message
  33013. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33014. checkMessageManagerIsLocked
  33015. Component* const child = childComponentList_ [index];
  33016. if (child != 0)
  33017. {
  33018. sendFakeMouseMove();
  33019. child->repaintParent();
  33020. childComponentList_.remove (index);
  33021. child->parentComponent_ = 0;
  33022. JUCE_TRY
  33023. {
  33024. if ((currentlyFocusedComponent == child)
  33025. || child->isParentOf (currentlyFocusedComponent))
  33026. {
  33027. // get rid first to force the grabKeyboardFocus to change to us.
  33028. giveAwayFocus();
  33029. grabKeyboardFocus();
  33030. }
  33031. }
  33032. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33033. catch (const std::exception& e)
  33034. {
  33035. currentlyFocusedComponent = 0;
  33036. Desktop::getInstance().triggerFocusCallback();
  33037. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33038. }
  33039. catch (...)
  33040. {
  33041. currentlyFocusedComponent = 0;
  33042. Desktop::getInstance().triggerFocusCallback();
  33043. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33044. }
  33045. #endif
  33046. child->internalHierarchyChanged();
  33047. internalChildrenChanged();
  33048. }
  33049. return child;
  33050. }
  33051. void Component::removeAllChildren()
  33052. {
  33053. while (childComponentList_.size() > 0)
  33054. removeChildComponent (childComponentList_.size() - 1);
  33055. }
  33056. void Component::deleteAllChildren()
  33057. {
  33058. while (childComponentList_.size() > 0)
  33059. delete (removeChildComponent (childComponentList_.size() - 1));
  33060. }
  33061. int Component::getNumChildComponents() const throw()
  33062. {
  33063. return childComponentList_.size();
  33064. }
  33065. Component* Component::getChildComponent (const int index) const throw()
  33066. {
  33067. return childComponentList_ [index];
  33068. }
  33069. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  33070. {
  33071. return childComponentList_.indexOf (const_cast <Component*> (child));
  33072. }
  33073. Component* Component::getTopLevelComponent() const throw()
  33074. {
  33075. const Component* comp = this;
  33076. while (comp->parentComponent_ != 0)
  33077. comp = comp->parentComponent_;
  33078. return const_cast <Component*> (comp);
  33079. }
  33080. bool Component::isParentOf (const Component* possibleChild) const throw()
  33081. {
  33082. while (possibleChild != 0)
  33083. {
  33084. possibleChild = possibleChild->parentComponent_;
  33085. if (possibleChild == this)
  33086. return true;
  33087. }
  33088. return false;
  33089. }
  33090. void Component::parentHierarchyChanged()
  33091. {
  33092. }
  33093. void Component::childrenChanged()
  33094. {
  33095. }
  33096. void Component::internalChildrenChanged()
  33097. {
  33098. if (componentListeners.isEmpty())
  33099. {
  33100. childrenChanged();
  33101. }
  33102. else
  33103. {
  33104. BailOutChecker checker (this);
  33105. childrenChanged();
  33106. if (! checker.shouldBailOut())
  33107. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  33108. }
  33109. }
  33110. void Component::internalHierarchyChanged()
  33111. {
  33112. BailOutChecker checker (this);
  33113. parentHierarchyChanged();
  33114. if (checker.shouldBailOut())
  33115. return;
  33116. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  33117. if (checker.shouldBailOut())
  33118. return;
  33119. for (int i = childComponentList_.size(); --i >= 0;)
  33120. {
  33121. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  33122. if (checker.shouldBailOut())
  33123. {
  33124. // you really shouldn't delete the parent component during a callback telling you
  33125. // that it's changed..
  33126. jassertfalse;
  33127. return;
  33128. }
  33129. i = jmin (i, childComponentList_.size());
  33130. }
  33131. }
  33132. int Component::runModalLoop()
  33133. {
  33134. if (! MessageManager::getInstance()->isThisTheMessageThread())
  33135. {
  33136. // use a callback so this can be called from non-gui threads
  33137. return (int) (pointer_sized_int) MessageManager::getInstance()
  33138. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  33139. }
  33140. if (! isCurrentlyModal())
  33141. enterModalState (true);
  33142. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  33143. }
  33144. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  33145. {
  33146. // if component methods are being called from threads other than the message
  33147. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33148. checkMessageManagerIsLocked
  33149. // Check for an attempt to make a component modal when it already is!
  33150. // This can cause nasty problems..
  33151. jassert (! flags.currentlyModalFlag);
  33152. if (! isCurrentlyModal())
  33153. {
  33154. ModalComponentManager::getInstance()->startModal (this, callback);
  33155. flags.currentlyModalFlag = true;
  33156. setVisible (true);
  33157. if (takeKeyboardFocus_)
  33158. grabKeyboardFocus();
  33159. }
  33160. }
  33161. void Component::exitModalState (const int returnValue)
  33162. {
  33163. if (isCurrentlyModal())
  33164. {
  33165. if (MessageManager::getInstance()->isThisTheMessageThread())
  33166. {
  33167. ModalComponentManager::getInstance()->endModal (this, returnValue);
  33168. flags.currentlyModalFlag = false;
  33169. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33170. }
  33171. else
  33172. {
  33173. class ExitModalStateMessage : public CallbackMessage
  33174. {
  33175. public:
  33176. ExitModalStateMessage (Component* const target_, const int result_)
  33177. : target (target_), result (result_) {}
  33178. void messageCallback()
  33179. {
  33180. if (target != 0)
  33181. target->exitModalState (result);
  33182. }
  33183. private:
  33184. Component::SafePointer<Component> target;
  33185. int result;
  33186. };
  33187. (new ExitModalStateMessage (this, returnValue))->post();
  33188. }
  33189. }
  33190. }
  33191. bool Component::isCurrentlyModal() const throw()
  33192. {
  33193. return flags.currentlyModalFlag
  33194. && getCurrentlyModalComponent() == this;
  33195. }
  33196. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33197. {
  33198. Component* const mc = getCurrentlyModalComponent();
  33199. return mc != 0
  33200. && mc != this
  33201. && (! mc->isParentOf (this))
  33202. && ! mc->canModalEventBeSentToComponent (this);
  33203. }
  33204. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33205. {
  33206. return ModalComponentManager::getInstance()->getNumModalComponents();
  33207. }
  33208. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33209. {
  33210. return ModalComponentManager::getInstance()->getModalComponent (index);
  33211. }
  33212. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33213. {
  33214. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33215. }
  33216. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33217. {
  33218. return flags.bringToFrontOnClickFlag;
  33219. }
  33220. void Component::setMouseCursor (const MouseCursor& cursor)
  33221. {
  33222. if (cursor_ != cursor)
  33223. {
  33224. cursor_ = cursor;
  33225. if (flags.visibleFlag)
  33226. updateMouseCursor();
  33227. }
  33228. }
  33229. const MouseCursor Component::getMouseCursor()
  33230. {
  33231. return cursor_;
  33232. }
  33233. void Component::updateMouseCursor() const
  33234. {
  33235. sendFakeMouseMove();
  33236. }
  33237. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33238. {
  33239. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33240. }
  33241. void Component::setAlpha (const float newAlpha)
  33242. {
  33243. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  33244. if (componentTransparency != newIntAlpha)
  33245. {
  33246. componentTransparency = newIntAlpha;
  33247. if (flags.hasHeavyweightPeerFlag)
  33248. {
  33249. ComponentPeer* const peer = getPeer();
  33250. if (peer != 0)
  33251. peer->setAlpha (newAlpha);
  33252. }
  33253. else
  33254. {
  33255. repaint();
  33256. }
  33257. }
  33258. }
  33259. float Component::getAlpha() const
  33260. {
  33261. return (255 - componentTransparency) / 255.0f;
  33262. }
  33263. void Component::repaintParent()
  33264. {
  33265. if (flags.visibleFlag)
  33266. internalRepaint (0, 0, getWidth(), getHeight());
  33267. }
  33268. void Component::repaint()
  33269. {
  33270. repaint (0, 0, getWidth(), getHeight());
  33271. }
  33272. void Component::repaint (const int x, const int y,
  33273. const int w, const int h)
  33274. {
  33275. bufferedImage_ = Image::null;
  33276. if (flags.visibleFlag)
  33277. internalRepaint (x, y, w, h);
  33278. }
  33279. void Component::repaint (const Rectangle<int>& area)
  33280. {
  33281. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33282. }
  33283. void Component::internalRepaint (int x, int y, int w, int h)
  33284. {
  33285. // if component methods are being called from threads other than the message
  33286. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33287. checkMessageManagerIsLocked
  33288. if (x < 0)
  33289. {
  33290. w += x;
  33291. x = 0;
  33292. }
  33293. if (x + w > getWidth())
  33294. w = getWidth() - x;
  33295. if (w > 0)
  33296. {
  33297. if (y < 0)
  33298. {
  33299. h += y;
  33300. y = 0;
  33301. }
  33302. if (y + h > getHeight())
  33303. h = getHeight() - y;
  33304. if (h > 0)
  33305. {
  33306. if (parentComponent_ != 0)
  33307. {
  33308. if (parentComponent_->flags.visibleFlag)
  33309. parentComponent_->internalRepaint (x + getX(), y + getY(), w, h);
  33310. }
  33311. else if (flags.hasHeavyweightPeerFlag)
  33312. {
  33313. ComponentPeer* const peer = getPeer();
  33314. if (peer != 0)
  33315. peer->repaint (Rectangle<int> (x, y, w, h));
  33316. }
  33317. }
  33318. }
  33319. }
  33320. void Component::paintComponent (Graphics& g)
  33321. {
  33322. if (flags.bufferToImageFlag)
  33323. {
  33324. if (bufferedImage_.isNull())
  33325. {
  33326. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33327. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33328. Graphics imG (bufferedImage_);
  33329. paint (imG);
  33330. }
  33331. g.setColour (Colours::black.withAlpha (getAlpha()));
  33332. g.drawImageAt (bufferedImage_, 0, 0);
  33333. }
  33334. else
  33335. {
  33336. paint (g);
  33337. }
  33338. }
  33339. void Component::paintComponentAndChildren (Graphics& g)
  33340. {
  33341. const Rectangle<int> clipBounds (g.getClipBounds());
  33342. if (flags.dontClipGraphicsFlag)
  33343. {
  33344. paintComponent (g);
  33345. }
  33346. else
  33347. {
  33348. g.saveState();
  33349. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33350. if (! g.isClipEmpty())
  33351. paintComponent (g);
  33352. g.restoreState();
  33353. }
  33354. for (int i = 0; i < childComponentList_.size(); ++i)
  33355. {
  33356. Component* const child = childComponentList_.getUnchecked (i);
  33357. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33358. {
  33359. g.saveState();
  33360. if (child->flags.dontClipGraphicsFlag)
  33361. {
  33362. g.setOrigin (child->getX(), child->getY());
  33363. child->paintEntireComponent (g, false);
  33364. }
  33365. else
  33366. {
  33367. if (g.reduceClipRegion (child->getBounds()))
  33368. {
  33369. bool nothingClipped = true;
  33370. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33371. {
  33372. const Component* const sibling = childComponentList_.getUnchecked (j);
  33373. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33374. {
  33375. nothingClipped = false;
  33376. g.excludeClipRegion (sibling->getBounds());
  33377. }
  33378. }
  33379. if (nothingClipped || ! g.isClipEmpty())
  33380. {
  33381. g.setOrigin (child->getX(), child->getY());
  33382. child->paintEntireComponent (g, false);
  33383. }
  33384. }
  33385. }
  33386. g.restoreState();
  33387. }
  33388. }
  33389. g.saveState();
  33390. paintOverChildren (g);
  33391. g.restoreState();
  33392. }
  33393. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33394. {
  33395. jassert (! g.isClipEmpty());
  33396. #if JUCE_DEBUG
  33397. flags.isInsidePaintCall = true;
  33398. #endif
  33399. if (effect_ != 0)
  33400. {
  33401. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33402. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33403. {
  33404. Graphics g2 (effectImage);
  33405. paintComponentAndChildren (g2);
  33406. }
  33407. effect_->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33408. }
  33409. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33410. {
  33411. if (componentTransparency < 255)
  33412. {
  33413. Image temp (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33414. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33415. {
  33416. Graphics tempG (temp);
  33417. tempG.reduceClipRegion (g.getClipBounds());
  33418. paintEntireComponent (tempG, true);
  33419. }
  33420. g.setColour (Colours::black.withAlpha (getAlpha()));
  33421. g.drawImageAt (temp, 0, 0);
  33422. }
  33423. }
  33424. else
  33425. {
  33426. paintComponentAndChildren (g);
  33427. }
  33428. #if JUCE_DEBUG
  33429. flags.isInsidePaintCall = false;
  33430. #endif
  33431. }
  33432. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33433. {
  33434. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33435. }
  33436. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33437. const bool clipImageToComponentBounds)
  33438. {
  33439. Rectangle<int> r (areaToGrab);
  33440. if (clipImageToComponentBounds)
  33441. r = r.getIntersection (getLocalBounds());
  33442. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33443. jmax (1, r.getWidth()),
  33444. jmax (1, r.getHeight()),
  33445. true);
  33446. Graphics imageContext (componentImage);
  33447. imageContext.setOrigin (-r.getX(), -r.getY());
  33448. paintEntireComponent (imageContext, true);
  33449. return componentImage;
  33450. }
  33451. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33452. {
  33453. if (effect_ != effect)
  33454. {
  33455. effect_ = effect;
  33456. repaint();
  33457. }
  33458. }
  33459. LookAndFeel& Component::getLookAndFeel() const throw()
  33460. {
  33461. const Component* c = this;
  33462. do
  33463. {
  33464. if (c->lookAndFeel_ != 0)
  33465. return *(c->lookAndFeel_);
  33466. c = c->parentComponent_;
  33467. }
  33468. while (c != 0);
  33469. return LookAndFeel::getDefaultLookAndFeel();
  33470. }
  33471. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33472. {
  33473. if (lookAndFeel_ != newLookAndFeel)
  33474. {
  33475. lookAndFeel_ = newLookAndFeel;
  33476. sendLookAndFeelChange();
  33477. }
  33478. }
  33479. void Component::lookAndFeelChanged()
  33480. {
  33481. }
  33482. void Component::sendLookAndFeelChange()
  33483. {
  33484. repaint();
  33485. SafePointer<Component> safePointer (this);
  33486. lookAndFeelChanged();
  33487. if (safePointer != 0)
  33488. {
  33489. for (int i = childComponentList_.size(); --i >= 0;)
  33490. {
  33491. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33492. if (safePointer == 0)
  33493. return;
  33494. i = jmin (i, childComponentList_.size());
  33495. }
  33496. }
  33497. }
  33498. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33499. {
  33500. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33501. if (v != 0)
  33502. return Colour ((int) *v);
  33503. if (inheritFromParent && parentComponent_ != 0)
  33504. return parentComponent_->findColour (colourId, true);
  33505. return getLookAndFeel().findColour (colourId);
  33506. }
  33507. bool Component::isColourSpecified (const int colourId) const
  33508. {
  33509. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33510. }
  33511. void Component::removeColour (const int colourId)
  33512. {
  33513. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33514. colourChanged();
  33515. }
  33516. void Component::setColour (const int colourId, const Colour& colour)
  33517. {
  33518. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33519. colourChanged();
  33520. }
  33521. void Component::copyAllExplicitColoursTo (Component& target) const
  33522. {
  33523. bool changed = false;
  33524. for (int i = properties.size(); --i >= 0;)
  33525. {
  33526. const Identifier name (properties.getName(i));
  33527. if (name.toString().startsWith ("jcclr_"))
  33528. if (target.properties.set (name, properties [name]))
  33529. changed = true;
  33530. }
  33531. if (changed)
  33532. target.colourChanged();
  33533. }
  33534. void Component::colourChanged()
  33535. {
  33536. }
  33537. const Rectangle<int> Component::getLocalBounds() const throw()
  33538. {
  33539. return Rectangle<int> (getWidth(), getHeight());
  33540. }
  33541. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33542. {
  33543. result.clear();
  33544. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33545. if (! unclipped.isEmpty())
  33546. {
  33547. result.add (unclipped);
  33548. if (includeSiblings)
  33549. {
  33550. const Component* const c = getTopLevelComponent();
  33551. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33552. c->getLocalBounds(), this);
  33553. }
  33554. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33555. result.consolidate();
  33556. }
  33557. }
  33558. void Component::mouseEnter (const MouseEvent&)
  33559. {
  33560. // base class does nothing
  33561. }
  33562. void Component::mouseExit (const MouseEvent&)
  33563. {
  33564. // base class does nothing
  33565. }
  33566. void Component::mouseDown (const MouseEvent&)
  33567. {
  33568. // base class does nothing
  33569. }
  33570. void Component::mouseUp (const MouseEvent&)
  33571. {
  33572. // base class does nothing
  33573. }
  33574. void Component::mouseDrag (const MouseEvent&)
  33575. {
  33576. // base class does nothing
  33577. }
  33578. void Component::mouseMove (const MouseEvent&)
  33579. {
  33580. // base class does nothing
  33581. }
  33582. void Component::mouseDoubleClick (const MouseEvent&)
  33583. {
  33584. // base class does nothing
  33585. }
  33586. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33587. {
  33588. // the base class just passes this event up to its parent..
  33589. if (parentComponent_ != 0)
  33590. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33591. wheelIncrementX, wheelIncrementY);
  33592. }
  33593. void Component::resized()
  33594. {
  33595. // base class does nothing
  33596. }
  33597. void Component::moved()
  33598. {
  33599. // base class does nothing
  33600. }
  33601. void Component::childBoundsChanged (Component*)
  33602. {
  33603. // base class does nothing
  33604. }
  33605. void Component::parentSizeChanged()
  33606. {
  33607. // base class does nothing
  33608. }
  33609. void Component::addComponentListener (ComponentListener* const newListener)
  33610. {
  33611. componentListeners.add (newListener);
  33612. }
  33613. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33614. {
  33615. componentListeners.remove (listenerToRemove);
  33616. }
  33617. void Component::inputAttemptWhenModal()
  33618. {
  33619. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33620. getLookAndFeel().playAlertSound();
  33621. }
  33622. bool Component::canModalEventBeSentToComponent (const Component*)
  33623. {
  33624. return false;
  33625. }
  33626. void Component::internalModalInputAttempt()
  33627. {
  33628. Component* const current = getCurrentlyModalComponent();
  33629. if (current != 0)
  33630. current->inputAttemptWhenModal();
  33631. }
  33632. void Component::paint (Graphics&)
  33633. {
  33634. // all painting is done in the subclasses
  33635. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33636. }
  33637. void Component::paintOverChildren (Graphics&)
  33638. {
  33639. // all painting is done in the subclasses
  33640. }
  33641. void Component::postCommandMessage (const int commandId)
  33642. {
  33643. class CustomCommandMessage : public CallbackMessage
  33644. {
  33645. public:
  33646. CustomCommandMessage (Component* const target_, const int commandId_)
  33647. : target (target_), commandId (commandId_) {}
  33648. void messageCallback()
  33649. {
  33650. if (target != 0)
  33651. target->handleCommandMessage (commandId);
  33652. }
  33653. private:
  33654. Component::SafePointer<Component> target;
  33655. int commandId;
  33656. };
  33657. (new CustomCommandMessage (this, commandId))->post();
  33658. }
  33659. void Component::handleCommandMessage (int)
  33660. {
  33661. // used by subclasses
  33662. }
  33663. void Component::addMouseListener (MouseListener* const newListener,
  33664. const bool wantsEventsForAllNestedChildComponents)
  33665. {
  33666. // if component methods are being called from threads other than the message
  33667. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33668. checkMessageManagerIsLocked
  33669. // If you register a component as a mouselistener for itself, it'll receive all the events
  33670. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33671. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33672. if (mouseListeners_ == 0)
  33673. mouseListeners_ = new MouseListenerList();
  33674. mouseListeners_->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33675. }
  33676. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33677. {
  33678. // if component methods are being called from threads other than the message
  33679. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33680. checkMessageManagerIsLocked
  33681. if (mouseListeners_ != 0)
  33682. mouseListeners_->removeListener (listenerToRemove);
  33683. }
  33684. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33685. {
  33686. if (isCurrentlyBlockedByAnotherModalComponent())
  33687. {
  33688. // if something else is modal, always just show a normal mouse cursor
  33689. source.showMouseCursor (MouseCursor::NormalCursor);
  33690. return;
  33691. }
  33692. if (! flags.mouseInsideFlag)
  33693. {
  33694. flags.mouseInsideFlag = true;
  33695. flags.mouseOverFlag = true;
  33696. flags.mouseDownFlag = false;
  33697. BailOutChecker checker (this);
  33698. if (flags.repaintOnMouseActivityFlag)
  33699. repaint();
  33700. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33701. this, this, time, relativePos, time, 0, false);
  33702. mouseEnter (me);
  33703. if (checker.shouldBailOut())
  33704. return;
  33705. Desktop::getInstance().resetTimer();
  33706. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33707. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseEnter, me);
  33708. }
  33709. }
  33710. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33711. {
  33712. BailOutChecker checker (this);
  33713. if (flags.mouseDownFlag)
  33714. {
  33715. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33716. if (checker.shouldBailOut())
  33717. return;
  33718. }
  33719. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33720. {
  33721. flags.mouseInsideFlag = false;
  33722. flags.mouseOverFlag = false;
  33723. flags.mouseDownFlag = false;
  33724. if (flags.repaintOnMouseActivityFlag)
  33725. repaint();
  33726. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33727. this, this, time, relativePos, time, 0, false);
  33728. mouseExit (me);
  33729. if (checker.shouldBailOut())
  33730. return;
  33731. Desktop::getInstance().resetTimer();
  33732. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33733. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseExit, me);
  33734. }
  33735. }
  33736. class InternalDragRepeater : public Timer
  33737. {
  33738. public:
  33739. InternalDragRepeater()
  33740. {}
  33741. ~InternalDragRepeater()
  33742. {
  33743. clearSingletonInstance();
  33744. }
  33745. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33746. void timerCallback()
  33747. {
  33748. Desktop& desktop = Desktop::getInstance();
  33749. int numMiceDown = 0;
  33750. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33751. {
  33752. MouseInputSource* const source = desktop.getMouseSource(i);
  33753. if (source->isDragging())
  33754. {
  33755. source->triggerFakeMove();
  33756. ++numMiceDown;
  33757. }
  33758. }
  33759. if (numMiceDown == 0)
  33760. deleteInstance();
  33761. }
  33762. juce_UseDebuggingNewOperator
  33763. private:
  33764. InternalDragRepeater (const InternalDragRepeater&);
  33765. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33766. };
  33767. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33768. void Component::beginDragAutoRepeat (const int interval)
  33769. {
  33770. if (interval > 0)
  33771. {
  33772. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33773. InternalDragRepeater::getInstance()->startTimer (interval);
  33774. }
  33775. else
  33776. {
  33777. InternalDragRepeater::deleteInstance();
  33778. }
  33779. }
  33780. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33781. {
  33782. Desktop& desktop = Desktop::getInstance();
  33783. BailOutChecker checker (this);
  33784. if (isCurrentlyBlockedByAnotherModalComponent())
  33785. {
  33786. internalModalInputAttempt();
  33787. if (checker.shouldBailOut())
  33788. return;
  33789. // If processing the input attempt has exited the modal loop, we'll allow the event
  33790. // to be delivered..
  33791. if (isCurrentlyBlockedByAnotherModalComponent())
  33792. {
  33793. // allow blocked mouse-events to go to global listeners..
  33794. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33795. this, this, time, relativePos, time,
  33796. source.getNumberOfMultipleClicks(), false);
  33797. desktop.resetTimer();
  33798. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33799. return;
  33800. }
  33801. }
  33802. {
  33803. Component* c = this;
  33804. while (c != 0)
  33805. {
  33806. if (c->isBroughtToFrontOnMouseClick())
  33807. {
  33808. c->toFront (true);
  33809. if (checker.shouldBailOut())
  33810. return;
  33811. }
  33812. c = c->parentComponent_;
  33813. }
  33814. }
  33815. if (! flags.dontFocusOnMouseClickFlag)
  33816. {
  33817. grabFocusInternal (focusChangedByMouseClick);
  33818. if (checker.shouldBailOut())
  33819. return;
  33820. }
  33821. flags.mouseDownFlag = true;
  33822. flags.mouseOverFlag = true;
  33823. if (flags.repaintOnMouseActivityFlag)
  33824. repaint();
  33825. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33826. this, this, time, relativePos, time,
  33827. source.getNumberOfMultipleClicks(), false);
  33828. mouseDown (me);
  33829. if (checker.shouldBailOut())
  33830. return;
  33831. desktop.resetTimer();
  33832. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33833. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDown, me);
  33834. }
  33835. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33836. {
  33837. if (flags.mouseDownFlag)
  33838. {
  33839. Desktop& desktop = Desktop::getInstance();
  33840. flags.mouseDownFlag = false;
  33841. BailOutChecker checker (this);
  33842. if (flags.repaintOnMouseActivityFlag)
  33843. repaint();
  33844. const MouseEvent me (source, relativePos,
  33845. oldModifiers, this, this, time,
  33846. getLocalPoint (0, source.getLastMouseDownPosition()),
  33847. source.getLastMouseDownTime(),
  33848. source.getNumberOfMultipleClicks(),
  33849. source.hasMouseMovedSignificantlySincePressed());
  33850. mouseUp (me);
  33851. if (checker.shouldBailOut())
  33852. return;
  33853. desktop.resetTimer();
  33854. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33855. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseUp, me);
  33856. if (checker.shouldBailOut())
  33857. return;
  33858. // check for double-click
  33859. if (me.getNumberOfClicks() >= 2)
  33860. {
  33861. mouseDoubleClick (me);
  33862. if (checker.shouldBailOut())
  33863. return;
  33864. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33865. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDoubleClick, me);
  33866. }
  33867. }
  33868. }
  33869. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33870. {
  33871. if (flags.mouseDownFlag)
  33872. {
  33873. Desktop& desktop = Desktop::getInstance();
  33874. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33875. BailOutChecker checker (this);
  33876. const MouseEvent me (source, relativePos,
  33877. source.getCurrentModifiers(), this, this, time,
  33878. getLocalPoint (0, source.getLastMouseDownPosition()),
  33879. source.getLastMouseDownTime(),
  33880. source.getNumberOfMultipleClicks(),
  33881. source.hasMouseMovedSignificantlySincePressed());
  33882. mouseDrag (me);
  33883. if (checker.shouldBailOut())
  33884. return;
  33885. desktop.resetTimer();
  33886. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33887. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseDrag, me);
  33888. }
  33889. }
  33890. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33891. {
  33892. Desktop& desktop = Desktop::getInstance();
  33893. BailOutChecker checker (this);
  33894. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33895. this, this, time, relativePos, time, 0, false);
  33896. if (isCurrentlyBlockedByAnotherModalComponent())
  33897. {
  33898. // allow blocked mouse-events to go to global listeners..
  33899. desktop.sendMouseMove();
  33900. }
  33901. else
  33902. {
  33903. flags.mouseOverFlag = true;
  33904. mouseMove (me);
  33905. if (checker.shouldBailOut())
  33906. return;
  33907. desktop.resetTimer();
  33908. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33909. MouseListenerList::sendMouseEvent (this, checker, &MouseListener::mouseMove, me);
  33910. }
  33911. }
  33912. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33913. const Time& time, const float amountX, const float amountY)
  33914. {
  33915. Desktop& desktop = Desktop::getInstance();
  33916. BailOutChecker checker (this);
  33917. const float wheelIncrementX = amountX / 256.0f;
  33918. const float wheelIncrementY = amountY / 256.0f;
  33919. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33920. this, this, time, relativePos, time, 0, false);
  33921. if (isCurrentlyBlockedByAnotherModalComponent())
  33922. {
  33923. // allow blocked mouse-events to go to global listeners..
  33924. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33925. }
  33926. else
  33927. {
  33928. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33929. if (checker.shouldBailOut())
  33930. return;
  33931. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33932. MouseListenerList::sendWheelEvent (this, checker, me, wheelIncrementX, wheelIncrementY);
  33933. }
  33934. }
  33935. void Component::sendFakeMouseMove() const
  33936. {
  33937. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33938. }
  33939. void Component::broughtToFront()
  33940. {
  33941. }
  33942. void Component::internalBroughtToFront()
  33943. {
  33944. if (flags.hasHeavyweightPeerFlag)
  33945. Desktop::getInstance().componentBroughtToFront (this);
  33946. BailOutChecker checker (this);
  33947. broughtToFront();
  33948. if (checker.shouldBailOut())
  33949. return;
  33950. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33951. if (checker.shouldBailOut())
  33952. return;
  33953. // When brought to the front and there's a modal component blocking this one,
  33954. // we need to bring the modal one to the front instead..
  33955. Component* const cm = getCurrentlyModalComponent();
  33956. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33957. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33958. }
  33959. void Component::focusGained (FocusChangeType)
  33960. {
  33961. // base class does nothing
  33962. }
  33963. void Component::internalFocusGain (const FocusChangeType cause)
  33964. {
  33965. SafePointer<Component> safePointer (this);
  33966. focusGained (cause);
  33967. if (safePointer != 0)
  33968. internalChildFocusChange (cause);
  33969. }
  33970. void Component::focusLost (FocusChangeType)
  33971. {
  33972. // base class does nothing
  33973. }
  33974. void Component::internalFocusLoss (const FocusChangeType cause)
  33975. {
  33976. SafePointer<Component> safePointer (this);
  33977. focusLost (focusChangedDirectly);
  33978. if (safePointer != 0)
  33979. internalChildFocusChange (cause);
  33980. }
  33981. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33982. {
  33983. // base class does nothing
  33984. }
  33985. void Component::internalChildFocusChange (FocusChangeType cause)
  33986. {
  33987. const bool childIsNowFocused = hasKeyboardFocus (true);
  33988. if (flags.childCompFocusedFlag != childIsNowFocused)
  33989. {
  33990. flags.childCompFocusedFlag = childIsNowFocused;
  33991. SafePointer<Component> safePointer (this);
  33992. focusOfChildComponentChanged (cause);
  33993. if (safePointer == 0)
  33994. return;
  33995. }
  33996. if (parentComponent_ != 0)
  33997. parentComponent_->internalChildFocusChange (cause);
  33998. }
  33999. bool Component::isEnabled() const throw()
  34000. {
  34001. return (! flags.isDisabledFlag)
  34002. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  34003. }
  34004. void Component::setEnabled (const bool shouldBeEnabled)
  34005. {
  34006. if (flags.isDisabledFlag == shouldBeEnabled)
  34007. {
  34008. flags.isDisabledFlag = ! shouldBeEnabled;
  34009. // if any parent components are disabled, setting our flag won't make a difference,
  34010. // so no need to send a change message
  34011. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  34012. sendEnablementChangeMessage();
  34013. }
  34014. }
  34015. void Component::sendEnablementChangeMessage()
  34016. {
  34017. SafePointer<Component> safePointer (this);
  34018. enablementChanged();
  34019. if (safePointer == 0)
  34020. return;
  34021. for (int i = getNumChildComponents(); --i >= 0;)
  34022. {
  34023. Component* const c = getChildComponent (i);
  34024. if (c != 0)
  34025. {
  34026. c->sendEnablementChangeMessage();
  34027. if (safePointer == 0)
  34028. return;
  34029. }
  34030. }
  34031. }
  34032. void Component::enablementChanged()
  34033. {
  34034. }
  34035. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34036. {
  34037. flags.wantsFocusFlag = wantsFocus;
  34038. }
  34039. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34040. {
  34041. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34042. }
  34043. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34044. {
  34045. return ! flags.dontFocusOnMouseClickFlag;
  34046. }
  34047. bool Component::getWantsKeyboardFocus() const throw()
  34048. {
  34049. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34050. }
  34051. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34052. {
  34053. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34054. }
  34055. bool Component::isFocusContainer() const throw()
  34056. {
  34057. return flags.isFocusContainerFlag;
  34058. }
  34059. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34060. int Component::getExplicitFocusOrder() const
  34061. {
  34062. return properties [juce_explicitFocusOrderId];
  34063. }
  34064. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34065. {
  34066. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34067. }
  34068. KeyboardFocusTraverser* Component::createFocusTraverser()
  34069. {
  34070. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34071. return new KeyboardFocusTraverser();
  34072. return parentComponent_->createFocusTraverser();
  34073. }
  34074. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34075. {
  34076. // give the focus to this component
  34077. if (currentlyFocusedComponent != this)
  34078. {
  34079. JUCE_TRY
  34080. {
  34081. // get the focus onto our desktop window
  34082. ComponentPeer* const peer = getPeer();
  34083. if (peer != 0)
  34084. {
  34085. SafePointer<Component> safePointer (this);
  34086. peer->grabFocus();
  34087. if (peer->isFocused() && currentlyFocusedComponent != this)
  34088. {
  34089. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34090. currentlyFocusedComponent = this;
  34091. Desktop::getInstance().triggerFocusCallback();
  34092. // call this after setting currentlyFocusedComponent so that the one that's
  34093. // losing it has a chance to see where focus is going
  34094. if (componentLosingFocus != 0)
  34095. componentLosingFocus->internalFocusLoss (cause);
  34096. if (currentlyFocusedComponent == this)
  34097. {
  34098. focusGained (cause);
  34099. if (safePointer != 0)
  34100. internalChildFocusChange (cause);
  34101. }
  34102. }
  34103. }
  34104. }
  34105. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34106. catch (const std::exception& e)
  34107. {
  34108. currentlyFocusedComponent = 0;
  34109. Desktop::getInstance().triggerFocusCallback();
  34110. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34111. }
  34112. catch (...)
  34113. {
  34114. currentlyFocusedComponent = 0;
  34115. Desktop::getInstance().triggerFocusCallback();
  34116. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34117. }
  34118. #endif
  34119. }
  34120. }
  34121. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34122. {
  34123. if (isShowing())
  34124. {
  34125. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34126. {
  34127. takeKeyboardFocus (cause);
  34128. }
  34129. else
  34130. {
  34131. if (isParentOf (currentlyFocusedComponent)
  34132. && currentlyFocusedComponent->isShowing())
  34133. {
  34134. // do nothing if the focused component is actually a child of ours..
  34135. }
  34136. else
  34137. {
  34138. // find the default child component..
  34139. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34140. if (traverser != 0)
  34141. {
  34142. Component* const defaultComp = traverser->getDefaultComponent (this);
  34143. traverser = 0;
  34144. if (defaultComp != 0)
  34145. {
  34146. defaultComp->grabFocusInternal (cause, false);
  34147. return;
  34148. }
  34149. }
  34150. if (canTryParent && parentComponent_ != 0)
  34151. {
  34152. // if no children want it and we're allowed to try our parent comp,
  34153. // then pass up to parent, which will try our siblings.
  34154. parentComponent_->grabFocusInternal (cause, true);
  34155. }
  34156. }
  34157. }
  34158. }
  34159. }
  34160. void Component::grabKeyboardFocus()
  34161. {
  34162. // if component methods are being called from threads other than the message
  34163. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34164. checkMessageManagerIsLocked
  34165. grabFocusInternal (focusChangedDirectly);
  34166. }
  34167. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34168. {
  34169. // if component methods are being called from threads other than the message
  34170. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34171. checkMessageManagerIsLocked
  34172. if (parentComponent_ != 0)
  34173. {
  34174. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34175. if (traverser != 0)
  34176. {
  34177. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34178. : traverser->getPreviousComponent (this);
  34179. traverser = 0;
  34180. if (nextComp != 0)
  34181. {
  34182. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34183. {
  34184. SafePointer<Component> nextCompPointer (nextComp);
  34185. internalModalInputAttempt();
  34186. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34187. return;
  34188. }
  34189. nextComp->grabFocusInternal (focusChangedByTabKey);
  34190. return;
  34191. }
  34192. }
  34193. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34194. }
  34195. }
  34196. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34197. {
  34198. return (currentlyFocusedComponent == this)
  34199. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34200. }
  34201. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34202. {
  34203. return currentlyFocusedComponent;
  34204. }
  34205. void Component::giveAwayFocus()
  34206. {
  34207. // use a copy so we can clear the value before the call
  34208. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34209. currentlyFocusedComponent = 0;
  34210. Desktop::getInstance().triggerFocusCallback();
  34211. if (componentLosingFocus != 0)
  34212. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34213. }
  34214. bool Component::isMouseOver() const throw()
  34215. {
  34216. return flags.mouseOverFlag;
  34217. }
  34218. bool Component::isMouseButtonDown() const throw()
  34219. {
  34220. return flags.mouseDownFlag;
  34221. }
  34222. bool Component::isMouseOverOrDragging() const throw()
  34223. {
  34224. return flags.mouseOverFlag || flags.mouseDownFlag;
  34225. }
  34226. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34227. {
  34228. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34229. }
  34230. const Point<int> Component::getMouseXYRelative() const
  34231. {
  34232. return getLocalPoint (0, Desktop::getMousePosition());
  34233. }
  34234. const Rectangle<int> Component::getParentMonitorArea() const
  34235. {
  34236. return Desktop::getInstance()
  34237. .getMonitorAreaContaining (localPointToGlobal (getLocalBounds().getCentre()));
  34238. }
  34239. void Component::addKeyListener (KeyListener* const newListener)
  34240. {
  34241. if (keyListeners_ == 0)
  34242. keyListeners_ = new Array <KeyListener*>();
  34243. keyListeners_->addIfNotAlreadyThere (newListener);
  34244. }
  34245. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34246. {
  34247. if (keyListeners_ != 0)
  34248. keyListeners_->removeValue (listenerToRemove);
  34249. }
  34250. bool Component::keyPressed (const KeyPress&)
  34251. {
  34252. return false;
  34253. }
  34254. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34255. {
  34256. return false;
  34257. }
  34258. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34259. {
  34260. if (parentComponent_ != 0)
  34261. parentComponent_->modifierKeysChanged (modifiers);
  34262. }
  34263. void Component::internalModifierKeysChanged()
  34264. {
  34265. sendFakeMouseMove();
  34266. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34267. }
  34268. ComponentPeer* Component::getPeer() const
  34269. {
  34270. if (flags.hasHeavyweightPeerFlag)
  34271. return ComponentPeer::getPeerFor (this);
  34272. else if (parentComponent_ != 0)
  34273. return parentComponent_->getPeer();
  34274. else
  34275. return 0;
  34276. }
  34277. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34278. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34279. {
  34280. jassert (component1 != 0);
  34281. }
  34282. bool Component::BailOutChecker::shouldBailOut() const throw()
  34283. {
  34284. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34285. }
  34286. END_JUCE_NAMESPACE
  34287. /*** End of inlined file: juce_Component.cpp ***/
  34288. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34289. BEGIN_JUCE_NAMESPACE
  34290. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34291. void ComponentListener::componentBroughtToFront (Component&) {}
  34292. void ComponentListener::componentVisibilityChanged (Component&) {}
  34293. void ComponentListener::componentChildrenChanged (Component&) {}
  34294. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34295. void ComponentListener::componentNameChanged (Component&) {}
  34296. void ComponentListener::componentBeingDeleted (Component&) {}
  34297. END_JUCE_NAMESPACE
  34298. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34299. /*** Start of inlined file: juce_Desktop.cpp ***/
  34300. BEGIN_JUCE_NAMESPACE
  34301. Desktop::Desktop()
  34302. : mouseClickCounter (0),
  34303. kioskModeComponent (0),
  34304. allowedOrientations (allOrientations)
  34305. {
  34306. createMouseInputSources();
  34307. refreshMonitorSizes();
  34308. }
  34309. Desktop::~Desktop()
  34310. {
  34311. jassert (instance == this);
  34312. instance = 0;
  34313. // doh! If you don't delete all your windows before exiting, you're going to
  34314. // be leaking memory!
  34315. jassert (desktopComponents.size() == 0);
  34316. }
  34317. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34318. {
  34319. if (instance == 0)
  34320. instance = new Desktop();
  34321. return *instance;
  34322. }
  34323. Desktop* Desktop::instance = 0;
  34324. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34325. const bool clipToWorkArea);
  34326. void Desktop::refreshMonitorSizes()
  34327. {
  34328. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34329. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34330. monitorCoordsClipped.clear();
  34331. monitorCoordsUnclipped.clear();
  34332. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34333. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34334. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34335. if (oldClipped != monitorCoordsClipped
  34336. || oldUnclipped != monitorCoordsUnclipped)
  34337. {
  34338. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34339. {
  34340. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34341. if (p != 0)
  34342. p->handleScreenSizeChange();
  34343. }
  34344. }
  34345. }
  34346. int Desktop::getNumDisplayMonitors() const throw()
  34347. {
  34348. return monitorCoordsClipped.size();
  34349. }
  34350. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34351. {
  34352. return clippedToWorkArea ? monitorCoordsClipped [index]
  34353. : monitorCoordsUnclipped [index];
  34354. }
  34355. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34356. {
  34357. RectangleList rl;
  34358. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34359. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34360. return rl;
  34361. }
  34362. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34363. {
  34364. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34365. }
  34366. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34367. {
  34368. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34369. double bestDistance = 1.0e10;
  34370. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34371. {
  34372. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34373. if (rect.contains (position))
  34374. return rect;
  34375. const double distance = rect.getCentre().getDistanceFrom (position);
  34376. if (distance < bestDistance)
  34377. {
  34378. bestDistance = distance;
  34379. best = rect;
  34380. }
  34381. }
  34382. return best;
  34383. }
  34384. int Desktop::getNumComponents() const throw()
  34385. {
  34386. return desktopComponents.size();
  34387. }
  34388. Component* Desktop::getComponent (const int index) const throw()
  34389. {
  34390. return desktopComponents [index];
  34391. }
  34392. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34393. {
  34394. for (int i = desktopComponents.size(); --i >= 0;)
  34395. {
  34396. Component* const c = desktopComponents.getUnchecked(i);
  34397. if (c->isVisible())
  34398. {
  34399. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34400. if (c->contains (relative))
  34401. return c->getComponentAt (relative);
  34402. }
  34403. }
  34404. return 0;
  34405. }
  34406. void Desktop::addDesktopComponent (Component* const c)
  34407. {
  34408. jassert (c != 0);
  34409. jassert (! desktopComponents.contains (c));
  34410. desktopComponents.addIfNotAlreadyThere (c);
  34411. }
  34412. void Desktop::removeDesktopComponent (Component* const c)
  34413. {
  34414. desktopComponents.removeValue (c);
  34415. }
  34416. void Desktop::componentBroughtToFront (Component* const c)
  34417. {
  34418. const int index = desktopComponents.indexOf (c);
  34419. jassert (index >= 0);
  34420. if (index >= 0)
  34421. {
  34422. int newIndex = -1;
  34423. if (! c->isAlwaysOnTop())
  34424. {
  34425. newIndex = desktopComponents.size();
  34426. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34427. --newIndex;
  34428. --newIndex;
  34429. }
  34430. desktopComponents.move (index, newIndex);
  34431. }
  34432. }
  34433. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34434. {
  34435. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34436. }
  34437. int Desktop::getMouseButtonClickCounter() throw()
  34438. {
  34439. return getInstance().mouseClickCounter;
  34440. }
  34441. void Desktop::incrementMouseClickCounter() throw()
  34442. {
  34443. ++mouseClickCounter;
  34444. }
  34445. int Desktop::getNumDraggingMouseSources() const throw()
  34446. {
  34447. int num = 0;
  34448. for (int i = mouseSources.size(); --i >= 0;)
  34449. if (mouseSources.getUnchecked(i)->isDragging())
  34450. ++num;
  34451. return num;
  34452. }
  34453. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34454. {
  34455. int num = 0;
  34456. for (int i = mouseSources.size(); --i >= 0;)
  34457. {
  34458. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34459. if (mi->isDragging())
  34460. {
  34461. if (index == num)
  34462. return mi;
  34463. ++num;
  34464. }
  34465. }
  34466. return 0;
  34467. }
  34468. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34469. {
  34470. focusListeners.add (listener);
  34471. }
  34472. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34473. {
  34474. focusListeners.remove (listener);
  34475. }
  34476. void Desktop::triggerFocusCallback()
  34477. {
  34478. triggerAsyncUpdate();
  34479. }
  34480. void Desktop::handleAsyncUpdate()
  34481. {
  34482. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34483. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34484. }
  34485. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34486. {
  34487. mouseListeners.add (listener);
  34488. resetTimer();
  34489. }
  34490. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34491. {
  34492. mouseListeners.remove (listener);
  34493. resetTimer();
  34494. }
  34495. void Desktop::timerCallback()
  34496. {
  34497. if (lastFakeMouseMove != getMousePosition())
  34498. sendMouseMove();
  34499. }
  34500. void Desktop::sendMouseMove()
  34501. {
  34502. if (! mouseListeners.isEmpty())
  34503. {
  34504. startTimer (20);
  34505. lastFakeMouseMove = getMousePosition();
  34506. Component* const target = findComponentAt (lastFakeMouseMove);
  34507. if (target != 0)
  34508. {
  34509. Component::BailOutChecker checker (target);
  34510. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34511. const Time now (Time::getCurrentTime());
  34512. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34513. target, target, now, pos, now, 0, false);
  34514. if (me.mods.isAnyMouseButtonDown())
  34515. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34516. else
  34517. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34518. }
  34519. }
  34520. }
  34521. void Desktop::resetTimer()
  34522. {
  34523. if (mouseListeners.size() == 0)
  34524. stopTimer();
  34525. else
  34526. startTimer (100);
  34527. lastFakeMouseMove = getMousePosition();
  34528. }
  34529. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34530. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34531. {
  34532. if (kioskModeComponent != componentToUse)
  34533. {
  34534. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34535. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34536. if (kioskModeComponent != 0)
  34537. {
  34538. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34539. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34540. }
  34541. kioskModeComponent = componentToUse;
  34542. if (kioskModeComponent != 0)
  34543. {
  34544. // Only components that are already on the desktop can be put into kiosk mode!
  34545. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34546. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34547. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34548. }
  34549. }
  34550. }
  34551. void Desktop::setOrientationsEnabled (const int newOrientations)
  34552. {
  34553. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34554. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34555. allowedOrientations = newOrientations;
  34556. }
  34557. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34558. {
  34559. // Make sure you only pass one valid flag in here...
  34560. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34561. return (allowedOrientations & orientation) != 0;
  34562. }
  34563. END_JUCE_NAMESPACE
  34564. /*** End of inlined file: juce_Desktop.cpp ***/
  34565. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34566. BEGIN_JUCE_NAMESPACE
  34567. class ModalComponentManager::ModalItem : public ComponentListener
  34568. {
  34569. public:
  34570. ModalItem (Component* const comp, Callback* const callback)
  34571. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34572. {
  34573. if (callback != 0)
  34574. callbacks.add (callback);
  34575. jassert (comp != 0);
  34576. component->addComponentListener (this);
  34577. }
  34578. ~ModalItem()
  34579. {
  34580. if (! isDeleted)
  34581. component->removeComponentListener (this);
  34582. }
  34583. void componentBeingDeleted (Component&)
  34584. {
  34585. isDeleted = true;
  34586. cancel();
  34587. }
  34588. void componentVisibilityChanged (Component&)
  34589. {
  34590. if (! component->isShowing())
  34591. cancel();
  34592. }
  34593. void componentParentHierarchyChanged (Component&)
  34594. {
  34595. if (! component->isShowing())
  34596. cancel();
  34597. }
  34598. void cancel()
  34599. {
  34600. if (isActive)
  34601. {
  34602. isActive = false;
  34603. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34604. }
  34605. }
  34606. Component* component;
  34607. OwnedArray<Callback> callbacks;
  34608. int returnValue;
  34609. bool isActive, isDeleted;
  34610. private:
  34611. ModalItem (const ModalItem&);
  34612. ModalItem& operator= (const ModalItem&);
  34613. };
  34614. ModalComponentManager::ModalComponentManager()
  34615. {
  34616. }
  34617. ModalComponentManager::~ModalComponentManager()
  34618. {
  34619. clearSingletonInstance();
  34620. }
  34621. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34622. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34623. {
  34624. if (component != 0)
  34625. stack.add (new ModalItem (component, callback));
  34626. }
  34627. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34628. {
  34629. if (callback != 0)
  34630. {
  34631. ScopedPointer<Callback> callbackDeleter (callback);
  34632. for (int i = stack.size(); --i >= 0;)
  34633. {
  34634. ModalItem* const item = stack.getUnchecked(i);
  34635. if (item->component == component)
  34636. {
  34637. item->callbacks.add (callback);
  34638. callbackDeleter.release();
  34639. break;
  34640. }
  34641. }
  34642. }
  34643. }
  34644. void ModalComponentManager::endModal (Component* component)
  34645. {
  34646. for (int i = stack.size(); --i >= 0;)
  34647. {
  34648. ModalItem* const item = stack.getUnchecked(i);
  34649. if (item->component == component)
  34650. item->cancel();
  34651. }
  34652. }
  34653. void ModalComponentManager::endModal (Component* component, int returnValue)
  34654. {
  34655. for (int i = stack.size(); --i >= 0;)
  34656. {
  34657. ModalItem* const item = stack.getUnchecked(i);
  34658. if (item->component == component)
  34659. {
  34660. item->returnValue = returnValue;
  34661. item->cancel();
  34662. }
  34663. }
  34664. }
  34665. int ModalComponentManager::getNumModalComponents() const
  34666. {
  34667. int n = 0;
  34668. for (int i = 0; i < stack.size(); ++i)
  34669. if (stack.getUnchecked(i)->isActive)
  34670. ++n;
  34671. return n;
  34672. }
  34673. Component* ModalComponentManager::getModalComponent (const int index) const
  34674. {
  34675. int n = 0;
  34676. for (int i = stack.size(); --i >= 0;)
  34677. {
  34678. const ModalItem* const item = stack.getUnchecked(i);
  34679. if (item->isActive)
  34680. if (n++ == index)
  34681. return item->component;
  34682. }
  34683. return 0;
  34684. }
  34685. bool ModalComponentManager::isModal (Component* const comp) const
  34686. {
  34687. for (int i = stack.size(); --i >= 0;)
  34688. {
  34689. const ModalItem* const item = stack.getUnchecked(i);
  34690. if (item->isActive && item->component == comp)
  34691. return true;
  34692. }
  34693. return false;
  34694. }
  34695. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34696. {
  34697. return comp == getModalComponent (0);
  34698. }
  34699. void ModalComponentManager::handleAsyncUpdate()
  34700. {
  34701. for (int i = stack.size(); --i >= 0;)
  34702. {
  34703. const ModalItem* const item = stack.getUnchecked(i);
  34704. if (! item->isActive)
  34705. {
  34706. for (int j = item->callbacks.size(); --j >= 0;)
  34707. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34708. stack.remove (i);
  34709. }
  34710. }
  34711. }
  34712. void ModalComponentManager::bringModalComponentsToFront()
  34713. {
  34714. ComponentPeer* lastOne = 0;
  34715. for (int i = 0; i < getNumModalComponents(); ++i)
  34716. {
  34717. Component* const c = getModalComponent (i);
  34718. if (c == 0)
  34719. break;
  34720. ComponentPeer* peer = c->getPeer();
  34721. if (peer != 0 && peer != lastOne)
  34722. {
  34723. if (lastOne == 0)
  34724. {
  34725. peer->toFront (true);
  34726. peer->grabFocus();
  34727. }
  34728. else
  34729. peer->toBehind (lastOne);
  34730. lastOne = peer;
  34731. }
  34732. }
  34733. }
  34734. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34735. {
  34736. public:
  34737. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34738. ~ReturnValueRetriever() {}
  34739. void modalStateFinished (int returnValue)
  34740. {
  34741. finished = true;
  34742. value = returnValue;
  34743. }
  34744. private:
  34745. int& value;
  34746. bool& finished;
  34747. ReturnValueRetriever (const ReturnValueRetriever&);
  34748. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  34749. };
  34750. int ModalComponentManager::runEventLoopForCurrentComponent()
  34751. {
  34752. // This can only be run from the message thread!
  34753. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34754. Component* currentlyModal = getModalComponent (0);
  34755. if (currentlyModal == 0)
  34756. return 0;
  34757. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34758. int returnValue = 0;
  34759. bool finished = false;
  34760. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34761. JUCE_TRY
  34762. {
  34763. while (! finished)
  34764. {
  34765. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34766. break;
  34767. }
  34768. }
  34769. JUCE_CATCH_EXCEPTION
  34770. if (prevFocused != 0)
  34771. prevFocused->grabKeyboardFocus();
  34772. return returnValue;
  34773. }
  34774. END_JUCE_NAMESPACE
  34775. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34776. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34777. BEGIN_JUCE_NAMESPACE
  34778. ArrowButton::ArrowButton (const String& name,
  34779. float arrowDirectionInRadians,
  34780. const Colour& arrowColour)
  34781. : Button (name),
  34782. colour (arrowColour)
  34783. {
  34784. path.lineTo (0.0f, 1.0f);
  34785. path.lineTo (1.0f, 0.5f);
  34786. path.closeSubPath();
  34787. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34788. 0.5f, 0.5f));
  34789. setComponentEffect (&shadow);
  34790. buttonStateChanged();
  34791. }
  34792. ArrowButton::~ArrowButton()
  34793. {
  34794. }
  34795. void ArrowButton::paintButton (Graphics& g,
  34796. bool /*isMouseOverButton*/,
  34797. bool /*isButtonDown*/)
  34798. {
  34799. g.setColour (colour);
  34800. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34801. (float) offset,
  34802. (float) (getWidth() - 3),
  34803. (float) (getHeight() - 3),
  34804. false));
  34805. }
  34806. void ArrowButton::buttonStateChanged()
  34807. {
  34808. offset = (isDown()) ? 1 : 0;
  34809. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34810. 0.3f, -1, 0);
  34811. }
  34812. END_JUCE_NAMESPACE
  34813. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34814. /*** Start of inlined file: juce_Button.cpp ***/
  34815. BEGIN_JUCE_NAMESPACE
  34816. class Button::RepeatTimer : public Timer
  34817. {
  34818. public:
  34819. RepeatTimer (Button& owner_) : owner (owner_) {}
  34820. void timerCallback() { owner.repeatTimerCallback(); }
  34821. juce_UseDebuggingNewOperator
  34822. private:
  34823. Button& owner;
  34824. RepeatTimer (const RepeatTimer&);
  34825. RepeatTimer& operator= (const RepeatTimer&);
  34826. };
  34827. Button::Button (const String& name)
  34828. : Component (name),
  34829. text (name),
  34830. buttonPressTime (0),
  34831. lastTimeCallbackTime (0),
  34832. commandManagerToUse (0),
  34833. autoRepeatDelay (-1),
  34834. autoRepeatSpeed (0),
  34835. autoRepeatMinimumDelay (-1),
  34836. radioGroupId (0),
  34837. commandID (0),
  34838. connectedEdgeFlags (0),
  34839. buttonState (buttonNormal),
  34840. lastToggleState (false),
  34841. clickTogglesState (false),
  34842. needsToRelease (false),
  34843. needsRepainting (false),
  34844. isKeyDown (false),
  34845. triggerOnMouseDown (false),
  34846. generateTooltip (false)
  34847. {
  34848. setWantsKeyboardFocus (true);
  34849. isOn.addListener (this);
  34850. }
  34851. Button::~Button()
  34852. {
  34853. isOn.removeListener (this);
  34854. if (commandManagerToUse != 0)
  34855. commandManagerToUse->removeListener (this);
  34856. repeatTimer = 0;
  34857. clearShortcuts();
  34858. }
  34859. void Button::setButtonText (const String& newText)
  34860. {
  34861. if (text != newText)
  34862. {
  34863. text = newText;
  34864. repaint();
  34865. }
  34866. }
  34867. void Button::setTooltip (const String& newTooltip)
  34868. {
  34869. SettableTooltipClient::setTooltip (newTooltip);
  34870. generateTooltip = false;
  34871. }
  34872. const String Button::getTooltip()
  34873. {
  34874. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34875. {
  34876. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34877. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34878. for (int i = 0; i < keyPresses.size(); ++i)
  34879. {
  34880. const String key (keyPresses.getReference(i).getTextDescription());
  34881. tt << " [";
  34882. if (key.length() == 1)
  34883. tt << TRANS("shortcut") << ": '" << key << "']";
  34884. else
  34885. tt << key << ']';
  34886. }
  34887. return tt;
  34888. }
  34889. return SettableTooltipClient::getTooltip();
  34890. }
  34891. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34892. {
  34893. if (connectedEdgeFlags != connectedEdgeFlags_)
  34894. {
  34895. connectedEdgeFlags = connectedEdgeFlags_;
  34896. repaint();
  34897. }
  34898. }
  34899. void Button::setToggleState (const bool shouldBeOn,
  34900. const bool sendChangeNotification)
  34901. {
  34902. if (shouldBeOn != lastToggleState)
  34903. {
  34904. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34905. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34906. lastToggleState = shouldBeOn;
  34907. repaint();
  34908. if (sendChangeNotification)
  34909. {
  34910. Component::SafePointer<Component> deletionWatcher (this);
  34911. sendClickMessage (ModifierKeys());
  34912. if (deletionWatcher == 0)
  34913. return;
  34914. }
  34915. if (lastToggleState)
  34916. turnOffOtherButtonsInGroup (sendChangeNotification);
  34917. }
  34918. }
  34919. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34920. {
  34921. clickTogglesState = shouldToggle;
  34922. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34923. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34924. // it is that this button represents, and the button will update its state to reflect this
  34925. // in the applicationCommandListChanged() method.
  34926. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34927. }
  34928. bool Button::getClickingTogglesState() const throw()
  34929. {
  34930. return clickTogglesState;
  34931. }
  34932. void Button::valueChanged (Value& value)
  34933. {
  34934. if (value.refersToSameSourceAs (isOn))
  34935. setToggleState (isOn.getValue(), true);
  34936. }
  34937. void Button::setRadioGroupId (const int newGroupId)
  34938. {
  34939. if (radioGroupId != newGroupId)
  34940. {
  34941. radioGroupId = newGroupId;
  34942. if (lastToggleState)
  34943. turnOffOtherButtonsInGroup (true);
  34944. }
  34945. }
  34946. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34947. {
  34948. Component* const p = getParentComponent();
  34949. if (p != 0 && radioGroupId != 0)
  34950. {
  34951. Component::SafePointer<Component> deletionWatcher (this);
  34952. for (int i = p->getNumChildComponents(); --i >= 0;)
  34953. {
  34954. Component* const c = p->getChildComponent (i);
  34955. if (c != this)
  34956. {
  34957. Button* const b = dynamic_cast <Button*> (c);
  34958. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34959. {
  34960. b->setToggleState (false, sendChangeNotification);
  34961. if (deletionWatcher == 0)
  34962. return;
  34963. }
  34964. }
  34965. }
  34966. }
  34967. }
  34968. void Button::enablementChanged()
  34969. {
  34970. updateState (0);
  34971. repaint();
  34972. }
  34973. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34974. {
  34975. ButtonState state = buttonNormal;
  34976. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34977. {
  34978. Point<int> mousePos;
  34979. if (e == 0)
  34980. mousePos = getMouseXYRelative();
  34981. else
  34982. mousePos = e->getEventRelativeTo (this).getPosition();
  34983. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34984. const bool down = isMouseButtonDown();
  34985. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34986. state = buttonDown;
  34987. else if (over)
  34988. state = buttonOver;
  34989. }
  34990. setState (state);
  34991. return state;
  34992. }
  34993. void Button::setState (const ButtonState newState)
  34994. {
  34995. if (buttonState != newState)
  34996. {
  34997. buttonState = newState;
  34998. repaint();
  34999. if (buttonState == buttonDown)
  35000. {
  35001. buttonPressTime = Time::getApproximateMillisecondCounter();
  35002. lastTimeCallbackTime = buttonPressTime;
  35003. }
  35004. sendStateMessage();
  35005. }
  35006. }
  35007. bool Button::isDown() const throw()
  35008. {
  35009. return buttonState == buttonDown;
  35010. }
  35011. bool Button::isOver() const throw()
  35012. {
  35013. return buttonState != buttonNormal;
  35014. }
  35015. void Button::buttonStateChanged()
  35016. {
  35017. }
  35018. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35019. {
  35020. const uint32 now = Time::getApproximateMillisecondCounter();
  35021. return now > buttonPressTime ? now - buttonPressTime : 0;
  35022. }
  35023. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35024. {
  35025. triggerOnMouseDown = isTriggeredOnMouseDown;
  35026. }
  35027. void Button::clicked()
  35028. {
  35029. }
  35030. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35031. {
  35032. clicked();
  35033. }
  35034. static const int clickMessageId = 0x2f3f4f99;
  35035. void Button::triggerClick()
  35036. {
  35037. postCommandMessage (clickMessageId);
  35038. }
  35039. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35040. {
  35041. if (clickTogglesState)
  35042. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35043. sendClickMessage (modifiers);
  35044. }
  35045. void Button::flashButtonState()
  35046. {
  35047. if (isEnabled())
  35048. {
  35049. needsToRelease = true;
  35050. setState (buttonDown);
  35051. getRepeatTimer().startTimer (100);
  35052. }
  35053. }
  35054. void Button::handleCommandMessage (int commandId)
  35055. {
  35056. if (commandId == clickMessageId)
  35057. {
  35058. if (isEnabled())
  35059. {
  35060. flashButtonState();
  35061. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35062. }
  35063. }
  35064. else
  35065. {
  35066. Component::handleCommandMessage (commandId);
  35067. }
  35068. }
  35069. void Button::addButtonListener (ButtonListener* const newListener)
  35070. {
  35071. buttonListeners.add (newListener);
  35072. }
  35073. void Button::removeButtonListener (ButtonListener* const listener)
  35074. {
  35075. buttonListeners.remove (listener);
  35076. }
  35077. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35078. {
  35079. Component::BailOutChecker checker (this);
  35080. if (commandManagerToUse != 0 && commandID != 0)
  35081. {
  35082. ApplicationCommandTarget::InvocationInfo info (commandID);
  35083. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35084. info.originatingComponent = this;
  35085. commandManagerToUse->invoke (info, true);
  35086. }
  35087. clicked (modifiers);
  35088. if (! checker.shouldBailOut())
  35089. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35090. }
  35091. void Button::sendStateMessage()
  35092. {
  35093. Component::BailOutChecker checker (this);
  35094. buttonStateChanged();
  35095. if (! checker.shouldBailOut())
  35096. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35097. }
  35098. void Button::paint (Graphics& g)
  35099. {
  35100. if (needsToRelease && isEnabled())
  35101. {
  35102. needsToRelease = false;
  35103. needsRepainting = true;
  35104. }
  35105. paintButton (g, isOver(), isDown());
  35106. }
  35107. void Button::mouseEnter (const MouseEvent& e)
  35108. {
  35109. updateState (&e);
  35110. }
  35111. void Button::mouseExit (const MouseEvent& e)
  35112. {
  35113. updateState (&e);
  35114. }
  35115. void Button::mouseDown (const MouseEvent& e)
  35116. {
  35117. updateState (&e);
  35118. if (isDown())
  35119. {
  35120. if (autoRepeatDelay >= 0)
  35121. getRepeatTimer().startTimer (autoRepeatDelay);
  35122. if (triggerOnMouseDown)
  35123. internalClickCallback (e.mods);
  35124. }
  35125. }
  35126. void Button::mouseUp (const MouseEvent& e)
  35127. {
  35128. const bool wasDown = isDown();
  35129. updateState (&e);
  35130. if (wasDown && isOver() && ! triggerOnMouseDown)
  35131. internalClickCallback (e.mods);
  35132. }
  35133. void Button::mouseDrag (const MouseEvent& e)
  35134. {
  35135. const ButtonState oldState = buttonState;
  35136. updateState (&e);
  35137. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35138. getRepeatTimer().startTimer (autoRepeatSpeed);
  35139. }
  35140. void Button::focusGained (FocusChangeType)
  35141. {
  35142. updateState (0);
  35143. repaint();
  35144. }
  35145. void Button::focusLost (FocusChangeType)
  35146. {
  35147. updateState (0);
  35148. repaint();
  35149. }
  35150. void Button::setVisible (bool shouldBeVisible)
  35151. {
  35152. if (shouldBeVisible != isVisible())
  35153. {
  35154. Component::setVisible (shouldBeVisible);
  35155. if (! shouldBeVisible)
  35156. needsToRelease = false;
  35157. updateState (0);
  35158. }
  35159. else
  35160. {
  35161. Component::setVisible (shouldBeVisible);
  35162. }
  35163. }
  35164. void Button::parentHierarchyChanged()
  35165. {
  35166. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35167. if (newKeySource != keySource.getComponent())
  35168. {
  35169. if (keySource != 0)
  35170. keySource->removeKeyListener (this);
  35171. keySource = newKeySource;
  35172. if (keySource != 0)
  35173. keySource->addKeyListener (this);
  35174. }
  35175. }
  35176. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35177. const int commandID_,
  35178. const bool generateTooltip_)
  35179. {
  35180. commandID = commandID_;
  35181. generateTooltip = generateTooltip_;
  35182. if (commandManagerToUse != commandManagerToUse_)
  35183. {
  35184. if (commandManagerToUse != 0)
  35185. commandManagerToUse->removeListener (this);
  35186. commandManagerToUse = commandManagerToUse_;
  35187. if (commandManagerToUse != 0)
  35188. commandManagerToUse->addListener (this);
  35189. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35190. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35191. // it is that this button represents, and the button will update its state to reflect this
  35192. // in the applicationCommandListChanged() method.
  35193. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35194. }
  35195. if (commandManagerToUse != 0)
  35196. applicationCommandListChanged();
  35197. else
  35198. setEnabled (true);
  35199. }
  35200. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35201. {
  35202. if (info.commandID == commandID
  35203. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35204. {
  35205. flashButtonState();
  35206. }
  35207. }
  35208. void Button::applicationCommandListChanged()
  35209. {
  35210. if (commandManagerToUse != 0)
  35211. {
  35212. ApplicationCommandInfo info (0);
  35213. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35214. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35215. if (target != 0)
  35216. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35217. }
  35218. }
  35219. void Button::addShortcut (const KeyPress& key)
  35220. {
  35221. if (key.isValid())
  35222. {
  35223. jassert (! isRegisteredForShortcut (key)); // already registered!
  35224. shortcuts.add (key);
  35225. parentHierarchyChanged();
  35226. }
  35227. }
  35228. void Button::clearShortcuts()
  35229. {
  35230. shortcuts.clear();
  35231. parentHierarchyChanged();
  35232. }
  35233. bool Button::isShortcutPressed() const
  35234. {
  35235. if (! isCurrentlyBlockedByAnotherModalComponent())
  35236. {
  35237. for (int i = shortcuts.size(); --i >= 0;)
  35238. if (shortcuts.getReference(i).isCurrentlyDown())
  35239. return true;
  35240. }
  35241. return false;
  35242. }
  35243. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35244. {
  35245. for (int i = shortcuts.size(); --i >= 0;)
  35246. if (key == shortcuts.getReference(i))
  35247. return true;
  35248. return false;
  35249. }
  35250. bool Button::keyStateChanged (const bool, Component*)
  35251. {
  35252. if (! isEnabled())
  35253. return false;
  35254. const bool wasDown = isKeyDown;
  35255. isKeyDown = isShortcutPressed();
  35256. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35257. getRepeatTimer().startTimer (autoRepeatDelay);
  35258. updateState (0);
  35259. if (isEnabled() && wasDown && ! isKeyDown)
  35260. {
  35261. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35262. // (return immediately - this button may now have been deleted)
  35263. return true;
  35264. }
  35265. return wasDown || isKeyDown;
  35266. }
  35267. bool Button::keyPressed (const KeyPress&, Component*)
  35268. {
  35269. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35270. return isShortcutPressed();
  35271. }
  35272. bool Button::keyPressed (const KeyPress& key)
  35273. {
  35274. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35275. {
  35276. triggerClick();
  35277. return true;
  35278. }
  35279. return false;
  35280. }
  35281. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35282. const int repeatMillisecs,
  35283. const int minimumDelayInMillisecs) throw()
  35284. {
  35285. autoRepeatDelay = initialDelayMillisecs;
  35286. autoRepeatSpeed = repeatMillisecs;
  35287. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35288. }
  35289. void Button::repeatTimerCallback()
  35290. {
  35291. if (needsRepainting)
  35292. {
  35293. getRepeatTimer().stopTimer();
  35294. updateState (0);
  35295. needsRepainting = false;
  35296. }
  35297. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35298. {
  35299. int repeatSpeed = autoRepeatSpeed;
  35300. if (autoRepeatMinimumDelay >= 0)
  35301. {
  35302. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35303. timeHeldDown *= timeHeldDown;
  35304. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35305. }
  35306. repeatSpeed = jmax (1, repeatSpeed);
  35307. getRepeatTimer().startTimer (repeatSpeed);
  35308. const uint32 now = Time::getApproximateMillisecondCounter();
  35309. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35310. lastTimeCallbackTime = now;
  35311. Component::SafePointer<Component> deletionWatcher (this);
  35312. for (int i = numTimesToCallback; --i >= 0;)
  35313. {
  35314. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35315. if (deletionWatcher == 0 || ! isDown())
  35316. return;
  35317. }
  35318. }
  35319. else if (! needsToRelease)
  35320. {
  35321. getRepeatTimer().stopTimer();
  35322. }
  35323. }
  35324. Button::RepeatTimer& Button::getRepeatTimer()
  35325. {
  35326. if (repeatTimer == 0)
  35327. repeatTimer = new RepeatTimer (*this);
  35328. return *repeatTimer;
  35329. }
  35330. END_JUCE_NAMESPACE
  35331. /*** End of inlined file: juce_Button.cpp ***/
  35332. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35333. BEGIN_JUCE_NAMESPACE
  35334. DrawableButton::DrawableButton (const String& name,
  35335. const DrawableButton::ButtonStyle buttonStyle)
  35336. : Button (name),
  35337. style (buttonStyle),
  35338. edgeIndent (3)
  35339. {
  35340. if (buttonStyle == ImageOnButtonBackground)
  35341. {
  35342. backgroundOff = Colour (0xffbbbbff);
  35343. backgroundOn = Colour (0xff3333ff);
  35344. }
  35345. else
  35346. {
  35347. backgroundOff = Colours::transparentBlack;
  35348. backgroundOn = Colour (0xaabbbbff);
  35349. }
  35350. }
  35351. DrawableButton::~DrawableButton()
  35352. {
  35353. deleteImages();
  35354. }
  35355. void DrawableButton::deleteImages()
  35356. {
  35357. }
  35358. void DrawableButton::setImages (const Drawable* normal,
  35359. const Drawable* over,
  35360. const Drawable* down,
  35361. const Drawable* disabled,
  35362. const Drawable* normalOn,
  35363. const Drawable* overOn,
  35364. const Drawable* downOn,
  35365. const Drawable* disabledOn)
  35366. {
  35367. deleteImages();
  35368. jassert (normal != 0); // you really need to give it at least a normal image..
  35369. if (normal != 0)
  35370. normalImage = normal->createCopy();
  35371. if (over != 0)
  35372. overImage = over->createCopy();
  35373. if (down != 0)
  35374. downImage = down->createCopy();
  35375. if (disabled != 0)
  35376. disabledImage = disabled->createCopy();
  35377. if (normalOn != 0)
  35378. normalImageOn = normalOn->createCopy();
  35379. if (overOn != 0)
  35380. overImageOn = overOn->createCopy();
  35381. if (downOn != 0)
  35382. downImageOn = downOn->createCopy();
  35383. if (disabledOn != 0)
  35384. disabledImageOn = disabledOn->createCopy();
  35385. repaint();
  35386. }
  35387. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35388. {
  35389. if (style != newStyle)
  35390. {
  35391. style = newStyle;
  35392. repaint();
  35393. }
  35394. }
  35395. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35396. const Colour& toggledOnColour)
  35397. {
  35398. if (backgroundOff != toggledOffColour
  35399. || backgroundOn != toggledOnColour)
  35400. {
  35401. backgroundOff = toggledOffColour;
  35402. backgroundOn = toggledOnColour;
  35403. repaint();
  35404. }
  35405. }
  35406. const Colour& DrawableButton::getBackgroundColour() const throw()
  35407. {
  35408. return getToggleState() ? backgroundOn
  35409. : backgroundOff;
  35410. }
  35411. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35412. {
  35413. edgeIndent = numPixelsIndent;
  35414. repaint();
  35415. }
  35416. void DrawableButton::paintButton (Graphics& g,
  35417. bool isMouseOverButton,
  35418. bool isButtonDown)
  35419. {
  35420. Rectangle<int> imageSpace;
  35421. if (style == ImageOnButtonBackground)
  35422. {
  35423. const int insetX = getWidth() / 4;
  35424. const int insetY = getHeight() / 4;
  35425. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35426. getLookAndFeel().drawButtonBackground (g, *this,
  35427. getBackgroundColour(),
  35428. isMouseOverButton,
  35429. isButtonDown);
  35430. }
  35431. else
  35432. {
  35433. g.fillAll (getBackgroundColour());
  35434. const int textH = (style == ImageAboveTextLabel)
  35435. ? jmin (16, proportionOfHeight (0.25f))
  35436. : 0;
  35437. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35438. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35439. imageSpace.setBounds (indentX, indentY,
  35440. getWidth() - indentX * 2,
  35441. getHeight() - indentY * 2 - textH);
  35442. if (textH > 0)
  35443. {
  35444. g.setFont ((float) textH);
  35445. g.setColour (findColour (DrawableButton::textColourId)
  35446. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35447. g.drawFittedText (getButtonText(),
  35448. 2, getHeight() - textH - 1,
  35449. getWidth() - 4, textH,
  35450. Justification::centred, 1);
  35451. }
  35452. }
  35453. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35454. g.setOpacity (1.0f);
  35455. const Drawable* imageToDraw = 0;
  35456. if (isEnabled())
  35457. {
  35458. imageToDraw = getCurrentImage();
  35459. }
  35460. else
  35461. {
  35462. imageToDraw = getToggleState() ? disabledImageOn
  35463. : disabledImage;
  35464. if (imageToDraw == 0)
  35465. {
  35466. g.setOpacity (0.4f);
  35467. imageToDraw = getNormalImage();
  35468. }
  35469. }
  35470. if (imageToDraw != 0)
  35471. {
  35472. if (style == ImageRaw)
  35473. imageToDraw->draw (g, 1.0f);
  35474. else
  35475. imageToDraw->drawWithin (g, imageSpace.toFloat(), RectanglePlacement::centred, 1.0f);
  35476. }
  35477. }
  35478. const Drawable* DrawableButton::getCurrentImage() const throw()
  35479. {
  35480. if (isDown())
  35481. return getDownImage();
  35482. if (isOver())
  35483. return getOverImage();
  35484. return getNormalImage();
  35485. }
  35486. const Drawable* DrawableButton::getNormalImage() const throw()
  35487. {
  35488. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35489. : normalImage;
  35490. }
  35491. const Drawable* DrawableButton::getOverImage() const throw()
  35492. {
  35493. const Drawable* d = normalImage;
  35494. if (getToggleState())
  35495. {
  35496. if (overImageOn != 0)
  35497. d = overImageOn;
  35498. else if (normalImageOn != 0)
  35499. d = normalImageOn;
  35500. else if (overImage != 0)
  35501. d = overImage;
  35502. }
  35503. else
  35504. {
  35505. if (overImage != 0)
  35506. d = overImage;
  35507. }
  35508. return d;
  35509. }
  35510. const Drawable* DrawableButton::getDownImage() const throw()
  35511. {
  35512. const Drawable* d = normalImage;
  35513. if (getToggleState())
  35514. {
  35515. if (downImageOn != 0)
  35516. d = downImageOn;
  35517. else if (overImageOn != 0)
  35518. d = overImageOn;
  35519. else if (normalImageOn != 0)
  35520. d = normalImageOn;
  35521. else if (downImage != 0)
  35522. d = downImage;
  35523. else
  35524. d = getOverImage();
  35525. }
  35526. else
  35527. {
  35528. if (downImage != 0)
  35529. d = downImage;
  35530. else
  35531. d = getOverImage();
  35532. }
  35533. return d;
  35534. }
  35535. END_JUCE_NAMESPACE
  35536. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35537. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35538. BEGIN_JUCE_NAMESPACE
  35539. HyperlinkButton::HyperlinkButton (const String& linkText,
  35540. const URL& linkURL)
  35541. : Button (linkText),
  35542. url (linkURL),
  35543. font (14.0f, Font::underlined),
  35544. resizeFont (true),
  35545. justification (Justification::centred)
  35546. {
  35547. setMouseCursor (MouseCursor::PointingHandCursor);
  35548. setTooltip (linkURL.toString (false));
  35549. }
  35550. HyperlinkButton::~HyperlinkButton()
  35551. {
  35552. }
  35553. void HyperlinkButton::setFont (const Font& newFont,
  35554. const bool resizeToMatchComponentHeight,
  35555. const Justification& justificationType)
  35556. {
  35557. font = newFont;
  35558. resizeFont = resizeToMatchComponentHeight;
  35559. justification = justificationType;
  35560. repaint();
  35561. }
  35562. void HyperlinkButton::setURL (const URL& newURL) throw()
  35563. {
  35564. url = newURL;
  35565. setTooltip (newURL.toString (false));
  35566. }
  35567. const Font HyperlinkButton::getFontToUse() const
  35568. {
  35569. Font f (font);
  35570. if (resizeFont)
  35571. f.setHeight (getHeight() * 0.7f);
  35572. return f;
  35573. }
  35574. void HyperlinkButton::changeWidthToFitText()
  35575. {
  35576. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35577. }
  35578. void HyperlinkButton::colourChanged()
  35579. {
  35580. repaint();
  35581. }
  35582. void HyperlinkButton::clicked()
  35583. {
  35584. if (url.isWellFormed())
  35585. url.launchInDefaultBrowser();
  35586. }
  35587. void HyperlinkButton::paintButton (Graphics& g,
  35588. bool isMouseOverButton,
  35589. bool isButtonDown)
  35590. {
  35591. const Colour textColour (findColour (textColourId));
  35592. if (isEnabled())
  35593. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35594. : textColour);
  35595. else
  35596. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35597. g.setFont (getFontToUse());
  35598. g.drawText (getButtonText(),
  35599. 2, 0, getWidth() - 2, getHeight(),
  35600. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35601. true);
  35602. }
  35603. END_JUCE_NAMESPACE
  35604. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35605. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35606. BEGIN_JUCE_NAMESPACE
  35607. ImageButton::ImageButton (const String& text_)
  35608. : Button (text_),
  35609. scaleImageToFit (true),
  35610. preserveProportions (true),
  35611. alphaThreshold (0),
  35612. imageX (0),
  35613. imageY (0),
  35614. imageW (0),
  35615. imageH (0),
  35616. normalImage (0),
  35617. overImage (0),
  35618. downImage (0)
  35619. {
  35620. }
  35621. ImageButton::~ImageButton()
  35622. {
  35623. }
  35624. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35625. const bool rescaleImagesWhenButtonSizeChanges,
  35626. const bool preserveImageProportions,
  35627. const Image& normalImage_,
  35628. const float imageOpacityWhenNormal,
  35629. const Colour& overlayColourWhenNormal,
  35630. const Image& overImage_,
  35631. const float imageOpacityWhenOver,
  35632. const Colour& overlayColourWhenOver,
  35633. const Image& downImage_,
  35634. const float imageOpacityWhenDown,
  35635. const Colour& overlayColourWhenDown,
  35636. const float hitTestAlphaThreshold)
  35637. {
  35638. normalImage = normalImage_;
  35639. overImage = overImage_;
  35640. downImage = downImage_;
  35641. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35642. {
  35643. imageW = normalImage.getWidth();
  35644. imageH = normalImage.getHeight();
  35645. setSize (imageW, imageH);
  35646. }
  35647. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35648. preserveProportions = preserveImageProportions;
  35649. normalOpacity = imageOpacityWhenNormal;
  35650. normalOverlay = overlayColourWhenNormal;
  35651. overOpacity = imageOpacityWhenOver;
  35652. overOverlay = overlayColourWhenOver;
  35653. downOpacity = imageOpacityWhenDown;
  35654. downOverlay = overlayColourWhenDown;
  35655. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35656. repaint();
  35657. }
  35658. const Image ImageButton::getCurrentImage() const
  35659. {
  35660. if (isDown() || getToggleState())
  35661. return getDownImage();
  35662. if (isOver())
  35663. return getOverImage();
  35664. return getNormalImage();
  35665. }
  35666. const Image ImageButton::getNormalImage() const
  35667. {
  35668. return normalImage;
  35669. }
  35670. const Image ImageButton::getOverImage() const
  35671. {
  35672. return overImage.isValid() ? overImage
  35673. : normalImage;
  35674. }
  35675. const Image ImageButton::getDownImage() const
  35676. {
  35677. return downImage.isValid() ? downImage
  35678. : getOverImage();
  35679. }
  35680. void ImageButton::paintButton (Graphics& g,
  35681. bool isMouseOverButton,
  35682. bool isButtonDown)
  35683. {
  35684. if (! isEnabled())
  35685. {
  35686. isMouseOverButton = false;
  35687. isButtonDown = false;
  35688. }
  35689. Image im (getCurrentImage());
  35690. if (im.isValid())
  35691. {
  35692. const int iw = im.getWidth();
  35693. const int ih = im.getHeight();
  35694. imageW = getWidth();
  35695. imageH = getHeight();
  35696. imageX = (imageW - iw) >> 1;
  35697. imageY = (imageH - ih) >> 1;
  35698. if (scaleImageToFit)
  35699. {
  35700. if (preserveProportions)
  35701. {
  35702. int newW, newH;
  35703. const float imRatio = ih / (float)iw;
  35704. const float destRatio = imageH / (float)imageW;
  35705. if (imRatio > destRatio)
  35706. {
  35707. newW = roundToInt (imageH / imRatio);
  35708. newH = imageH;
  35709. }
  35710. else
  35711. {
  35712. newW = imageW;
  35713. newH = roundToInt (imageW * imRatio);
  35714. }
  35715. imageX = (imageW - newW) / 2;
  35716. imageY = (imageH - newH) / 2;
  35717. imageW = newW;
  35718. imageH = newH;
  35719. }
  35720. else
  35721. {
  35722. imageX = 0;
  35723. imageY = 0;
  35724. }
  35725. }
  35726. if (! scaleImageToFit)
  35727. {
  35728. imageW = iw;
  35729. imageH = ih;
  35730. }
  35731. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35732. isButtonDown ? downOverlay
  35733. : (isMouseOverButton ? overOverlay
  35734. : normalOverlay),
  35735. isButtonDown ? downOpacity
  35736. : (isMouseOverButton ? overOpacity
  35737. : normalOpacity),
  35738. *this);
  35739. }
  35740. }
  35741. bool ImageButton::hitTest (int x, int y)
  35742. {
  35743. if (alphaThreshold == 0)
  35744. return true;
  35745. Image im (getCurrentImage());
  35746. return im.isNull() || (imageW > 0 && imageH > 0
  35747. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35748. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35749. }
  35750. END_JUCE_NAMESPACE
  35751. /*** End of inlined file: juce_ImageButton.cpp ***/
  35752. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35753. BEGIN_JUCE_NAMESPACE
  35754. ShapeButton::ShapeButton (const String& text_,
  35755. const Colour& normalColour_,
  35756. const Colour& overColour_,
  35757. const Colour& downColour_)
  35758. : Button (text_),
  35759. normalColour (normalColour_),
  35760. overColour (overColour_),
  35761. downColour (downColour_),
  35762. maintainShapeProportions (false),
  35763. outlineWidth (0.0f)
  35764. {
  35765. }
  35766. ShapeButton::~ShapeButton()
  35767. {
  35768. }
  35769. void ShapeButton::setColours (const Colour& newNormalColour,
  35770. const Colour& newOverColour,
  35771. const Colour& newDownColour)
  35772. {
  35773. normalColour = newNormalColour;
  35774. overColour = newOverColour;
  35775. downColour = newDownColour;
  35776. }
  35777. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35778. const float newOutlineWidth)
  35779. {
  35780. outlineColour = newOutlineColour;
  35781. outlineWidth = newOutlineWidth;
  35782. }
  35783. void ShapeButton::setShape (const Path& newShape,
  35784. const bool resizeNowToFitThisShape,
  35785. const bool maintainShapeProportions_,
  35786. const bool hasShadow)
  35787. {
  35788. shape = newShape;
  35789. maintainShapeProportions = maintainShapeProportions_;
  35790. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35791. setComponentEffect ((hasShadow) ? &shadow : 0);
  35792. if (resizeNowToFitThisShape)
  35793. {
  35794. Rectangle<float> bounds (shape.getBounds());
  35795. if (hasShadow)
  35796. bounds.expand (4.0f, 4.0f);
  35797. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35798. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35799. 1 + (int) (bounds.getHeight() + outlineWidth));
  35800. }
  35801. }
  35802. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35803. {
  35804. if (! isEnabled())
  35805. {
  35806. isMouseOverButton = false;
  35807. isButtonDown = false;
  35808. }
  35809. g.setColour ((isButtonDown) ? downColour
  35810. : (isMouseOverButton) ? overColour
  35811. : normalColour);
  35812. int w = getWidth();
  35813. int h = getHeight();
  35814. if (getComponentEffect() != 0)
  35815. {
  35816. w -= 4;
  35817. h -= 4;
  35818. }
  35819. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35820. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35821. w - offset - outlineWidth,
  35822. h - offset - outlineWidth,
  35823. maintainShapeProportions));
  35824. g.fillPath (shape, trans);
  35825. if (outlineWidth > 0.0f)
  35826. {
  35827. g.setColour (outlineColour);
  35828. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35829. }
  35830. }
  35831. END_JUCE_NAMESPACE
  35832. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35833. /*** Start of inlined file: juce_TextButton.cpp ***/
  35834. BEGIN_JUCE_NAMESPACE
  35835. TextButton::TextButton (const String& name,
  35836. const String& toolTip)
  35837. : Button (name)
  35838. {
  35839. setTooltip (toolTip);
  35840. }
  35841. TextButton::~TextButton()
  35842. {
  35843. }
  35844. void TextButton::paintButton (Graphics& g,
  35845. bool isMouseOverButton,
  35846. bool isButtonDown)
  35847. {
  35848. getLookAndFeel().drawButtonBackground (g, *this,
  35849. findColour (getToggleState() ? buttonOnColourId
  35850. : buttonColourId),
  35851. isMouseOverButton,
  35852. isButtonDown);
  35853. getLookAndFeel().drawButtonText (g, *this,
  35854. isMouseOverButton,
  35855. isButtonDown);
  35856. }
  35857. void TextButton::colourChanged()
  35858. {
  35859. repaint();
  35860. }
  35861. const Font TextButton::getFont()
  35862. {
  35863. return Font (jmin (15.0f, getHeight() * 0.6f));
  35864. }
  35865. void TextButton::changeWidthToFitText (const int newHeight)
  35866. {
  35867. if (newHeight >= 0)
  35868. setSize (jmax (1, getWidth()), newHeight);
  35869. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35870. getHeight());
  35871. }
  35872. END_JUCE_NAMESPACE
  35873. /*** End of inlined file: juce_TextButton.cpp ***/
  35874. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35875. BEGIN_JUCE_NAMESPACE
  35876. ToggleButton::ToggleButton (const String& buttonText)
  35877. : Button (buttonText)
  35878. {
  35879. setClickingTogglesState (true);
  35880. }
  35881. ToggleButton::~ToggleButton()
  35882. {
  35883. }
  35884. void ToggleButton::paintButton (Graphics& g,
  35885. bool isMouseOverButton,
  35886. bool isButtonDown)
  35887. {
  35888. getLookAndFeel().drawToggleButton (g, *this,
  35889. isMouseOverButton,
  35890. isButtonDown);
  35891. }
  35892. void ToggleButton::changeWidthToFitText()
  35893. {
  35894. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35895. }
  35896. void ToggleButton::colourChanged()
  35897. {
  35898. repaint();
  35899. }
  35900. END_JUCE_NAMESPACE
  35901. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35902. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35903. BEGIN_JUCE_NAMESPACE
  35904. ToolbarButton::ToolbarButton (const int itemId_,
  35905. const String& buttonText,
  35906. Drawable* const normalImage_,
  35907. Drawable* const toggledOnImage_)
  35908. : ToolbarItemComponent (itemId_, buttonText, true),
  35909. normalImage (normalImage_),
  35910. toggledOnImage (toggledOnImage_)
  35911. {
  35912. jassert (normalImage_ != 0);
  35913. }
  35914. ToolbarButton::~ToolbarButton()
  35915. {
  35916. }
  35917. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35918. bool /*isToolbarVertical*/,
  35919. int& preferredSize,
  35920. int& minSize, int& maxSize)
  35921. {
  35922. preferredSize = minSize = maxSize = toolbarDepth;
  35923. return true;
  35924. }
  35925. void ToolbarButton::paintButtonArea (Graphics& g,
  35926. int width, int height,
  35927. bool /*isMouseOver*/,
  35928. bool /*isMouseDown*/)
  35929. {
  35930. Drawable* d = normalImage;
  35931. if (getToggleState() && toggledOnImage != 0)
  35932. d = toggledOnImage;
  35933. const Rectangle<float> area (0.0f, 0.0f, (float) width, (float) height);
  35934. if (! isEnabled())
  35935. {
  35936. Image im (Image::ARGB, width, height, true);
  35937. {
  35938. Graphics g2 (im);
  35939. d->drawWithin (g2, area, RectanglePlacement::centred, 1.0f);
  35940. }
  35941. im.desaturate();
  35942. g.drawImageAt (im, 0, 0);
  35943. }
  35944. else
  35945. {
  35946. d->drawWithin (g, area, RectanglePlacement::centred, 1.0f);
  35947. }
  35948. }
  35949. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35950. {
  35951. }
  35952. END_JUCE_NAMESPACE
  35953. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35954. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35955. BEGIN_JUCE_NAMESPACE
  35956. class CodeDocumentLine
  35957. {
  35958. public:
  35959. CodeDocumentLine (const juce_wchar* const line_,
  35960. const int lineLength_,
  35961. const int numNewLineChars,
  35962. const int lineStartInFile_)
  35963. : line (line_, lineLength_),
  35964. lineStartInFile (lineStartInFile_),
  35965. lineLength (lineLength_),
  35966. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35967. {
  35968. }
  35969. ~CodeDocumentLine()
  35970. {
  35971. }
  35972. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35973. {
  35974. const juce_wchar* const t = text;
  35975. int pos = 0;
  35976. while (t [pos] != 0)
  35977. {
  35978. const int startOfLine = pos;
  35979. int numNewLineChars = 0;
  35980. while (t[pos] != 0)
  35981. {
  35982. if (t[pos] == '\r')
  35983. {
  35984. ++numNewLineChars;
  35985. ++pos;
  35986. if (t[pos] == '\n')
  35987. {
  35988. ++numNewLineChars;
  35989. ++pos;
  35990. }
  35991. break;
  35992. }
  35993. if (t[pos] == '\n')
  35994. {
  35995. ++numNewLineChars;
  35996. ++pos;
  35997. break;
  35998. }
  35999. ++pos;
  36000. }
  36001. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  36002. numNewLineChars, startOfLine));
  36003. }
  36004. jassert (pos == text.length());
  36005. }
  36006. bool endsWithLineBreak() const throw()
  36007. {
  36008. return lineLengthWithoutNewLines != lineLength;
  36009. }
  36010. void updateLength() throw()
  36011. {
  36012. lineLengthWithoutNewLines = lineLength = line.length();
  36013. while (lineLengthWithoutNewLines > 0
  36014. && (line [lineLengthWithoutNewLines - 1] == '\n'
  36015. || line [lineLengthWithoutNewLines - 1] == '\r'))
  36016. {
  36017. --lineLengthWithoutNewLines;
  36018. }
  36019. }
  36020. String line;
  36021. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36022. };
  36023. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36024. : document (document_),
  36025. currentLine (document_->lines[0]),
  36026. line (0),
  36027. position (0)
  36028. {
  36029. }
  36030. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36031. : document (other.document),
  36032. currentLine (other.currentLine),
  36033. line (other.line),
  36034. position (other.position)
  36035. {
  36036. }
  36037. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36038. {
  36039. document = other.document;
  36040. currentLine = other.currentLine;
  36041. line = other.line;
  36042. position = other.position;
  36043. return *this;
  36044. }
  36045. CodeDocument::Iterator::~Iterator() throw()
  36046. {
  36047. }
  36048. juce_wchar CodeDocument::Iterator::nextChar()
  36049. {
  36050. if (currentLine == 0)
  36051. return 0;
  36052. jassert (currentLine == document->lines.getUnchecked (line));
  36053. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36054. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36055. {
  36056. ++line;
  36057. currentLine = document->lines [line];
  36058. }
  36059. return result;
  36060. }
  36061. void CodeDocument::Iterator::skip()
  36062. {
  36063. if (currentLine != 0)
  36064. {
  36065. jassert (currentLine == document->lines.getUnchecked (line));
  36066. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36067. {
  36068. ++line;
  36069. currentLine = document->lines [line];
  36070. }
  36071. }
  36072. }
  36073. void CodeDocument::Iterator::skipToEndOfLine()
  36074. {
  36075. if (currentLine != 0)
  36076. {
  36077. jassert (currentLine == document->lines.getUnchecked (line));
  36078. ++line;
  36079. currentLine = document->lines [line];
  36080. if (currentLine != 0)
  36081. position = currentLine->lineStartInFile;
  36082. else
  36083. position = document->getNumCharacters();
  36084. }
  36085. }
  36086. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36087. {
  36088. if (currentLine == 0)
  36089. return 0;
  36090. jassert (currentLine == document->lines.getUnchecked (line));
  36091. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36092. }
  36093. void CodeDocument::Iterator::skipWhitespace()
  36094. {
  36095. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36096. skip();
  36097. }
  36098. bool CodeDocument::Iterator::isEOF() const throw()
  36099. {
  36100. return currentLine == 0;
  36101. }
  36102. CodeDocument::Position::Position() throw()
  36103. : owner (0), characterPos (0), line (0),
  36104. indexInLine (0), positionMaintained (false)
  36105. {
  36106. }
  36107. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36108. const int line_, const int indexInLine_) throw()
  36109. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36110. characterPos (0), line (line_),
  36111. indexInLine (indexInLine_), positionMaintained (false)
  36112. {
  36113. setLineAndIndex (line_, indexInLine_);
  36114. }
  36115. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36116. const int characterPos_) throw()
  36117. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36118. positionMaintained (false)
  36119. {
  36120. setPosition (characterPos_);
  36121. }
  36122. CodeDocument::Position::Position (const Position& other) throw()
  36123. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36124. indexInLine (other.indexInLine), positionMaintained (false)
  36125. {
  36126. jassert (*this == other);
  36127. }
  36128. CodeDocument::Position::~Position()
  36129. {
  36130. setPositionMaintained (false);
  36131. }
  36132. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36133. {
  36134. if (this != &other)
  36135. {
  36136. const bool wasPositionMaintained = positionMaintained;
  36137. if (owner != other.owner)
  36138. setPositionMaintained (false);
  36139. owner = other.owner;
  36140. line = other.line;
  36141. indexInLine = other.indexInLine;
  36142. characterPos = other.characterPos;
  36143. setPositionMaintained (wasPositionMaintained);
  36144. jassert (*this == other);
  36145. }
  36146. return *this;
  36147. }
  36148. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36149. {
  36150. jassert ((characterPos == other.characterPos)
  36151. == (line == other.line && indexInLine == other.indexInLine));
  36152. return characterPos == other.characterPos
  36153. && line == other.line
  36154. && indexInLine == other.indexInLine
  36155. && owner == other.owner;
  36156. }
  36157. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36158. {
  36159. return ! operator== (other);
  36160. }
  36161. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36162. {
  36163. jassert (owner != 0);
  36164. if (owner->lines.size() == 0)
  36165. {
  36166. line = 0;
  36167. indexInLine = 0;
  36168. characterPos = 0;
  36169. }
  36170. else
  36171. {
  36172. if (newLine >= owner->lines.size())
  36173. {
  36174. line = owner->lines.size() - 1;
  36175. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36176. jassert (l != 0);
  36177. indexInLine = l->lineLengthWithoutNewLines;
  36178. characterPos = l->lineStartInFile + indexInLine;
  36179. }
  36180. else
  36181. {
  36182. line = jmax (0, newLine);
  36183. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36184. jassert (l != 0);
  36185. if (l->lineLengthWithoutNewLines > 0)
  36186. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36187. else
  36188. indexInLine = 0;
  36189. characterPos = l->lineStartInFile + indexInLine;
  36190. }
  36191. }
  36192. }
  36193. void CodeDocument::Position::setPosition (const int newPosition)
  36194. {
  36195. jassert (owner != 0);
  36196. line = 0;
  36197. indexInLine = 0;
  36198. characterPos = 0;
  36199. if (newPosition > 0)
  36200. {
  36201. int lineStart = 0;
  36202. int lineEnd = owner->lines.size();
  36203. for (;;)
  36204. {
  36205. if (lineEnd - lineStart < 4)
  36206. {
  36207. for (int i = lineStart; i < lineEnd; ++i)
  36208. {
  36209. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36210. int index = newPosition - l->lineStartInFile;
  36211. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36212. {
  36213. line = i;
  36214. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36215. characterPos = l->lineStartInFile + indexInLine;
  36216. }
  36217. }
  36218. break;
  36219. }
  36220. else
  36221. {
  36222. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36223. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36224. if (newPosition >= mid->lineStartInFile)
  36225. lineStart = midIndex;
  36226. else
  36227. lineEnd = midIndex;
  36228. }
  36229. }
  36230. }
  36231. }
  36232. void CodeDocument::Position::moveBy (int characterDelta)
  36233. {
  36234. jassert (owner != 0);
  36235. if (characterDelta == 1)
  36236. {
  36237. setPosition (getPosition());
  36238. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36239. if (line < owner->lines.size())
  36240. {
  36241. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36242. if (indexInLine + characterDelta < l->lineLength
  36243. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36244. ++characterDelta;
  36245. }
  36246. }
  36247. setPosition (characterPos + characterDelta);
  36248. }
  36249. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36250. {
  36251. CodeDocument::Position p (*this);
  36252. p.moveBy (characterDelta);
  36253. return p;
  36254. }
  36255. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36256. {
  36257. CodeDocument::Position p (*this);
  36258. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36259. return p;
  36260. }
  36261. const juce_wchar CodeDocument::Position::getCharacter() const
  36262. {
  36263. const CodeDocumentLine* const l = owner->lines [line];
  36264. return l == 0 ? 0 : l->line [getIndexInLine()];
  36265. }
  36266. const String CodeDocument::Position::getLineText() const
  36267. {
  36268. const CodeDocumentLine* const l = owner->lines [line];
  36269. return l == 0 ? String::empty : l->line;
  36270. }
  36271. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36272. {
  36273. if (isMaintained != positionMaintained)
  36274. {
  36275. positionMaintained = isMaintained;
  36276. if (owner != 0)
  36277. {
  36278. if (isMaintained)
  36279. {
  36280. jassert (! owner->positionsToMaintain.contains (this));
  36281. owner->positionsToMaintain.add (this);
  36282. }
  36283. else
  36284. {
  36285. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36286. jassert (owner->positionsToMaintain.contains (this));
  36287. owner->positionsToMaintain.removeValue (this);
  36288. }
  36289. }
  36290. }
  36291. }
  36292. CodeDocument::CodeDocument()
  36293. : undoManager (std::numeric_limits<int>::max(), 10000),
  36294. currentActionIndex (0),
  36295. indexOfSavedState (-1),
  36296. maximumLineLength (-1),
  36297. newLineChars ("\r\n")
  36298. {
  36299. }
  36300. CodeDocument::~CodeDocument()
  36301. {
  36302. }
  36303. const String CodeDocument::getAllContent() const
  36304. {
  36305. return getTextBetween (Position (this, 0),
  36306. Position (this, lines.size(), 0));
  36307. }
  36308. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36309. {
  36310. if (end.getPosition() <= start.getPosition())
  36311. return String::empty;
  36312. const int startLine = start.getLineNumber();
  36313. const int endLine = end.getLineNumber();
  36314. if (startLine == endLine)
  36315. {
  36316. CodeDocumentLine* const line = lines [startLine];
  36317. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36318. }
  36319. String result;
  36320. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36321. String::Concatenator concatenator (result);
  36322. const int maxLine = jmin (lines.size() - 1, endLine);
  36323. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36324. {
  36325. const CodeDocumentLine* line = lines.getUnchecked(i);
  36326. int len = line->lineLength;
  36327. if (i == startLine)
  36328. {
  36329. const int index = start.getIndexInLine();
  36330. concatenator.append (line->line.substring (index, len));
  36331. }
  36332. else if (i == endLine)
  36333. {
  36334. len = end.getIndexInLine();
  36335. concatenator.append (line->line.substring (0, len));
  36336. }
  36337. else
  36338. {
  36339. concatenator.append (line->line);
  36340. }
  36341. }
  36342. return result;
  36343. }
  36344. int CodeDocument::getNumCharacters() const throw()
  36345. {
  36346. const CodeDocumentLine* const lastLine = lines.getLast();
  36347. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36348. }
  36349. const String CodeDocument::getLine (const int lineIndex) const throw()
  36350. {
  36351. const CodeDocumentLine* const line = lines [lineIndex];
  36352. return (line == 0) ? String::empty : line->line;
  36353. }
  36354. int CodeDocument::getMaximumLineLength() throw()
  36355. {
  36356. if (maximumLineLength < 0)
  36357. {
  36358. maximumLineLength = 0;
  36359. for (int i = lines.size(); --i >= 0;)
  36360. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36361. }
  36362. return maximumLineLength;
  36363. }
  36364. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36365. {
  36366. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36367. }
  36368. void CodeDocument::insertText (const Position& position, const String& text)
  36369. {
  36370. insert (text, position.getPosition(), true);
  36371. }
  36372. void CodeDocument::replaceAllContent (const String& newContent)
  36373. {
  36374. remove (0, getNumCharacters(), true);
  36375. insert (newContent, 0, true);
  36376. }
  36377. bool CodeDocument::loadFromStream (InputStream& stream)
  36378. {
  36379. replaceAllContent (stream.readEntireStreamAsString());
  36380. setSavePoint();
  36381. clearUndoHistory();
  36382. return true;
  36383. }
  36384. bool CodeDocument::writeToStream (OutputStream& stream)
  36385. {
  36386. for (int i = 0; i < lines.size(); ++i)
  36387. {
  36388. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36389. const char* utf8 = temp.toUTF8();
  36390. if (! stream.write (utf8, (int) strlen (utf8)))
  36391. return false;
  36392. }
  36393. return true;
  36394. }
  36395. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36396. {
  36397. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36398. newLineChars = newLine;
  36399. }
  36400. void CodeDocument::newTransaction()
  36401. {
  36402. undoManager.beginNewTransaction (String::empty);
  36403. }
  36404. void CodeDocument::undo()
  36405. {
  36406. newTransaction();
  36407. undoManager.undo();
  36408. }
  36409. void CodeDocument::redo()
  36410. {
  36411. undoManager.redo();
  36412. }
  36413. void CodeDocument::clearUndoHistory()
  36414. {
  36415. undoManager.clearUndoHistory();
  36416. }
  36417. void CodeDocument::setSavePoint() throw()
  36418. {
  36419. indexOfSavedState = currentActionIndex;
  36420. }
  36421. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36422. {
  36423. return currentActionIndex != indexOfSavedState;
  36424. }
  36425. namespace CodeDocumentHelpers
  36426. {
  36427. int getCharacterType (const juce_wchar character) throw()
  36428. {
  36429. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36430. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36431. }
  36432. }
  36433. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36434. {
  36435. Position p (position);
  36436. const int maxDistance = 256;
  36437. int i = 0;
  36438. while (i < maxDistance
  36439. && CharacterFunctions::isWhitespace (p.getCharacter())
  36440. && (i == 0 || (p.getCharacter() != '\n'
  36441. && p.getCharacter() != '\r')))
  36442. {
  36443. ++i;
  36444. p.moveBy (1);
  36445. }
  36446. if (i == 0)
  36447. {
  36448. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36449. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36450. {
  36451. ++i;
  36452. p.moveBy (1);
  36453. }
  36454. while (i < maxDistance
  36455. && CharacterFunctions::isWhitespace (p.getCharacter())
  36456. && (i == 0 || (p.getCharacter() != '\n'
  36457. && p.getCharacter() != '\r')))
  36458. {
  36459. ++i;
  36460. p.moveBy (1);
  36461. }
  36462. }
  36463. return p;
  36464. }
  36465. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36466. {
  36467. Position p (position);
  36468. const int maxDistance = 256;
  36469. int i = 0;
  36470. bool stoppedAtLineStart = false;
  36471. while (i < maxDistance)
  36472. {
  36473. const juce_wchar c = p.movedBy (-1).getCharacter();
  36474. if (c == '\r' || c == '\n')
  36475. {
  36476. stoppedAtLineStart = true;
  36477. if (i > 0)
  36478. break;
  36479. }
  36480. if (! CharacterFunctions::isWhitespace (c))
  36481. break;
  36482. p.moveBy (-1);
  36483. ++i;
  36484. }
  36485. if (i < maxDistance && ! stoppedAtLineStart)
  36486. {
  36487. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36488. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36489. {
  36490. p.moveBy (-1);
  36491. ++i;
  36492. }
  36493. }
  36494. return p;
  36495. }
  36496. void CodeDocument::checkLastLineStatus()
  36497. {
  36498. while (lines.size() > 0
  36499. && lines.getLast()->lineLength == 0
  36500. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36501. {
  36502. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36503. lines.removeLast();
  36504. }
  36505. const CodeDocumentLine* const lastLine = lines.getLast();
  36506. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36507. {
  36508. // check that there's an empty line at the end if the preceding one ends in a newline..
  36509. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36510. }
  36511. }
  36512. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36513. {
  36514. listeners.add (listener);
  36515. }
  36516. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36517. {
  36518. listeners.remove (listener);
  36519. }
  36520. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36521. {
  36522. Position startPos (this, startLine, 0);
  36523. Position endPos (this, endLine, 0);
  36524. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36525. }
  36526. class CodeDocumentInsertAction : public UndoableAction
  36527. {
  36528. CodeDocument& owner;
  36529. const String text;
  36530. int insertPos;
  36531. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36532. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36533. public:
  36534. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36535. : owner (owner_),
  36536. text (text_),
  36537. insertPos (insertPos_)
  36538. {
  36539. }
  36540. ~CodeDocumentInsertAction() {}
  36541. bool perform()
  36542. {
  36543. owner.currentActionIndex++;
  36544. owner.insert (text, insertPos, false);
  36545. return true;
  36546. }
  36547. bool undo()
  36548. {
  36549. owner.currentActionIndex--;
  36550. owner.remove (insertPos, insertPos + text.length(), false);
  36551. return true;
  36552. }
  36553. int getSizeInUnits() { return text.length() + 32; }
  36554. };
  36555. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36556. {
  36557. if (text.isEmpty())
  36558. return;
  36559. if (undoable)
  36560. {
  36561. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36562. }
  36563. else
  36564. {
  36565. Position pos (this, insertPos);
  36566. const int firstAffectedLine = pos.getLineNumber();
  36567. int lastAffectedLine = firstAffectedLine + 1;
  36568. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36569. String textInsideOriginalLine (text);
  36570. if (firstLine != 0)
  36571. {
  36572. const int index = pos.getIndexInLine();
  36573. textInsideOriginalLine = firstLine->line.substring (0, index)
  36574. + textInsideOriginalLine
  36575. + firstLine->line.substring (index);
  36576. }
  36577. maximumLineLength = -1;
  36578. Array <CodeDocumentLine*> newLines;
  36579. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36580. jassert (newLines.size() > 0);
  36581. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36582. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36583. lines.set (firstAffectedLine, newFirstLine);
  36584. if (newLines.size() > 1)
  36585. {
  36586. for (int i = 1; i < newLines.size(); ++i)
  36587. {
  36588. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36589. lines.insert (firstAffectedLine + i, l);
  36590. }
  36591. lastAffectedLine = lines.size();
  36592. }
  36593. int i, lineStart = newFirstLine->lineStartInFile;
  36594. for (i = firstAffectedLine; i < lines.size(); ++i)
  36595. {
  36596. CodeDocumentLine* const l = lines.getUnchecked (i);
  36597. l->lineStartInFile = lineStart;
  36598. lineStart += l->lineLength;
  36599. }
  36600. checkLastLineStatus();
  36601. const int newTextLength = text.length();
  36602. for (i = 0; i < positionsToMaintain.size(); ++i)
  36603. {
  36604. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36605. if (p->getPosition() >= insertPos)
  36606. p->setPosition (p->getPosition() + newTextLength);
  36607. }
  36608. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36609. }
  36610. }
  36611. class CodeDocumentDeleteAction : public UndoableAction
  36612. {
  36613. CodeDocument& owner;
  36614. int startPos, endPos;
  36615. String removedText;
  36616. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36617. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36618. public:
  36619. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36620. : owner (owner_),
  36621. startPos (startPos_),
  36622. endPos (endPos_)
  36623. {
  36624. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36625. CodeDocument::Position (&owner, endPos));
  36626. }
  36627. ~CodeDocumentDeleteAction() {}
  36628. bool perform()
  36629. {
  36630. owner.currentActionIndex++;
  36631. owner.remove (startPos, endPos, false);
  36632. return true;
  36633. }
  36634. bool undo()
  36635. {
  36636. owner.currentActionIndex--;
  36637. owner.insert (removedText, startPos, false);
  36638. return true;
  36639. }
  36640. int getSizeInUnits() { return removedText.length() + 32; }
  36641. };
  36642. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36643. {
  36644. if (endPos <= startPos)
  36645. return;
  36646. if (undoable)
  36647. {
  36648. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36649. }
  36650. else
  36651. {
  36652. Position startPosition (this, startPos);
  36653. Position endPosition (this, endPos);
  36654. maximumLineLength = -1;
  36655. const int firstAffectedLine = startPosition.getLineNumber();
  36656. const int endLine = endPosition.getLineNumber();
  36657. int lastAffectedLine = firstAffectedLine + 1;
  36658. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36659. if (firstAffectedLine == endLine)
  36660. {
  36661. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36662. + firstLine->line.substring (endPosition.getIndexInLine());
  36663. firstLine->updateLength();
  36664. }
  36665. else
  36666. {
  36667. lastAffectedLine = lines.size();
  36668. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36669. jassert (lastLine != 0);
  36670. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36671. + lastLine->line.substring (endPosition.getIndexInLine());
  36672. firstLine->updateLength();
  36673. int numLinesToRemove = endLine - firstAffectedLine;
  36674. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36675. }
  36676. int i;
  36677. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36678. {
  36679. CodeDocumentLine* const l = lines.getUnchecked (i);
  36680. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36681. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36682. }
  36683. checkLastLineStatus();
  36684. const int totalChars = getNumCharacters();
  36685. for (i = 0; i < positionsToMaintain.size(); ++i)
  36686. {
  36687. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36688. if (p->getPosition() > startPosition.getPosition())
  36689. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36690. if (p->getPosition() > totalChars)
  36691. p->setPosition (totalChars);
  36692. }
  36693. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36694. }
  36695. }
  36696. END_JUCE_NAMESPACE
  36697. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36698. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36699. BEGIN_JUCE_NAMESPACE
  36700. class CodeEditorComponent::CaretComponent : public Component,
  36701. public Timer
  36702. {
  36703. public:
  36704. CaretComponent (CodeEditorComponent& owner_)
  36705. : owner (owner_)
  36706. {
  36707. setAlwaysOnTop (true);
  36708. setInterceptsMouseClicks (false, false);
  36709. }
  36710. void paint (Graphics& g)
  36711. {
  36712. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36713. }
  36714. void timerCallback()
  36715. {
  36716. setVisible (shouldBeShown() && ! isVisible());
  36717. }
  36718. void updatePosition()
  36719. {
  36720. startTimer (400);
  36721. setVisible (shouldBeShown());
  36722. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36723. }
  36724. private:
  36725. CodeEditorComponent& owner;
  36726. CaretComponent (const CaretComponent&);
  36727. CaretComponent& operator= (const CaretComponent&);
  36728. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36729. };
  36730. class CodeEditorComponent::CodeEditorLine
  36731. {
  36732. public:
  36733. CodeEditorLine() throw()
  36734. : highlightColumnStart (0), highlightColumnEnd (0)
  36735. {
  36736. }
  36737. ~CodeEditorLine() throw()
  36738. {
  36739. }
  36740. bool update (CodeDocument& document, int lineNum,
  36741. CodeDocument::Iterator& source,
  36742. CodeTokeniser* analyser, const int spacesPerTab,
  36743. const CodeDocument::Position& selectionStart,
  36744. const CodeDocument::Position& selectionEnd)
  36745. {
  36746. Array <SyntaxToken> newTokens;
  36747. newTokens.ensureStorageAllocated (8);
  36748. if (analyser == 0)
  36749. {
  36750. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36751. }
  36752. else if (lineNum < document.getNumLines())
  36753. {
  36754. const CodeDocument::Position pos (&document, lineNum, 0);
  36755. createTokens (pos.getPosition(), pos.getLineText(),
  36756. source, analyser, newTokens);
  36757. }
  36758. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36759. int newHighlightStart = 0;
  36760. int newHighlightEnd = 0;
  36761. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36762. {
  36763. const String line (document.getLine (lineNum));
  36764. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36765. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36766. line, spacesPerTab);
  36767. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36768. line, spacesPerTab);
  36769. }
  36770. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36771. {
  36772. highlightColumnStart = newHighlightStart;
  36773. highlightColumnEnd = newHighlightEnd;
  36774. }
  36775. else
  36776. {
  36777. if (tokens.size() == newTokens.size())
  36778. {
  36779. bool allTheSame = true;
  36780. for (int i = newTokens.size(); --i >= 0;)
  36781. {
  36782. if (tokens.getReference(i) != newTokens.getReference(i))
  36783. {
  36784. allTheSame = false;
  36785. break;
  36786. }
  36787. }
  36788. if (allTheSame)
  36789. return false;
  36790. }
  36791. }
  36792. tokens.swapWithArray (newTokens);
  36793. return true;
  36794. }
  36795. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36796. float x, const int y, const int baselineOffset, const int lineHeight,
  36797. const Colour& highlightColour) const
  36798. {
  36799. if (highlightColumnStart < highlightColumnEnd)
  36800. {
  36801. g.setColour (highlightColour);
  36802. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36803. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36804. }
  36805. int lastType = std::numeric_limits<int>::min();
  36806. for (int i = 0; i < tokens.size(); ++i)
  36807. {
  36808. SyntaxToken& token = tokens.getReference(i);
  36809. if (lastType != token.tokenType)
  36810. {
  36811. lastType = token.tokenType;
  36812. g.setColour (owner.getColourForTokenType (lastType));
  36813. }
  36814. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36815. if (i < tokens.size() - 1)
  36816. {
  36817. if (token.width < 0)
  36818. token.width = font.getStringWidthFloat (token.text);
  36819. x += token.width;
  36820. }
  36821. }
  36822. }
  36823. private:
  36824. struct SyntaxToken
  36825. {
  36826. String text;
  36827. int tokenType;
  36828. float width;
  36829. SyntaxToken (const String& text_, const int type) throw()
  36830. : text (text_), tokenType (type), width (-1.0f)
  36831. {
  36832. }
  36833. bool operator!= (const SyntaxToken& other) const throw()
  36834. {
  36835. return text != other.text || tokenType != other.tokenType;
  36836. }
  36837. };
  36838. Array <SyntaxToken> tokens;
  36839. int highlightColumnStart, highlightColumnEnd;
  36840. static void createTokens (int startPosition, const String& lineText,
  36841. CodeDocument::Iterator& source,
  36842. CodeTokeniser* analyser,
  36843. Array <SyntaxToken>& newTokens)
  36844. {
  36845. CodeDocument::Iterator lastIterator (source);
  36846. const int lineLength = lineText.length();
  36847. for (;;)
  36848. {
  36849. int tokenType = analyser->readNextToken (source);
  36850. int tokenStart = lastIterator.getPosition();
  36851. int tokenEnd = source.getPosition();
  36852. if (tokenEnd <= tokenStart)
  36853. break;
  36854. tokenEnd -= startPosition;
  36855. if (tokenEnd > 0)
  36856. {
  36857. tokenStart -= startPosition;
  36858. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36859. tokenType));
  36860. if (tokenEnd >= lineLength)
  36861. break;
  36862. }
  36863. lastIterator = source;
  36864. }
  36865. source = lastIterator;
  36866. }
  36867. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36868. {
  36869. int x = 0;
  36870. for (int i = 0; i < tokens.size(); ++i)
  36871. {
  36872. SyntaxToken& t = tokens.getReference(i);
  36873. for (;;)
  36874. {
  36875. int tabPos = t.text.indexOfChar ('\t');
  36876. if (tabPos < 0)
  36877. break;
  36878. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36879. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36880. }
  36881. x += t.text.length();
  36882. }
  36883. }
  36884. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36885. {
  36886. jassert (index <= line.length());
  36887. int col = 0;
  36888. for (int i = 0; i < index; ++i)
  36889. {
  36890. if (line[i] != '\t')
  36891. ++col;
  36892. else
  36893. col += spacesPerTab - (col % spacesPerTab);
  36894. }
  36895. return col;
  36896. }
  36897. };
  36898. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36899. CodeTokeniser* const codeTokeniser_)
  36900. : document (document_),
  36901. firstLineOnScreen (0),
  36902. gutter (5),
  36903. spacesPerTab (4),
  36904. lineHeight (0),
  36905. linesOnScreen (0),
  36906. columnsOnScreen (0),
  36907. scrollbarThickness (16),
  36908. columnToTryToMaintain (-1),
  36909. useSpacesForTabs (false),
  36910. xOffset (0),
  36911. verticalScrollBar (true),
  36912. horizontalScrollBar (false),
  36913. codeTokeniser (codeTokeniser_)
  36914. {
  36915. caretPos = CodeDocument::Position (&document_, 0, 0);
  36916. caretPos.setPositionMaintained (true);
  36917. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36918. selectionStart.setPositionMaintained (true);
  36919. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36920. selectionEnd.setPositionMaintained (true);
  36921. setOpaque (true);
  36922. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36923. setWantsKeyboardFocus (true);
  36924. addAndMakeVisible (&verticalScrollBar);
  36925. verticalScrollBar.setSingleStepSize (1.0);
  36926. addAndMakeVisible (&horizontalScrollBar);
  36927. horizontalScrollBar.setSingleStepSize (1.0);
  36928. addAndMakeVisible (caret = new CaretComponent (*this));
  36929. Font f (12.0f);
  36930. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36931. setFont (f);
  36932. resetToDefaultColours();
  36933. verticalScrollBar.addListener (this);
  36934. horizontalScrollBar.addListener (this);
  36935. document.addListener (this);
  36936. }
  36937. CodeEditorComponent::~CodeEditorComponent()
  36938. {
  36939. document.removeListener (this);
  36940. }
  36941. void CodeEditorComponent::loadContent (const String& newContent)
  36942. {
  36943. clearCachedIterators (0);
  36944. document.replaceAllContent (newContent);
  36945. document.clearUndoHistory();
  36946. document.setSavePoint();
  36947. caretPos.setPosition (0);
  36948. selectionStart.setPosition (0);
  36949. selectionEnd.setPosition (0);
  36950. scrollToLine (0);
  36951. }
  36952. bool CodeEditorComponent::isTextInputActive() const
  36953. {
  36954. return true;
  36955. }
  36956. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36957. const CodeDocument::Position& affectedTextEnd)
  36958. {
  36959. clearCachedIterators (affectedTextStart.getLineNumber());
  36960. triggerAsyncUpdate();
  36961. caret->updatePosition();
  36962. columnToTryToMaintain = -1;
  36963. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36964. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36965. deselectAll();
  36966. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36967. || caretPos.getPosition() < affectedTextStart.getPosition())
  36968. moveCaretTo (affectedTextStart, false);
  36969. updateScrollBars();
  36970. }
  36971. void CodeEditorComponent::resized()
  36972. {
  36973. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36974. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36975. lines.clear();
  36976. rebuildLineTokens();
  36977. caret->updatePosition();
  36978. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36979. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36980. updateScrollBars();
  36981. }
  36982. void CodeEditorComponent::paint (Graphics& g)
  36983. {
  36984. handleUpdateNowIfNeeded();
  36985. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36986. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36987. g.setFont (font);
  36988. const int baselineOffset = (int) font.getAscent();
  36989. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36990. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36991. const Rectangle<int> clip (g.getClipBounds());
  36992. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36993. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36994. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36995. {
  36996. lines.getUnchecked(j)->draw (*this, g, font,
  36997. (float) (gutter - xOffset * charWidth),
  36998. lineHeight * j, baselineOffset, lineHeight,
  36999. highlightColour);
  37000. }
  37001. }
  37002. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  37003. {
  37004. if (scrollbarThickness != thickness)
  37005. {
  37006. scrollbarThickness = thickness;
  37007. resized();
  37008. }
  37009. }
  37010. void CodeEditorComponent::handleAsyncUpdate()
  37011. {
  37012. rebuildLineTokens();
  37013. }
  37014. void CodeEditorComponent::rebuildLineTokens()
  37015. {
  37016. cancelPendingUpdate();
  37017. const int numNeeded = linesOnScreen + 1;
  37018. int minLineToRepaint = numNeeded;
  37019. int maxLineToRepaint = 0;
  37020. if (numNeeded != lines.size())
  37021. {
  37022. lines.clear();
  37023. for (int i = numNeeded; --i >= 0;)
  37024. lines.add (new CodeEditorLine());
  37025. minLineToRepaint = 0;
  37026. maxLineToRepaint = numNeeded;
  37027. }
  37028. jassert (numNeeded == lines.size());
  37029. CodeDocument::Iterator source (&document);
  37030. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37031. for (int i = 0; i < numNeeded; ++i)
  37032. {
  37033. CodeEditorLine* const line = lines.getUnchecked(i);
  37034. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37035. selectionStart, selectionEnd))
  37036. {
  37037. minLineToRepaint = jmin (minLineToRepaint, i);
  37038. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37039. }
  37040. }
  37041. if (minLineToRepaint <= maxLineToRepaint)
  37042. {
  37043. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37044. verticalScrollBar.getX() - gutter,
  37045. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37046. }
  37047. }
  37048. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37049. {
  37050. caretPos = newPos;
  37051. columnToTryToMaintain = -1;
  37052. if (highlighting)
  37053. {
  37054. if (dragType == notDragging)
  37055. {
  37056. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37057. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37058. dragType = draggingSelectionStart;
  37059. else
  37060. dragType = draggingSelectionEnd;
  37061. }
  37062. if (dragType == draggingSelectionStart)
  37063. {
  37064. selectionStart = caretPos;
  37065. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37066. {
  37067. const CodeDocument::Position temp (selectionStart);
  37068. selectionStart = selectionEnd;
  37069. selectionEnd = temp;
  37070. dragType = draggingSelectionEnd;
  37071. }
  37072. }
  37073. else
  37074. {
  37075. selectionEnd = caretPos;
  37076. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37077. {
  37078. const CodeDocument::Position temp (selectionStart);
  37079. selectionStart = selectionEnd;
  37080. selectionEnd = temp;
  37081. dragType = draggingSelectionStart;
  37082. }
  37083. }
  37084. triggerAsyncUpdate();
  37085. }
  37086. else
  37087. {
  37088. deselectAll();
  37089. }
  37090. caret->updatePosition();
  37091. scrollToKeepCaretOnScreen();
  37092. updateScrollBars();
  37093. }
  37094. void CodeEditorComponent::deselectAll()
  37095. {
  37096. if (selectionStart != selectionEnd)
  37097. triggerAsyncUpdate();
  37098. selectionStart = caretPos;
  37099. selectionEnd = caretPos;
  37100. }
  37101. void CodeEditorComponent::updateScrollBars()
  37102. {
  37103. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37104. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  37105. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37106. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  37107. }
  37108. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37109. {
  37110. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37111. newFirstLineOnScreen);
  37112. if (newFirstLineOnScreen != firstLineOnScreen)
  37113. {
  37114. firstLineOnScreen = newFirstLineOnScreen;
  37115. caret->updatePosition();
  37116. updateCachedIterators (firstLineOnScreen);
  37117. triggerAsyncUpdate();
  37118. }
  37119. }
  37120. void CodeEditorComponent::scrollToColumnInternal (double column)
  37121. {
  37122. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37123. if (xOffset != newOffset)
  37124. {
  37125. xOffset = newOffset;
  37126. caret->updatePosition();
  37127. repaint();
  37128. }
  37129. }
  37130. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37131. {
  37132. scrollToLineInternal (newFirstLineOnScreen);
  37133. updateScrollBars();
  37134. }
  37135. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37136. {
  37137. scrollToColumnInternal (newFirstColumnOnScreen);
  37138. updateScrollBars();
  37139. }
  37140. void CodeEditorComponent::scrollBy (int deltaLines)
  37141. {
  37142. scrollToLine (firstLineOnScreen + deltaLines);
  37143. }
  37144. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37145. {
  37146. if (caretPos.getLineNumber() < firstLineOnScreen)
  37147. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37148. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37149. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37150. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37151. if (column >= xOffset + columnsOnScreen - 1)
  37152. scrollToColumn (column + 1 - columnsOnScreen);
  37153. else if (column < xOffset)
  37154. scrollToColumn (column);
  37155. }
  37156. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37157. {
  37158. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37159. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37160. roundToInt (charWidth),
  37161. lineHeight);
  37162. }
  37163. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37164. {
  37165. const int line = y / lineHeight + firstLineOnScreen;
  37166. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37167. const int index = columnToIndex (line, column);
  37168. return CodeDocument::Position (&document, line, index);
  37169. }
  37170. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37171. {
  37172. document.deleteSection (selectionStart, selectionEnd);
  37173. if (newText.isNotEmpty())
  37174. document.insertText (caretPos, newText);
  37175. scrollToKeepCaretOnScreen();
  37176. }
  37177. void CodeEditorComponent::insertTabAtCaret()
  37178. {
  37179. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37180. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37181. {
  37182. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37183. }
  37184. if (useSpacesForTabs)
  37185. {
  37186. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37187. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37188. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37189. }
  37190. else
  37191. {
  37192. insertTextAtCaret ("\t");
  37193. }
  37194. }
  37195. void CodeEditorComponent::cut()
  37196. {
  37197. insertTextAtCaret (String::empty);
  37198. }
  37199. void CodeEditorComponent::copy()
  37200. {
  37201. newTransaction();
  37202. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37203. if (selection.isNotEmpty())
  37204. SystemClipboard::copyTextToClipboard (selection);
  37205. }
  37206. void CodeEditorComponent::copyThenCut()
  37207. {
  37208. copy();
  37209. cut();
  37210. newTransaction();
  37211. }
  37212. void CodeEditorComponent::paste()
  37213. {
  37214. newTransaction();
  37215. const String clip (SystemClipboard::getTextFromClipboard());
  37216. if (clip.isNotEmpty())
  37217. insertTextAtCaret (clip);
  37218. newTransaction();
  37219. }
  37220. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37221. {
  37222. newTransaction();
  37223. if (moveInWholeWordSteps)
  37224. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37225. else
  37226. moveCaretTo (caretPos.movedBy (-1), selecting);
  37227. }
  37228. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37229. {
  37230. newTransaction();
  37231. if (moveInWholeWordSteps)
  37232. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37233. else
  37234. moveCaretTo (caretPos.movedBy (1), selecting);
  37235. }
  37236. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37237. {
  37238. CodeDocument::Position pos (caretPos);
  37239. const int newLineNum = pos.getLineNumber() + delta;
  37240. if (columnToTryToMaintain < 0)
  37241. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37242. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37243. const int colToMaintain = columnToTryToMaintain;
  37244. moveCaretTo (pos, selecting);
  37245. columnToTryToMaintain = colToMaintain;
  37246. }
  37247. void CodeEditorComponent::cursorDown (const bool selecting)
  37248. {
  37249. newTransaction();
  37250. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37251. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37252. else
  37253. moveLineDelta (1, selecting);
  37254. }
  37255. void CodeEditorComponent::cursorUp (const bool selecting)
  37256. {
  37257. newTransaction();
  37258. if (caretPos.getLineNumber() == 0)
  37259. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37260. else
  37261. moveLineDelta (-1, selecting);
  37262. }
  37263. void CodeEditorComponent::pageDown (const bool selecting)
  37264. {
  37265. newTransaction();
  37266. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37267. moveLineDelta (linesOnScreen, selecting);
  37268. }
  37269. void CodeEditorComponent::pageUp (const bool selecting)
  37270. {
  37271. newTransaction();
  37272. scrollBy (-linesOnScreen);
  37273. moveLineDelta (-linesOnScreen, selecting);
  37274. }
  37275. void CodeEditorComponent::scrollUp()
  37276. {
  37277. newTransaction();
  37278. scrollBy (1);
  37279. if (caretPos.getLineNumber() < firstLineOnScreen)
  37280. moveLineDelta (1, false);
  37281. }
  37282. void CodeEditorComponent::scrollDown()
  37283. {
  37284. newTransaction();
  37285. scrollBy (-1);
  37286. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37287. moveLineDelta (-1, false);
  37288. }
  37289. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37290. {
  37291. newTransaction();
  37292. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37293. }
  37294. namespace CodeEditorHelpers
  37295. {
  37296. int findFirstNonWhitespaceChar (const String& line) throw()
  37297. {
  37298. const int len = line.length();
  37299. for (int i = 0; i < len; ++i)
  37300. if (! CharacterFunctions::isWhitespace (line [i]))
  37301. return i;
  37302. return 0;
  37303. }
  37304. }
  37305. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37306. {
  37307. newTransaction();
  37308. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37309. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37310. index = 0;
  37311. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37312. }
  37313. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37314. {
  37315. newTransaction();
  37316. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37317. }
  37318. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37319. {
  37320. newTransaction();
  37321. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37322. }
  37323. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37324. {
  37325. if (moveInWholeWordSteps)
  37326. {
  37327. cut(); // in case something is already highlighted
  37328. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37329. }
  37330. else
  37331. {
  37332. if (selectionStart == selectionEnd)
  37333. selectionStart.moveBy (-1);
  37334. }
  37335. cut();
  37336. }
  37337. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37338. {
  37339. if (moveInWholeWordSteps)
  37340. {
  37341. cut(); // in case something is already highlighted
  37342. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37343. }
  37344. else
  37345. {
  37346. if (selectionStart == selectionEnd)
  37347. selectionEnd.moveBy (1);
  37348. else
  37349. newTransaction();
  37350. }
  37351. cut();
  37352. }
  37353. void CodeEditorComponent::selectAll()
  37354. {
  37355. newTransaction();
  37356. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37357. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37358. }
  37359. void CodeEditorComponent::undo()
  37360. {
  37361. document.undo();
  37362. scrollToKeepCaretOnScreen();
  37363. }
  37364. void CodeEditorComponent::redo()
  37365. {
  37366. document.redo();
  37367. scrollToKeepCaretOnScreen();
  37368. }
  37369. void CodeEditorComponent::newTransaction()
  37370. {
  37371. document.newTransaction();
  37372. startTimer (600);
  37373. }
  37374. void CodeEditorComponent::timerCallback()
  37375. {
  37376. newTransaction();
  37377. }
  37378. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37379. {
  37380. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37381. }
  37382. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37383. {
  37384. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37385. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37386. }
  37387. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37388. {
  37389. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37390. CodeDocument::Position (&document, range.getEnd()));
  37391. }
  37392. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37393. {
  37394. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37395. const bool shiftDown = key.getModifiers().isShiftDown();
  37396. if (key.isKeyCode (KeyPress::leftKey))
  37397. {
  37398. cursorLeft (moveInWholeWordSteps, shiftDown);
  37399. }
  37400. else if (key.isKeyCode (KeyPress::rightKey))
  37401. {
  37402. cursorRight (moveInWholeWordSteps, shiftDown);
  37403. }
  37404. else if (key.isKeyCode (KeyPress::upKey))
  37405. {
  37406. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37407. scrollDown();
  37408. #if JUCE_MAC
  37409. else if (key.getModifiers().isCommandDown())
  37410. goToStartOfDocument (shiftDown);
  37411. #endif
  37412. else
  37413. cursorUp (shiftDown);
  37414. }
  37415. else if (key.isKeyCode (KeyPress::downKey))
  37416. {
  37417. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37418. scrollUp();
  37419. #if JUCE_MAC
  37420. else if (key.getModifiers().isCommandDown())
  37421. goToEndOfDocument (shiftDown);
  37422. #endif
  37423. else
  37424. cursorDown (shiftDown);
  37425. }
  37426. else if (key.isKeyCode (KeyPress::pageDownKey))
  37427. {
  37428. pageDown (shiftDown);
  37429. }
  37430. else if (key.isKeyCode (KeyPress::pageUpKey))
  37431. {
  37432. pageUp (shiftDown);
  37433. }
  37434. else if (key.isKeyCode (KeyPress::homeKey))
  37435. {
  37436. if (moveInWholeWordSteps)
  37437. goToStartOfDocument (shiftDown);
  37438. else
  37439. goToStartOfLine (shiftDown);
  37440. }
  37441. else if (key.isKeyCode (KeyPress::endKey))
  37442. {
  37443. if (moveInWholeWordSteps)
  37444. goToEndOfDocument (shiftDown);
  37445. else
  37446. goToEndOfLine (shiftDown);
  37447. }
  37448. else if (key.isKeyCode (KeyPress::backspaceKey))
  37449. {
  37450. backspace (moveInWholeWordSteps);
  37451. }
  37452. else if (key.isKeyCode (KeyPress::deleteKey))
  37453. {
  37454. deleteForward (moveInWholeWordSteps);
  37455. }
  37456. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37457. {
  37458. copy();
  37459. }
  37460. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37461. {
  37462. copyThenCut();
  37463. }
  37464. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37465. {
  37466. paste();
  37467. }
  37468. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37469. {
  37470. undo();
  37471. }
  37472. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37473. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37474. {
  37475. redo();
  37476. }
  37477. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37478. {
  37479. selectAll();
  37480. }
  37481. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37482. {
  37483. insertTabAtCaret();
  37484. }
  37485. else if (key == KeyPress::returnKey)
  37486. {
  37487. newTransaction();
  37488. insertTextAtCaret (document.getNewLineCharacters());
  37489. }
  37490. else if (key.isKeyCode (KeyPress::escapeKey))
  37491. {
  37492. newTransaction();
  37493. }
  37494. else if (key.getTextCharacter() >= ' ')
  37495. {
  37496. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37497. }
  37498. else
  37499. {
  37500. return false;
  37501. }
  37502. return true;
  37503. }
  37504. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37505. {
  37506. newTransaction();
  37507. dragType = notDragging;
  37508. if (! e.mods.isPopupMenu())
  37509. {
  37510. beginDragAutoRepeat (100);
  37511. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37512. }
  37513. else
  37514. {
  37515. /*PopupMenu m;
  37516. addPopupMenuItems (m, &e);
  37517. const int result = m.show();
  37518. if (result != 0)
  37519. performPopupMenuAction (result);
  37520. */
  37521. }
  37522. }
  37523. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37524. {
  37525. if (! e.mods.isPopupMenu())
  37526. moveCaretTo (getPositionAt (e.x, e.y), true);
  37527. }
  37528. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37529. {
  37530. newTransaction();
  37531. beginDragAutoRepeat (0);
  37532. dragType = notDragging;
  37533. }
  37534. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37535. {
  37536. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37537. CodeDocument::Position tokenEnd (tokenStart);
  37538. if (e.getNumberOfClicks() > 2)
  37539. {
  37540. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37541. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37542. }
  37543. else
  37544. {
  37545. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37546. tokenEnd.moveBy (1);
  37547. tokenStart = tokenEnd;
  37548. while (tokenStart.getIndexInLine() > 0
  37549. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37550. tokenStart.moveBy (-1);
  37551. }
  37552. moveCaretTo (tokenEnd, false);
  37553. moveCaretTo (tokenStart, true);
  37554. }
  37555. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37556. {
  37557. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37558. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37559. {
  37560. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37561. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37562. }
  37563. else
  37564. {
  37565. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37566. }
  37567. }
  37568. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37569. {
  37570. if (scrollBarThatHasMoved == &verticalScrollBar)
  37571. scrollToLineInternal ((int) newRangeStart);
  37572. else
  37573. scrollToColumnInternal (newRangeStart);
  37574. }
  37575. void CodeEditorComponent::focusGained (FocusChangeType)
  37576. {
  37577. caret->updatePosition();
  37578. }
  37579. void CodeEditorComponent::focusLost (FocusChangeType)
  37580. {
  37581. caret->updatePosition();
  37582. }
  37583. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37584. {
  37585. useSpacesForTabs = insertSpaces;
  37586. if (spacesPerTab != numSpaces)
  37587. {
  37588. spacesPerTab = numSpaces;
  37589. triggerAsyncUpdate();
  37590. }
  37591. }
  37592. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37593. {
  37594. const String line (document.getLine (lineNum));
  37595. jassert (index <= line.length());
  37596. int col = 0;
  37597. for (int i = 0; i < index; ++i)
  37598. {
  37599. if (line[i] != '\t')
  37600. ++col;
  37601. else
  37602. col += getTabSize() - (col % getTabSize());
  37603. }
  37604. return col;
  37605. }
  37606. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37607. {
  37608. const String line (document.getLine (lineNum));
  37609. const int lineLength = line.length();
  37610. int i, col = 0;
  37611. for (i = 0; i < lineLength; ++i)
  37612. {
  37613. if (line[i] != '\t')
  37614. ++col;
  37615. else
  37616. col += getTabSize() - (col % getTabSize());
  37617. if (col > column)
  37618. break;
  37619. }
  37620. return i;
  37621. }
  37622. void CodeEditorComponent::setFont (const Font& newFont)
  37623. {
  37624. font = newFont;
  37625. charWidth = font.getStringWidthFloat ("0");
  37626. lineHeight = roundToInt (font.getHeight());
  37627. resized();
  37628. }
  37629. void CodeEditorComponent::resetToDefaultColours()
  37630. {
  37631. coloursForTokenCategories.clear();
  37632. if (codeTokeniser != 0)
  37633. {
  37634. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37635. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37636. }
  37637. }
  37638. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37639. {
  37640. jassert (tokenType < 256);
  37641. while (coloursForTokenCategories.size() < tokenType)
  37642. coloursForTokenCategories.add (Colours::black);
  37643. coloursForTokenCategories.set (tokenType, colour);
  37644. repaint();
  37645. }
  37646. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37647. {
  37648. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37649. return findColour (CodeEditorComponent::defaultTextColourId);
  37650. return coloursForTokenCategories.getReference (tokenType);
  37651. }
  37652. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37653. {
  37654. int i;
  37655. for (i = cachedIterators.size(); --i >= 0;)
  37656. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37657. break;
  37658. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37659. }
  37660. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37661. {
  37662. const int maxNumCachedPositions = 5000;
  37663. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37664. if (cachedIterators.size() == 0)
  37665. cachedIterators.add (new CodeDocument::Iterator (&document));
  37666. if (codeTokeniser == 0)
  37667. return;
  37668. for (;;)
  37669. {
  37670. CodeDocument::Iterator* last = cachedIterators.getLast();
  37671. if (last->getLine() >= maxLineNum)
  37672. break;
  37673. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37674. cachedIterators.add (t);
  37675. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37676. for (;;)
  37677. {
  37678. codeTokeniser->readNextToken (*t);
  37679. if (t->getLine() >= targetLine)
  37680. break;
  37681. if (t->isEOF())
  37682. return;
  37683. }
  37684. }
  37685. }
  37686. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37687. {
  37688. if (codeTokeniser == 0)
  37689. return;
  37690. for (int i = cachedIterators.size(); --i >= 0;)
  37691. {
  37692. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37693. if (t->getPosition() <= position)
  37694. {
  37695. source = *t;
  37696. break;
  37697. }
  37698. }
  37699. while (source.getPosition() < position)
  37700. {
  37701. const CodeDocument::Iterator original (source);
  37702. codeTokeniser->readNextToken (source);
  37703. if (source.getPosition() > position || source.isEOF())
  37704. {
  37705. source = original;
  37706. break;
  37707. }
  37708. }
  37709. }
  37710. END_JUCE_NAMESPACE
  37711. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37712. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37713. BEGIN_JUCE_NAMESPACE
  37714. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37715. {
  37716. }
  37717. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37718. {
  37719. }
  37720. namespace CppTokeniser
  37721. {
  37722. bool isIdentifierStart (const juce_wchar c) throw()
  37723. {
  37724. return CharacterFunctions::isLetter (c)
  37725. || c == '_' || c == '@';
  37726. }
  37727. bool isIdentifierBody (const juce_wchar c) throw()
  37728. {
  37729. return CharacterFunctions::isLetterOrDigit (c)
  37730. || c == '_' || c == '@';
  37731. }
  37732. bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37733. {
  37734. static const juce_wchar* const keywords2Char[] =
  37735. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37736. static const juce_wchar* const keywords3Char[] =
  37737. { 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 };
  37738. static const juce_wchar* const keywords4Char[] =
  37739. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37740. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37741. static const juce_wchar* const keywords5Char[] =
  37742. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37743. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37744. static const juce_wchar* const keywords6Char[] =
  37745. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37746. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37747. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37748. static const juce_wchar* const keywordsOther[] =
  37749. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37750. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37751. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37752. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37753. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37754. const juce_wchar* const* k;
  37755. switch (tokenLength)
  37756. {
  37757. case 2: k = keywords2Char; break;
  37758. case 3: k = keywords3Char; break;
  37759. case 4: k = keywords4Char; break;
  37760. case 5: k = keywords5Char; break;
  37761. case 6: k = keywords6Char; break;
  37762. default:
  37763. if (tokenLength < 2 || tokenLength > 16)
  37764. return false;
  37765. k = keywordsOther;
  37766. break;
  37767. }
  37768. int i = 0;
  37769. while (k[i] != 0)
  37770. {
  37771. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37772. return true;
  37773. ++i;
  37774. }
  37775. return false;
  37776. }
  37777. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37778. {
  37779. int tokenLength = 0;
  37780. juce_wchar possibleIdentifier [19];
  37781. while (isIdentifierBody (source.peekNextChar()))
  37782. {
  37783. const juce_wchar c = source.nextChar();
  37784. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37785. possibleIdentifier [tokenLength] = c;
  37786. ++tokenLength;
  37787. }
  37788. if (tokenLength > 1 && tokenLength <= 16)
  37789. {
  37790. possibleIdentifier [tokenLength] = 0;
  37791. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37792. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37793. }
  37794. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37795. }
  37796. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37797. {
  37798. const juce_wchar c = source.peekNextChar();
  37799. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37800. source.skip();
  37801. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37802. return false;
  37803. return true;
  37804. }
  37805. bool isHexDigit (const juce_wchar c) throw()
  37806. {
  37807. return (c >= '0' && c <= '9')
  37808. || (c >= 'a' && c <= 'f')
  37809. || (c >= 'A' && c <= 'F');
  37810. }
  37811. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37812. {
  37813. if (source.nextChar() != '0')
  37814. return false;
  37815. juce_wchar c = source.nextChar();
  37816. if (c != 'x' && c != 'X')
  37817. return false;
  37818. int numDigits = 0;
  37819. while (isHexDigit (source.peekNextChar()))
  37820. {
  37821. ++numDigits;
  37822. source.skip();
  37823. }
  37824. if (numDigits == 0)
  37825. return false;
  37826. return skipNumberSuffix (source);
  37827. }
  37828. bool isOctalDigit (const juce_wchar c) throw()
  37829. {
  37830. return c >= '0' && c <= '7';
  37831. }
  37832. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37833. {
  37834. if (source.nextChar() != '0')
  37835. return false;
  37836. if (! isOctalDigit (source.nextChar()))
  37837. return false;
  37838. while (isOctalDigit (source.peekNextChar()))
  37839. source.skip();
  37840. return skipNumberSuffix (source);
  37841. }
  37842. bool isDecimalDigit (const juce_wchar c) throw()
  37843. {
  37844. return c >= '0' && c <= '9';
  37845. }
  37846. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37847. {
  37848. int numChars = 0;
  37849. while (isDecimalDigit (source.peekNextChar()))
  37850. {
  37851. ++numChars;
  37852. source.skip();
  37853. }
  37854. if (numChars == 0)
  37855. return false;
  37856. return skipNumberSuffix (source);
  37857. }
  37858. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37859. {
  37860. int numDigits = 0;
  37861. while (isDecimalDigit (source.peekNextChar()))
  37862. {
  37863. source.skip();
  37864. ++numDigits;
  37865. }
  37866. const bool hasPoint = (source.peekNextChar() == '.');
  37867. if (hasPoint)
  37868. {
  37869. source.skip();
  37870. while (isDecimalDigit (source.peekNextChar()))
  37871. {
  37872. source.skip();
  37873. ++numDigits;
  37874. }
  37875. }
  37876. if (numDigits == 0)
  37877. return false;
  37878. juce_wchar c = source.peekNextChar();
  37879. const bool hasExponent = (c == 'e' || c == 'E');
  37880. if (hasExponent)
  37881. {
  37882. source.skip();
  37883. c = source.peekNextChar();
  37884. if (c == '+' || c == '-')
  37885. source.skip();
  37886. int numExpDigits = 0;
  37887. while (isDecimalDigit (source.peekNextChar()))
  37888. {
  37889. source.skip();
  37890. ++numExpDigits;
  37891. }
  37892. if (numExpDigits == 0)
  37893. return false;
  37894. }
  37895. c = source.peekNextChar();
  37896. if (c == 'f' || c == 'F')
  37897. source.skip();
  37898. else if (! (hasExponent || hasPoint))
  37899. return false;
  37900. return true;
  37901. }
  37902. int parseNumber (CodeDocument::Iterator& source)
  37903. {
  37904. const CodeDocument::Iterator original (source);
  37905. if (parseFloatLiteral (source))
  37906. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37907. source = original;
  37908. if (parseHexLiteral (source))
  37909. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37910. source = original;
  37911. if (parseOctalLiteral (source))
  37912. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37913. source = original;
  37914. if (parseDecimalLiteral (source))
  37915. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37916. source = original;
  37917. source.skip();
  37918. return CPlusPlusCodeTokeniser::tokenType_error;
  37919. }
  37920. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37921. {
  37922. const juce_wchar quote = source.nextChar();
  37923. for (;;)
  37924. {
  37925. const juce_wchar c = source.nextChar();
  37926. if (c == quote || c == 0)
  37927. break;
  37928. if (c == '\\')
  37929. source.skip();
  37930. }
  37931. }
  37932. void skipComment (CodeDocument::Iterator& source) throw()
  37933. {
  37934. bool lastWasStar = false;
  37935. for (;;)
  37936. {
  37937. const juce_wchar c = source.nextChar();
  37938. if (c == 0 || (c == '/' && lastWasStar))
  37939. break;
  37940. lastWasStar = (c == '*');
  37941. }
  37942. }
  37943. }
  37944. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37945. {
  37946. int result = tokenType_error;
  37947. source.skipWhitespace();
  37948. juce_wchar firstChar = source.peekNextChar();
  37949. switch (firstChar)
  37950. {
  37951. case 0:
  37952. source.skip();
  37953. break;
  37954. case '0':
  37955. case '1':
  37956. case '2':
  37957. case '3':
  37958. case '4':
  37959. case '5':
  37960. case '6':
  37961. case '7':
  37962. case '8':
  37963. case '9':
  37964. result = CppTokeniser::parseNumber (source);
  37965. break;
  37966. case '.':
  37967. result = CppTokeniser::parseNumber (source);
  37968. if (result == tokenType_error)
  37969. result = tokenType_punctuation;
  37970. break;
  37971. case ',':
  37972. case ';':
  37973. case ':':
  37974. source.skip();
  37975. result = tokenType_punctuation;
  37976. break;
  37977. case '(':
  37978. case ')':
  37979. case '{':
  37980. case '}':
  37981. case '[':
  37982. case ']':
  37983. source.skip();
  37984. result = tokenType_bracket;
  37985. break;
  37986. case '"':
  37987. case '\'':
  37988. CppTokeniser::skipQuotedString (source);
  37989. result = tokenType_stringLiteral;
  37990. break;
  37991. case '+':
  37992. result = tokenType_operator;
  37993. source.skip();
  37994. if (source.peekNextChar() == '+')
  37995. source.skip();
  37996. else if (source.peekNextChar() == '=')
  37997. source.skip();
  37998. break;
  37999. case '-':
  38000. source.skip();
  38001. result = CppTokeniser::parseNumber (source);
  38002. if (result == tokenType_error)
  38003. {
  38004. result = tokenType_operator;
  38005. if (source.peekNextChar() == '-')
  38006. source.skip();
  38007. else if (source.peekNextChar() == '=')
  38008. source.skip();
  38009. }
  38010. break;
  38011. case '*':
  38012. case '%':
  38013. case '=':
  38014. case '!':
  38015. result = tokenType_operator;
  38016. source.skip();
  38017. if (source.peekNextChar() == '=')
  38018. source.skip();
  38019. break;
  38020. case '/':
  38021. result = tokenType_operator;
  38022. source.skip();
  38023. if (source.peekNextChar() == '=')
  38024. {
  38025. source.skip();
  38026. }
  38027. else if (source.peekNextChar() == '/')
  38028. {
  38029. result = tokenType_comment;
  38030. source.skipToEndOfLine();
  38031. }
  38032. else if (source.peekNextChar() == '*')
  38033. {
  38034. source.skip();
  38035. result = tokenType_comment;
  38036. CppTokeniser::skipComment (source);
  38037. }
  38038. break;
  38039. case '?':
  38040. case '~':
  38041. source.skip();
  38042. result = tokenType_operator;
  38043. break;
  38044. case '<':
  38045. source.skip();
  38046. result = tokenType_operator;
  38047. if (source.peekNextChar() == '=')
  38048. {
  38049. source.skip();
  38050. }
  38051. else if (source.peekNextChar() == '<')
  38052. {
  38053. source.skip();
  38054. if (source.peekNextChar() == '=')
  38055. source.skip();
  38056. }
  38057. break;
  38058. case '>':
  38059. source.skip();
  38060. result = tokenType_operator;
  38061. if (source.peekNextChar() == '=')
  38062. {
  38063. source.skip();
  38064. }
  38065. else if (source.peekNextChar() == '<')
  38066. {
  38067. source.skip();
  38068. if (source.peekNextChar() == '=')
  38069. source.skip();
  38070. }
  38071. break;
  38072. case '|':
  38073. source.skip();
  38074. result = tokenType_operator;
  38075. if (source.peekNextChar() == '=')
  38076. {
  38077. source.skip();
  38078. }
  38079. else if (source.peekNextChar() == '|')
  38080. {
  38081. source.skip();
  38082. if (source.peekNextChar() == '=')
  38083. source.skip();
  38084. }
  38085. break;
  38086. case '&':
  38087. source.skip();
  38088. result = tokenType_operator;
  38089. if (source.peekNextChar() == '=')
  38090. {
  38091. source.skip();
  38092. }
  38093. else if (source.peekNextChar() == '&')
  38094. {
  38095. source.skip();
  38096. if (source.peekNextChar() == '=')
  38097. source.skip();
  38098. }
  38099. break;
  38100. case '^':
  38101. source.skip();
  38102. result = tokenType_operator;
  38103. if (source.peekNextChar() == '=')
  38104. {
  38105. source.skip();
  38106. }
  38107. else if (source.peekNextChar() == '^')
  38108. {
  38109. source.skip();
  38110. if (source.peekNextChar() == '=')
  38111. source.skip();
  38112. }
  38113. break;
  38114. case '#':
  38115. result = tokenType_preprocessor;
  38116. source.skipToEndOfLine();
  38117. break;
  38118. default:
  38119. if (CppTokeniser::isIdentifierStart (firstChar))
  38120. result = CppTokeniser::parseIdentifier (source);
  38121. else
  38122. source.skip();
  38123. break;
  38124. }
  38125. return result;
  38126. }
  38127. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38128. {
  38129. const char* const types[] =
  38130. {
  38131. "Error",
  38132. "Comment",
  38133. "C++ keyword",
  38134. "Identifier",
  38135. "Integer literal",
  38136. "Float literal",
  38137. "String literal",
  38138. "Operator",
  38139. "Bracket",
  38140. "Punctuation",
  38141. "Preprocessor line",
  38142. 0
  38143. };
  38144. return StringArray (types);
  38145. }
  38146. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38147. {
  38148. const uint32 colours[] =
  38149. {
  38150. 0xffcc0000, // error
  38151. 0xff00aa00, // comment
  38152. 0xff0000cc, // keyword
  38153. 0xff000000, // identifier
  38154. 0xff880000, // int literal
  38155. 0xff885500, // float literal
  38156. 0xff990099, // string literal
  38157. 0xff225500, // operator
  38158. 0xff000055, // bracket
  38159. 0xff004400, // punctuation
  38160. 0xff660000 // preprocessor
  38161. };
  38162. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38163. return Colour (colours [tokenType]);
  38164. return Colours::black;
  38165. }
  38166. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38167. {
  38168. return CppTokeniser::isReservedKeyword (token, token.length());
  38169. }
  38170. END_JUCE_NAMESPACE
  38171. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38172. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38173. BEGIN_JUCE_NAMESPACE
  38174. ComboBox::ComboBox (const String& name)
  38175. : Component (name),
  38176. lastCurrentId (0),
  38177. isButtonDown (false),
  38178. separatorPending (false),
  38179. menuActive (false),
  38180. noChoicesMessage (TRANS("(no choices)"))
  38181. {
  38182. setRepaintsOnMouseActivity (true);
  38183. lookAndFeelChanged();
  38184. currentId.addListener (this);
  38185. }
  38186. ComboBox::~ComboBox()
  38187. {
  38188. currentId.removeListener (this);
  38189. if (menuActive)
  38190. PopupMenu::dismissAllActiveMenus();
  38191. label = 0;
  38192. }
  38193. void ComboBox::setEditableText (const bool isEditable)
  38194. {
  38195. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38196. {
  38197. label->setEditable (isEditable, isEditable, false);
  38198. setWantsKeyboardFocus (! isEditable);
  38199. resized();
  38200. }
  38201. }
  38202. bool ComboBox::isTextEditable() const throw()
  38203. {
  38204. return label->isEditable();
  38205. }
  38206. void ComboBox::setJustificationType (const Justification& justification)
  38207. {
  38208. label->setJustificationType (justification);
  38209. }
  38210. const Justification ComboBox::getJustificationType() const throw()
  38211. {
  38212. return label->getJustificationType();
  38213. }
  38214. void ComboBox::setTooltip (const String& newTooltip)
  38215. {
  38216. SettableTooltipClient::setTooltip (newTooltip);
  38217. label->setTooltip (newTooltip);
  38218. }
  38219. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38220. {
  38221. // you can't add empty strings to the list..
  38222. jassert (newItemText.isNotEmpty());
  38223. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38224. jassert (newItemId != 0);
  38225. // you shouldn't use duplicate item IDs!
  38226. jassert (getItemForId (newItemId) == 0);
  38227. if (newItemText.isNotEmpty() && newItemId != 0)
  38228. {
  38229. if (separatorPending)
  38230. {
  38231. separatorPending = false;
  38232. ItemInfo* const item = new ItemInfo();
  38233. item->itemId = 0;
  38234. item->isEnabled = false;
  38235. item->isHeading = false;
  38236. items.add (item);
  38237. }
  38238. ItemInfo* const item = new ItemInfo();
  38239. item->name = newItemText;
  38240. item->itemId = newItemId;
  38241. item->isEnabled = true;
  38242. item->isHeading = false;
  38243. items.add (item);
  38244. }
  38245. }
  38246. void ComboBox::addSeparator()
  38247. {
  38248. separatorPending = (items.size() > 0);
  38249. }
  38250. void ComboBox::addSectionHeading (const String& headingName)
  38251. {
  38252. // you can't add empty strings to the list..
  38253. jassert (headingName.isNotEmpty());
  38254. if (headingName.isNotEmpty())
  38255. {
  38256. if (separatorPending)
  38257. {
  38258. separatorPending = false;
  38259. ItemInfo* const item = new ItemInfo();
  38260. item->itemId = 0;
  38261. item->isEnabled = false;
  38262. item->isHeading = false;
  38263. items.add (item);
  38264. }
  38265. ItemInfo* const item = new ItemInfo();
  38266. item->name = headingName;
  38267. item->itemId = 0;
  38268. item->isEnabled = true;
  38269. item->isHeading = true;
  38270. items.add (item);
  38271. }
  38272. }
  38273. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38274. {
  38275. ItemInfo* const item = getItemForId (itemId);
  38276. if (item != 0)
  38277. item->isEnabled = shouldBeEnabled;
  38278. }
  38279. void ComboBox::changeItemText (const int itemId, const String& newText)
  38280. {
  38281. ItemInfo* const item = getItemForId (itemId);
  38282. jassert (item != 0);
  38283. if (item != 0)
  38284. item->name = newText;
  38285. }
  38286. void ComboBox::clear (const bool dontSendChangeMessage)
  38287. {
  38288. items.clear();
  38289. separatorPending = false;
  38290. if (! label->isEditable())
  38291. setSelectedItemIndex (-1, dontSendChangeMessage);
  38292. }
  38293. bool ComboBox::ItemInfo::isSeparator() const throw()
  38294. {
  38295. return name.isEmpty();
  38296. }
  38297. bool ComboBox::ItemInfo::isRealItem() const throw()
  38298. {
  38299. return ! (isHeading || name.isEmpty());
  38300. }
  38301. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38302. {
  38303. if (itemId != 0)
  38304. {
  38305. for (int i = items.size(); --i >= 0;)
  38306. if (items.getUnchecked(i)->itemId == itemId)
  38307. return items.getUnchecked(i);
  38308. }
  38309. return 0;
  38310. }
  38311. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38312. {
  38313. int n = 0;
  38314. for (int i = 0; i < items.size(); ++i)
  38315. {
  38316. ItemInfo* const item = items.getUnchecked(i);
  38317. if (item->isRealItem())
  38318. if (n++ == index)
  38319. return item;
  38320. }
  38321. return 0;
  38322. }
  38323. int ComboBox::getNumItems() const throw()
  38324. {
  38325. int n = 0;
  38326. for (int i = items.size(); --i >= 0;)
  38327. if (items.getUnchecked(i)->isRealItem())
  38328. ++n;
  38329. return n;
  38330. }
  38331. const String ComboBox::getItemText (const int index) const
  38332. {
  38333. const ItemInfo* const item = getItemForIndex (index);
  38334. if (item != 0)
  38335. return item->name;
  38336. return String::empty;
  38337. }
  38338. int ComboBox::getItemId (const int index) const throw()
  38339. {
  38340. const ItemInfo* const item = getItemForIndex (index);
  38341. return (item != 0) ? item->itemId : 0;
  38342. }
  38343. int ComboBox::indexOfItemId (const int itemId) const throw()
  38344. {
  38345. int n = 0;
  38346. for (int i = 0; i < items.size(); ++i)
  38347. {
  38348. const ItemInfo* const item = items.getUnchecked(i);
  38349. if (item->isRealItem())
  38350. {
  38351. if (item->itemId == itemId)
  38352. return n;
  38353. ++n;
  38354. }
  38355. }
  38356. return -1;
  38357. }
  38358. int ComboBox::getSelectedItemIndex() const
  38359. {
  38360. int index = indexOfItemId (currentId.getValue());
  38361. if (getText() != getItemText (index))
  38362. index = -1;
  38363. return index;
  38364. }
  38365. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38366. {
  38367. setSelectedId (getItemId (index), dontSendChangeMessage);
  38368. }
  38369. int ComboBox::getSelectedId() const throw()
  38370. {
  38371. const ItemInfo* const item = getItemForId (currentId.getValue());
  38372. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38373. }
  38374. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38375. {
  38376. const ItemInfo* const item = getItemForId (newItemId);
  38377. const String newItemText (item != 0 ? item->name : String::empty);
  38378. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38379. {
  38380. if (! dontSendChangeMessage)
  38381. triggerAsyncUpdate();
  38382. label->setText (newItemText, false);
  38383. lastCurrentId = newItemId;
  38384. currentId = newItemId;
  38385. repaint(); // for the benefit of the 'none selected' text
  38386. }
  38387. }
  38388. void ComboBox::valueChanged (Value&)
  38389. {
  38390. if (lastCurrentId != (int) currentId.getValue())
  38391. setSelectedId (currentId.getValue(), false);
  38392. }
  38393. const String ComboBox::getText() const
  38394. {
  38395. return label->getText();
  38396. }
  38397. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38398. {
  38399. for (int i = items.size(); --i >= 0;)
  38400. {
  38401. const ItemInfo* const item = items.getUnchecked(i);
  38402. if (item->isRealItem()
  38403. && item->name == newText)
  38404. {
  38405. setSelectedId (item->itemId, dontSendChangeMessage);
  38406. return;
  38407. }
  38408. }
  38409. lastCurrentId = 0;
  38410. currentId = 0;
  38411. if (label->getText() != newText)
  38412. {
  38413. label->setText (newText, false);
  38414. if (! dontSendChangeMessage)
  38415. triggerAsyncUpdate();
  38416. }
  38417. repaint();
  38418. }
  38419. void ComboBox::showEditor()
  38420. {
  38421. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38422. label->showEditor();
  38423. }
  38424. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38425. {
  38426. if (textWhenNothingSelected != newMessage)
  38427. {
  38428. textWhenNothingSelected = newMessage;
  38429. repaint();
  38430. }
  38431. }
  38432. const String ComboBox::getTextWhenNothingSelected() const
  38433. {
  38434. return textWhenNothingSelected;
  38435. }
  38436. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38437. {
  38438. noChoicesMessage = newMessage;
  38439. }
  38440. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38441. {
  38442. return noChoicesMessage;
  38443. }
  38444. void ComboBox::paint (Graphics& g)
  38445. {
  38446. getLookAndFeel().drawComboBox (g,
  38447. getWidth(),
  38448. getHeight(),
  38449. isButtonDown,
  38450. label->getRight(),
  38451. 0,
  38452. getWidth() - label->getRight(),
  38453. getHeight(),
  38454. *this);
  38455. if (textWhenNothingSelected.isNotEmpty()
  38456. && label->getText().isEmpty()
  38457. && ! label->isBeingEdited())
  38458. {
  38459. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38460. g.setFont (label->getFont());
  38461. g.drawFittedText (textWhenNothingSelected,
  38462. label->getX() + 2, label->getY() + 1,
  38463. label->getWidth() - 4, label->getHeight() - 2,
  38464. label->getJustificationType(),
  38465. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38466. }
  38467. }
  38468. void ComboBox::resized()
  38469. {
  38470. if (getHeight() > 0 && getWidth() > 0)
  38471. getLookAndFeel().positionComboBoxText (*this, *label);
  38472. }
  38473. void ComboBox::enablementChanged()
  38474. {
  38475. repaint();
  38476. }
  38477. void ComboBox::lookAndFeelChanged()
  38478. {
  38479. repaint();
  38480. {
  38481. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38482. jassert (newLabel != 0);
  38483. if (label != 0)
  38484. {
  38485. newLabel->setEditable (label->isEditable());
  38486. newLabel->setJustificationType (label->getJustificationType());
  38487. newLabel->setTooltip (label->getTooltip());
  38488. newLabel->setText (label->getText(), false);
  38489. }
  38490. label = newLabel;
  38491. }
  38492. addAndMakeVisible (label);
  38493. label->addListener (this);
  38494. label->addMouseListener (this, false);
  38495. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38496. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38497. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38498. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38499. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38500. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38501. resized();
  38502. }
  38503. void ComboBox::colourChanged()
  38504. {
  38505. lookAndFeelChanged();
  38506. }
  38507. bool ComboBox::keyPressed (const KeyPress& key)
  38508. {
  38509. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38510. {
  38511. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38512. return true;
  38513. }
  38514. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38515. {
  38516. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38517. return true;
  38518. }
  38519. else if (key.isKeyCode (KeyPress::returnKey))
  38520. {
  38521. showPopup();
  38522. return true;
  38523. }
  38524. return false;
  38525. }
  38526. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38527. {
  38528. // only forward key events that aren't used by this component
  38529. return isKeyDown
  38530. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38531. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38532. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38533. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38534. }
  38535. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38536. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38537. void ComboBox::labelTextChanged (Label*)
  38538. {
  38539. triggerAsyncUpdate();
  38540. }
  38541. class ComboBox::Callback : public ModalComponentManager::Callback
  38542. {
  38543. public:
  38544. Callback (ComboBox* const box_)
  38545. : box (box_)
  38546. {
  38547. }
  38548. void modalStateFinished (int returnValue)
  38549. {
  38550. if (box != 0)
  38551. {
  38552. box->menuActive = false;
  38553. if (returnValue != 0)
  38554. box->setSelectedId (returnValue);
  38555. }
  38556. }
  38557. private:
  38558. Component::SafePointer<ComboBox> box;
  38559. Callback (const Callback&);
  38560. Callback& operator= (const Callback&);
  38561. };
  38562. void ComboBox::showPopup()
  38563. {
  38564. if (! menuActive)
  38565. {
  38566. const int selectedId = getSelectedId();
  38567. PopupMenu menu;
  38568. menu.setLookAndFeel (&getLookAndFeel());
  38569. for (int i = 0; i < items.size(); ++i)
  38570. {
  38571. const ItemInfo* const item = items.getUnchecked(i);
  38572. if (item->isSeparator())
  38573. menu.addSeparator();
  38574. else if (item->isHeading)
  38575. menu.addSectionHeader (item->name);
  38576. else
  38577. menu.addItem (item->itemId, item->name,
  38578. item->isEnabled, item->itemId == selectedId);
  38579. }
  38580. if (items.size() == 0)
  38581. menu.addItem (1, noChoicesMessage, false);
  38582. menuActive = true;
  38583. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38584. new Callback (this));
  38585. }
  38586. }
  38587. void ComboBox::mouseDown (const MouseEvent& e)
  38588. {
  38589. beginDragAutoRepeat (300);
  38590. isButtonDown = isEnabled();
  38591. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38592. showPopup();
  38593. }
  38594. void ComboBox::mouseDrag (const MouseEvent& e)
  38595. {
  38596. beginDragAutoRepeat (50);
  38597. if (isButtonDown && ! e.mouseWasClicked())
  38598. showPopup();
  38599. }
  38600. void ComboBox::mouseUp (const MouseEvent& e2)
  38601. {
  38602. if (isButtonDown)
  38603. {
  38604. isButtonDown = false;
  38605. repaint();
  38606. const MouseEvent e (e2.getEventRelativeTo (this));
  38607. if (reallyContains (e.x, e.y, true)
  38608. && (e2.eventComponent == this || ! label->isEditable()))
  38609. {
  38610. showPopup();
  38611. }
  38612. }
  38613. }
  38614. void ComboBox::addListener (ComboBoxListener* const listener)
  38615. {
  38616. listeners.add (listener);
  38617. }
  38618. void ComboBox::removeListener (ComboBoxListener* const listener)
  38619. {
  38620. listeners.remove (listener);
  38621. }
  38622. void ComboBox::handleAsyncUpdate()
  38623. {
  38624. Component::BailOutChecker checker (this);
  38625. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38626. }
  38627. END_JUCE_NAMESPACE
  38628. /*** End of inlined file: juce_ComboBox.cpp ***/
  38629. /*** Start of inlined file: juce_Label.cpp ***/
  38630. BEGIN_JUCE_NAMESPACE
  38631. Label::Label (const String& componentName,
  38632. const String& labelText)
  38633. : Component (componentName),
  38634. textValue (labelText),
  38635. lastTextValue (labelText),
  38636. font (15.0f),
  38637. justification (Justification::centredLeft),
  38638. ownerComponent (0),
  38639. horizontalBorderSize (5),
  38640. verticalBorderSize (1),
  38641. minimumHorizontalScale (0.7f),
  38642. editSingleClick (false),
  38643. editDoubleClick (false),
  38644. lossOfFocusDiscardsChanges (false)
  38645. {
  38646. setColour (TextEditor::textColourId, Colours::black);
  38647. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38648. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38649. textValue.addListener (this);
  38650. }
  38651. Label::~Label()
  38652. {
  38653. textValue.removeListener (this);
  38654. if (ownerComponent != 0)
  38655. ownerComponent->removeComponentListener (this);
  38656. editor = 0;
  38657. }
  38658. void Label::setText (const String& newText,
  38659. const bool broadcastChangeMessage)
  38660. {
  38661. hideEditor (true);
  38662. if (lastTextValue != newText)
  38663. {
  38664. lastTextValue = newText;
  38665. textValue = newText;
  38666. repaint();
  38667. textWasChanged();
  38668. if (ownerComponent != 0)
  38669. componentMovedOrResized (*ownerComponent, true, true);
  38670. if (broadcastChangeMessage)
  38671. callChangeListeners();
  38672. }
  38673. }
  38674. const String Label::getText (const bool returnActiveEditorContents) const
  38675. {
  38676. return (returnActiveEditorContents && isBeingEdited())
  38677. ? editor->getText()
  38678. : textValue.toString();
  38679. }
  38680. void Label::valueChanged (Value&)
  38681. {
  38682. if (lastTextValue != textValue.toString())
  38683. setText (textValue.toString(), true);
  38684. }
  38685. void Label::setFont (const Font& newFont)
  38686. {
  38687. if (font != newFont)
  38688. {
  38689. font = newFont;
  38690. repaint();
  38691. }
  38692. }
  38693. const Font& Label::getFont() const throw()
  38694. {
  38695. return font;
  38696. }
  38697. void Label::setEditable (const bool editOnSingleClick,
  38698. const bool editOnDoubleClick,
  38699. const bool lossOfFocusDiscardsChanges_)
  38700. {
  38701. editSingleClick = editOnSingleClick;
  38702. editDoubleClick = editOnDoubleClick;
  38703. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38704. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38705. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38706. }
  38707. void Label::setJustificationType (const Justification& newJustification)
  38708. {
  38709. if (justification != newJustification)
  38710. {
  38711. justification = newJustification;
  38712. repaint();
  38713. }
  38714. }
  38715. void Label::setBorderSize (int h, int v)
  38716. {
  38717. if (horizontalBorderSize != h || verticalBorderSize != v)
  38718. {
  38719. horizontalBorderSize = h;
  38720. verticalBorderSize = v;
  38721. repaint();
  38722. }
  38723. }
  38724. Component* Label::getAttachedComponent() const
  38725. {
  38726. return static_cast<Component*> (ownerComponent);
  38727. }
  38728. void Label::attachToComponent (Component* owner,
  38729. const bool onLeft)
  38730. {
  38731. if (ownerComponent != 0)
  38732. ownerComponent->removeComponentListener (this);
  38733. ownerComponent = owner;
  38734. leftOfOwnerComp = onLeft;
  38735. if (ownerComponent != 0)
  38736. {
  38737. setVisible (owner->isVisible());
  38738. ownerComponent->addComponentListener (this);
  38739. componentParentHierarchyChanged (*ownerComponent);
  38740. componentMovedOrResized (*ownerComponent, true, true);
  38741. }
  38742. }
  38743. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38744. {
  38745. if (leftOfOwnerComp)
  38746. {
  38747. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38748. component.getHeight());
  38749. setTopRightPosition (component.getX(), component.getY());
  38750. }
  38751. else
  38752. {
  38753. setSize (component.getWidth(),
  38754. 8 + roundToInt (getFont().getHeight()));
  38755. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38756. }
  38757. }
  38758. void Label::componentParentHierarchyChanged (Component& component)
  38759. {
  38760. if (component.getParentComponent() != 0)
  38761. component.getParentComponent()->addChildComponent (this);
  38762. }
  38763. void Label::componentVisibilityChanged (Component& component)
  38764. {
  38765. setVisible (component.isVisible());
  38766. }
  38767. void Label::textWasEdited()
  38768. {
  38769. }
  38770. void Label::textWasChanged()
  38771. {
  38772. }
  38773. void Label::showEditor()
  38774. {
  38775. if (editor == 0)
  38776. {
  38777. addAndMakeVisible (editor = createEditorComponent());
  38778. editor->setText (getText(), false);
  38779. editor->addListener (this);
  38780. editor->grabKeyboardFocus();
  38781. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38782. editor->addListener (this);
  38783. resized();
  38784. repaint();
  38785. editorShown (editor);
  38786. enterModalState (false);
  38787. editor->grabKeyboardFocus();
  38788. }
  38789. }
  38790. void Label::editorShown (TextEditor* /*editorComponent*/)
  38791. {
  38792. }
  38793. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38794. {
  38795. }
  38796. bool Label::updateFromTextEditorContents()
  38797. {
  38798. jassert (editor != 0);
  38799. const String newText (editor->getText());
  38800. if (textValue.toString() != newText)
  38801. {
  38802. lastTextValue = newText;
  38803. textValue = newText;
  38804. repaint();
  38805. textWasChanged();
  38806. if (ownerComponent != 0)
  38807. componentMovedOrResized (*ownerComponent, true, true);
  38808. return true;
  38809. }
  38810. return false;
  38811. }
  38812. void Label::hideEditor (const bool discardCurrentEditorContents)
  38813. {
  38814. if (editor != 0)
  38815. {
  38816. Component::SafePointer<Component> deletionChecker (this);
  38817. editorAboutToBeHidden (editor);
  38818. const bool changed = (! discardCurrentEditorContents)
  38819. && updateFromTextEditorContents();
  38820. editor = 0;
  38821. repaint();
  38822. if (changed)
  38823. textWasEdited();
  38824. if (deletionChecker != 0)
  38825. exitModalState (0);
  38826. if (changed && deletionChecker != 0)
  38827. callChangeListeners();
  38828. }
  38829. }
  38830. void Label::inputAttemptWhenModal()
  38831. {
  38832. if (editor != 0)
  38833. {
  38834. if (lossOfFocusDiscardsChanges)
  38835. textEditorEscapeKeyPressed (*editor);
  38836. else
  38837. textEditorReturnKeyPressed (*editor);
  38838. }
  38839. }
  38840. bool Label::isBeingEdited() const throw()
  38841. {
  38842. return editor != 0;
  38843. }
  38844. TextEditor* Label::createEditorComponent()
  38845. {
  38846. TextEditor* const ed = new TextEditor (getName());
  38847. ed->setFont (font);
  38848. // copy these colours from our own settings..
  38849. const int cols[] = { TextEditor::backgroundColourId,
  38850. TextEditor::textColourId,
  38851. TextEditor::highlightColourId,
  38852. TextEditor::highlightedTextColourId,
  38853. TextEditor::caretColourId,
  38854. TextEditor::outlineColourId,
  38855. TextEditor::focusedOutlineColourId,
  38856. TextEditor::shadowColourId };
  38857. for (int i = 0; i < numElementsInArray (cols); ++i)
  38858. ed->setColour (cols[i], findColour (cols[i]));
  38859. return ed;
  38860. }
  38861. void Label::paint (Graphics& g)
  38862. {
  38863. getLookAndFeel().drawLabel (g, *this);
  38864. }
  38865. void Label::mouseUp (const MouseEvent& e)
  38866. {
  38867. if (editSingleClick
  38868. && e.mouseWasClicked()
  38869. && contains (e.getPosition())
  38870. && ! e.mods.isPopupMenu())
  38871. {
  38872. showEditor();
  38873. }
  38874. }
  38875. void Label::mouseDoubleClick (const MouseEvent& e)
  38876. {
  38877. if (editDoubleClick && ! e.mods.isPopupMenu())
  38878. showEditor();
  38879. }
  38880. void Label::resized()
  38881. {
  38882. if (editor != 0)
  38883. editor->setBoundsInset (BorderSize (0));
  38884. }
  38885. void Label::focusGained (FocusChangeType cause)
  38886. {
  38887. if (editSingleClick && cause == focusChangedByTabKey)
  38888. showEditor();
  38889. }
  38890. void Label::enablementChanged()
  38891. {
  38892. repaint();
  38893. }
  38894. void Label::colourChanged()
  38895. {
  38896. repaint();
  38897. }
  38898. void Label::setMinimumHorizontalScale (const float newScale)
  38899. {
  38900. if (minimumHorizontalScale != newScale)
  38901. {
  38902. minimumHorizontalScale = newScale;
  38903. repaint();
  38904. }
  38905. }
  38906. // We'll use a custom focus traverser here to make sure focus goes from the
  38907. // text editor to another component rather than back to the label itself.
  38908. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38909. {
  38910. public:
  38911. LabelKeyboardFocusTraverser() {}
  38912. Component* getNextComponent (Component* current)
  38913. {
  38914. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38915. ? current->getParentComponent() : current);
  38916. }
  38917. Component* getPreviousComponent (Component* current)
  38918. {
  38919. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38920. ? current->getParentComponent() : current);
  38921. }
  38922. };
  38923. KeyboardFocusTraverser* Label::createFocusTraverser()
  38924. {
  38925. return new LabelKeyboardFocusTraverser();
  38926. }
  38927. void Label::addListener (LabelListener* const listener)
  38928. {
  38929. listeners.add (listener);
  38930. }
  38931. void Label::removeListener (LabelListener* const listener)
  38932. {
  38933. listeners.remove (listener);
  38934. }
  38935. void Label::callChangeListeners()
  38936. {
  38937. Component::BailOutChecker checker (this);
  38938. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38939. }
  38940. void Label::textEditorTextChanged (TextEditor& ed)
  38941. {
  38942. if (editor != 0)
  38943. {
  38944. jassert (&ed == editor);
  38945. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38946. {
  38947. if (lossOfFocusDiscardsChanges)
  38948. textEditorEscapeKeyPressed (ed);
  38949. else
  38950. textEditorReturnKeyPressed (ed);
  38951. }
  38952. }
  38953. }
  38954. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38955. {
  38956. if (editor != 0)
  38957. {
  38958. jassert (&ed == editor);
  38959. (void) ed;
  38960. const bool changed = updateFromTextEditorContents();
  38961. hideEditor (true);
  38962. if (changed)
  38963. {
  38964. Component::SafePointer<Component> deletionChecker (this);
  38965. textWasEdited();
  38966. if (deletionChecker != 0)
  38967. callChangeListeners();
  38968. }
  38969. }
  38970. }
  38971. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38972. {
  38973. if (editor != 0)
  38974. {
  38975. jassert (&ed == editor);
  38976. (void) ed;
  38977. editor->setText (textValue.toString(), false);
  38978. hideEditor (true);
  38979. }
  38980. }
  38981. void Label::textEditorFocusLost (TextEditor& ed)
  38982. {
  38983. textEditorTextChanged (ed);
  38984. }
  38985. END_JUCE_NAMESPACE
  38986. /*** End of inlined file: juce_Label.cpp ***/
  38987. /*** Start of inlined file: juce_ListBox.cpp ***/
  38988. BEGIN_JUCE_NAMESPACE
  38989. class ListBoxRowComponent : public Component,
  38990. public TooltipClient
  38991. {
  38992. public:
  38993. ListBoxRowComponent (ListBox& owner_)
  38994. : owner (owner_), row (-1),
  38995. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38996. {
  38997. }
  38998. void paint (Graphics& g)
  38999. {
  39000. if (owner.getModel() != 0)
  39001. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  39002. }
  39003. void update (const int row_, const bool selected_)
  39004. {
  39005. if (row != row_ || selected != selected_)
  39006. {
  39007. repaint();
  39008. row = row_;
  39009. selected = selected_;
  39010. }
  39011. if (owner.getModel() != 0)
  39012. {
  39013. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  39014. if (customComponent != 0)
  39015. {
  39016. addAndMakeVisible (customComponent);
  39017. customComponent->setBounds (getLocalBounds());
  39018. }
  39019. }
  39020. }
  39021. void mouseDown (const MouseEvent& e)
  39022. {
  39023. isDragging = false;
  39024. selectRowOnMouseUp = false;
  39025. if (isEnabled())
  39026. {
  39027. if (! selected)
  39028. {
  39029. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39030. if (owner.getModel() != 0)
  39031. owner.getModel()->listBoxItemClicked (row, e);
  39032. }
  39033. else
  39034. {
  39035. selectRowOnMouseUp = true;
  39036. }
  39037. }
  39038. }
  39039. void mouseUp (const MouseEvent& e)
  39040. {
  39041. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39042. {
  39043. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39044. if (owner.getModel() != 0)
  39045. owner.getModel()->listBoxItemClicked (row, e);
  39046. }
  39047. }
  39048. void mouseDoubleClick (const MouseEvent& e)
  39049. {
  39050. if (owner.getModel() != 0 && isEnabled())
  39051. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39052. }
  39053. void mouseDrag (const MouseEvent& e)
  39054. {
  39055. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39056. {
  39057. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39058. if (selectedRows.size() > 0)
  39059. {
  39060. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39061. if (dragDescription.isNotEmpty())
  39062. {
  39063. isDragging = true;
  39064. owner.startDragAndDrop (e, dragDescription);
  39065. }
  39066. }
  39067. }
  39068. }
  39069. void resized()
  39070. {
  39071. if (customComponent != 0)
  39072. customComponent->setBounds (getLocalBounds());
  39073. }
  39074. const String getTooltip()
  39075. {
  39076. if (owner.getModel() != 0)
  39077. return owner.getModel()->getTooltipForRow (row);
  39078. return String::empty;
  39079. }
  39080. juce_UseDebuggingNewOperator
  39081. ScopedPointer<Component> customComponent;
  39082. private:
  39083. ListBox& owner;
  39084. int row;
  39085. bool selected, isDragging, selectRowOnMouseUp;
  39086. ListBoxRowComponent (const ListBoxRowComponent&);
  39087. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39088. };
  39089. class ListViewport : public Viewport
  39090. {
  39091. public:
  39092. ListViewport (ListBox& owner_)
  39093. : owner (owner_)
  39094. {
  39095. setWantsKeyboardFocus (false);
  39096. Component* const content = new Component();
  39097. setViewedComponent (content);
  39098. content->addMouseListener (this, false);
  39099. content->setWantsKeyboardFocus (false);
  39100. }
  39101. ~ListViewport()
  39102. {
  39103. }
  39104. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39105. {
  39106. return rows [row % jmax (1, rows.size())];
  39107. }
  39108. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  39109. {
  39110. return (row >= firstIndex && row < firstIndex + rows.size())
  39111. ? getComponentForRow (row) : 0;
  39112. }
  39113. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39114. {
  39115. const int index = getIndexOfChildComponent (rowComponent);
  39116. const int num = rows.size();
  39117. for (int i = num; --i >= 0;)
  39118. if (((firstIndex + i) % jmax (1, num)) == index)
  39119. return firstIndex + i;
  39120. return -1;
  39121. }
  39122. void visibleAreaChanged (int, int, int, int)
  39123. {
  39124. updateVisibleArea (true);
  39125. if (owner.getModel() != 0)
  39126. owner.getModel()->listWasScrolled();
  39127. }
  39128. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39129. {
  39130. hasUpdated = false;
  39131. const int newX = getViewedComponent()->getX();
  39132. int newY = getViewedComponent()->getY();
  39133. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39134. const int newH = owner.totalItems * owner.getRowHeight();
  39135. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39136. newY = getMaximumVisibleHeight() - newH;
  39137. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39138. if (makeSureItUpdatesContent && ! hasUpdated)
  39139. updateContents();
  39140. }
  39141. void updateContents()
  39142. {
  39143. hasUpdated = true;
  39144. const int rowHeight = owner.getRowHeight();
  39145. if (rowHeight > 0)
  39146. {
  39147. const int y = getViewPositionY();
  39148. const int w = getViewedComponent()->getWidth();
  39149. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39150. rows.removeRange (numNeeded, rows.size());
  39151. while (numNeeded > rows.size())
  39152. {
  39153. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  39154. rows.add (newRow);
  39155. getViewedComponent()->addAndMakeVisible (newRow);
  39156. }
  39157. firstIndex = y / rowHeight;
  39158. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39159. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39160. for (int i = 0; i < numNeeded; ++i)
  39161. {
  39162. const int row = i + firstIndex;
  39163. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39164. if (rowComp != 0)
  39165. {
  39166. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39167. rowComp->update (row, owner.isRowSelected (row));
  39168. }
  39169. }
  39170. }
  39171. if (owner.headerComponent != 0)
  39172. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39173. owner.outlineThickness,
  39174. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39175. getViewedComponent()->getWidth()),
  39176. owner.headerComponent->getHeight());
  39177. }
  39178. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  39179. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  39180. {
  39181. hasUpdated = false;
  39182. if (row < firstWholeIndex && ! dontScroll)
  39183. {
  39184. setViewPosition (getViewPositionX(), row * rowHeight);
  39185. }
  39186. else if (row >= lastWholeIndex && ! dontScroll)
  39187. {
  39188. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  39189. if (row >= lastRowSelected + rowsOnScreen
  39190. && rowsOnScreen < totalItems - 1
  39191. && ! isMouseClick)
  39192. {
  39193. setViewPosition (getViewPositionX(),
  39194. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  39195. }
  39196. else
  39197. {
  39198. setViewPosition (getViewPositionX(),
  39199. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39200. }
  39201. }
  39202. if (! hasUpdated)
  39203. updateContents();
  39204. }
  39205. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  39206. {
  39207. if (row < firstWholeIndex)
  39208. {
  39209. setViewPosition (getViewPositionX(), row * rowHeight);
  39210. }
  39211. else if (row >= lastWholeIndex)
  39212. {
  39213. setViewPosition (getViewPositionX(),
  39214. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39215. }
  39216. }
  39217. void paint (Graphics& g)
  39218. {
  39219. if (isOpaque())
  39220. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39221. }
  39222. bool keyPressed (const KeyPress& key)
  39223. {
  39224. if (key.isKeyCode (KeyPress::upKey)
  39225. || key.isKeyCode (KeyPress::downKey)
  39226. || key.isKeyCode (KeyPress::pageUpKey)
  39227. || key.isKeyCode (KeyPress::pageDownKey)
  39228. || key.isKeyCode (KeyPress::homeKey)
  39229. || key.isKeyCode (KeyPress::endKey))
  39230. {
  39231. // we want to avoid these keypresses going to the viewport, and instead allow
  39232. // them to pass up to our listbox..
  39233. return false;
  39234. }
  39235. return Viewport::keyPressed (key);
  39236. }
  39237. juce_UseDebuggingNewOperator
  39238. private:
  39239. ListBox& owner;
  39240. OwnedArray<ListBoxRowComponent> rows;
  39241. int firstIndex, firstWholeIndex, lastWholeIndex;
  39242. bool hasUpdated;
  39243. ListViewport (const ListViewport&);
  39244. ListViewport& operator= (const ListViewport&);
  39245. };
  39246. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39247. : Component (name),
  39248. model (model_),
  39249. totalItems (0),
  39250. rowHeight (22),
  39251. minimumRowWidth (0),
  39252. outlineThickness (0),
  39253. lastRowSelected (-1),
  39254. mouseMoveSelects (false),
  39255. multipleSelection (false),
  39256. hasDoneInitialUpdate (false)
  39257. {
  39258. addAndMakeVisible (viewport = new ListViewport (*this));
  39259. setWantsKeyboardFocus (true);
  39260. colourChanged();
  39261. }
  39262. ListBox::~ListBox()
  39263. {
  39264. headerComponent = 0;
  39265. viewport = 0;
  39266. }
  39267. void ListBox::setModel (ListBoxModel* const newModel)
  39268. {
  39269. if (model != newModel)
  39270. {
  39271. model = newModel;
  39272. repaint();
  39273. updateContent();
  39274. }
  39275. }
  39276. void ListBox::setMultipleSelectionEnabled (bool b)
  39277. {
  39278. multipleSelection = b;
  39279. }
  39280. void ListBox::setMouseMoveSelectsRows (bool b)
  39281. {
  39282. mouseMoveSelects = b;
  39283. if (b)
  39284. addMouseListener (this, true);
  39285. }
  39286. void ListBox::paint (Graphics& g)
  39287. {
  39288. if (! hasDoneInitialUpdate)
  39289. updateContent();
  39290. g.fillAll (findColour (backgroundColourId));
  39291. }
  39292. void ListBox::paintOverChildren (Graphics& g)
  39293. {
  39294. if (outlineThickness > 0)
  39295. {
  39296. g.setColour (findColour (outlineColourId));
  39297. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39298. }
  39299. }
  39300. void ListBox::resized()
  39301. {
  39302. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39303. outlineThickness,
  39304. outlineThickness,
  39305. outlineThickness));
  39306. viewport->setSingleStepSizes (20, getRowHeight());
  39307. viewport->updateVisibleArea (false);
  39308. }
  39309. void ListBox::visibilityChanged()
  39310. {
  39311. viewport->updateVisibleArea (true);
  39312. }
  39313. Viewport* ListBox::getViewport() const throw()
  39314. {
  39315. return viewport;
  39316. }
  39317. void ListBox::updateContent()
  39318. {
  39319. hasDoneInitialUpdate = true;
  39320. totalItems = (model != 0) ? model->getNumRows() : 0;
  39321. bool selectionChanged = false;
  39322. if (selected [selected.size() - 1] >= totalItems)
  39323. {
  39324. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39325. lastRowSelected = getSelectedRow (0);
  39326. selectionChanged = true;
  39327. }
  39328. viewport->updateVisibleArea (isVisible());
  39329. viewport->resized();
  39330. if (selectionChanged && model != 0)
  39331. model->selectedRowsChanged (lastRowSelected);
  39332. }
  39333. void ListBox::selectRow (const int row,
  39334. bool dontScroll,
  39335. bool deselectOthersFirst)
  39336. {
  39337. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39338. }
  39339. void ListBox::selectRowInternal (const int row,
  39340. bool dontScroll,
  39341. bool deselectOthersFirst,
  39342. bool isMouseClick)
  39343. {
  39344. if (! multipleSelection)
  39345. deselectOthersFirst = true;
  39346. if ((! isRowSelected (row))
  39347. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39348. {
  39349. if (((unsigned int) row) < (unsigned int) totalItems)
  39350. {
  39351. if (deselectOthersFirst)
  39352. selected.clear();
  39353. selected.addRange (Range<int> (row, row + 1));
  39354. if (getHeight() == 0 || getWidth() == 0)
  39355. dontScroll = true;
  39356. viewport->selectRow (row, getRowHeight(), dontScroll,
  39357. lastRowSelected, totalItems, isMouseClick);
  39358. lastRowSelected = row;
  39359. model->selectedRowsChanged (row);
  39360. }
  39361. else
  39362. {
  39363. if (deselectOthersFirst)
  39364. deselectAllRows();
  39365. }
  39366. }
  39367. }
  39368. void ListBox::deselectRow (const int row)
  39369. {
  39370. if (selected.contains (row))
  39371. {
  39372. selected.removeRange (Range <int> (row, row + 1));
  39373. if (row == lastRowSelected)
  39374. lastRowSelected = getSelectedRow (0);
  39375. viewport->updateContents();
  39376. model->selectedRowsChanged (lastRowSelected);
  39377. }
  39378. }
  39379. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39380. const bool sendNotificationEventToModel)
  39381. {
  39382. selected = setOfRowsToBeSelected;
  39383. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39384. if (! isRowSelected (lastRowSelected))
  39385. lastRowSelected = getSelectedRow (0);
  39386. viewport->updateContents();
  39387. if ((model != 0) && sendNotificationEventToModel)
  39388. model->selectedRowsChanged (lastRowSelected);
  39389. }
  39390. const SparseSet<int> ListBox::getSelectedRows() const
  39391. {
  39392. return selected;
  39393. }
  39394. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39395. {
  39396. if (multipleSelection && (firstRow != lastRow))
  39397. {
  39398. const int numRows = totalItems - 1;
  39399. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39400. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39401. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39402. jmax (firstRow, lastRow) + 1));
  39403. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39404. }
  39405. selectRowInternal (lastRow, false, false, true);
  39406. }
  39407. void ListBox::flipRowSelection (const int row)
  39408. {
  39409. if (isRowSelected (row))
  39410. deselectRow (row);
  39411. else
  39412. selectRowInternal (row, false, false, true);
  39413. }
  39414. void ListBox::deselectAllRows()
  39415. {
  39416. if (! selected.isEmpty())
  39417. {
  39418. selected.clear();
  39419. lastRowSelected = -1;
  39420. viewport->updateContents();
  39421. if (model != 0)
  39422. model->selectedRowsChanged (lastRowSelected);
  39423. }
  39424. }
  39425. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39426. const ModifierKeys& mods)
  39427. {
  39428. if (multipleSelection && mods.isCommandDown())
  39429. {
  39430. flipRowSelection (row);
  39431. }
  39432. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39433. {
  39434. selectRangeOfRows (lastRowSelected, row);
  39435. }
  39436. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39437. {
  39438. selectRowInternal (row, false, true, true);
  39439. }
  39440. }
  39441. int ListBox::getNumSelectedRows() const
  39442. {
  39443. return selected.size();
  39444. }
  39445. int ListBox::getSelectedRow (const int index) const
  39446. {
  39447. return (((unsigned int) index) < (unsigned int) selected.size())
  39448. ? selected [index] : -1;
  39449. }
  39450. bool ListBox::isRowSelected (const int row) const
  39451. {
  39452. return selected.contains (row);
  39453. }
  39454. int ListBox::getLastRowSelected() const
  39455. {
  39456. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39457. }
  39458. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39459. {
  39460. if (((unsigned int) x) < (unsigned int) getWidth())
  39461. {
  39462. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39463. if (((unsigned int) row) < (unsigned int) totalItems)
  39464. return row;
  39465. }
  39466. return -1;
  39467. }
  39468. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39469. {
  39470. if (((unsigned int) x) < (unsigned int) getWidth())
  39471. {
  39472. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39473. return jlimit (0, totalItems, row);
  39474. }
  39475. return -1;
  39476. }
  39477. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39478. {
  39479. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39480. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39481. }
  39482. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39483. {
  39484. return viewport->getRowNumberOfComponent (rowComponent);
  39485. }
  39486. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39487. const bool relativeToComponentTopLeft) const throw()
  39488. {
  39489. int y = viewport->getY() + rowHeight * rowNumber;
  39490. if (relativeToComponentTopLeft)
  39491. y -= viewport->getViewPositionY();
  39492. return Rectangle<int> (viewport->getX(), y,
  39493. viewport->getViewedComponent()->getWidth(), rowHeight);
  39494. }
  39495. void ListBox::setVerticalPosition (const double proportion)
  39496. {
  39497. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39498. viewport->setViewPosition (viewport->getViewPositionX(),
  39499. jmax (0, roundToInt (proportion * offscreen)));
  39500. }
  39501. double ListBox::getVerticalPosition() const
  39502. {
  39503. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39504. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39505. : 0;
  39506. }
  39507. int ListBox::getVisibleRowWidth() const throw()
  39508. {
  39509. return viewport->getViewWidth();
  39510. }
  39511. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39512. {
  39513. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39514. }
  39515. bool ListBox::keyPressed (const KeyPress& key)
  39516. {
  39517. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39518. const bool multiple = multipleSelection
  39519. && (lastRowSelected >= 0)
  39520. && (key.getModifiers().isShiftDown()
  39521. || key.getModifiers().isCtrlDown()
  39522. || key.getModifiers().isCommandDown());
  39523. if (key.isKeyCode (KeyPress::upKey))
  39524. {
  39525. if (multiple)
  39526. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39527. else
  39528. selectRow (jmax (0, lastRowSelected - 1));
  39529. }
  39530. else if (key.isKeyCode (KeyPress::returnKey)
  39531. && isRowSelected (lastRowSelected))
  39532. {
  39533. if (model != 0)
  39534. model->returnKeyPressed (lastRowSelected);
  39535. }
  39536. else if (key.isKeyCode (KeyPress::pageUpKey))
  39537. {
  39538. if (multiple)
  39539. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39540. else
  39541. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39542. }
  39543. else if (key.isKeyCode (KeyPress::pageDownKey))
  39544. {
  39545. if (multiple)
  39546. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39547. else
  39548. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39549. }
  39550. else if (key.isKeyCode (KeyPress::homeKey))
  39551. {
  39552. if (multiple && key.getModifiers().isShiftDown())
  39553. selectRangeOfRows (lastRowSelected, 0);
  39554. else
  39555. selectRow (0);
  39556. }
  39557. else if (key.isKeyCode (KeyPress::endKey))
  39558. {
  39559. if (multiple && key.getModifiers().isShiftDown())
  39560. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39561. else
  39562. selectRow (totalItems - 1);
  39563. }
  39564. else if (key.isKeyCode (KeyPress::downKey))
  39565. {
  39566. if (multiple)
  39567. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39568. else
  39569. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39570. }
  39571. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39572. && isRowSelected (lastRowSelected))
  39573. {
  39574. if (model != 0)
  39575. model->deleteKeyPressed (lastRowSelected);
  39576. }
  39577. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39578. {
  39579. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39580. }
  39581. else
  39582. {
  39583. return false;
  39584. }
  39585. return true;
  39586. }
  39587. bool ListBox::keyStateChanged (const bool isKeyDown)
  39588. {
  39589. return isKeyDown
  39590. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39591. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39592. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39593. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39594. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39595. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39596. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39597. }
  39598. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39599. {
  39600. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39601. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39602. }
  39603. void ListBox::mouseMove (const MouseEvent& e)
  39604. {
  39605. if (mouseMoveSelects)
  39606. {
  39607. const MouseEvent e2 (e.getEventRelativeTo (this));
  39608. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39609. }
  39610. }
  39611. void ListBox::mouseExit (const MouseEvent& e)
  39612. {
  39613. mouseMove (e);
  39614. }
  39615. void ListBox::mouseUp (const MouseEvent& e)
  39616. {
  39617. if (e.mouseWasClicked() && model != 0)
  39618. model->backgroundClicked();
  39619. }
  39620. void ListBox::setRowHeight (const int newHeight)
  39621. {
  39622. rowHeight = jmax (1, newHeight);
  39623. viewport->setSingleStepSizes (20, rowHeight);
  39624. updateContent();
  39625. }
  39626. int ListBox::getNumRowsOnScreen() const throw()
  39627. {
  39628. return viewport->getMaximumVisibleHeight() / rowHeight;
  39629. }
  39630. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39631. {
  39632. minimumRowWidth = newMinimumWidth;
  39633. updateContent();
  39634. }
  39635. int ListBox::getVisibleContentWidth() const throw()
  39636. {
  39637. return viewport->getMaximumVisibleWidth();
  39638. }
  39639. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39640. {
  39641. return viewport->getVerticalScrollBar();
  39642. }
  39643. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39644. {
  39645. return viewport->getHorizontalScrollBar();
  39646. }
  39647. void ListBox::colourChanged()
  39648. {
  39649. setOpaque (findColour (backgroundColourId).isOpaque());
  39650. viewport->setOpaque (isOpaque());
  39651. repaint();
  39652. }
  39653. void ListBox::setOutlineThickness (const int outlineThickness_)
  39654. {
  39655. outlineThickness = outlineThickness_;
  39656. resized();
  39657. }
  39658. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39659. {
  39660. if (headerComponent != newHeaderComponent)
  39661. {
  39662. headerComponent = newHeaderComponent;
  39663. addAndMakeVisible (newHeaderComponent);
  39664. ListBox::resized();
  39665. }
  39666. }
  39667. void ListBox::repaintRow (const int rowNumber) throw()
  39668. {
  39669. repaint (getRowPosition (rowNumber, true));
  39670. }
  39671. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39672. {
  39673. Rectangle<int> imageArea;
  39674. const int firstRow = getRowContainingPosition (0, 0);
  39675. int i;
  39676. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39677. {
  39678. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39679. if (rowComp != 0 && isRowSelected (firstRow + i))
  39680. {
  39681. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39682. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39683. imageArea = imageArea.getUnion (rowRect);
  39684. }
  39685. }
  39686. imageArea = imageArea.getIntersection (getLocalBounds());
  39687. imageX = imageArea.getX();
  39688. imageY = imageArea.getY();
  39689. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39690. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39691. {
  39692. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39693. if (rowComp != 0 && isRowSelected (firstRow + i))
  39694. {
  39695. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39696. Graphics g (snapshot);
  39697. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39698. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39699. rowComp->paintEntireComponent (g, false);
  39700. }
  39701. }
  39702. return snapshot;
  39703. }
  39704. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39705. {
  39706. DragAndDropContainer* const dragContainer
  39707. = DragAndDropContainer::findParentDragContainerFor (this);
  39708. if (dragContainer != 0)
  39709. {
  39710. int x, y;
  39711. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39712. dragImage.multiplyAllAlphas (0.6f);
  39713. MouseEvent e2 (e.getEventRelativeTo (this));
  39714. const Point<int> p (x - e2.x, y - e2.y);
  39715. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39716. }
  39717. else
  39718. {
  39719. // to be able to do a drag-and-drop operation, the listbox needs to
  39720. // be inside a component which is also a DragAndDropContainer.
  39721. jassertfalse;
  39722. }
  39723. }
  39724. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39725. {
  39726. (void) existingComponentToUpdate;
  39727. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39728. return 0;
  39729. }
  39730. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39731. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39732. void ListBoxModel::backgroundClicked() {}
  39733. void ListBoxModel::selectedRowsChanged (int) {}
  39734. void ListBoxModel::deleteKeyPressed (int) {}
  39735. void ListBoxModel::returnKeyPressed (int) {}
  39736. void ListBoxModel::listWasScrolled() {}
  39737. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39738. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39739. END_JUCE_NAMESPACE
  39740. /*** End of inlined file: juce_ListBox.cpp ***/
  39741. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39742. BEGIN_JUCE_NAMESPACE
  39743. ProgressBar::ProgressBar (double& progress_)
  39744. : progress (progress_),
  39745. displayPercentage (true),
  39746. lastCallbackTime (0)
  39747. {
  39748. currentValue = jlimit (0.0, 1.0, progress);
  39749. }
  39750. ProgressBar::~ProgressBar()
  39751. {
  39752. }
  39753. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39754. {
  39755. displayPercentage = shouldDisplayPercentage;
  39756. repaint();
  39757. }
  39758. void ProgressBar::setTextToDisplay (const String& text)
  39759. {
  39760. displayPercentage = false;
  39761. displayedMessage = text;
  39762. }
  39763. void ProgressBar::lookAndFeelChanged()
  39764. {
  39765. setOpaque (findColour (backgroundColourId).isOpaque());
  39766. }
  39767. void ProgressBar::colourChanged()
  39768. {
  39769. lookAndFeelChanged();
  39770. }
  39771. void ProgressBar::paint (Graphics& g)
  39772. {
  39773. String text;
  39774. if (displayPercentage)
  39775. {
  39776. if (currentValue >= 0 && currentValue <= 1.0)
  39777. text << roundToInt (currentValue * 100.0) << '%';
  39778. }
  39779. else
  39780. {
  39781. text = displayedMessage;
  39782. }
  39783. getLookAndFeel().drawProgressBar (g, *this,
  39784. getWidth(), getHeight(),
  39785. currentValue, text);
  39786. }
  39787. void ProgressBar::visibilityChanged()
  39788. {
  39789. if (isVisible())
  39790. startTimer (30);
  39791. else
  39792. stopTimer();
  39793. }
  39794. void ProgressBar::timerCallback()
  39795. {
  39796. double newProgress = progress;
  39797. const uint32 now = Time::getMillisecondCounter();
  39798. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39799. lastCallbackTime = now;
  39800. if (currentValue != newProgress
  39801. || newProgress < 0 || newProgress >= 1.0
  39802. || currentMessage != displayedMessage)
  39803. {
  39804. if (currentValue < newProgress
  39805. && newProgress >= 0 && newProgress < 1.0
  39806. && currentValue >= 0 && currentValue < 1.0)
  39807. {
  39808. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39809. newProgress);
  39810. }
  39811. currentValue = newProgress;
  39812. currentMessage = displayedMessage;
  39813. repaint();
  39814. }
  39815. }
  39816. END_JUCE_NAMESPACE
  39817. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39818. /*** Start of inlined file: juce_Slider.cpp ***/
  39819. BEGIN_JUCE_NAMESPACE
  39820. class SliderPopupDisplayComponent : public BubbleComponent
  39821. {
  39822. public:
  39823. SliderPopupDisplayComponent (Slider* const owner_)
  39824. : owner (owner_),
  39825. font (15.0f, Font::bold)
  39826. {
  39827. setAlwaysOnTop (true);
  39828. }
  39829. ~SliderPopupDisplayComponent()
  39830. {
  39831. }
  39832. void paintContent (Graphics& g, int w, int h)
  39833. {
  39834. g.setFont (font);
  39835. g.setColour (Colours::black);
  39836. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39837. }
  39838. void getContentSize (int& w, int& h)
  39839. {
  39840. w = font.getStringWidth (text) + 18;
  39841. h = (int) (font.getHeight() * 1.6f);
  39842. }
  39843. void updatePosition (const String& newText)
  39844. {
  39845. if (text != newText)
  39846. {
  39847. text = newText;
  39848. repaint();
  39849. }
  39850. BubbleComponent::setPosition (owner);
  39851. }
  39852. juce_UseDebuggingNewOperator
  39853. private:
  39854. Slider* owner;
  39855. Font font;
  39856. String text;
  39857. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39858. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39859. };
  39860. Slider::Slider (const String& name)
  39861. : Component (name),
  39862. lastCurrentValue (0),
  39863. lastValueMin (0),
  39864. lastValueMax (0),
  39865. minimum (0),
  39866. maximum (10),
  39867. interval (0),
  39868. skewFactor (1.0),
  39869. velocityModeSensitivity (1.0),
  39870. velocityModeOffset (0.0),
  39871. velocityModeThreshold (1),
  39872. rotaryStart (float_Pi * 1.2f),
  39873. rotaryEnd (float_Pi * 2.8f),
  39874. numDecimalPlaces (7),
  39875. sliderRegionStart (0),
  39876. sliderRegionSize (1),
  39877. sliderBeingDragged (-1),
  39878. pixelsForFullDragExtent (250),
  39879. style (LinearHorizontal),
  39880. textBoxPos (TextBoxLeft),
  39881. textBoxWidth (80),
  39882. textBoxHeight (20),
  39883. incDecButtonMode (incDecButtonsNotDraggable),
  39884. editableText (true),
  39885. doubleClickToValue (false),
  39886. isVelocityBased (false),
  39887. userKeyOverridesVelocity (true),
  39888. rotaryStop (true),
  39889. incDecButtonsSideBySide (false),
  39890. sendChangeOnlyOnRelease (false),
  39891. popupDisplayEnabled (false),
  39892. menuEnabled (false),
  39893. menuShown (false),
  39894. scrollWheelEnabled (true),
  39895. snapsToMousePos (true),
  39896. popupDisplay (0),
  39897. parentForPopupDisplay (0)
  39898. {
  39899. setWantsKeyboardFocus (false);
  39900. setRepaintsOnMouseActivity (true);
  39901. lookAndFeelChanged();
  39902. updateText();
  39903. currentValue.addListener (this);
  39904. valueMin.addListener (this);
  39905. valueMax.addListener (this);
  39906. }
  39907. Slider::~Slider()
  39908. {
  39909. currentValue.removeListener (this);
  39910. valueMin.removeListener (this);
  39911. valueMax.removeListener (this);
  39912. popupDisplay = 0;
  39913. }
  39914. void Slider::handleAsyncUpdate()
  39915. {
  39916. cancelPendingUpdate();
  39917. Component::BailOutChecker checker (this);
  39918. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39919. }
  39920. void Slider::sendDragStart()
  39921. {
  39922. startedDragging();
  39923. Component::BailOutChecker checker (this);
  39924. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39925. }
  39926. void Slider::sendDragEnd()
  39927. {
  39928. stoppedDragging();
  39929. sliderBeingDragged = -1;
  39930. Component::BailOutChecker checker (this);
  39931. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39932. }
  39933. void Slider::addListener (SliderListener* const listener)
  39934. {
  39935. listeners.add (listener);
  39936. }
  39937. void Slider::removeListener (SliderListener* const listener)
  39938. {
  39939. listeners.remove (listener);
  39940. }
  39941. void Slider::setSliderStyle (const SliderStyle newStyle)
  39942. {
  39943. if (style != newStyle)
  39944. {
  39945. style = newStyle;
  39946. repaint();
  39947. lookAndFeelChanged();
  39948. }
  39949. }
  39950. void Slider::setRotaryParameters (const float startAngleRadians,
  39951. const float endAngleRadians,
  39952. const bool stopAtEnd)
  39953. {
  39954. // make sure the values are sensible..
  39955. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39956. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39957. jassert (rotaryStart < rotaryEnd);
  39958. rotaryStart = startAngleRadians;
  39959. rotaryEnd = endAngleRadians;
  39960. rotaryStop = stopAtEnd;
  39961. }
  39962. void Slider::setVelocityBasedMode (const bool velBased)
  39963. {
  39964. isVelocityBased = velBased;
  39965. }
  39966. void Slider::setVelocityModeParameters (const double sensitivity,
  39967. const int threshold,
  39968. const double offset,
  39969. const bool userCanPressKeyToSwapMode)
  39970. {
  39971. jassert (threshold >= 0);
  39972. jassert (sensitivity > 0);
  39973. jassert (offset >= 0);
  39974. velocityModeSensitivity = sensitivity;
  39975. velocityModeOffset = offset;
  39976. velocityModeThreshold = threshold;
  39977. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39978. }
  39979. void Slider::setSkewFactor (const double factor)
  39980. {
  39981. skewFactor = factor;
  39982. }
  39983. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39984. {
  39985. if (maximum > minimum)
  39986. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39987. / (maximum - minimum));
  39988. }
  39989. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39990. {
  39991. jassert (distanceForFullScaleDrag > 0);
  39992. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39993. }
  39994. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39995. {
  39996. if (incDecButtonMode != mode)
  39997. {
  39998. incDecButtonMode = mode;
  39999. lookAndFeelChanged();
  40000. }
  40001. }
  40002. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  40003. const bool isReadOnly,
  40004. const int textEntryBoxWidth,
  40005. const int textEntryBoxHeight)
  40006. {
  40007. if (textBoxPos != newPosition
  40008. || editableText != (! isReadOnly)
  40009. || textBoxWidth != textEntryBoxWidth
  40010. || textBoxHeight != textEntryBoxHeight)
  40011. {
  40012. textBoxPos = newPosition;
  40013. editableText = ! isReadOnly;
  40014. textBoxWidth = textEntryBoxWidth;
  40015. textBoxHeight = textEntryBoxHeight;
  40016. repaint();
  40017. lookAndFeelChanged();
  40018. }
  40019. }
  40020. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40021. {
  40022. editableText = shouldBeEditable;
  40023. if (valueBox != 0)
  40024. valueBox->setEditable (shouldBeEditable && isEnabled());
  40025. }
  40026. void Slider::showTextBox()
  40027. {
  40028. jassert (editableText); // this should probably be avoided in read-only sliders.
  40029. if (valueBox != 0)
  40030. valueBox->showEditor();
  40031. }
  40032. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40033. {
  40034. if (valueBox != 0)
  40035. {
  40036. valueBox->hideEditor (discardCurrentEditorContents);
  40037. if (discardCurrentEditorContents)
  40038. updateText();
  40039. }
  40040. }
  40041. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40042. {
  40043. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40044. }
  40045. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40046. {
  40047. snapsToMousePos = shouldSnapToMouse;
  40048. }
  40049. void Slider::setPopupDisplayEnabled (const bool enabled,
  40050. Component* const parentComponentToUse)
  40051. {
  40052. popupDisplayEnabled = enabled;
  40053. parentForPopupDisplay = parentComponentToUse;
  40054. }
  40055. void Slider::colourChanged()
  40056. {
  40057. lookAndFeelChanged();
  40058. }
  40059. void Slider::lookAndFeelChanged()
  40060. {
  40061. LookAndFeel& lf = getLookAndFeel();
  40062. if (textBoxPos != NoTextBox)
  40063. {
  40064. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40065. : getTextFromValue (currentValue.getValue()));
  40066. valueBox = 0;
  40067. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40068. valueBox->setWantsKeyboardFocus (false);
  40069. valueBox->setText (previousTextBoxContent, false);
  40070. valueBox->setEditable (editableText && isEnabled());
  40071. valueBox->addListener (this);
  40072. if (style == LinearBar)
  40073. valueBox->addMouseListener (this, false);
  40074. valueBox->setTooltip (getTooltip());
  40075. }
  40076. if (style == IncDecButtons)
  40077. {
  40078. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40079. incButton->addButtonListener (this);
  40080. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40081. decButton->addButtonListener (this);
  40082. if (incDecButtonMode != incDecButtonsNotDraggable)
  40083. {
  40084. incButton->addMouseListener (this, false);
  40085. decButton->addMouseListener (this, false);
  40086. }
  40087. else
  40088. {
  40089. incButton->setRepeatSpeed (300, 100, 20);
  40090. incButton->addMouseListener (decButton, false);
  40091. decButton->setRepeatSpeed (300, 100, 20);
  40092. decButton->addMouseListener (incButton, false);
  40093. }
  40094. incButton->setTooltip (getTooltip());
  40095. decButton->setTooltip (getTooltip());
  40096. }
  40097. else
  40098. {
  40099. incButton = 0;
  40100. decButton = 0;
  40101. }
  40102. setComponentEffect (lf.getSliderEffect());
  40103. resized();
  40104. repaint();
  40105. }
  40106. void Slider::setRange (const double newMin,
  40107. const double newMax,
  40108. const double newInt)
  40109. {
  40110. if (minimum != newMin
  40111. || maximum != newMax
  40112. || interval != newInt)
  40113. {
  40114. minimum = newMin;
  40115. maximum = newMax;
  40116. interval = newInt;
  40117. // figure out the number of DPs needed to display all values at this
  40118. // interval setting.
  40119. numDecimalPlaces = 7;
  40120. if (newInt != 0)
  40121. {
  40122. int v = abs ((int) (newInt * 10000000));
  40123. while ((v % 10) == 0)
  40124. {
  40125. --numDecimalPlaces;
  40126. v /= 10;
  40127. }
  40128. }
  40129. // keep the current values inside the new range..
  40130. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40131. {
  40132. setValue (getValue(), false, false);
  40133. }
  40134. else
  40135. {
  40136. setMinValue (getMinValue(), false, false);
  40137. setMaxValue (getMaxValue(), false, false);
  40138. }
  40139. updateText();
  40140. }
  40141. }
  40142. void Slider::triggerChangeMessage (const bool synchronous)
  40143. {
  40144. if (synchronous)
  40145. handleAsyncUpdate();
  40146. else
  40147. triggerAsyncUpdate();
  40148. valueChanged();
  40149. }
  40150. void Slider::valueChanged (Value& value)
  40151. {
  40152. if (value.refersToSameSourceAs (currentValue))
  40153. {
  40154. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40155. setValue (currentValue.getValue(), false, false);
  40156. }
  40157. else if (value.refersToSameSourceAs (valueMin))
  40158. setMinValue (valueMin.getValue(), false, false, true);
  40159. else if (value.refersToSameSourceAs (valueMax))
  40160. setMaxValue (valueMax.getValue(), false, false, true);
  40161. }
  40162. double Slider::getValue() const
  40163. {
  40164. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40165. // methods to get the two values.
  40166. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40167. return currentValue.getValue();
  40168. }
  40169. void Slider::setValue (double newValue,
  40170. const bool sendUpdateMessage,
  40171. const bool sendMessageSynchronously)
  40172. {
  40173. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40174. // methods to set the two values.
  40175. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40176. newValue = constrainedValue (newValue);
  40177. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40178. {
  40179. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40180. newValue = jlimit ((double) valueMin.getValue(),
  40181. (double) valueMax.getValue(),
  40182. newValue);
  40183. }
  40184. if (newValue != lastCurrentValue)
  40185. {
  40186. if (valueBox != 0)
  40187. valueBox->hideEditor (true);
  40188. lastCurrentValue = newValue;
  40189. currentValue = newValue;
  40190. updateText();
  40191. repaint();
  40192. if (popupDisplay != 0)
  40193. {
  40194. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40195. ->updatePosition (getTextFromValue (newValue));
  40196. popupDisplay->repaint();
  40197. }
  40198. if (sendUpdateMessage)
  40199. triggerChangeMessage (sendMessageSynchronously);
  40200. }
  40201. }
  40202. double Slider::getMinValue() const
  40203. {
  40204. // The minimum value only applies to sliders that are in two- or three-value mode.
  40205. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40206. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40207. return valueMin.getValue();
  40208. }
  40209. double Slider::getMaxValue() const
  40210. {
  40211. // The maximum value only applies to sliders that are in two- or three-value mode.
  40212. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40213. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40214. return valueMax.getValue();
  40215. }
  40216. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40217. {
  40218. // The minimum value only applies to sliders that are in two- or three-value mode.
  40219. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40220. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40221. newValue = constrainedValue (newValue);
  40222. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40223. {
  40224. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40225. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40226. newValue = jmin ((double) valueMax.getValue(), newValue);
  40227. }
  40228. else
  40229. {
  40230. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40231. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40232. newValue = jmin (lastCurrentValue, newValue);
  40233. }
  40234. if (lastValueMin != newValue)
  40235. {
  40236. lastValueMin = newValue;
  40237. valueMin = newValue;
  40238. repaint();
  40239. if (popupDisplay != 0)
  40240. {
  40241. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40242. ->updatePosition (getTextFromValue (newValue));
  40243. popupDisplay->repaint();
  40244. }
  40245. if (sendUpdateMessage)
  40246. triggerChangeMessage (sendMessageSynchronously);
  40247. }
  40248. }
  40249. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40250. {
  40251. // The maximum value only applies to sliders that are in two- or three-value mode.
  40252. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40253. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40254. newValue = constrainedValue (newValue);
  40255. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40256. {
  40257. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40258. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40259. newValue = jmax ((double) valueMin.getValue(), newValue);
  40260. }
  40261. else
  40262. {
  40263. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40264. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40265. newValue = jmax (lastCurrentValue, newValue);
  40266. }
  40267. if (lastValueMax != newValue)
  40268. {
  40269. lastValueMax = newValue;
  40270. valueMax = newValue;
  40271. repaint();
  40272. if (popupDisplay != 0)
  40273. {
  40274. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40275. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40276. popupDisplay->repaint();
  40277. }
  40278. if (sendUpdateMessage)
  40279. triggerChangeMessage (sendMessageSynchronously);
  40280. }
  40281. }
  40282. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40283. const double valueToSetOnDoubleClick)
  40284. {
  40285. doubleClickToValue = isDoubleClickEnabled;
  40286. doubleClickReturnValue = valueToSetOnDoubleClick;
  40287. }
  40288. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40289. {
  40290. isEnabled_ = doubleClickToValue;
  40291. return doubleClickReturnValue;
  40292. }
  40293. void Slider::updateText()
  40294. {
  40295. if (valueBox != 0)
  40296. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40297. }
  40298. void Slider::setTextValueSuffix (const String& suffix)
  40299. {
  40300. if (textSuffix != suffix)
  40301. {
  40302. textSuffix = suffix;
  40303. updateText();
  40304. }
  40305. }
  40306. const String Slider::getTextValueSuffix() const
  40307. {
  40308. return textSuffix;
  40309. }
  40310. const String Slider::getTextFromValue (double v)
  40311. {
  40312. if (getNumDecimalPlacesToDisplay() > 0)
  40313. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40314. else
  40315. return String (roundToInt (v)) + getTextValueSuffix();
  40316. }
  40317. double Slider::getValueFromText (const String& text)
  40318. {
  40319. String t (text.trimStart());
  40320. if (t.endsWith (textSuffix))
  40321. t = t.substring (0, t.length() - textSuffix.length());
  40322. while (t.startsWithChar ('+'))
  40323. t = t.substring (1).trimStart();
  40324. return t.initialSectionContainingOnly ("0123456789.,-")
  40325. .getDoubleValue();
  40326. }
  40327. double Slider::proportionOfLengthToValue (double proportion)
  40328. {
  40329. if (skewFactor != 1.0 && proportion > 0.0)
  40330. proportion = exp (log (proportion) / skewFactor);
  40331. return minimum + (maximum - minimum) * proportion;
  40332. }
  40333. double Slider::valueToProportionOfLength (double value)
  40334. {
  40335. const double n = (value - minimum) / (maximum - minimum);
  40336. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40337. }
  40338. double Slider::snapValue (double attemptedValue, const bool)
  40339. {
  40340. return attemptedValue;
  40341. }
  40342. void Slider::startedDragging()
  40343. {
  40344. }
  40345. void Slider::stoppedDragging()
  40346. {
  40347. }
  40348. void Slider::valueChanged()
  40349. {
  40350. }
  40351. void Slider::enablementChanged()
  40352. {
  40353. repaint();
  40354. }
  40355. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40356. {
  40357. menuEnabled = menuEnabled_;
  40358. }
  40359. void Slider::setScrollWheelEnabled (const bool enabled)
  40360. {
  40361. scrollWheelEnabled = enabled;
  40362. }
  40363. void Slider::labelTextChanged (Label* label)
  40364. {
  40365. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40366. if (newValue != (double) currentValue.getValue())
  40367. {
  40368. sendDragStart();
  40369. setValue (newValue, true, true);
  40370. sendDragEnd();
  40371. }
  40372. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40373. }
  40374. void Slider::buttonClicked (Button* button)
  40375. {
  40376. if (style == IncDecButtons)
  40377. {
  40378. sendDragStart();
  40379. if (button == incButton)
  40380. setValue (snapValue (getValue() + interval, false), true, true);
  40381. else if (button == decButton)
  40382. setValue (snapValue (getValue() - interval, false), true, true);
  40383. sendDragEnd();
  40384. }
  40385. }
  40386. double Slider::constrainedValue (double value) const
  40387. {
  40388. if (interval > 0)
  40389. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40390. if (value <= minimum || maximum <= minimum)
  40391. value = minimum;
  40392. else if (value >= maximum)
  40393. value = maximum;
  40394. return value;
  40395. }
  40396. float Slider::getLinearSliderPos (const double value)
  40397. {
  40398. double sliderPosProportional;
  40399. if (maximum > minimum)
  40400. {
  40401. if (value < minimum)
  40402. {
  40403. sliderPosProportional = 0.0;
  40404. }
  40405. else if (value > maximum)
  40406. {
  40407. sliderPosProportional = 1.0;
  40408. }
  40409. else
  40410. {
  40411. sliderPosProportional = valueToProportionOfLength (value);
  40412. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40413. }
  40414. }
  40415. else
  40416. {
  40417. sliderPosProportional = 0.5;
  40418. }
  40419. if (isVertical() || style == IncDecButtons)
  40420. sliderPosProportional = 1.0 - sliderPosProportional;
  40421. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40422. }
  40423. bool Slider::isHorizontal() const
  40424. {
  40425. return style == LinearHorizontal
  40426. || style == LinearBar
  40427. || style == TwoValueHorizontal
  40428. || style == ThreeValueHorizontal;
  40429. }
  40430. bool Slider::isVertical() const
  40431. {
  40432. return style == LinearVertical
  40433. || style == TwoValueVertical
  40434. || style == ThreeValueVertical;
  40435. }
  40436. bool Slider::incDecDragDirectionIsHorizontal() const
  40437. {
  40438. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40439. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40440. }
  40441. float Slider::getPositionOfValue (const double value)
  40442. {
  40443. if (isHorizontal() || isVertical())
  40444. {
  40445. return getLinearSliderPos (value);
  40446. }
  40447. else
  40448. {
  40449. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40450. return 0.0f;
  40451. }
  40452. }
  40453. void Slider::paint (Graphics& g)
  40454. {
  40455. if (style != IncDecButtons)
  40456. {
  40457. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40458. {
  40459. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40460. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40461. getLookAndFeel().drawRotarySlider (g,
  40462. sliderRect.getX(),
  40463. sliderRect.getY(),
  40464. sliderRect.getWidth(),
  40465. sliderRect.getHeight(),
  40466. sliderPos,
  40467. rotaryStart, rotaryEnd,
  40468. *this);
  40469. }
  40470. else
  40471. {
  40472. getLookAndFeel().drawLinearSlider (g,
  40473. sliderRect.getX(),
  40474. sliderRect.getY(),
  40475. sliderRect.getWidth(),
  40476. sliderRect.getHeight(),
  40477. getLinearSliderPos (lastCurrentValue),
  40478. getLinearSliderPos (lastValueMin),
  40479. getLinearSliderPos (lastValueMax),
  40480. style,
  40481. *this);
  40482. }
  40483. if (style == LinearBar && valueBox == 0)
  40484. {
  40485. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40486. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40487. }
  40488. }
  40489. }
  40490. void Slider::resized()
  40491. {
  40492. int minXSpace = 0;
  40493. int minYSpace = 0;
  40494. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40495. minXSpace = 30;
  40496. else
  40497. minYSpace = 15;
  40498. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40499. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40500. if (style == LinearBar)
  40501. {
  40502. if (valueBox != 0)
  40503. valueBox->setBounds (getLocalBounds());
  40504. }
  40505. else
  40506. {
  40507. if (textBoxPos == NoTextBox)
  40508. {
  40509. sliderRect = getLocalBounds();
  40510. }
  40511. else if (textBoxPos == TextBoxLeft)
  40512. {
  40513. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40514. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40515. }
  40516. else if (textBoxPos == TextBoxRight)
  40517. {
  40518. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40519. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40520. }
  40521. else if (textBoxPos == TextBoxAbove)
  40522. {
  40523. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40524. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40525. }
  40526. else if (textBoxPos == TextBoxBelow)
  40527. {
  40528. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40529. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40530. }
  40531. }
  40532. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40533. if (style == LinearBar)
  40534. {
  40535. const int barIndent = 1;
  40536. sliderRegionStart = barIndent;
  40537. sliderRegionSize = getWidth() - barIndent * 2;
  40538. sliderRect.setBounds (sliderRegionStart, barIndent,
  40539. sliderRegionSize, getHeight() - barIndent * 2);
  40540. }
  40541. else if (isHorizontal())
  40542. {
  40543. sliderRegionStart = sliderRect.getX() + indent;
  40544. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40545. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40546. sliderRegionSize, sliderRect.getHeight());
  40547. }
  40548. else if (isVertical())
  40549. {
  40550. sliderRegionStart = sliderRect.getY() + indent;
  40551. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40552. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40553. sliderRect.getWidth(), sliderRegionSize);
  40554. }
  40555. else
  40556. {
  40557. sliderRegionStart = 0;
  40558. sliderRegionSize = 100;
  40559. }
  40560. if (style == IncDecButtons)
  40561. {
  40562. Rectangle<int> buttonRect (sliderRect);
  40563. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40564. buttonRect.expand (-2, 0);
  40565. else
  40566. buttonRect.expand (0, -2);
  40567. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40568. if (incDecButtonsSideBySide)
  40569. {
  40570. decButton->setBounds (buttonRect.getX(),
  40571. buttonRect.getY(),
  40572. buttonRect.getWidth() / 2,
  40573. buttonRect.getHeight());
  40574. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40575. incButton->setBounds (buttonRect.getCentreX(),
  40576. buttonRect.getY(),
  40577. buttonRect.getWidth() / 2,
  40578. buttonRect.getHeight());
  40579. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40580. }
  40581. else
  40582. {
  40583. incButton->setBounds (buttonRect.getX(),
  40584. buttonRect.getY(),
  40585. buttonRect.getWidth(),
  40586. buttonRect.getHeight() / 2);
  40587. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40588. decButton->setBounds (buttonRect.getX(),
  40589. buttonRect.getCentreY(),
  40590. buttonRect.getWidth(),
  40591. buttonRect.getHeight() / 2);
  40592. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40593. }
  40594. }
  40595. }
  40596. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40597. {
  40598. repaint();
  40599. }
  40600. void Slider::mouseDown (const MouseEvent& e)
  40601. {
  40602. mouseWasHidden = false;
  40603. incDecDragged = false;
  40604. mouseXWhenLastDragged = e.x;
  40605. mouseYWhenLastDragged = e.y;
  40606. mouseDragStartX = e.getMouseDownX();
  40607. mouseDragStartY = e.getMouseDownY();
  40608. if (isEnabled())
  40609. {
  40610. if (e.mods.isPopupMenu() && menuEnabled)
  40611. {
  40612. menuShown = true;
  40613. PopupMenu m;
  40614. m.setLookAndFeel (&getLookAndFeel());
  40615. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40616. m.addSeparator();
  40617. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40618. {
  40619. PopupMenu rotaryMenu;
  40620. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40621. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40622. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40623. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40624. }
  40625. const int r = m.show();
  40626. if (r == 1)
  40627. {
  40628. setVelocityBasedMode (! isVelocityBased);
  40629. }
  40630. else if (r == 2)
  40631. {
  40632. setSliderStyle (Rotary);
  40633. }
  40634. else if (r == 3)
  40635. {
  40636. setSliderStyle (RotaryHorizontalDrag);
  40637. }
  40638. else if (r == 4)
  40639. {
  40640. setSliderStyle (RotaryVerticalDrag);
  40641. }
  40642. }
  40643. else if (maximum > minimum)
  40644. {
  40645. menuShown = false;
  40646. if (valueBox != 0)
  40647. valueBox->hideEditor (true);
  40648. sliderBeingDragged = 0;
  40649. if (style == TwoValueHorizontal
  40650. || style == TwoValueVertical
  40651. || style == ThreeValueHorizontal
  40652. || style == ThreeValueVertical)
  40653. {
  40654. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40655. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40656. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40657. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40658. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40659. {
  40660. if (maxPosDistance <= minPosDistance)
  40661. sliderBeingDragged = 2;
  40662. else
  40663. sliderBeingDragged = 1;
  40664. }
  40665. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40666. {
  40667. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40668. sliderBeingDragged = 1;
  40669. else if (normalPosDistance >= maxPosDistance)
  40670. sliderBeingDragged = 2;
  40671. }
  40672. }
  40673. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40674. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40675. * valueToProportionOfLength (currentValue.getValue());
  40676. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40677. : ((sliderBeingDragged == 1) ? valueMin
  40678. : currentValue)).getValue();
  40679. valueOnMouseDown = valueWhenLastDragged;
  40680. if (popupDisplayEnabled)
  40681. {
  40682. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40683. popupDisplay = popup;
  40684. if (parentForPopupDisplay != 0)
  40685. {
  40686. parentForPopupDisplay->addChildComponent (popup);
  40687. }
  40688. else
  40689. {
  40690. popup->addToDesktop (0);
  40691. }
  40692. popup->setVisible (true);
  40693. }
  40694. sendDragStart();
  40695. mouseDrag (e);
  40696. }
  40697. }
  40698. }
  40699. void Slider::mouseUp (const MouseEvent&)
  40700. {
  40701. if (isEnabled()
  40702. && (! menuShown)
  40703. && (maximum > minimum)
  40704. && (style != IncDecButtons || incDecDragged))
  40705. {
  40706. restoreMouseIfHidden();
  40707. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40708. triggerChangeMessage (false);
  40709. sendDragEnd();
  40710. popupDisplay = 0;
  40711. if (style == IncDecButtons)
  40712. {
  40713. incButton->setState (Button::buttonNormal);
  40714. decButton->setState (Button::buttonNormal);
  40715. }
  40716. }
  40717. }
  40718. void Slider::restoreMouseIfHidden()
  40719. {
  40720. if (mouseWasHidden)
  40721. {
  40722. mouseWasHidden = false;
  40723. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40724. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40725. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40726. : ((sliderBeingDragged == 1) ? getMinValue()
  40727. : (double) currentValue.getValue());
  40728. Point<int> mousePos;
  40729. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40730. {
  40731. mousePos = Desktop::getLastMouseDownPosition();
  40732. if (style == RotaryHorizontalDrag)
  40733. {
  40734. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40735. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40736. }
  40737. else
  40738. {
  40739. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40740. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40741. }
  40742. }
  40743. else
  40744. {
  40745. const int pixelPos = (int) getLinearSliderPos (pos);
  40746. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40747. isVertical() ? pixelPos : (getHeight() / 2)));
  40748. }
  40749. Desktop::setMousePosition (mousePos);
  40750. }
  40751. }
  40752. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40753. {
  40754. if (isEnabled()
  40755. && style != IncDecButtons
  40756. && style != Rotary
  40757. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40758. {
  40759. restoreMouseIfHidden();
  40760. }
  40761. }
  40762. namespace SliderHelpers
  40763. {
  40764. double smallestAngleBetween (double a1, double a2) throw()
  40765. {
  40766. return jmin (std::abs (a1 - a2),
  40767. std::abs (a1 + double_Pi * 2.0 - a2),
  40768. std::abs (a2 + double_Pi * 2.0 - a1));
  40769. }
  40770. }
  40771. void Slider::mouseDrag (const MouseEvent& e)
  40772. {
  40773. if (isEnabled()
  40774. && (! menuShown)
  40775. && (maximum > minimum))
  40776. {
  40777. if (style == Rotary)
  40778. {
  40779. int dx = e.x - sliderRect.getCentreX();
  40780. int dy = e.y - sliderRect.getCentreY();
  40781. if (dx * dx + dy * dy > 25)
  40782. {
  40783. double angle = std::atan2 ((double) dx, (double) -dy);
  40784. while (angle < 0.0)
  40785. angle += double_Pi * 2.0;
  40786. if (rotaryStop && ! e.mouseWasClicked())
  40787. {
  40788. if (std::abs (angle - lastAngle) > double_Pi)
  40789. {
  40790. if (angle >= lastAngle)
  40791. angle -= double_Pi * 2.0;
  40792. else
  40793. angle += double_Pi * 2.0;
  40794. }
  40795. if (angle >= lastAngle)
  40796. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40797. else
  40798. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40799. }
  40800. else
  40801. {
  40802. while (angle < rotaryStart)
  40803. angle += double_Pi * 2.0;
  40804. if (angle > rotaryEnd)
  40805. {
  40806. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40807. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40808. angle = rotaryStart;
  40809. else
  40810. angle = rotaryEnd;
  40811. }
  40812. }
  40813. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40814. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40815. lastAngle = angle;
  40816. }
  40817. }
  40818. else
  40819. {
  40820. if (style == LinearBar && e.mouseWasClicked()
  40821. && valueBox != 0 && valueBox->isEditable())
  40822. return;
  40823. if (style == IncDecButtons && ! incDecDragged)
  40824. {
  40825. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40826. return;
  40827. incDecDragged = true;
  40828. mouseDragStartX = e.x;
  40829. mouseDragStartY = e.y;
  40830. }
  40831. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40832. : false))
  40833. || ((maximum - minimum) / sliderRegionSize < interval))
  40834. {
  40835. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40836. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40837. if (style == RotaryHorizontalDrag
  40838. || style == RotaryVerticalDrag
  40839. || style == IncDecButtons
  40840. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40841. && ! snapsToMousePos))
  40842. {
  40843. const int mouseDiff = (style == RotaryHorizontalDrag
  40844. || style == LinearHorizontal
  40845. || style == LinearBar
  40846. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40847. ? e.x - mouseDragStartX
  40848. : mouseDragStartY - e.y;
  40849. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40850. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40851. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40852. if (style == IncDecButtons)
  40853. {
  40854. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40855. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40856. }
  40857. }
  40858. else
  40859. {
  40860. if (isVertical())
  40861. scaledMousePos = 1.0 - scaledMousePos;
  40862. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40863. }
  40864. }
  40865. else
  40866. {
  40867. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40868. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40869. ? e.x - mouseXWhenLastDragged
  40870. : e.y - mouseYWhenLastDragged;
  40871. const double maxSpeed = jmax (200, sliderRegionSize);
  40872. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40873. if (speed != 0)
  40874. {
  40875. speed = 0.2 * velocityModeSensitivity
  40876. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40877. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40878. / maxSpeed))));
  40879. if (mouseDiff < 0)
  40880. speed = -speed;
  40881. if (isVertical() || style == RotaryVerticalDrag
  40882. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40883. speed = -speed;
  40884. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40885. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40886. e.source.enableUnboundedMouseMovement (true, false);
  40887. mouseWasHidden = true;
  40888. }
  40889. }
  40890. }
  40891. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40892. if (sliderBeingDragged == 0)
  40893. {
  40894. setValue (snapValue (valueWhenLastDragged, true),
  40895. ! sendChangeOnlyOnRelease, true);
  40896. }
  40897. else if (sliderBeingDragged == 1)
  40898. {
  40899. setMinValue (snapValue (valueWhenLastDragged, true),
  40900. ! sendChangeOnlyOnRelease, false, true);
  40901. if (e.mods.isShiftDown())
  40902. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40903. else
  40904. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40905. }
  40906. else
  40907. {
  40908. jassert (sliderBeingDragged == 2);
  40909. setMaxValue (snapValue (valueWhenLastDragged, true),
  40910. ! sendChangeOnlyOnRelease, false, true);
  40911. if (e.mods.isShiftDown())
  40912. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40913. else
  40914. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40915. }
  40916. mouseXWhenLastDragged = e.x;
  40917. mouseYWhenLastDragged = e.y;
  40918. }
  40919. }
  40920. void Slider::mouseDoubleClick (const MouseEvent&)
  40921. {
  40922. if (doubleClickToValue
  40923. && isEnabled()
  40924. && style != IncDecButtons
  40925. && minimum <= doubleClickReturnValue
  40926. && maximum >= doubleClickReturnValue)
  40927. {
  40928. sendDragStart();
  40929. setValue (doubleClickReturnValue, true, true);
  40930. sendDragEnd();
  40931. }
  40932. }
  40933. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40934. {
  40935. if (scrollWheelEnabled && isEnabled()
  40936. && style != TwoValueHorizontal
  40937. && style != TwoValueVertical)
  40938. {
  40939. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40940. {
  40941. if (valueBox != 0)
  40942. valueBox->hideEditor (false);
  40943. const double value = (double) currentValue.getValue();
  40944. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40945. const double currentPos = valueToProportionOfLength (value);
  40946. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40947. double delta = (newValue != value)
  40948. ? jmax (std::abs (newValue - value), interval) : 0;
  40949. if (value > newValue)
  40950. delta = -delta;
  40951. sendDragStart();
  40952. setValue (snapValue (value + delta, false), true, true);
  40953. sendDragEnd();
  40954. }
  40955. }
  40956. else
  40957. {
  40958. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40959. }
  40960. }
  40961. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40962. {
  40963. }
  40964. void SliderListener::sliderDragEnded (Slider*)
  40965. {
  40966. }
  40967. END_JUCE_NAMESPACE
  40968. /*** End of inlined file: juce_Slider.cpp ***/
  40969. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40970. BEGIN_JUCE_NAMESPACE
  40971. class DragOverlayComp : public Component
  40972. {
  40973. public:
  40974. DragOverlayComp (const Image& image_)
  40975. : image (image_)
  40976. {
  40977. image.duplicateIfShared();
  40978. image.multiplyAllAlphas (0.8f);
  40979. setAlwaysOnTop (true);
  40980. }
  40981. ~DragOverlayComp()
  40982. {
  40983. }
  40984. void paint (Graphics& g)
  40985. {
  40986. g.drawImageAt (image, 0, 0);
  40987. }
  40988. private:
  40989. Image image;
  40990. DragOverlayComp (const DragOverlayComp&);
  40991. DragOverlayComp& operator= (const DragOverlayComp&);
  40992. };
  40993. TableHeaderComponent::TableHeaderComponent()
  40994. : columnsChanged (false),
  40995. columnsResized (false),
  40996. sortChanged (false),
  40997. menuActive (true),
  40998. stretchToFit (false),
  40999. columnIdBeingResized (0),
  41000. columnIdBeingDragged (0),
  41001. columnIdUnderMouse (0),
  41002. lastDeliberateWidth (0)
  41003. {
  41004. }
  41005. TableHeaderComponent::~TableHeaderComponent()
  41006. {
  41007. dragOverlayComp = 0;
  41008. }
  41009. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41010. {
  41011. menuActive = hasMenu;
  41012. }
  41013. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41014. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41015. {
  41016. if (onlyCountVisibleColumns)
  41017. {
  41018. int num = 0;
  41019. for (int i = columns.size(); --i >= 0;)
  41020. if (columns.getUnchecked(i)->isVisible())
  41021. ++num;
  41022. return num;
  41023. }
  41024. else
  41025. {
  41026. return columns.size();
  41027. }
  41028. }
  41029. const String TableHeaderComponent::getColumnName (const int columnId) const
  41030. {
  41031. const ColumnInfo* const ci = getInfoForId (columnId);
  41032. return ci != 0 ? ci->name : String::empty;
  41033. }
  41034. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41035. {
  41036. ColumnInfo* const ci = getInfoForId (columnId);
  41037. if (ci != 0 && ci->name != newName)
  41038. {
  41039. ci->name = newName;
  41040. sendColumnsChanged();
  41041. }
  41042. }
  41043. void TableHeaderComponent::addColumn (const String& columnName,
  41044. const int columnId,
  41045. const int width,
  41046. const int minimumWidth,
  41047. const int maximumWidth,
  41048. const int propertyFlags,
  41049. const int insertIndex)
  41050. {
  41051. // can't have a duplicate or null ID!
  41052. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41053. jassert (width > 0);
  41054. ColumnInfo* const ci = new ColumnInfo();
  41055. ci->name = columnName;
  41056. ci->id = columnId;
  41057. ci->width = width;
  41058. ci->lastDeliberateWidth = width;
  41059. ci->minimumWidth = minimumWidth;
  41060. ci->maximumWidth = maximumWidth;
  41061. if (ci->maximumWidth < 0)
  41062. ci->maximumWidth = std::numeric_limits<int>::max();
  41063. jassert (ci->maximumWidth >= ci->minimumWidth);
  41064. ci->propertyFlags = propertyFlags;
  41065. columns.insert (insertIndex, ci);
  41066. sendColumnsChanged();
  41067. }
  41068. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41069. {
  41070. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41071. if (index >= 0)
  41072. {
  41073. columns.remove (index);
  41074. sortChanged = true;
  41075. sendColumnsChanged();
  41076. }
  41077. }
  41078. void TableHeaderComponent::removeAllColumns()
  41079. {
  41080. if (columns.size() > 0)
  41081. {
  41082. columns.clear();
  41083. sendColumnsChanged();
  41084. }
  41085. }
  41086. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41087. {
  41088. const int currentIndex = getIndexOfColumnId (columnId, false);
  41089. newIndex = visibleIndexToTotalIndex (newIndex);
  41090. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41091. {
  41092. columns.move (currentIndex, newIndex);
  41093. sendColumnsChanged();
  41094. }
  41095. }
  41096. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41097. {
  41098. const ColumnInfo* const ci = getInfoForId (columnId);
  41099. return ci != 0 ? ci->width : 0;
  41100. }
  41101. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41102. {
  41103. ColumnInfo* const ci = getInfoForId (columnId);
  41104. if (ci != 0 && ci->width != newWidth)
  41105. {
  41106. const int numColumns = getNumColumns (true);
  41107. ci->lastDeliberateWidth = ci->width
  41108. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41109. if (stretchToFit)
  41110. {
  41111. const int index = getIndexOfColumnId (columnId, true) + 1;
  41112. if (((unsigned int) index) < (unsigned int) numColumns)
  41113. {
  41114. const int x = getColumnPosition (index).getX();
  41115. if (lastDeliberateWidth == 0)
  41116. lastDeliberateWidth = getTotalWidth();
  41117. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41118. }
  41119. }
  41120. repaint();
  41121. columnsResized = true;
  41122. triggerAsyncUpdate();
  41123. }
  41124. }
  41125. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41126. {
  41127. int n = 0;
  41128. for (int i = 0; i < columns.size(); ++i)
  41129. {
  41130. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41131. {
  41132. if (columns.getUnchecked(i)->id == columnId)
  41133. return n;
  41134. ++n;
  41135. }
  41136. }
  41137. return -1;
  41138. }
  41139. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41140. {
  41141. if (onlyCountVisibleColumns)
  41142. index = visibleIndexToTotalIndex (index);
  41143. const ColumnInfo* const ci = columns [index];
  41144. return (ci != 0) ? ci->id : 0;
  41145. }
  41146. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41147. {
  41148. int x = 0, width = 0, n = 0;
  41149. for (int i = 0; i < columns.size(); ++i)
  41150. {
  41151. x += width;
  41152. if (columns.getUnchecked(i)->isVisible())
  41153. {
  41154. width = columns.getUnchecked(i)->width;
  41155. if (n++ == index)
  41156. break;
  41157. }
  41158. else
  41159. {
  41160. width = 0;
  41161. }
  41162. }
  41163. return Rectangle<int> (x, 0, width, getHeight());
  41164. }
  41165. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41166. {
  41167. if (xToFind >= 0)
  41168. {
  41169. int x = 0;
  41170. for (int i = 0; i < columns.size(); ++i)
  41171. {
  41172. const ColumnInfo* const ci = columns.getUnchecked(i);
  41173. if (ci->isVisible())
  41174. {
  41175. x += ci->width;
  41176. if (xToFind < x)
  41177. return ci->id;
  41178. }
  41179. }
  41180. }
  41181. return 0;
  41182. }
  41183. int TableHeaderComponent::getTotalWidth() const
  41184. {
  41185. int w = 0;
  41186. for (int i = columns.size(); --i >= 0;)
  41187. if (columns.getUnchecked(i)->isVisible())
  41188. w += columns.getUnchecked(i)->width;
  41189. return w;
  41190. }
  41191. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41192. {
  41193. stretchToFit = shouldStretchToFit;
  41194. lastDeliberateWidth = getTotalWidth();
  41195. resized();
  41196. }
  41197. bool TableHeaderComponent::isStretchToFitActive() const
  41198. {
  41199. return stretchToFit;
  41200. }
  41201. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41202. {
  41203. if (stretchToFit && getWidth() > 0
  41204. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41205. {
  41206. lastDeliberateWidth = targetTotalWidth;
  41207. resizeColumnsToFit (0, targetTotalWidth);
  41208. }
  41209. }
  41210. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41211. {
  41212. targetTotalWidth = jmax (targetTotalWidth, 0);
  41213. StretchableObjectResizer sor;
  41214. int i;
  41215. for (i = firstColumnIndex; i < columns.size(); ++i)
  41216. {
  41217. ColumnInfo* const ci = columns.getUnchecked(i);
  41218. if (ci->isVisible())
  41219. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41220. }
  41221. sor.resizeToFit (targetTotalWidth);
  41222. int visIndex = 0;
  41223. for (i = firstColumnIndex; i < columns.size(); ++i)
  41224. {
  41225. ColumnInfo* const ci = columns.getUnchecked(i);
  41226. if (ci->isVisible())
  41227. {
  41228. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41229. (int) std::floor (sor.getItemSize (visIndex++)));
  41230. if (newWidth != ci->width)
  41231. {
  41232. ci->width = newWidth;
  41233. repaint();
  41234. columnsResized = true;
  41235. triggerAsyncUpdate();
  41236. }
  41237. }
  41238. }
  41239. }
  41240. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41241. {
  41242. ColumnInfo* const ci = getInfoForId (columnId);
  41243. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41244. {
  41245. if (shouldBeVisible)
  41246. ci->propertyFlags |= visible;
  41247. else
  41248. ci->propertyFlags &= ~visible;
  41249. sendColumnsChanged();
  41250. resized();
  41251. }
  41252. }
  41253. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41254. {
  41255. const ColumnInfo* const ci = getInfoForId (columnId);
  41256. return ci != 0 && ci->isVisible();
  41257. }
  41258. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41259. {
  41260. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41261. {
  41262. for (int i = columns.size(); --i >= 0;)
  41263. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41264. ColumnInfo* const ci = getInfoForId (columnId);
  41265. if (ci != 0)
  41266. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41267. reSortTable();
  41268. }
  41269. }
  41270. int TableHeaderComponent::getSortColumnId() const
  41271. {
  41272. for (int i = columns.size(); --i >= 0;)
  41273. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41274. return columns.getUnchecked(i)->id;
  41275. return 0;
  41276. }
  41277. bool TableHeaderComponent::isSortedForwards() const
  41278. {
  41279. for (int i = columns.size(); --i >= 0;)
  41280. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41281. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41282. return true;
  41283. }
  41284. void TableHeaderComponent::reSortTable()
  41285. {
  41286. sortChanged = true;
  41287. repaint();
  41288. triggerAsyncUpdate();
  41289. }
  41290. const String TableHeaderComponent::toString() const
  41291. {
  41292. String s;
  41293. XmlElement doc ("TABLELAYOUT");
  41294. doc.setAttribute ("sortedCol", getSortColumnId());
  41295. doc.setAttribute ("sortForwards", isSortedForwards());
  41296. for (int i = 0; i < columns.size(); ++i)
  41297. {
  41298. const ColumnInfo* const ci = columns.getUnchecked (i);
  41299. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41300. e->setAttribute ("id", ci->id);
  41301. e->setAttribute ("visible", ci->isVisible());
  41302. e->setAttribute ("width", ci->width);
  41303. }
  41304. return doc.createDocument (String::empty, true, false);
  41305. }
  41306. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41307. {
  41308. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41309. int index = 0;
  41310. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41311. {
  41312. forEachXmlChildElement (*storedXml, col)
  41313. {
  41314. const int tabId = col->getIntAttribute ("id");
  41315. ColumnInfo* const ci = getInfoForId (tabId);
  41316. if (ci != 0)
  41317. {
  41318. columns.move (columns.indexOf (ci), index);
  41319. ci->width = col->getIntAttribute ("width");
  41320. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41321. }
  41322. ++index;
  41323. }
  41324. columnsResized = true;
  41325. sendColumnsChanged();
  41326. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41327. storedXml->getBoolAttribute ("sortForwards", true));
  41328. }
  41329. }
  41330. void TableHeaderComponent::addListener (Listener* const newListener)
  41331. {
  41332. listeners.addIfNotAlreadyThere (newListener);
  41333. }
  41334. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41335. {
  41336. listeners.removeValue (listenerToRemove);
  41337. }
  41338. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41339. {
  41340. const ColumnInfo* const ci = getInfoForId (columnId);
  41341. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41342. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41343. }
  41344. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41345. {
  41346. for (int i = 0; i < columns.size(); ++i)
  41347. {
  41348. const ColumnInfo* const ci = columns.getUnchecked(i);
  41349. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41350. menu.addItem (ci->id, ci->name,
  41351. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41352. isColumnVisible (ci->id));
  41353. }
  41354. }
  41355. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41356. {
  41357. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41358. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41359. }
  41360. void TableHeaderComponent::paint (Graphics& g)
  41361. {
  41362. LookAndFeel& lf = getLookAndFeel();
  41363. lf.drawTableHeaderBackground (g, *this);
  41364. const Rectangle<int> clip (g.getClipBounds());
  41365. int x = 0;
  41366. for (int i = 0; i < columns.size(); ++i)
  41367. {
  41368. const ColumnInfo* const ci = columns.getUnchecked(i);
  41369. if (ci->isVisible())
  41370. {
  41371. if (x + ci->width > clip.getX()
  41372. && (ci->id != columnIdBeingDragged
  41373. || dragOverlayComp == 0
  41374. || ! dragOverlayComp->isVisible()))
  41375. {
  41376. g.saveState();
  41377. g.setOrigin (x, 0);
  41378. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41379. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41380. ci->id == columnIdUnderMouse,
  41381. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41382. ci->propertyFlags);
  41383. g.restoreState();
  41384. }
  41385. x += ci->width;
  41386. if (x >= clip.getRight())
  41387. break;
  41388. }
  41389. }
  41390. }
  41391. void TableHeaderComponent::resized()
  41392. {
  41393. }
  41394. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41395. {
  41396. updateColumnUnderMouse (e.x, e.y);
  41397. }
  41398. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41399. {
  41400. updateColumnUnderMouse (e.x, e.y);
  41401. }
  41402. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41403. {
  41404. updateColumnUnderMouse (e.x, e.y);
  41405. }
  41406. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41407. {
  41408. repaint();
  41409. columnIdBeingResized = 0;
  41410. columnIdBeingDragged = 0;
  41411. if (columnIdUnderMouse != 0)
  41412. {
  41413. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41414. if (e.mods.isPopupMenu())
  41415. columnClicked (columnIdUnderMouse, e.mods);
  41416. }
  41417. if (menuActive && e.mods.isPopupMenu())
  41418. showColumnChooserMenu (columnIdUnderMouse);
  41419. }
  41420. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41421. {
  41422. if (columnIdBeingResized == 0
  41423. && columnIdBeingDragged == 0
  41424. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41425. {
  41426. dragOverlayComp = 0;
  41427. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41428. if (columnIdBeingResized != 0)
  41429. {
  41430. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41431. initialColumnWidth = ci->width;
  41432. }
  41433. else
  41434. {
  41435. beginDrag (e);
  41436. }
  41437. }
  41438. if (columnIdBeingResized != 0)
  41439. {
  41440. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41441. if (ci != 0)
  41442. {
  41443. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41444. initialColumnWidth + e.getDistanceFromDragStartX());
  41445. if (stretchToFit)
  41446. {
  41447. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41448. int minWidthOnRight = 0;
  41449. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41450. if (columns.getUnchecked (i)->isVisible())
  41451. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41452. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41453. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41454. }
  41455. setColumnWidth (columnIdBeingResized, w);
  41456. }
  41457. }
  41458. else if (columnIdBeingDragged != 0)
  41459. {
  41460. if (e.y >= -50 && e.y < getHeight() + 50)
  41461. {
  41462. if (dragOverlayComp != 0)
  41463. {
  41464. dragOverlayComp->setVisible (true);
  41465. dragOverlayComp->setBounds (jlimit (0,
  41466. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41467. e.x - draggingColumnOffset),
  41468. 0,
  41469. dragOverlayComp->getWidth(),
  41470. getHeight());
  41471. for (int i = columns.size(); --i >= 0;)
  41472. {
  41473. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41474. int newIndex = currentIndex;
  41475. if (newIndex > 0)
  41476. {
  41477. // if the previous column isn't draggable, we can't move our column
  41478. // past it, because that'd change the undraggable column's position..
  41479. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41480. if ((previous->propertyFlags & draggable) != 0)
  41481. {
  41482. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41483. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41484. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41485. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41486. {
  41487. --newIndex;
  41488. }
  41489. }
  41490. }
  41491. if (newIndex < columns.size() - 1)
  41492. {
  41493. // if the next column isn't draggable, we can't move our column
  41494. // past it, because that'd change the undraggable column's position..
  41495. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41496. if ((nextCol->propertyFlags & draggable) != 0)
  41497. {
  41498. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41499. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41500. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41501. > abs (dragOverlayComp->getRight() - rightOfNext))
  41502. {
  41503. ++newIndex;
  41504. }
  41505. }
  41506. }
  41507. if (newIndex != currentIndex)
  41508. moveColumn (columnIdBeingDragged, newIndex);
  41509. else
  41510. break;
  41511. }
  41512. }
  41513. }
  41514. else
  41515. {
  41516. endDrag (draggingColumnOriginalIndex);
  41517. }
  41518. }
  41519. }
  41520. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41521. {
  41522. if (columnIdBeingDragged == 0)
  41523. {
  41524. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41525. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41526. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41527. {
  41528. columnIdBeingDragged = 0;
  41529. }
  41530. else
  41531. {
  41532. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41533. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41534. const int temp = columnIdBeingDragged;
  41535. columnIdBeingDragged = 0;
  41536. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41537. columnIdBeingDragged = temp;
  41538. dragOverlayComp->setBounds (columnRect);
  41539. for (int i = listeners.size(); --i >= 0;)
  41540. {
  41541. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41542. i = jmin (i, listeners.size() - 1);
  41543. }
  41544. }
  41545. }
  41546. }
  41547. void TableHeaderComponent::endDrag (const int finalIndex)
  41548. {
  41549. if (columnIdBeingDragged != 0)
  41550. {
  41551. moveColumn (columnIdBeingDragged, finalIndex);
  41552. columnIdBeingDragged = 0;
  41553. repaint();
  41554. for (int i = listeners.size(); --i >= 0;)
  41555. {
  41556. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41557. i = jmin (i, listeners.size() - 1);
  41558. }
  41559. }
  41560. }
  41561. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41562. {
  41563. mouseDrag (e);
  41564. for (int i = columns.size(); --i >= 0;)
  41565. if (columns.getUnchecked (i)->isVisible())
  41566. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41567. columnIdBeingResized = 0;
  41568. repaint();
  41569. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41570. updateColumnUnderMouse (e.x, e.y);
  41571. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41572. columnClicked (columnIdUnderMouse, e.mods);
  41573. dragOverlayComp = 0;
  41574. }
  41575. const MouseCursor TableHeaderComponent::getMouseCursor()
  41576. {
  41577. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41578. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41579. return Component::getMouseCursor();
  41580. }
  41581. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41582. {
  41583. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41584. }
  41585. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41586. {
  41587. for (int i = columns.size(); --i >= 0;)
  41588. if (columns.getUnchecked(i)->id == id)
  41589. return columns.getUnchecked(i);
  41590. return 0;
  41591. }
  41592. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41593. {
  41594. int n = 0;
  41595. for (int i = 0; i < columns.size(); ++i)
  41596. {
  41597. if (columns.getUnchecked(i)->isVisible())
  41598. {
  41599. if (n == visibleIndex)
  41600. return i;
  41601. ++n;
  41602. }
  41603. }
  41604. return -1;
  41605. }
  41606. void TableHeaderComponent::sendColumnsChanged()
  41607. {
  41608. if (stretchToFit && lastDeliberateWidth > 0)
  41609. resizeAllColumnsToFit (lastDeliberateWidth);
  41610. repaint();
  41611. columnsChanged = true;
  41612. triggerAsyncUpdate();
  41613. }
  41614. void TableHeaderComponent::handleAsyncUpdate()
  41615. {
  41616. const bool changed = columnsChanged || sortChanged;
  41617. const bool sized = columnsResized || changed;
  41618. const bool sorted = sortChanged;
  41619. columnsChanged = false;
  41620. columnsResized = false;
  41621. sortChanged = false;
  41622. if (sorted)
  41623. {
  41624. for (int i = listeners.size(); --i >= 0;)
  41625. {
  41626. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41627. i = jmin (i, listeners.size() - 1);
  41628. }
  41629. }
  41630. if (changed)
  41631. {
  41632. for (int i = listeners.size(); --i >= 0;)
  41633. {
  41634. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41635. i = jmin (i, listeners.size() - 1);
  41636. }
  41637. }
  41638. if (sized)
  41639. {
  41640. for (int i = listeners.size(); --i >= 0;)
  41641. {
  41642. listeners.getUnchecked(i)->tableColumnsResized (this);
  41643. i = jmin (i, listeners.size() - 1);
  41644. }
  41645. }
  41646. }
  41647. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41648. {
  41649. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41650. {
  41651. const int draggableDistance = 3;
  41652. int x = 0;
  41653. for (int i = 0; i < columns.size(); ++i)
  41654. {
  41655. const ColumnInfo* const ci = columns.getUnchecked(i);
  41656. if (ci->isVisible())
  41657. {
  41658. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41659. && (ci->propertyFlags & resizable) != 0)
  41660. return ci->id;
  41661. x += ci->width;
  41662. }
  41663. }
  41664. }
  41665. return 0;
  41666. }
  41667. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41668. {
  41669. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  41670. ? getColumnIdAtX (x) : 0;
  41671. if (newCol != columnIdUnderMouse)
  41672. {
  41673. columnIdUnderMouse = newCol;
  41674. repaint();
  41675. }
  41676. }
  41677. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41678. {
  41679. PopupMenu m;
  41680. addMenuItems (m, columnIdClicked);
  41681. if (m.getNumItems() > 0)
  41682. {
  41683. m.setLookAndFeel (&getLookAndFeel());
  41684. const int result = m.show();
  41685. if (result != 0)
  41686. reactToMenuItem (result, columnIdClicked);
  41687. }
  41688. }
  41689. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41690. {
  41691. }
  41692. END_JUCE_NAMESPACE
  41693. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41694. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41695. BEGIN_JUCE_NAMESPACE
  41696. class TableListRowComp : public Component,
  41697. public TooltipClient
  41698. {
  41699. public:
  41700. TableListRowComp (TableListBox& owner_)
  41701. : owner (owner_), row (-1), isSelected (false)
  41702. {
  41703. }
  41704. void paint (Graphics& g)
  41705. {
  41706. TableListBoxModel* const model = owner.getModel();
  41707. if (model != 0)
  41708. {
  41709. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41710. const TableHeaderComponent& header = owner.getHeader();
  41711. const int numColumns = header.getNumColumns (true);
  41712. for (int i = 0; i < numColumns; ++i)
  41713. {
  41714. if (columnComponents[i] == 0)
  41715. {
  41716. const int columnId = header.getColumnIdOfIndex (i, true);
  41717. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41718. g.saveState();
  41719. g.reduceClipRegion (columnRect);
  41720. g.setOrigin (columnRect.getX(), 0);
  41721. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41722. g.restoreState();
  41723. }
  41724. }
  41725. }
  41726. }
  41727. void update (const int newRow, const bool isNowSelected)
  41728. {
  41729. jassert (newRow >= 0);
  41730. if (newRow != row || isNowSelected != isSelected)
  41731. {
  41732. row = newRow;
  41733. isSelected = isNowSelected;
  41734. repaint();
  41735. }
  41736. TableListBoxModel* const model = owner.getModel();
  41737. if (model != 0 && row < owner.getNumRows())
  41738. {
  41739. const Identifier columnProperty ("_tableColumnId");
  41740. const int numColumns = owner.getHeader().getNumColumns (true);
  41741. for (int i = 0; i < numColumns; ++i)
  41742. {
  41743. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41744. Component* comp = columnComponents[i];
  41745. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41746. {
  41747. columnComponents.set (i, 0);
  41748. comp = 0;
  41749. }
  41750. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41751. columnComponents.set (i, comp, false);
  41752. if (comp != 0)
  41753. {
  41754. comp->getProperties().set (columnProperty, columnId);
  41755. addAndMakeVisible (comp);
  41756. resizeCustomComp (i);
  41757. }
  41758. }
  41759. columnComponents.removeRange (numColumns, columnComponents.size());
  41760. }
  41761. else
  41762. {
  41763. columnComponents.clear();
  41764. }
  41765. }
  41766. void resized()
  41767. {
  41768. for (int i = columnComponents.size(); --i >= 0;)
  41769. resizeCustomComp (i);
  41770. }
  41771. void resizeCustomComp (const int index)
  41772. {
  41773. Component* const c = columnComponents.getUnchecked (index);
  41774. if (c != 0)
  41775. c->setBounds (owner.getHeader().getColumnPosition (index)
  41776. .withY (0).withHeight (getHeight()));
  41777. }
  41778. void mouseDown (const MouseEvent& e)
  41779. {
  41780. isDragging = false;
  41781. selectRowOnMouseUp = false;
  41782. if (isEnabled())
  41783. {
  41784. if (! isSelected)
  41785. {
  41786. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41787. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41788. if (columnId != 0 && owner.getModel() != 0)
  41789. owner.getModel()->cellClicked (row, columnId, e);
  41790. }
  41791. else
  41792. {
  41793. selectRowOnMouseUp = true;
  41794. }
  41795. }
  41796. }
  41797. void mouseDrag (const MouseEvent& e)
  41798. {
  41799. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41800. {
  41801. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41802. if (selectedRows.size() > 0)
  41803. {
  41804. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41805. if (dragDescription.isNotEmpty())
  41806. {
  41807. isDragging = true;
  41808. owner.startDragAndDrop (e, dragDescription);
  41809. }
  41810. }
  41811. }
  41812. }
  41813. void mouseUp (const MouseEvent& e)
  41814. {
  41815. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41816. {
  41817. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41818. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41819. if (columnId != 0 && owner.getModel() != 0)
  41820. owner.getModel()->cellClicked (row, columnId, e);
  41821. }
  41822. }
  41823. void mouseDoubleClick (const MouseEvent& e)
  41824. {
  41825. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41826. if (columnId != 0 && owner.getModel() != 0)
  41827. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41828. }
  41829. const String getTooltip()
  41830. {
  41831. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41832. if (columnId != 0 && owner.getModel() != 0)
  41833. return owner.getModel()->getCellTooltip (row, columnId);
  41834. return String::empty;
  41835. }
  41836. Component* findChildComponentForColumn (const int columnId) const
  41837. {
  41838. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41839. }
  41840. juce_UseDebuggingNewOperator
  41841. private:
  41842. TableListBox& owner;
  41843. OwnedArray<Component> columnComponents;
  41844. int row;
  41845. bool isSelected, isDragging, selectRowOnMouseUp;
  41846. TableListRowComp (const TableListRowComp&);
  41847. TableListRowComp& operator= (const TableListRowComp&);
  41848. };
  41849. class TableListBoxHeader : public TableHeaderComponent
  41850. {
  41851. public:
  41852. TableListBoxHeader (TableListBox& owner_)
  41853. : owner (owner_)
  41854. {
  41855. }
  41856. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41857. {
  41858. if (owner.isAutoSizeMenuOptionShown())
  41859. {
  41860. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41861. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41862. menu.addSeparator();
  41863. }
  41864. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41865. }
  41866. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41867. {
  41868. switch (menuReturnId)
  41869. {
  41870. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41871. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41872. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41873. }
  41874. }
  41875. juce_UseDebuggingNewOperator
  41876. private:
  41877. TableListBox& owner;
  41878. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41879. TableListBoxHeader (const TableListBoxHeader&);
  41880. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41881. };
  41882. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41883. : ListBox (name, 0),
  41884. model (model_),
  41885. autoSizeOptionsShown (true)
  41886. {
  41887. ListBox::model = this;
  41888. header = new TableListBoxHeader (*this);
  41889. header->setSize (100, 28);
  41890. header->addListener (this);
  41891. setHeaderComponent (header);
  41892. }
  41893. TableListBox::~TableListBox()
  41894. {
  41895. header = 0;
  41896. }
  41897. void TableListBox::setModel (TableListBoxModel* const newModel)
  41898. {
  41899. if (model != newModel)
  41900. {
  41901. model = newModel;
  41902. updateContent();
  41903. }
  41904. }
  41905. int TableListBox::getHeaderHeight() const
  41906. {
  41907. return header->getHeight();
  41908. }
  41909. void TableListBox::setHeaderHeight (const int newHeight)
  41910. {
  41911. header->setSize (header->getWidth(), newHeight);
  41912. resized();
  41913. }
  41914. void TableListBox::autoSizeColumn (const int columnId)
  41915. {
  41916. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41917. if (width > 0)
  41918. header->setColumnWidth (columnId, width);
  41919. }
  41920. void TableListBox::autoSizeAllColumns()
  41921. {
  41922. for (int i = 0; i < header->getNumColumns (true); ++i)
  41923. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41924. }
  41925. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41926. {
  41927. autoSizeOptionsShown = shouldBeShown;
  41928. }
  41929. bool TableListBox::isAutoSizeMenuOptionShown() const
  41930. {
  41931. return autoSizeOptionsShown;
  41932. }
  41933. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41934. const bool relativeToComponentTopLeft) const
  41935. {
  41936. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41937. if (relativeToComponentTopLeft)
  41938. headerCell.translate (header->getX(), 0);
  41939. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41940. .withX (headerCell.getX())
  41941. .withWidth (headerCell.getWidth());
  41942. }
  41943. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41944. {
  41945. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41946. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41947. }
  41948. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41949. {
  41950. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41951. if (scrollbar != 0)
  41952. {
  41953. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41954. double x = scrollbar->getCurrentRangeStart();
  41955. const double w = scrollbar->getCurrentRangeSize();
  41956. if (pos.getX() < x)
  41957. x = pos.getX();
  41958. else if (pos.getRight() > x + w)
  41959. x += jmax (0.0, pos.getRight() - (x + w));
  41960. scrollbar->setCurrentRangeStart (x);
  41961. }
  41962. }
  41963. int TableListBox::getNumRows()
  41964. {
  41965. return model != 0 ? model->getNumRows() : 0;
  41966. }
  41967. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41968. {
  41969. }
  41970. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41971. {
  41972. if (existingComponentToUpdate == 0)
  41973. existingComponentToUpdate = new TableListRowComp (*this);
  41974. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41975. return existingComponentToUpdate;
  41976. }
  41977. void TableListBox::selectedRowsChanged (int row)
  41978. {
  41979. if (model != 0)
  41980. model->selectedRowsChanged (row);
  41981. }
  41982. void TableListBox::deleteKeyPressed (int row)
  41983. {
  41984. if (model != 0)
  41985. model->deleteKeyPressed (row);
  41986. }
  41987. void TableListBox::returnKeyPressed (int row)
  41988. {
  41989. if (model != 0)
  41990. model->returnKeyPressed (row);
  41991. }
  41992. void TableListBox::backgroundClicked()
  41993. {
  41994. if (model != 0)
  41995. model->backgroundClicked();
  41996. }
  41997. void TableListBox::listWasScrolled()
  41998. {
  41999. if (model != 0)
  42000. model->listWasScrolled();
  42001. }
  42002. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  42003. {
  42004. setMinimumContentWidth (header->getTotalWidth());
  42005. repaint();
  42006. updateColumnComponents();
  42007. }
  42008. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42009. {
  42010. setMinimumContentWidth (header->getTotalWidth());
  42011. repaint();
  42012. updateColumnComponents();
  42013. }
  42014. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42015. {
  42016. if (model != 0)
  42017. model->sortOrderChanged (header->getSortColumnId(),
  42018. header->isSortedForwards());
  42019. }
  42020. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42021. {
  42022. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42023. repaint();
  42024. }
  42025. void TableListBox::resized()
  42026. {
  42027. ListBox::resized();
  42028. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42029. setMinimumContentWidth (header->getTotalWidth());
  42030. }
  42031. void TableListBox::updateColumnComponents() const
  42032. {
  42033. const int firstRow = getRowContainingPosition (0, 0);
  42034. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42035. {
  42036. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42037. if (rowComp != 0)
  42038. rowComp->resized();
  42039. }
  42040. }
  42041. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  42042. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  42043. void TableListBoxModel::backgroundClicked() {}
  42044. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  42045. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  42046. void TableListBoxModel::selectedRowsChanged (int) {}
  42047. void TableListBoxModel::deleteKeyPressed (int) {}
  42048. void TableListBoxModel::returnKeyPressed (int) {}
  42049. void TableListBoxModel::listWasScrolled() {}
  42050. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  42051. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  42052. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42053. {
  42054. (void) existingComponentToUpdate;
  42055. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42056. return 0;
  42057. }
  42058. END_JUCE_NAMESPACE
  42059. /*** End of inlined file: juce_TableListBox.cpp ***/
  42060. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42061. BEGIN_JUCE_NAMESPACE
  42062. // a word or space that can't be broken down any further
  42063. struct TextAtom
  42064. {
  42065. String atomText;
  42066. float width;
  42067. int numChars;
  42068. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42069. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42070. const String getText (const juce_wchar passwordCharacter) const
  42071. {
  42072. if (passwordCharacter == 0)
  42073. return atomText;
  42074. else
  42075. return String::repeatedString (String::charToString (passwordCharacter),
  42076. atomText.length());
  42077. }
  42078. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42079. {
  42080. if (passwordCharacter == 0)
  42081. return atomText.substring (0, numChars);
  42082. else if (isNewLine())
  42083. return String::empty;
  42084. else
  42085. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42086. }
  42087. };
  42088. // a run of text with a single font and colour
  42089. class TextEditor::UniformTextSection
  42090. {
  42091. public:
  42092. UniformTextSection (const String& text,
  42093. const Font& font_,
  42094. const Colour& colour_,
  42095. const juce_wchar passwordCharacter)
  42096. : font (font_),
  42097. colour (colour_)
  42098. {
  42099. initialiseAtoms (text, passwordCharacter);
  42100. }
  42101. UniformTextSection (const UniformTextSection& other)
  42102. : font (other.font),
  42103. colour (other.colour)
  42104. {
  42105. atoms.ensureStorageAllocated (other.atoms.size());
  42106. for (int i = 0; i < other.atoms.size(); ++i)
  42107. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42108. }
  42109. ~UniformTextSection()
  42110. {
  42111. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42112. }
  42113. void clear()
  42114. {
  42115. for (int i = atoms.size(); --i >= 0;)
  42116. delete getAtom(i);
  42117. atoms.clear();
  42118. }
  42119. int getNumAtoms() const
  42120. {
  42121. return atoms.size();
  42122. }
  42123. TextAtom* getAtom (const int index) const throw()
  42124. {
  42125. return atoms.getUnchecked (index);
  42126. }
  42127. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42128. {
  42129. if (other.atoms.size() > 0)
  42130. {
  42131. TextAtom* const lastAtom = atoms.getLast();
  42132. int i = 0;
  42133. if (lastAtom != 0)
  42134. {
  42135. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42136. {
  42137. TextAtom* const first = other.getAtom(0);
  42138. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42139. {
  42140. lastAtom->atomText += first->atomText;
  42141. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42142. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42143. delete first;
  42144. ++i;
  42145. }
  42146. }
  42147. }
  42148. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42149. while (i < other.atoms.size())
  42150. {
  42151. atoms.add (other.getAtom(i));
  42152. ++i;
  42153. }
  42154. }
  42155. }
  42156. UniformTextSection* split (const int indexToBreakAt,
  42157. const juce_wchar passwordCharacter)
  42158. {
  42159. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42160. font, colour,
  42161. passwordCharacter);
  42162. int index = 0;
  42163. for (int i = 0; i < atoms.size(); ++i)
  42164. {
  42165. TextAtom* const atom = getAtom(i);
  42166. const int nextIndex = index + atom->numChars;
  42167. if (index == indexToBreakAt)
  42168. {
  42169. int j;
  42170. for (j = i; j < atoms.size(); ++j)
  42171. section2->atoms.add (getAtom (j));
  42172. for (j = atoms.size(); --j >= i;)
  42173. atoms.remove (j);
  42174. break;
  42175. }
  42176. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42177. {
  42178. TextAtom* const secondAtom = new TextAtom();
  42179. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42180. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42181. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42182. section2->atoms.add (secondAtom);
  42183. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42184. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42185. atom->numChars = (uint16) (indexToBreakAt - index);
  42186. int j;
  42187. for (j = i + 1; j < atoms.size(); ++j)
  42188. section2->atoms.add (getAtom (j));
  42189. for (j = atoms.size(); --j > i;)
  42190. atoms.remove (j);
  42191. break;
  42192. }
  42193. index = nextIndex;
  42194. }
  42195. return section2;
  42196. }
  42197. void appendAllText (String::Concatenator& concatenator) const
  42198. {
  42199. for (int i = 0; i < atoms.size(); ++i)
  42200. concatenator.append (getAtom(i)->atomText);
  42201. }
  42202. void appendSubstring (String::Concatenator& concatenator,
  42203. const Range<int>& range) const
  42204. {
  42205. int index = 0;
  42206. for (int i = 0; i < atoms.size(); ++i)
  42207. {
  42208. const TextAtom* const atom = getAtom (i);
  42209. const int nextIndex = index + atom->numChars;
  42210. if (range.getStart() < nextIndex)
  42211. {
  42212. if (range.getEnd() <= index)
  42213. break;
  42214. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42215. if (! r.isEmpty())
  42216. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42217. }
  42218. index = nextIndex;
  42219. }
  42220. }
  42221. int getTotalLength() const
  42222. {
  42223. int total = 0;
  42224. for (int i = atoms.size(); --i >= 0;)
  42225. total += getAtom(i)->numChars;
  42226. return total;
  42227. }
  42228. void setFont (const Font& newFont,
  42229. const juce_wchar passwordCharacter)
  42230. {
  42231. if (font != newFont)
  42232. {
  42233. font = newFont;
  42234. for (int i = atoms.size(); --i >= 0;)
  42235. {
  42236. TextAtom* const atom = atoms.getUnchecked(i);
  42237. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42238. }
  42239. }
  42240. }
  42241. juce_UseDebuggingNewOperator
  42242. Font font;
  42243. Colour colour;
  42244. private:
  42245. Array <TextAtom*> atoms;
  42246. void initialiseAtoms (const String& textToParse,
  42247. const juce_wchar passwordCharacter)
  42248. {
  42249. int i = 0;
  42250. const int len = textToParse.length();
  42251. const juce_wchar* const text = textToParse;
  42252. while (i < len)
  42253. {
  42254. int start = i;
  42255. // create a whitespace atom unless it starts with non-ws
  42256. if (CharacterFunctions::isWhitespace (text[i])
  42257. && text[i] != '\r'
  42258. && text[i] != '\n')
  42259. {
  42260. while (i < len
  42261. && CharacterFunctions::isWhitespace (text[i])
  42262. && text[i] != '\r'
  42263. && text[i] != '\n')
  42264. {
  42265. ++i;
  42266. }
  42267. }
  42268. else
  42269. {
  42270. if (text[i] == '\r')
  42271. {
  42272. ++i;
  42273. if ((i < len) && (text[i] == '\n'))
  42274. {
  42275. ++start;
  42276. ++i;
  42277. }
  42278. }
  42279. else if (text[i] == '\n')
  42280. {
  42281. ++i;
  42282. }
  42283. else
  42284. {
  42285. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42286. ++i;
  42287. }
  42288. }
  42289. TextAtom* const atom = new TextAtom();
  42290. atom->atomText = String (text + start, i - start);
  42291. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42292. atom->numChars = (uint16) (i - start);
  42293. atoms.add (atom);
  42294. }
  42295. }
  42296. UniformTextSection& operator= (const UniformTextSection& other);
  42297. };
  42298. class TextEditor::Iterator
  42299. {
  42300. public:
  42301. Iterator (const Array <UniformTextSection*>& sections_,
  42302. const float wordWrapWidth_,
  42303. const juce_wchar passwordCharacter_)
  42304. : indexInText (0),
  42305. lineY (0),
  42306. lineHeight (0),
  42307. maxDescent (0),
  42308. atomX (0),
  42309. atomRight (0),
  42310. atom (0),
  42311. currentSection (0),
  42312. sections (sections_),
  42313. sectionIndex (0),
  42314. atomIndex (0),
  42315. wordWrapWidth (wordWrapWidth_),
  42316. passwordCharacter (passwordCharacter_)
  42317. {
  42318. jassert (wordWrapWidth_ > 0);
  42319. if (sections.size() > 0)
  42320. {
  42321. currentSection = sections.getUnchecked (sectionIndex);
  42322. if (currentSection != 0)
  42323. beginNewLine();
  42324. }
  42325. }
  42326. Iterator (const Iterator& other)
  42327. : indexInText (other.indexInText),
  42328. lineY (other.lineY),
  42329. lineHeight (other.lineHeight),
  42330. maxDescent (other.maxDescent),
  42331. atomX (other.atomX),
  42332. atomRight (other.atomRight),
  42333. atom (other.atom),
  42334. currentSection (other.currentSection),
  42335. sections (other.sections),
  42336. sectionIndex (other.sectionIndex),
  42337. atomIndex (other.atomIndex),
  42338. wordWrapWidth (other.wordWrapWidth),
  42339. passwordCharacter (other.passwordCharacter),
  42340. tempAtom (other.tempAtom)
  42341. {
  42342. }
  42343. ~Iterator()
  42344. {
  42345. }
  42346. bool next()
  42347. {
  42348. if (atom == &tempAtom)
  42349. {
  42350. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42351. if (numRemaining > 0)
  42352. {
  42353. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42354. atomX = 0;
  42355. if (tempAtom.numChars > 0)
  42356. lineY += lineHeight;
  42357. indexInText += tempAtom.numChars;
  42358. GlyphArrangement g;
  42359. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42360. int split;
  42361. for (split = 0; split < g.getNumGlyphs(); ++split)
  42362. if (shouldWrap (g.getGlyph (split).getRight()))
  42363. break;
  42364. if (split > 0 && split <= numRemaining)
  42365. {
  42366. tempAtom.numChars = (uint16) split;
  42367. tempAtom.width = g.getGlyph (split - 1).getRight();
  42368. atomRight = atomX + tempAtom.width;
  42369. return true;
  42370. }
  42371. }
  42372. }
  42373. bool forceNewLine = false;
  42374. if (sectionIndex >= sections.size())
  42375. {
  42376. moveToEndOfLastAtom();
  42377. return false;
  42378. }
  42379. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42380. {
  42381. if (atomIndex >= currentSection->getNumAtoms())
  42382. {
  42383. if (++sectionIndex >= sections.size())
  42384. {
  42385. moveToEndOfLastAtom();
  42386. return false;
  42387. }
  42388. atomIndex = 0;
  42389. currentSection = sections.getUnchecked (sectionIndex);
  42390. }
  42391. else
  42392. {
  42393. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42394. if (! lastAtom->isWhitespace())
  42395. {
  42396. // handle the case where the last atom in a section is actually part of the same
  42397. // word as the first atom of the next section...
  42398. float right = atomRight + lastAtom->width;
  42399. float lineHeight2 = lineHeight;
  42400. float maxDescent2 = maxDescent;
  42401. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42402. {
  42403. const UniformTextSection* const s = sections.getUnchecked (section);
  42404. if (s->getNumAtoms() == 0)
  42405. break;
  42406. const TextAtom* const nextAtom = s->getAtom (0);
  42407. if (nextAtom->isWhitespace())
  42408. break;
  42409. right += nextAtom->width;
  42410. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42411. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42412. if (shouldWrap (right))
  42413. {
  42414. lineHeight = lineHeight2;
  42415. maxDescent = maxDescent2;
  42416. forceNewLine = true;
  42417. break;
  42418. }
  42419. if (s->getNumAtoms() > 1)
  42420. break;
  42421. }
  42422. }
  42423. }
  42424. }
  42425. if (atom != 0)
  42426. {
  42427. atomX = atomRight;
  42428. indexInText += atom->numChars;
  42429. if (atom->isNewLine())
  42430. beginNewLine();
  42431. }
  42432. atom = currentSection->getAtom (atomIndex);
  42433. atomRight = atomX + atom->width;
  42434. ++atomIndex;
  42435. if (shouldWrap (atomRight) || forceNewLine)
  42436. {
  42437. if (atom->isWhitespace())
  42438. {
  42439. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42440. atomRight = jmin (atomRight, wordWrapWidth);
  42441. }
  42442. else
  42443. {
  42444. atomRight = atom->width;
  42445. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42446. {
  42447. tempAtom = *atom;
  42448. tempAtom.width = 0;
  42449. tempAtom.numChars = 0;
  42450. atom = &tempAtom;
  42451. if (atomX > 0)
  42452. beginNewLine();
  42453. return next();
  42454. }
  42455. beginNewLine();
  42456. return true;
  42457. }
  42458. }
  42459. return true;
  42460. }
  42461. void beginNewLine()
  42462. {
  42463. atomX = 0;
  42464. lineY += lineHeight;
  42465. int tempSectionIndex = sectionIndex;
  42466. int tempAtomIndex = atomIndex;
  42467. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42468. lineHeight = section->font.getHeight();
  42469. maxDescent = section->font.getDescent();
  42470. float x = (atom != 0) ? atom->width : 0;
  42471. while (! shouldWrap (x))
  42472. {
  42473. if (tempSectionIndex >= sections.size())
  42474. break;
  42475. bool checkSize = false;
  42476. if (tempAtomIndex >= section->getNumAtoms())
  42477. {
  42478. if (++tempSectionIndex >= sections.size())
  42479. break;
  42480. tempAtomIndex = 0;
  42481. section = sections.getUnchecked (tempSectionIndex);
  42482. checkSize = true;
  42483. }
  42484. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42485. if (nextAtom == 0)
  42486. break;
  42487. x += nextAtom->width;
  42488. if (shouldWrap (x) || nextAtom->isNewLine())
  42489. break;
  42490. if (checkSize)
  42491. {
  42492. lineHeight = jmax (lineHeight, section->font.getHeight());
  42493. maxDescent = jmax (maxDescent, section->font.getDescent());
  42494. }
  42495. ++tempAtomIndex;
  42496. }
  42497. }
  42498. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42499. {
  42500. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42501. {
  42502. if (lastSection != currentSection)
  42503. {
  42504. lastSection = currentSection;
  42505. g.setColour (currentSection->colour);
  42506. g.setFont (currentSection->font);
  42507. }
  42508. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42509. GlyphArrangement ga;
  42510. ga.addLineOfText (currentSection->font,
  42511. atom->getTrimmedText (passwordCharacter),
  42512. atomX,
  42513. (float) roundToInt (lineY + lineHeight - maxDescent));
  42514. ga.draw (g);
  42515. }
  42516. }
  42517. void drawSelection (Graphics& g,
  42518. const Range<int>& selection) const
  42519. {
  42520. const int startX = roundToInt (indexToX (selection.getStart()));
  42521. const int endX = roundToInt (indexToX (selection.getEnd()));
  42522. const int y = roundToInt (lineY);
  42523. const int nextY = roundToInt (lineY + lineHeight);
  42524. g.fillRect (startX, y, endX - startX, nextY - y);
  42525. }
  42526. void drawSelectedText (Graphics& g,
  42527. const Range<int>& selection,
  42528. const Colour& selectedTextColour) const
  42529. {
  42530. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42531. {
  42532. GlyphArrangement ga;
  42533. ga.addLineOfText (currentSection->font,
  42534. atom->getTrimmedText (passwordCharacter),
  42535. atomX,
  42536. (float) roundToInt (lineY + lineHeight - maxDescent));
  42537. if (selection.getEnd() < indexInText + atom->numChars)
  42538. {
  42539. GlyphArrangement ga2 (ga);
  42540. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42541. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42542. g.setColour (currentSection->colour);
  42543. ga2.draw (g);
  42544. }
  42545. if (selection.getStart() > indexInText)
  42546. {
  42547. GlyphArrangement ga2 (ga);
  42548. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42549. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42550. g.setColour (currentSection->colour);
  42551. ga2.draw (g);
  42552. }
  42553. g.setColour (selectedTextColour);
  42554. ga.draw (g);
  42555. }
  42556. }
  42557. float indexToX (const int indexToFind) const
  42558. {
  42559. if (indexToFind <= indexInText)
  42560. return atomX;
  42561. if (indexToFind >= indexInText + atom->numChars)
  42562. return atomRight;
  42563. GlyphArrangement g;
  42564. g.addLineOfText (currentSection->font,
  42565. atom->getText (passwordCharacter),
  42566. atomX, 0.0f);
  42567. if (indexToFind - indexInText >= g.getNumGlyphs())
  42568. return atomRight;
  42569. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42570. }
  42571. int xToIndex (const float xToFind) const
  42572. {
  42573. if (xToFind <= atomX || atom->isNewLine())
  42574. return indexInText;
  42575. if (xToFind >= atomRight)
  42576. return indexInText + atom->numChars;
  42577. GlyphArrangement g;
  42578. g.addLineOfText (currentSection->font,
  42579. atom->getText (passwordCharacter),
  42580. atomX, 0.0f);
  42581. int j;
  42582. for (j = 0; j < g.getNumGlyphs(); ++j)
  42583. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42584. break;
  42585. return indexInText + j;
  42586. }
  42587. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42588. {
  42589. while (next())
  42590. {
  42591. if (indexInText + atom->numChars > index)
  42592. {
  42593. cx = indexToX (index);
  42594. cy = lineY;
  42595. lineHeight_ = lineHeight;
  42596. return true;
  42597. }
  42598. }
  42599. cx = atomX;
  42600. cy = lineY;
  42601. lineHeight_ = lineHeight;
  42602. return false;
  42603. }
  42604. juce_UseDebuggingNewOperator
  42605. int indexInText;
  42606. float lineY, lineHeight, maxDescent;
  42607. float atomX, atomRight;
  42608. const TextAtom* atom;
  42609. const UniformTextSection* currentSection;
  42610. private:
  42611. const Array <UniformTextSection*>& sections;
  42612. int sectionIndex, atomIndex;
  42613. const float wordWrapWidth;
  42614. const juce_wchar passwordCharacter;
  42615. TextAtom tempAtom;
  42616. Iterator& operator= (const Iterator&);
  42617. void moveToEndOfLastAtom()
  42618. {
  42619. if (atom != 0)
  42620. {
  42621. atomX = atomRight;
  42622. if (atom->isNewLine())
  42623. {
  42624. atomX = 0.0f;
  42625. lineY += lineHeight;
  42626. }
  42627. }
  42628. }
  42629. bool shouldWrap (const float x) const
  42630. {
  42631. return (x - 0.0001f) >= wordWrapWidth;
  42632. }
  42633. };
  42634. class TextEditor::InsertAction : public UndoableAction
  42635. {
  42636. TextEditor& owner;
  42637. const String text;
  42638. const int insertIndex, oldCaretPos, newCaretPos;
  42639. const Font font;
  42640. const Colour colour;
  42641. InsertAction (const InsertAction&);
  42642. InsertAction& operator= (const InsertAction&);
  42643. public:
  42644. InsertAction (TextEditor& owner_,
  42645. const String& text_,
  42646. const int insertIndex_,
  42647. const Font& font_,
  42648. const Colour& colour_,
  42649. const int oldCaretPos_,
  42650. const int newCaretPos_)
  42651. : owner (owner_),
  42652. text (text_),
  42653. insertIndex (insertIndex_),
  42654. oldCaretPos (oldCaretPos_),
  42655. newCaretPos (newCaretPos_),
  42656. font (font_),
  42657. colour (colour_)
  42658. {
  42659. }
  42660. ~InsertAction()
  42661. {
  42662. }
  42663. bool perform()
  42664. {
  42665. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42666. return true;
  42667. }
  42668. bool undo()
  42669. {
  42670. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42671. return true;
  42672. }
  42673. int getSizeInUnits()
  42674. {
  42675. return text.length() + 16;
  42676. }
  42677. };
  42678. class TextEditor::RemoveAction : public UndoableAction
  42679. {
  42680. TextEditor& owner;
  42681. const Range<int> range;
  42682. const int oldCaretPos, newCaretPos;
  42683. Array <UniformTextSection*> removedSections;
  42684. RemoveAction (const RemoveAction&);
  42685. RemoveAction& operator= (const RemoveAction&);
  42686. public:
  42687. RemoveAction (TextEditor& owner_,
  42688. const Range<int> range_,
  42689. const int oldCaretPos_,
  42690. const int newCaretPos_,
  42691. const Array <UniformTextSection*>& removedSections_)
  42692. : owner (owner_),
  42693. range (range_),
  42694. oldCaretPos (oldCaretPos_),
  42695. newCaretPos (newCaretPos_),
  42696. removedSections (removedSections_)
  42697. {
  42698. }
  42699. ~RemoveAction()
  42700. {
  42701. for (int i = removedSections.size(); --i >= 0;)
  42702. {
  42703. UniformTextSection* const section = removedSections.getUnchecked (i);
  42704. section->clear();
  42705. delete section;
  42706. }
  42707. }
  42708. bool perform()
  42709. {
  42710. owner.remove (range, 0, newCaretPos);
  42711. return true;
  42712. }
  42713. bool undo()
  42714. {
  42715. owner.reinsert (range.getStart(), removedSections);
  42716. owner.moveCursorTo (oldCaretPos, false);
  42717. return true;
  42718. }
  42719. int getSizeInUnits()
  42720. {
  42721. int n = 0;
  42722. for (int i = removedSections.size(); --i >= 0;)
  42723. n += removedSections.getUnchecked (i)->getTotalLength();
  42724. return n + 16;
  42725. }
  42726. };
  42727. class TextEditor::TextHolderComponent : public Component,
  42728. public Timer,
  42729. public ValueListener
  42730. {
  42731. public:
  42732. TextHolderComponent (TextEditor& owner_)
  42733. : owner (owner_)
  42734. {
  42735. setWantsKeyboardFocus (false);
  42736. setInterceptsMouseClicks (false, true);
  42737. owner.getTextValue().addListener (this);
  42738. }
  42739. ~TextHolderComponent()
  42740. {
  42741. owner.getTextValue().removeListener (this);
  42742. }
  42743. void paint (Graphics& g)
  42744. {
  42745. owner.drawContent (g);
  42746. }
  42747. void timerCallback()
  42748. {
  42749. owner.timerCallbackInt();
  42750. }
  42751. const MouseCursor getMouseCursor()
  42752. {
  42753. return owner.getMouseCursor();
  42754. }
  42755. void valueChanged (Value&)
  42756. {
  42757. owner.textWasChangedByValue();
  42758. }
  42759. private:
  42760. TextEditor& owner;
  42761. TextHolderComponent (const TextHolderComponent&);
  42762. TextHolderComponent& operator= (const TextHolderComponent&);
  42763. };
  42764. class TextEditorViewport : public Viewport
  42765. {
  42766. public:
  42767. TextEditorViewport (TextEditor* const owner_)
  42768. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42769. {
  42770. }
  42771. ~TextEditorViewport()
  42772. {
  42773. }
  42774. void visibleAreaChanged (int, int, int, int)
  42775. {
  42776. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42777. // appear and disappear, causing the wrap width to change.
  42778. {
  42779. const float wordWrapWidth = owner->getWordWrapWidth();
  42780. if (wordWrapWidth != lastWordWrapWidth)
  42781. {
  42782. lastWordWrapWidth = wordWrapWidth;
  42783. rentrant = true;
  42784. owner->updateTextHolderSize();
  42785. rentrant = false;
  42786. }
  42787. }
  42788. }
  42789. private:
  42790. TextEditor* const owner;
  42791. float lastWordWrapWidth;
  42792. bool rentrant;
  42793. TextEditorViewport (const TextEditorViewport&);
  42794. TextEditorViewport& operator= (const TextEditorViewport&);
  42795. };
  42796. namespace TextEditorDefs
  42797. {
  42798. const int flashSpeedIntervalMs = 380;
  42799. const int textChangeMessageId = 0x10003001;
  42800. const int returnKeyMessageId = 0x10003002;
  42801. const int escapeKeyMessageId = 0x10003003;
  42802. const int focusLossMessageId = 0x10003004;
  42803. const int maxActionsPerTransaction = 100;
  42804. int getCharacterCategory (const juce_wchar character)
  42805. {
  42806. return CharacterFunctions::isLetterOrDigit (character)
  42807. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42808. }
  42809. }
  42810. TextEditor::TextEditor (const String& name,
  42811. const juce_wchar passwordCharacter_)
  42812. : Component (name),
  42813. borderSize (1, 1, 1, 3),
  42814. readOnly (false),
  42815. multiline (false),
  42816. wordWrap (false),
  42817. returnKeyStartsNewLine (false),
  42818. caretVisible (true),
  42819. popupMenuEnabled (true),
  42820. selectAllTextWhenFocused (false),
  42821. scrollbarVisible (true),
  42822. wasFocused (false),
  42823. caretFlashState (true),
  42824. keepCursorOnScreen (true),
  42825. tabKeyUsed (false),
  42826. menuActive (false),
  42827. valueTextNeedsUpdating (false),
  42828. cursorX (0),
  42829. cursorY (0),
  42830. cursorHeight (0),
  42831. maxTextLength (0),
  42832. leftIndent (4),
  42833. topIndent (4),
  42834. lastTransactionTime (0),
  42835. currentFont (14.0f),
  42836. totalNumChars (0),
  42837. caretPosition (0),
  42838. passwordCharacter (passwordCharacter_),
  42839. dragType (notDragging)
  42840. {
  42841. setOpaque (true);
  42842. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42843. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42844. viewport->setWantsKeyboardFocus (false);
  42845. viewport->setScrollBarsShown (false, false);
  42846. setMouseCursor (MouseCursor::IBeamCursor);
  42847. setWantsKeyboardFocus (true);
  42848. }
  42849. TextEditor::~TextEditor()
  42850. {
  42851. textValue.referTo (Value());
  42852. clearInternal (0);
  42853. viewport = 0;
  42854. textHolder = 0;
  42855. }
  42856. void TextEditor::newTransaction()
  42857. {
  42858. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42859. undoManager.beginNewTransaction();
  42860. }
  42861. void TextEditor::doUndoRedo (const bool isRedo)
  42862. {
  42863. if (! isReadOnly())
  42864. {
  42865. if (isRedo ? undoManager.redo()
  42866. : undoManager.undo())
  42867. {
  42868. scrollToMakeSureCursorIsVisible();
  42869. repaint();
  42870. textChanged();
  42871. }
  42872. }
  42873. }
  42874. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42875. const bool shouldWordWrap)
  42876. {
  42877. if (multiline != shouldBeMultiLine
  42878. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42879. {
  42880. multiline = shouldBeMultiLine;
  42881. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42882. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42883. scrollbarVisible && multiline);
  42884. viewport->setViewPosition (0, 0);
  42885. resized();
  42886. scrollToMakeSureCursorIsVisible();
  42887. }
  42888. }
  42889. bool TextEditor::isMultiLine() const
  42890. {
  42891. return multiline;
  42892. }
  42893. void TextEditor::setScrollbarsShown (bool shown)
  42894. {
  42895. if (scrollbarVisible != shown)
  42896. {
  42897. scrollbarVisible = shown;
  42898. shown = shown && isMultiLine();
  42899. viewport->setScrollBarsShown (shown, shown);
  42900. }
  42901. }
  42902. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42903. {
  42904. if (readOnly != shouldBeReadOnly)
  42905. {
  42906. readOnly = shouldBeReadOnly;
  42907. enablementChanged();
  42908. }
  42909. }
  42910. bool TextEditor::isReadOnly() const
  42911. {
  42912. return readOnly || ! isEnabled();
  42913. }
  42914. bool TextEditor::isTextInputActive() const
  42915. {
  42916. return ! isReadOnly();
  42917. }
  42918. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42919. {
  42920. returnKeyStartsNewLine = shouldStartNewLine;
  42921. }
  42922. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42923. {
  42924. tabKeyUsed = shouldTabKeyBeUsed;
  42925. }
  42926. void TextEditor::setPopupMenuEnabled (const bool b)
  42927. {
  42928. popupMenuEnabled = b;
  42929. }
  42930. void TextEditor::setSelectAllWhenFocused (const bool b)
  42931. {
  42932. selectAllTextWhenFocused = b;
  42933. }
  42934. const Font TextEditor::getFont() const
  42935. {
  42936. return currentFont;
  42937. }
  42938. void TextEditor::setFont (const Font& newFont)
  42939. {
  42940. currentFont = newFont;
  42941. scrollToMakeSureCursorIsVisible();
  42942. }
  42943. void TextEditor::applyFontToAllText (const Font& newFont)
  42944. {
  42945. currentFont = newFont;
  42946. const Colour overallColour (findColour (textColourId));
  42947. for (int i = sections.size(); --i >= 0;)
  42948. {
  42949. UniformTextSection* const uts = sections.getUnchecked (i);
  42950. uts->setFont (newFont, passwordCharacter);
  42951. uts->colour = overallColour;
  42952. }
  42953. coalesceSimilarSections();
  42954. updateTextHolderSize();
  42955. scrollToMakeSureCursorIsVisible();
  42956. repaint();
  42957. }
  42958. void TextEditor::colourChanged()
  42959. {
  42960. setOpaque (findColour (backgroundColourId).isOpaque());
  42961. repaint();
  42962. }
  42963. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42964. {
  42965. caretVisible = shouldCaretBeVisible;
  42966. if (shouldCaretBeVisible)
  42967. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42968. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42969. : MouseCursor::NormalCursor);
  42970. }
  42971. void TextEditor::setInputRestrictions (const int maxLen,
  42972. const String& chars)
  42973. {
  42974. maxTextLength = jmax (0, maxLen);
  42975. allowedCharacters = chars;
  42976. }
  42977. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42978. {
  42979. textToShowWhenEmpty = text;
  42980. colourForTextWhenEmpty = colourToUse;
  42981. }
  42982. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42983. {
  42984. if (passwordCharacter != newPasswordCharacter)
  42985. {
  42986. passwordCharacter = newPasswordCharacter;
  42987. resized();
  42988. repaint();
  42989. }
  42990. }
  42991. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42992. {
  42993. viewport->setScrollBarThickness (newThicknessPixels);
  42994. }
  42995. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42996. {
  42997. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42998. }
  42999. void TextEditor::clear()
  43000. {
  43001. clearInternal (0);
  43002. updateTextHolderSize();
  43003. undoManager.clearUndoHistory();
  43004. }
  43005. void TextEditor::setText (const String& newText,
  43006. const bool sendTextChangeMessage)
  43007. {
  43008. const int newLength = newText.length();
  43009. if (newLength != getTotalNumChars() || getText() != newText)
  43010. {
  43011. const int oldCursorPos = caretPosition;
  43012. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43013. clearInternal (0);
  43014. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43015. // if you're adding text with line-feeds to a single-line text editor, it
  43016. // ain't gonna look right!
  43017. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43018. if (cursorWasAtEnd && ! isMultiLine())
  43019. moveCursorTo (getTotalNumChars(), false);
  43020. else
  43021. moveCursorTo (oldCursorPos, false);
  43022. if (sendTextChangeMessage)
  43023. textChanged();
  43024. updateTextHolderSize();
  43025. scrollToMakeSureCursorIsVisible();
  43026. undoManager.clearUndoHistory();
  43027. repaint();
  43028. }
  43029. }
  43030. Value& TextEditor::getTextValue()
  43031. {
  43032. if (valueTextNeedsUpdating)
  43033. {
  43034. valueTextNeedsUpdating = false;
  43035. textValue = getText();
  43036. }
  43037. return textValue;
  43038. }
  43039. void TextEditor::textWasChangedByValue()
  43040. {
  43041. if (textValue.getValueSource().getReferenceCount() > 1)
  43042. setText (textValue.getValue());
  43043. }
  43044. void TextEditor::textChanged()
  43045. {
  43046. updateTextHolderSize();
  43047. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43048. if (textValue.getValueSource().getReferenceCount() > 1)
  43049. {
  43050. valueTextNeedsUpdating = false;
  43051. textValue = getText();
  43052. }
  43053. }
  43054. void TextEditor::returnPressed()
  43055. {
  43056. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43057. }
  43058. void TextEditor::escapePressed()
  43059. {
  43060. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43061. }
  43062. void TextEditor::addListener (TextEditorListener* const newListener)
  43063. {
  43064. listeners.add (newListener);
  43065. }
  43066. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  43067. {
  43068. listeners.remove (listenerToRemove);
  43069. }
  43070. void TextEditor::timerCallbackInt()
  43071. {
  43072. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43073. if (caretFlashState != newState)
  43074. {
  43075. caretFlashState = newState;
  43076. if (caretFlashState)
  43077. wasFocused = true;
  43078. if (caretVisible
  43079. && hasKeyboardFocus (false)
  43080. && ! isReadOnly())
  43081. {
  43082. repaintCaret();
  43083. }
  43084. }
  43085. const unsigned int now = Time::getApproximateMillisecondCounter();
  43086. if (now > lastTransactionTime + 200)
  43087. newTransaction();
  43088. }
  43089. void TextEditor::repaintCaret()
  43090. {
  43091. if (! findColour (caretColourId).isTransparent())
  43092. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43093. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43094. 4,
  43095. roundToInt (cursorHeight) + 2);
  43096. }
  43097. void TextEditor::repaintText (const Range<int>& range)
  43098. {
  43099. if (! range.isEmpty())
  43100. {
  43101. float x = 0, y = 0, lh = currentFont.getHeight();
  43102. const float wordWrapWidth = getWordWrapWidth();
  43103. if (wordWrapWidth > 0)
  43104. {
  43105. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43106. i.getCharPosition (range.getStart(), x, y, lh);
  43107. const int y1 = (int) y;
  43108. int y2;
  43109. if (range.getEnd() >= getTotalNumChars())
  43110. {
  43111. y2 = textHolder->getHeight();
  43112. }
  43113. else
  43114. {
  43115. i.getCharPosition (range.getEnd(), x, y, lh);
  43116. y2 = (int) (y + lh * 2.0f);
  43117. }
  43118. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43119. }
  43120. }
  43121. }
  43122. void TextEditor::moveCaret (int newCaretPos)
  43123. {
  43124. if (newCaretPos < 0)
  43125. newCaretPos = 0;
  43126. else if (newCaretPos > getTotalNumChars())
  43127. newCaretPos = getTotalNumChars();
  43128. if (newCaretPos != getCaretPosition())
  43129. {
  43130. repaintCaret();
  43131. caretFlashState = true;
  43132. caretPosition = newCaretPos;
  43133. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43134. scrollToMakeSureCursorIsVisible();
  43135. repaintCaret();
  43136. }
  43137. }
  43138. void TextEditor::setCaretPosition (const int newIndex)
  43139. {
  43140. moveCursorTo (newIndex, false);
  43141. }
  43142. int TextEditor::getCaretPosition() const
  43143. {
  43144. return caretPosition;
  43145. }
  43146. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43147. const int desiredCaretY)
  43148. {
  43149. updateCaretPosition();
  43150. int vx = roundToInt (cursorX) - desiredCaretX;
  43151. int vy = roundToInt (cursorY) - desiredCaretY;
  43152. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43153. {
  43154. vx += desiredCaretX - proportionOfWidth (0.2f);
  43155. }
  43156. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43157. {
  43158. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43159. }
  43160. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43161. if (! isMultiLine())
  43162. {
  43163. vy = viewport->getViewPositionY();
  43164. }
  43165. else
  43166. {
  43167. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43168. const int curH = roundToInt (cursorHeight);
  43169. if (desiredCaretY < 0)
  43170. {
  43171. vy = jmax (0, desiredCaretY + vy);
  43172. }
  43173. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43174. {
  43175. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43176. }
  43177. }
  43178. viewport->setViewPosition (vx, vy);
  43179. }
  43180. const Rectangle<int> TextEditor::getCaretRectangle()
  43181. {
  43182. updateCaretPosition();
  43183. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43184. roundToInt (cursorY) - viewport->getY(),
  43185. 1, roundToInt (cursorHeight));
  43186. }
  43187. float TextEditor::getWordWrapWidth() const
  43188. {
  43189. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43190. : 1.0e10f;
  43191. }
  43192. void TextEditor::updateTextHolderSize()
  43193. {
  43194. const float wordWrapWidth = getWordWrapWidth();
  43195. if (wordWrapWidth > 0)
  43196. {
  43197. float maxWidth = 0.0f;
  43198. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43199. while (i.next())
  43200. maxWidth = jmax (maxWidth, i.atomRight);
  43201. const int w = leftIndent + roundToInt (maxWidth);
  43202. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43203. currentFont.getHeight()));
  43204. textHolder->setSize (w + 1, h + 1);
  43205. }
  43206. }
  43207. int TextEditor::getTextWidth() const
  43208. {
  43209. return textHolder->getWidth();
  43210. }
  43211. int TextEditor::getTextHeight() const
  43212. {
  43213. return textHolder->getHeight();
  43214. }
  43215. void TextEditor::setIndents (const int newLeftIndent,
  43216. const int newTopIndent)
  43217. {
  43218. leftIndent = newLeftIndent;
  43219. topIndent = newTopIndent;
  43220. }
  43221. void TextEditor::setBorder (const BorderSize& border)
  43222. {
  43223. borderSize = border;
  43224. resized();
  43225. }
  43226. const BorderSize TextEditor::getBorder() const
  43227. {
  43228. return borderSize;
  43229. }
  43230. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43231. {
  43232. keepCursorOnScreen = shouldScrollToShowCursor;
  43233. }
  43234. void TextEditor::updateCaretPosition()
  43235. {
  43236. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43237. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43238. }
  43239. void TextEditor::scrollToMakeSureCursorIsVisible()
  43240. {
  43241. updateCaretPosition();
  43242. if (keepCursorOnScreen)
  43243. {
  43244. int x = viewport->getViewPositionX();
  43245. int y = viewport->getViewPositionY();
  43246. const int relativeCursorX = roundToInt (cursorX) - x;
  43247. const int relativeCursorY = roundToInt (cursorY) - y;
  43248. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43249. {
  43250. x += relativeCursorX - proportionOfWidth (0.2f);
  43251. }
  43252. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43253. {
  43254. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43255. }
  43256. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43257. if (! isMultiLine())
  43258. {
  43259. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43260. }
  43261. else
  43262. {
  43263. const int curH = roundToInt (cursorHeight);
  43264. if (relativeCursorY < 0)
  43265. {
  43266. y = jmax (0, relativeCursorY + y);
  43267. }
  43268. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43269. {
  43270. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43271. }
  43272. }
  43273. viewport->setViewPosition (x, y);
  43274. }
  43275. }
  43276. void TextEditor::moveCursorTo (const int newPosition,
  43277. const bool isSelecting)
  43278. {
  43279. if (isSelecting)
  43280. {
  43281. moveCaret (newPosition);
  43282. const Range<int> oldSelection (selection);
  43283. if (dragType == notDragging)
  43284. {
  43285. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43286. dragType = draggingSelectionStart;
  43287. else
  43288. dragType = draggingSelectionEnd;
  43289. }
  43290. if (dragType == draggingSelectionStart)
  43291. {
  43292. if (getCaretPosition() >= selection.getEnd())
  43293. dragType = draggingSelectionEnd;
  43294. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43295. }
  43296. else
  43297. {
  43298. if (getCaretPosition() < selection.getStart())
  43299. dragType = draggingSelectionStart;
  43300. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43301. }
  43302. repaintText (selection.getUnionWith (oldSelection));
  43303. }
  43304. else
  43305. {
  43306. dragType = notDragging;
  43307. repaintText (selection);
  43308. moveCaret (newPosition);
  43309. selection = Range<int>::emptyRange (getCaretPosition());
  43310. }
  43311. }
  43312. int TextEditor::getTextIndexAt (const int x,
  43313. const int y)
  43314. {
  43315. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43316. (float) (y + viewport->getViewPositionY() - topIndent));
  43317. }
  43318. void TextEditor::insertTextAtCaret (const String& newText_)
  43319. {
  43320. String newText (newText_);
  43321. if (allowedCharacters.isNotEmpty())
  43322. newText = newText.retainCharacters (allowedCharacters);
  43323. if ((! returnKeyStartsNewLine) && newText == "\n")
  43324. {
  43325. returnPressed();
  43326. return;
  43327. }
  43328. if (! isMultiLine())
  43329. newText = newText.replaceCharacters ("\r\n", " ");
  43330. else
  43331. newText = newText.replace ("\r\n", "\n");
  43332. const int newCaretPos = selection.getStart() + newText.length();
  43333. const int insertIndex = selection.getStart();
  43334. remove (selection, getUndoManager(),
  43335. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43336. if (maxTextLength > 0)
  43337. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43338. if (newText.isNotEmpty())
  43339. insert (newText,
  43340. insertIndex,
  43341. currentFont,
  43342. findColour (textColourId),
  43343. getUndoManager(),
  43344. newCaretPos);
  43345. textChanged();
  43346. }
  43347. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43348. {
  43349. moveCursorTo (newSelection.getStart(), false);
  43350. moveCursorTo (newSelection.getEnd(), true);
  43351. }
  43352. void TextEditor::copy()
  43353. {
  43354. if (passwordCharacter == 0)
  43355. {
  43356. const String selectedText (getHighlightedText());
  43357. if (selectedText.isNotEmpty())
  43358. SystemClipboard::copyTextToClipboard (selectedText);
  43359. }
  43360. }
  43361. void TextEditor::paste()
  43362. {
  43363. if (! isReadOnly())
  43364. {
  43365. const String clip (SystemClipboard::getTextFromClipboard());
  43366. if (clip.isNotEmpty())
  43367. insertTextAtCaret (clip);
  43368. }
  43369. }
  43370. void TextEditor::cut()
  43371. {
  43372. if (! isReadOnly())
  43373. {
  43374. moveCaret (selection.getEnd());
  43375. insertTextAtCaret (String::empty);
  43376. }
  43377. }
  43378. void TextEditor::drawContent (Graphics& g)
  43379. {
  43380. const float wordWrapWidth = getWordWrapWidth();
  43381. if (wordWrapWidth > 0)
  43382. {
  43383. g.setOrigin (leftIndent, topIndent);
  43384. const Rectangle<int> clip (g.getClipBounds());
  43385. Colour selectedTextColour;
  43386. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43387. while (i.lineY + 200.0 < clip.getY() && i.next())
  43388. {}
  43389. if (! selection.isEmpty())
  43390. {
  43391. g.setColour (findColour (highlightColourId)
  43392. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43393. selectedTextColour = findColour (highlightedTextColourId);
  43394. Iterator i2 (i);
  43395. while (i2.next() && i2.lineY < clip.getBottom())
  43396. {
  43397. if (i2.lineY + i2.lineHeight >= clip.getY()
  43398. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43399. {
  43400. i2.drawSelection (g, selection);
  43401. }
  43402. }
  43403. }
  43404. const UniformTextSection* lastSection = 0;
  43405. while (i.next() && i.lineY < clip.getBottom())
  43406. {
  43407. if (i.lineY + i.lineHeight >= clip.getY())
  43408. {
  43409. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43410. {
  43411. i.drawSelectedText (g, selection, selectedTextColour);
  43412. lastSection = 0;
  43413. }
  43414. else
  43415. {
  43416. i.draw (g, lastSection);
  43417. }
  43418. }
  43419. }
  43420. }
  43421. }
  43422. void TextEditor::paint (Graphics& g)
  43423. {
  43424. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43425. }
  43426. void TextEditor::paintOverChildren (Graphics& g)
  43427. {
  43428. if (caretFlashState
  43429. && hasKeyboardFocus (false)
  43430. && caretVisible
  43431. && ! isReadOnly())
  43432. {
  43433. g.setColour (findColour (caretColourId));
  43434. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43435. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43436. 2.0f, cursorHeight);
  43437. }
  43438. if (textToShowWhenEmpty.isNotEmpty()
  43439. && (! hasKeyboardFocus (false))
  43440. && getTotalNumChars() == 0)
  43441. {
  43442. g.setColour (colourForTextWhenEmpty);
  43443. g.setFont (getFont());
  43444. if (isMultiLine())
  43445. {
  43446. g.drawText (textToShowWhenEmpty,
  43447. 0, 0, getWidth(), getHeight(),
  43448. Justification::centred, true);
  43449. }
  43450. else
  43451. {
  43452. g.drawText (textToShowWhenEmpty,
  43453. leftIndent, topIndent,
  43454. viewport->getWidth() - leftIndent,
  43455. viewport->getHeight() - topIndent,
  43456. Justification::centredLeft, true);
  43457. }
  43458. }
  43459. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43460. }
  43461. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43462. {
  43463. public:
  43464. TextEditorMenuPerformer (TextEditor* const editor_)
  43465. : editor (editor_)
  43466. {
  43467. }
  43468. void modalStateFinished (int returnValue)
  43469. {
  43470. if (editor != 0 && returnValue != 0)
  43471. editor->performPopupMenuAction (returnValue);
  43472. }
  43473. private:
  43474. Component::SafePointer<TextEditor> editor;
  43475. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43476. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43477. };
  43478. void TextEditor::mouseDown (const MouseEvent& e)
  43479. {
  43480. beginDragAutoRepeat (100);
  43481. newTransaction();
  43482. if (wasFocused || ! selectAllTextWhenFocused)
  43483. {
  43484. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43485. {
  43486. moveCursorTo (getTextIndexAt (e.x, e.y),
  43487. e.mods.isShiftDown());
  43488. }
  43489. else
  43490. {
  43491. PopupMenu m;
  43492. m.setLookAndFeel (&getLookAndFeel());
  43493. addPopupMenuItems (m, &e);
  43494. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43495. }
  43496. }
  43497. }
  43498. void TextEditor::mouseDrag (const MouseEvent& e)
  43499. {
  43500. if (wasFocused || ! selectAllTextWhenFocused)
  43501. {
  43502. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43503. {
  43504. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43505. }
  43506. }
  43507. }
  43508. void TextEditor::mouseUp (const MouseEvent& e)
  43509. {
  43510. newTransaction();
  43511. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43512. if (wasFocused || ! selectAllTextWhenFocused)
  43513. {
  43514. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43515. {
  43516. moveCaret (getTextIndexAt (e.x, e.y));
  43517. }
  43518. }
  43519. wasFocused = true;
  43520. }
  43521. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43522. {
  43523. int tokenEnd = getTextIndexAt (e.x, e.y);
  43524. int tokenStart = tokenEnd;
  43525. if (e.getNumberOfClicks() > 3)
  43526. {
  43527. tokenStart = 0;
  43528. tokenEnd = getTotalNumChars();
  43529. }
  43530. else
  43531. {
  43532. const String t (getText());
  43533. const int totalLength = getTotalNumChars();
  43534. while (tokenEnd < totalLength)
  43535. {
  43536. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43537. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43538. ++tokenEnd;
  43539. else
  43540. break;
  43541. }
  43542. tokenStart = tokenEnd;
  43543. while (tokenStart > 0)
  43544. {
  43545. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43546. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43547. --tokenStart;
  43548. else
  43549. break;
  43550. }
  43551. if (e.getNumberOfClicks() > 2)
  43552. {
  43553. while (tokenEnd < totalLength)
  43554. {
  43555. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43556. ++tokenEnd;
  43557. else
  43558. break;
  43559. }
  43560. while (tokenStart > 0)
  43561. {
  43562. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43563. --tokenStart;
  43564. else
  43565. break;
  43566. }
  43567. }
  43568. }
  43569. moveCursorTo (tokenEnd, false);
  43570. moveCursorTo (tokenStart, true);
  43571. }
  43572. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43573. {
  43574. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43575. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43576. }
  43577. bool TextEditor::keyPressed (const KeyPress& key)
  43578. {
  43579. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43580. return false;
  43581. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43582. if (key.isKeyCode (KeyPress::leftKey)
  43583. || key.isKeyCode (KeyPress::upKey))
  43584. {
  43585. newTransaction();
  43586. int newPos;
  43587. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43588. newPos = indexAtPosition (cursorX, cursorY - 1);
  43589. else if (moveInWholeWordSteps)
  43590. newPos = findWordBreakBefore (getCaretPosition());
  43591. else
  43592. newPos = getCaretPosition() - 1;
  43593. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43594. }
  43595. else if (key.isKeyCode (KeyPress::rightKey)
  43596. || key.isKeyCode (KeyPress::downKey))
  43597. {
  43598. newTransaction();
  43599. int newPos;
  43600. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43601. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43602. else if (moveInWholeWordSteps)
  43603. newPos = findWordBreakAfter (getCaretPosition());
  43604. else
  43605. newPos = getCaretPosition() + 1;
  43606. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43607. }
  43608. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43609. {
  43610. newTransaction();
  43611. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43612. key.getModifiers().isShiftDown());
  43613. }
  43614. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43615. {
  43616. newTransaction();
  43617. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43618. key.getModifiers().isShiftDown());
  43619. }
  43620. else if (key.isKeyCode (KeyPress::homeKey))
  43621. {
  43622. newTransaction();
  43623. if (isMultiLine() && ! moveInWholeWordSteps)
  43624. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43625. key.getModifiers().isShiftDown());
  43626. else
  43627. moveCursorTo (0, key.getModifiers().isShiftDown());
  43628. }
  43629. else if (key.isKeyCode (KeyPress::endKey))
  43630. {
  43631. newTransaction();
  43632. if (isMultiLine() && ! moveInWholeWordSteps)
  43633. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43634. key.getModifiers().isShiftDown());
  43635. else
  43636. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43637. }
  43638. else if (key.isKeyCode (KeyPress::backspaceKey))
  43639. {
  43640. if (moveInWholeWordSteps)
  43641. {
  43642. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43643. }
  43644. else
  43645. {
  43646. if (selection.isEmpty() && selection.getStart() > 0)
  43647. selection.setStart (selection.getEnd() - 1);
  43648. }
  43649. cut();
  43650. }
  43651. else if (key.isKeyCode (KeyPress::deleteKey))
  43652. {
  43653. if (key.getModifiers().isShiftDown())
  43654. copy();
  43655. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43656. selection.setEnd (selection.getStart() + 1);
  43657. cut();
  43658. }
  43659. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43660. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43661. {
  43662. newTransaction();
  43663. copy();
  43664. }
  43665. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43666. {
  43667. newTransaction();
  43668. copy();
  43669. cut();
  43670. }
  43671. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43672. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43673. {
  43674. newTransaction();
  43675. paste();
  43676. }
  43677. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43678. {
  43679. newTransaction();
  43680. doUndoRedo (false);
  43681. }
  43682. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43683. {
  43684. newTransaction();
  43685. doUndoRedo (true);
  43686. }
  43687. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43688. {
  43689. newTransaction();
  43690. moveCursorTo (getTotalNumChars(), false);
  43691. moveCursorTo (0, true);
  43692. }
  43693. else if (key == KeyPress::returnKey)
  43694. {
  43695. newTransaction();
  43696. insertTextAtCaret ("\n");
  43697. }
  43698. else if (key.isKeyCode (KeyPress::escapeKey))
  43699. {
  43700. newTransaction();
  43701. moveCursorTo (getCaretPosition(), false);
  43702. escapePressed();
  43703. }
  43704. else if (key.getTextCharacter() >= ' '
  43705. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43706. {
  43707. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43708. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43709. }
  43710. else
  43711. {
  43712. return false;
  43713. }
  43714. return true;
  43715. }
  43716. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43717. {
  43718. if (! isKeyDown)
  43719. return false;
  43720. #if JUCE_WINDOWS
  43721. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43722. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43723. #endif
  43724. // (overridden to avoid forwarding key events to the parent)
  43725. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43726. }
  43727. const int baseMenuItemID = 0x7fff0000;
  43728. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43729. {
  43730. const bool writable = ! isReadOnly();
  43731. if (passwordCharacter == 0)
  43732. {
  43733. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43734. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43735. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43736. }
  43737. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43738. m.addSeparator();
  43739. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43740. m.addSeparator();
  43741. if (getUndoManager() != 0)
  43742. {
  43743. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43744. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43745. }
  43746. }
  43747. void TextEditor::performPopupMenuAction (const int menuItemID)
  43748. {
  43749. switch (menuItemID)
  43750. {
  43751. case baseMenuItemID + 1:
  43752. copy();
  43753. cut();
  43754. break;
  43755. case baseMenuItemID + 2:
  43756. copy();
  43757. break;
  43758. case baseMenuItemID + 3:
  43759. paste();
  43760. break;
  43761. case baseMenuItemID + 4:
  43762. cut();
  43763. break;
  43764. case baseMenuItemID + 5:
  43765. moveCursorTo (getTotalNumChars(), false);
  43766. moveCursorTo (0, true);
  43767. break;
  43768. case baseMenuItemID + 6:
  43769. doUndoRedo (false);
  43770. break;
  43771. case baseMenuItemID + 7:
  43772. doUndoRedo (true);
  43773. break;
  43774. default:
  43775. break;
  43776. }
  43777. }
  43778. void TextEditor::focusGained (FocusChangeType)
  43779. {
  43780. newTransaction();
  43781. caretFlashState = true;
  43782. if (selectAllTextWhenFocused)
  43783. {
  43784. moveCursorTo (0, false);
  43785. moveCursorTo (getTotalNumChars(), true);
  43786. }
  43787. repaint();
  43788. if (caretVisible)
  43789. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43790. ComponentPeer* const peer = getPeer();
  43791. if (peer != 0 && ! isReadOnly())
  43792. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43793. }
  43794. void TextEditor::focusLost (FocusChangeType)
  43795. {
  43796. newTransaction();
  43797. wasFocused = false;
  43798. textHolder->stopTimer();
  43799. caretFlashState = false;
  43800. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43801. repaint();
  43802. }
  43803. void TextEditor::resized()
  43804. {
  43805. viewport->setBoundsInset (borderSize);
  43806. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43807. updateTextHolderSize();
  43808. if (! isMultiLine())
  43809. {
  43810. scrollToMakeSureCursorIsVisible();
  43811. }
  43812. else
  43813. {
  43814. updateCaretPosition();
  43815. }
  43816. }
  43817. void TextEditor::handleCommandMessage (const int commandId)
  43818. {
  43819. Component::BailOutChecker checker (this);
  43820. switch (commandId)
  43821. {
  43822. case TextEditorDefs::textChangeMessageId:
  43823. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43824. break;
  43825. case TextEditorDefs::returnKeyMessageId:
  43826. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43827. break;
  43828. case TextEditorDefs::escapeKeyMessageId:
  43829. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43830. break;
  43831. case TextEditorDefs::focusLossMessageId:
  43832. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43833. break;
  43834. default:
  43835. jassertfalse;
  43836. break;
  43837. }
  43838. }
  43839. void TextEditor::enablementChanged()
  43840. {
  43841. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43842. : MouseCursor::IBeamCursor);
  43843. repaint();
  43844. }
  43845. UndoManager* TextEditor::getUndoManager() throw()
  43846. {
  43847. return isReadOnly() ? 0 : &undoManager;
  43848. }
  43849. void TextEditor::clearInternal (UndoManager* const um)
  43850. {
  43851. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43852. }
  43853. void TextEditor::insert (const String& text,
  43854. const int insertIndex,
  43855. const Font& font,
  43856. const Colour& colour,
  43857. UndoManager* const um,
  43858. const int caretPositionToMoveTo)
  43859. {
  43860. if (text.isNotEmpty())
  43861. {
  43862. if (um != 0)
  43863. {
  43864. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43865. newTransaction();
  43866. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43867. caretPosition, caretPositionToMoveTo));
  43868. }
  43869. else
  43870. {
  43871. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43872. // a line gets moved due to word wrap
  43873. int index = 0;
  43874. int nextIndex = 0;
  43875. for (int i = 0; i < sections.size(); ++i)
  43876. {
  43877. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43878. if (insertIndex == index)
  43879. {
  43880. sections.insert (i, new UniformTextSection (text,
  43881. font, colour,
  43882. passwordCharacter));
  43883. break;
  43884. }
  43885. else if (insertIndex > index && insertIndex < nextIndex)
  43886. {
  43887. splitSection (i, insertIndex - index);
  43888. sections.insert (i + 1, new UniformTextSection (text,
  43889. font, colour,
  43890. passwordCharacter));
  43891. break;
  43892. }
  43893. index = nextIndex;
  43894. }
  43895. if (nextIndex == insertIndex)
  43896. sections.add (new UniformTextSection (text,
  43897. font, colour,
  43898. passwordCharacter));
  43899. coalesceSimilarSections();
  43900. totalNumChars = -1;
  43901. valueTextNeedsUpdating = true;
  43902. moveCursorTo (caretPositionToMoveTo, false);
  43903. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43904. }
  43905. }
  43906. }
  43907. void TextEditor::reinsert (const int insertIndex,
  43908. const Array <UniformTextSection*>& sectionsToInsert)
  43909. {
  43910. int index = 0;
  43911. int nextIndex = 0;
  43912. for (int i = 0; i < sections.size(); ++i)
  43913. {
  43914. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43915. if (insertIndex == index)
  43916. {
  43917. for (int j = sectionsToInsert.size(); --j >= 0;)
  43918. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43919. break;
  43920. }
  43921. else if (insertIndex > index && insertIndex < nextIndex)
  43922. {
  43923. splitSection (i, insertIndex - index);
  43924. for (int j = sectionsToInsert.size(); --j >= 0;)
  43925. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43926. break;
  43927. }
  43928. index = nextIndex;
  43929. }
  43930. if (nextIndex == insertIndex)
  43931. {
  43932. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43933. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43934. }
  43935. coalesceSimilarSections();
  43936. totalNumChars = -1;
  43937. valueTextNeedsUpdating = true;
  43938. }
  43939. void TextEditor::remove (const Range<int>& range,
  43940. UndoManager* const um,
  43941. const int caretPositionToMoveTo)
  43942. {
  43943. if (! range.isEmpty())
  43944. {
  43945. int index = 0;
  43946. for (int i = 0; i < sections.size(); ++i)
  43947. {
  43948. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43949. if (range.getStart() > index && range.getStart() < nextIndex)
  43950. {
  43951. splitSection (i, range.getStart() - index);
  43952. --i;
  43953. }
  43954. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43955. {
  43956. splitSection (i, range.getEnd() - index);
  43957. --i;
  43958. }
  43959. else
  43960. {
  43961. index = nextIndex;
  43962. if (index > range.getEnd())
  43963. break;
  43964. }
  43965. }
  43966. index = 0;
  43967. if (um != 0)
  43968. {
  43969. Array <UniformTextSection*> removedSections;
  43970. for (int i = 0; i < sections.size(); ++i)
  43971. {
  43972. if (range.getEnd() <= range.getStart())
  43973. break;
  43974. UniformTextSection* const section = sections.getUnchecked (i);
  43975. const int nextIndex = index + section->getTotalLength();
  43976. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43977. removedSections.add (new UniformTextSection (*section));
  43978. index = nextIndex;
  43979. }
  43980. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43981. newTransaction();
  43982. um->perform (new RemoveAction (*this, range, caretPosition,
  43983. caretPositionToMoveTo, removedSections));
  43984. }
  43985. else
  43986. {
  43987. Range<int> remainingRange (range);
  43988. for (int i = 0; i < sections.size(); ++i)
  43989. {
  43990. UniformTextSection* const section = sections.getUnchecked (i);
  43991. const int nextIndex = index + section->getTotalLength();
  43992. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43993. {
  43994. sections.remove(i);
  43995. section->clear();
  43996. delete section;
  43997. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43998. if (remainingRange.isEmpty())
  43999. break;
  44000. --i;
  44001. }
  44002. else
  44003. {
  44004. index = nextIndex;
  44005. }
  44006. }
  44007. coalesceSimilarSections();
  44008. totalNumChars = -1;
  44009. valueTextNeedsUpdating = true;
  44010. moveCursorTo (caretPositionToMoveTo, false);
  44011. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44012. }
  44013. }
  44014. }
  44015. const String TextEditor::getText() const
  44016. {
  44017. String t;
  44018. t.preallocateStorage (getTotalNumChars());
  44019. String::Concatenator concatenator (t);
  44020. for (int i = 0; i < sections.size(); ++i)
  44021. sections.getUnchecked (i)->appendAllText (concatenator);
  44022. return t;
  44023. }
  44024. const String TextEditor::getTextInRange (const Range<int>& range) const
  44025. {
  44026. String t;
  44027. if (! range.isEmpty())
  44028. {
  44029. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44030. String::Concatenator concatenator (t);
  44031. int index = 0;
  44032. for (int i = 0; i < sections.size(); ++i)
  44033. {
  44034. const UniformTextSection* const s = sections.getUnchecked (i);
  44035. const int nextIndex = index + s->getTotalLength();
  44036. if (range.getStart() < nextIndex)
  44037. {
  44038. if (range.getEnd() <= index)
  44039. break;
  44040. s->appendSubstring (concatenator, range - index);
  44041. }
  44042. index = nextIndex;
  44043. }
  44044. }
  44045. return t;
  44046. }
  44047. const String TextEditor::getHighlightedText() const
  44048. {
  44049. return getTextInRange (selection);
  44050. }
  44051. int TextEditor::getTotalNumChars() const
  44052. {
  44053. if (totalNumChars < 0)
  44054. {
  44055. totalNumChars = 0;
  44056. for (int i = sections.size(); --i >= 0;)
  44057. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44058. }
  44059. return totalNumChars;
  44060. }
  44061. bool TextEditor::isEmpty() const
  44062. {
  44063. return getTotalNumChars() == 0;
  44064. }
  44065. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44066. {
  44067. const float wordWrapWidth = getWordWrapWidth();
  44068. if (wordWrapWidth > 0 && sections.size() > 0)
  44069. {
  44070. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44071. i.getCharPosition (index, cx, cy, lineHeight);
  44072. }
  44073. else
  44074. {
  44075. cx = cy = 0;
  44076. lineHeight = currentFont.getHeight();
  44077. }
  44078. }
  44079. int TextEditor::indexAtPosition (const float x, const float y)
  44080. {
  44081. const float wordWrapWidth = getWordWrapWidth();
  44082. if (wordWrapWidth > 0)
  44083. {
  44084. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44085. while (i.next())
  44086. {
  44087. if (i.lineY + i.lineHeight > y)
  44088. {
  44089. if (i.lineY > y)
  44090. return jmax (0, i.indexInText - 1);
  44091. if (i.atomX >= x)
  44092. return i.indexInText;
  44093. if (x < i.atomRight)
  44094. return i.xToIndex (x);
  44095. }
  44096. }
  44097. }
  44098. return getTotalNumChars();
  44099. }
  44100. int TextEditor::findWordBreakAfter (const int position) const
  44101. {
  44102. const String t (getTextInRange (Range<int> (position, position + 512)));
  44103. const int totalLength = t.length();
  44104. int i = 0;
  44105. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44106. ++i;
  44107. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44108. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44109. ++i;
  44110. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44111. ++i;
  44112. return position + i;
  44113. }
  44114. int TextEditor::findWordBreakBefore (const int position) const
  44115. {
  44116. if (position <= 0)
  44117. return 0;
  44118. const int startOfBuffer = jmax (0, position - 512);
  44119. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44120. int i = position - startOfBuffer;
  44121. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44122. --i;
  44123. if (i > 0)
  44124. {
  44125. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44126. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44127. --i;
  44128. }
  44129. jassert (startOfBuffer + i >= 0);
  44130. return startOfBuffer + i;
  44131. }
  44132. void TextEditor::splitSection (const int sectionIndex,
  44133. const int charToSplitAt)
  44134. {
  44135. jassert (sections[sectionIndex] != 0);
  44136. sections.insert (sectionIndex + 1,
  44137. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44138. }
  44139. void TextEditor::coalesceSimilarSections()
  44140. {
  44141. for (int i = 0; i < sections.size() - 1; ++i)
  44142. {
  44143. UniformTextSection* const s1 = sections.getUnchecked (i);
  44144. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44145. if (s1->font == s2->font
  44146. && s1->colour == s2->colour)
  44147. {
  44148. s1->append (*s2, passwordCharacter);
  44149. sections.remove (i + 1);
  44150. delete s2;
  44151. --i;
  44152. }
  44153. }
  44154. }
  44155. END_JUCE_NAMESPACE
  44156. /*** End of inlined file: juce_TextEditor.cpp ***/
  44157. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44158. BEGIN_JUCE_NAMESPACE
  44159. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44160. class ToolbarSpacerComp : public ToolbarItemComponent
  44161. {
  44162. public:
  44163. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44164. : ToolbarItemComponent (itemId_, String::empty, false),
  44165. fixedSize (fixedSize_),
  44166. drawBar (drawBar_)
  44167. {
  44168. }
  44169. ~ToolbarSpacerComp()
  44170. {
  44171. }
  44172. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44173. int& preferredSize, int& minSize, int& maxSize)
  44174. {
  44175. if (fixedSize <= 0)
  44176. {
  44177. preferredSize = toolbarThickness * 2;
  44178. minSize = 4;
  44179. maxSize = 32768;
  44180. }
  44181. else
  44182. {
  44183. maxSize = roundToInt (toolbarThickness * fixedSize);
  44184. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44185. preferredSize = maxSize;
  44186. if (getEditingMode() == editableOnPalette)
  44187. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44188. }
  44189. return true;
  44190. }
  44191. void paintButtonArea (Graphics&, int, int, bool, bool)
  44192. {
  44193. }
  44194. void contentAreaChanged (const Rectangle<int>&)
  44195. {
  44196. }
  44197. int getResizeOrder() const throw()
  44198. {
  44199. return fixedSize <= 0 ? 0 : 1;
  44200. }
  44201. void paint (Graphics& g)
  44202. {
  44203. const int w = getWidth();
  44204. const int h = getHeight();
  44205. if (drawBar)
  44206. {
  44207. g.setColour (findColour (Toolbar::separatorColourId, true));
  44208. const float thickness = 0.2f;
  44209. if (isToolbarVertical())
  44210. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44211. else
  44212. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44213. }
  44214. if (getEditingMode() != normalMode && ! drawBar)
  44215. {
  44216. g.setColour (findColour (Toolbar::separatorColourId, true));
  44217. const int indentX = jmin (2, (w - 3) / 2);
  44218. const int indentY = jmin (2, (h - 3) / 2);
  44219. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44220. if (fixedSize <= 0)
  44221. {
  44222. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44223. if (isToolbarVertical())
  44224. {
  44225. x1 = w * 0.5f;
  44226. y1 = h * 0.4f;
  44227. x2 = x1;
  44228. y2 = indentX * 2.0f;
  44229. x3 = x1;
  44230. y3 = h * 0.6f;
  44231. x4 = x1;
  44232. y4 = h - y2;
  44233. hw = w * 0.15f;
  44234. hl = w * 0.2f;
  44235. }
  44236. else
  44237. {
  44238. x1 = w * 0.4f;
  44239. y1 = h * 0.5f;
  44240. x2 = indentX * 2.0f;
  44241. y2 = y1;
  44242. x3 = w * 0.6f;
  44243. y3 = y1;
  44244. x4 = w - x2;
  44245. y4 = y1;
  44246. hw = h * 0.15f;
  44247. hl = h * 0.2f;
  44248. }
  44249. Path p;
  44250. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44251. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44252. g.fillPath (p);
  44253. }
  44254. }
  44255. }
  44256. juce_UseDebuggingNewOperator
  44257. private:
  44258. const float fixedSize;
  44259. const bool drawBar;
  44260. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44261. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44262. };
  44263. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44264. {
  44265. public:
  44266. MissingItemsComponent (Toolbar& owner_, const int height_)
  44267. : PopupMenuCustomComponent (true),
  44268. owner (&owner_),
  44269. height (height_)
  44270. {
  44271. for (int i = owner_.items.size(); --i >= 0;)
  44272. {
  44273. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44274. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44275. {
  44276. oldIndexes.insert (0, i);
  44277. addAndMakeVisible (tc, 0);
  44278. }
  44279. }
  44280. layout (400);
  44281. }
  44282. ~MissingItemsComponent()
  44283. {
  44284. if (owner != 0)
  44285. {
  44286. for (int i = 0; i < getNumChildComponents(); ++i)
  44287. {
  44288. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44289. if (tc != 0)
  44290. {
  44291. tc->setVisible (false);
  44292. const int index = oldIndexes.remove (i);
  44293. owner->addChildComponent (tc, index);
  44294. --i;
  44295. }
  44296. }
  44297. owner->resized();
  44298. }
  44299. }
  44300. void layout (const int preferredWidth)
  44301. {
  44302. const int indent = 8;
  44303. int x = indent;
  44304. int y = indent;
  44305. int maxX = 0;
  44306. for (int i = 0; i < getNumChildComponents(); ++i)
  44307. {
  44308. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44309. if (tc != 0)
  44310. {
  44311. int preferredSize = 1, minSize = 1, maxSize = 1;
  44312. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44313. {
  44314. if (x + preferredSize > preferredWidth && x > indent)
  44315. {
  44316. x = indent;
  44317. y += height;
  44318. }
  44319. tc->setBounds (x, y, preferredSize, height);
  44320. x += preferredSize;
  44321. maxX = jmax (maxX, x);
  44322. }
  44323. }
  44324. }
  44325. setSize (maxX + 8, y + height + 8);
  44326. }
  44327. void getIdealSize (int& idealWidth, int& idealHeight)
  44328. {
  44329. idealWidth = getWidth();
  44330. idealHeight = getHeight();
  44331. }
  44332. juce_UseDebuggingNewOperator
  44333. private:
  44334. Component::SafePointer<Toolbar> owner;
  44335. const int height;
  44336. Array <int> oldIndexes;
  44337. MissingItemsComponent (const MissingItemsComponent&);
  44338. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44339. };
  44340. Toolbar::Toolbar()
  44341. : vertical (false),
  44342. isEditingActive (false),
  44343. toolbarStyle (Toolbar::iconsOnly)
  44344. {
  44345. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44346. missingItemsButton->setAlwaysOnTop (true);
  44347. missingItemsButton->addButtonListener (this);
  44348. }
  44349. Toolbar::~Toolbar()
  44350. {
  44351. items.clear();
  44352. }
  44353. void Toolbar::setVertical (const bool shouldBeVertical)
  44354. {
  44355. if (vertical != shouldBeVertical)
  44356. {
  44357. vertical = shouldBeVertical;
  44358. resized();
  44359. }
  44360. }
  44361. void Toolbar::clear()
  44362. {
  44363. items.clear();
  44364. resized();
  44365. }
  44366. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44367. {
  44368. if (itemId == ToolbarItemFactory::separatorBarId)
  44369. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44370. else if (itemId == ToolbarItemFactory::spacerId)
  44371. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44372. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44373. return new ToolbarSpacerComp (itemId, 0, false);
  44374. return factory.createItem (itemId);
  44375. }
  44376. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44377. const int itemId,
  44378. const int insertIndex)
  44379. {
  44380. // An ID can't be zero - this might indicate a mistake somewhere?
  44381. jassert (itemId != 0);
  44382. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44383. if (tc != 0)
  44384. {
  44385. #if JUCE_DEBUG
  44386. Array <int> allowedIds;
  44387. factory.getAllToolbarItemIds (allowedIds);
  44388. // If your factory can create an item for a given ID, it must also return
  44389. // that ID from its getAllToolbarItemIds() method!
  44390. jassert (allowedIds.contains (itemId));
  44391. #endif
  44392. items.insert (insertIndex, tc);
  44393. addAndMakeVisible (tc, insertIndex);
  44394. }
  44395. }
  44396. void Toolbar::addItem (ToolbarItemFactory& factory,
  44397. const int itemId,
  44398. const int insertIndex)
  44399. {
  44400. addItemInternal (factory, itemId, insertIndex);
  44401. resized();
  44402. }
  44403. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44404. {
  44405. Array <int> ids;
  44406. factoryToUse.getDefaultItemSet (ids);
  44407. clear();
  44408. for (int i = 0; i < ids.size(); ++i)
  44409. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44410. resized();
  44411. }
  44412. void Toolbar::removeToolbarItem (const int itemIndex)
  44413. {
  44414. items.remove (itemIndex);
  44415. resized();
  44416. }
  44417. int Toolbar::getNumItems() const throw()
  44418. {
  44419. return items.size();
  44420. }
  44421. int Toolbar::getItemId (const int itemIndex) const throw()
  44422. {
  44423. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44424. return tc != 0 ? tc->getItemId() : 0;
  44425. }
  44426. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44427. {
  44428. return items [itemIndex];
  44429. }
  44430. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44431. {
  44432. for (;;)
  44433. {
  44434. index += delta;
  44435. ToolbarItemComponent* const tc = getItemComponent (index);
  44436. if (tc == 0)
  44437. break;
  44438. if (tc->isActive)
  44439. return tc;
  44440. }
  44441. return 0;
  44442. }
  44443. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44444. {
  44445. if (toolbarStyle != newStyle)
  44446. {
  44447. toolbarStyle = newStyle;
  44448. updateAllItemPositions (false);
  44449. }
  44450. }
  44451. const String Toolbar::toString() const
  44452. {
  44453. String s ("TB:");
  44454. for (int i = 0; i < getNumItems(); ++i)
  44455. s << getItemId(i) << ' ';
  44456. return s.trimEnd();
  44457. }
  44458. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44459. const String& savedVersion)
  44460. {
  44461. if (! savedVersion.startsWith ("TB:"))
  44462. return false;
  44463. StringArray tokens;
  44464. tokens.addTokens (savedVersion.substring (3), false);
  44465. clear();
  44466. for (int i = 0; i < tokens.size(); ++i)
  44467. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44468. resized();
  44469. return true;
  44470. }
  44471. void Toolbar::paint (Graphics& g)
  44472. {
  44473. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44474. }
  44475. int Toolbar::getThickness() const throw()
  44476. {
  44477. return vertical ? getWidth() : getHeight();
  44478. }
  44479. int Toolbar::getLength() const throw()
  44480. {
  44481. return vertical ? getHeight() : getWidth();
  44482. }
  44483. void Toolbar::setEditingActive (const bool active)
  44484. {
  44485. if (isEditingActive != active)
  44486. {
  44487. isEditingActive = active;
  44488. updateAllItemPositions (false);
  44489. }
  44490. }
  44491. void Toolbar::resized()
  44492. {
  44493. updateAllItemPositions (false);
  44494. }
  44495. void Toolbar::updateAllItemPositions (const bool animate)
  44496. {
  44497. if (getWidth() > 0 && getHeight() > 0)
  44498. {
  44499. StretchableObjectResizer resizer;
  44500. int i;
  44501. for (i = 0; i < items.size(); ++i)
  44502. {
  44503. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44504. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44505. : ToolbarItemComponent::normalMode);
  44506. tc->setStyle (toolbarStyle);
  44507. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44508. int preferredSize = 1, minSize = 1, maxSize = 1;
  44509. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44510. preferredSize, minSize, maxSize))
  44511. {
  44512. tc->isActive = true;
  44513. resizer.addItem (preferredSize, minSize, maxSize,
  44514. spacer != 0 ? spacer->getResizeOrder() : 2);
  44515. }
  44516. else
  44517. {
  44518. tc->isActive = false;
  44519. tc->setVisible (false);
  44520. }
  44521. }
  44522. resizer.resizeToFit (getLength());
  44523. int totalLength = 0;
  44524. for (i = 0; i < resizer.getNumItems(); ++i)
  44525. totalLength += (int) resizer.getItemSize (i);
  44526. const bool itemsOffTheEnd = totalLength > getLength();
  44527. const int extrasButtonSize = getThickness() / 2;
  44528. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44529. missingItemsButton->setVisible (itemsOffTheEnd);
  44530. missingItemsButton->setEnabled (! isEditingActive);
  44531. if (vertical)
  44532. missingItemsButton->setCentrePosition (getWidth() / 2,
  44533. getHeight() - 4 - extrasButtonSize / 2);
  44534. else
  44535. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44536. getHeight() / 2);
  44537. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44538. : missingItemsButton->getX()) - 4
  44539. : getLength();
  44540. int pos = 0, activeIndex = 0;
  44541. for (i = 0; i < items.size(); ++i)
  44542. {
  44543. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44544. if (tc->isActive)
  44545. {
  44546. const int size = (int) resizer.getItemSize (activeIndex++);
  44547. Rectangle<int> newBounds;
  44548. if (vertical)
  44549. newBounds.setBounds (0, pos, getWidth(), size);
  44550. else
  44551. newBounds.setBounds (pos, 0, size, getHeight());
  44552. if (animate)
  44553. {
  44554. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44555. }
  44556. else
  44557. {
  44558. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44559. tc->setBounds (newBounds);
  44560. }
  44561. pos += size;
  44562. tc->setVisible (pos <= maxLength
  44563. && ((! tc->isBeingDragged)
  44564. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44565. }
  44566. }
  44567. }
  44568. }
  44569. void Toolbar::buttonClicked (Button*)
  44570. {
  44571. jassert (missingItemsButton->isShowing());
  44572. if (missingItemsButton->isShowing())
  44573. {
  44574. PopupMenu m;
  44575. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44576. m.showAt (missingItemsButton);
  44577. }
  44578. }
  44579. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44580. Component* /*sourceComponent*/)
  44581. {
  44582. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44583. }
  44584. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44585. {
  44586. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44587. if (tc != 0)
  44588. {
  44589. if (! items.contains (tc))
  44590. {
  44591. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44592. {
  44593. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44594. if (palette != 0)
  44595. palette->replaceComponent (tc);
  44596. }
  44597. else
  44598. {
  44599. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44600. }
  44601. items.add (tc);
  44602. addChildComponent (tc);
  44603. updateAllItemPositions (true);
  44604. }
  44605. for (int i = getNumItems(); --i >= 0;)
  44606. {
  44607. const int currentIndex = items.indexOf (tc);
  44608. int newIndex = currentIndex;
  44609. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44610. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44611. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44612. .getComponentDestination (getChildComponent (newIndex)));
  44613. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44614. if (prev != 0)
  44615. {
  44616. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44617. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44618. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44619. {
  44620. newIndex = getIndexOfChildComponent (prev);
  44621. }
  44622. }
  44623. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44624. if (next != 0)
  44625. {
  44626. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44627. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44628. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44629. {
  44630. newIndex = getIndexOfChildComponent (next) + 1;
  44631. }
  44632. }
  44633. if (newIndex == currentIndex)
  44634. break;
  44635. items.removeObject (tc, false);
  44636. removeChildComponent (tc);
  44637. addChildComponent (tc, newIndex);
  44638. items.insert (newIndex, tc);
  44639. updateAllItemPositions (true);
  44640. }
  44641. }
  44642. }
  44643. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44644. {
  44645. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44646. if (tc != 0 && isParentOf (tc))
  44647. {
  44648. items.removeObject (tc, false);
  44649. removeChildComponent (tc);
  44650. updateAllItemPositions (true);
  44651. }
  44652. }
  44653. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44654. {
  44655. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44656. if (tc != 0)
  44657. tc->setState (Button::buttonNormal);
  44658. }
  44659. void Toolbar::mouseDown (const MouseEvent&)
  44660. {
  44661. }
  44662. class ToolbarCustomisationDialog : public DialogWindow
  44663. {
  44664. public:
  44665. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44666. Toolbar* const toolbar_,
  44667. const int optionFlags)
  44668. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44669. toolbar (toolbar_)
  44670. {
  44671. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44672. setResizable (true, true);
  44673. setResizeLimits (400, 300, 1500, 1000);
  44674. positionNearBar();
  44675. }
  44676. ~ToolbarCustomisationDialog()
  44677. {
  44678. setContentComponent (0, true);
  44679. }
  44680. void closeButtonPressed()
  44681. {
  44682. setVisible (false);
  44683. }
  44684. bool canModalEventBeSentToComponent (const Component* comp)
  44685. {
  44686. return toolbar->isParentOf (comp);
  44687. }
  44688. void positionNearBar()
  44689. {
  44690. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44691. const int tbx = toolbar->getScreenX();
  44692. const int tby = toolbar->getScreenY();
  44693. const int gap = 8;
  44694. int x, y;
  44695. if (toolbar->isVertical())
  44696. {
  44697. y = tby;
  44698. if (tbx > screenSize.getCentreX())
  44699. x = tbx - getWidth() - gap;
  44700. else
  44701. x = tbx + toolbar->getWidth() + gap;
  44702. }
  44703. else
  44704. {
  44705. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44706. if (tby > screenSize.getCentreY())
  44707. y = tby - getHeight() - gap;
  44708. else
  44709. y = tby + toolbar->getHeight() + gap;
  44710. }
  44711. setTopLeftPosition (x, y);
  44712. }
  44713. private:
  44714. Toolbar* const toolbar;
  44715. class CustomiserPanel : public Component,
  44716. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44717. private ButtonListener
  44718. {
  44719. public:
  44720. CustomiserPanel (ToolbarItemFactory& factory_,
  44721. Toolbar* const toolbar_,
  44722. const int optionFlags)
  44723. : factory (factory_),
  44724. toolbar (toolbar_),
  44725. palette (factory_, toolbar_),
  44726. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44727. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44728. defaultButton (TRANS ("Restore to default set of items"))
  44729. {
  44730. addAndMakeVisible (&palette);
  44731. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44732. | Toolbar::allowIconsWithTextChoice
  44733. | Toolbar::allowTextOnlyChoice)) != 0)
  44734. {
  44735. addAndMakeVisible (&styleBox);
  44736. styleBox.setEditableText (false);
  44737. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44738. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44739. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44740. int selectedStyle = 0;
  44741. switch (toolbar_->getStyle())
  44742. {
  44743. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44744. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44745. case Toolbar::textOnly: selectedStyle = 3; break;
  44746. }
  44747. styleBox.setSelectedId (selectedStyle);
  44748. styleBox.addListener (this);
  44749. }
  44750. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44751. {
  44752. addAndMakeVisible (&defaultButton);
  44753. defaultButton.addButtonListener (this);
  44754. }
  44755. addAndMakeVisible (&instructions);
  44756. instructions.setFont (Font (13.0f));
  44757. setSize (500, 300);
  44758. }
  44759. void comboBoxChanged (ComboBox*)
  44760. {
  44761. switch (styleBox.getSelectedId())
  44762. {
  44763. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44764. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44765. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44766. }
  44767. palette.resized(); // to make it update the styles
  44768. }
  44769. void buttonClicked (Button*)
  44770. {
  44771. toolbar->addDefaultItems (factory);
  44772. }
  44773. void paint (Graphics& g)
  44774. {
  44775. Colour background;
  44776. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44777. if (dw != 0)
  44778. background = dw->getBackgroundColour();
  44779. g.setColour (background.contrasting().withAlpha (0.3f));
  44780. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44781. }
  44782. void resized()
  44783. {
  44784. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44785. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44786. defaultButton.changeWidthToFitText (22);
  44787. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44788. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44789. }
  44790. private:
  44791. ToolbarItemFactory& factory;
  44792. Toolbar* const toolbar;
  44793. ToolbarItemPalette palette;
  44794. Label instructions;
  44795. ComboBox styleBox;
  44796. TextButton defaultButton;
  44797. };
  44798. };
  44799. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44800. {
  44801. setEditingActive (true);
  44802. #if JUCE_DEBUG
  44803. Component::SafePointer<Component> checker (this);
  44804. #endif
  44805. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44806. dw.runModalLoop();
  44807. #if JUCE_DEBUG
  44808. jassert (checker != 0); // Don't delete the toolbar while it's being customised!
  44809. #endif
  44810. setEditingActive (false);
  44811. }
  44812. END_JUCE_NAMESPACE
  44813. /*** End of inlined file: juce_Toolbar.cpp ***/
  44814. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44815. BEGIN_JUCE_NAMESPACE
  44816. ToolbarItemFactory::ToolbarItemFactory()
  44817. {
  44818. }
  44819. ToolbarItemFactory::~ToolbarItemFactory()
  44820. {
  44821. }
  44822. class ItemDragAndDropOverlayComponent : public Component
  44823. {
  44824. public:
  44825. ItemDragAndDropOverlayComponent()
  44826. : isDragging (false)
  44827. {
  44828. setAlwaysOnTop (true);
  44829. setRepaintsOnMouseActivity (true);
  44830. setMouseCursor (MouseCursor::DraggingHandCursor);
  44831. }
  44832. ~ItemDragAndDropOverlayComponent()
  44833. {
  44834. }
  44835. void paint (Graphics& g)
  44836. {
  44837. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44838. if (isMouseOverOrDragging()
  44839. && tc != 0
  44840. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44841. {
  44842. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44843. g.drawRect (0, 0, getWidth(), getHeight(),
  44844. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44845. }
  44846. }
  44847. void mouseDown (const MouseEvent& e)
  44848. {
  44849. isDragging = false;
  44850. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44851. if (tc != 0)
  44852. {
  44853. tc->dragOffsetX = e.x;
  44854. tc->dragOffsetY = e.y;
  44855. }
  44856. }
  44857. void mouseDrag (const MouseEvent& e)
  44858. {
  44859. if (! (isDragging || e.mouseWasClicked()))
  44860. {
  44861. isDragging = true;
  44862. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44863. if (dnd != 0)
  44864. {
  44865. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44866. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44867. if (tc != 0)
  44868. {
  44869. tc->isBeingDragged = true;
  44870. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44871. tc->setVisible (false);
  44872. }
  44873. }
  44874. }
  44875. }
  44876. void mouseUp (const MouseEvent&)
  44877. {
  44878. isDragging = false;
  44879. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44880. if (tc != 0)
  44881. {
  44882. tc->isBeingDragged = false;
  44883. Toolbar* const tb = tc->getToolbar();
  44884. if (tb != 0)
  44885. tb->updateAllItemPositions (true);
  44886. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44887. delete tc;
  44888. }
  44889. }
  44890. void parentSizeChanged()
  44891. {
  44892. setBounds (0, 0, getParentWidth(), getParentHeight());
  44893. }
  44894. juce_UseDebuggingNewOperator
  44895. private:
  44896. bool isDragging;
  44897. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44898. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44899. };
  44900. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44901. const String& labelText,
  44902. const bool isBeingUsedAsAButton_)
  44903. : Button (labelText),
  44904. itemId (itemId_),
  44905. mode (normalMode),
  44906. toolbarStyle (Toolbar::iconsOnly),
  44907. dragOffsetX (0),
  44908. dragOffsetY (0),
  44909. isActive (true),
  44910. isBeingDragged (false),
  44911. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44912. {
  44913. // Your item ID can't be 0!
  44914. jassert (itemId_ != 0);
  44915. }
  44916. ToolbarItemComponent::~ToolbarItemComponent()
  44917. {
  44918. overlayComp = 0;
  44919. }
  44920. Toolbar* ToolbarItemComponent::getToolbar() const
  44921. {
  44922. return dynamic_cast <Toolbar*> (getParentComponent());
  44923. }
  44924. bool ToolbarItemComponent::isToolbarVertical() const
  44925. {
  44926. const Toolbar* const t = getToolbar();
  44927. return t != 0 && t->isVertical();
  44928. }
  44929. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44930. {
  44931. if (toolbarStyle != newStyle)
  44932. {
  44933. toolbarStyle = newStyle;
  44934. repaint();
  44935. resized();
  44936. }
  44937. }
  44938. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44939. {
  44940. if (isBeingUsedAsAButton)
  44941. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44942. over, down, *this);
  44943. if (toolbarStyle != Toolbar::iconsOnly)
  44944. {
  44945. const int indent = contentArea.getX();
  44946. int y = indent;
  44947. int h = getHeight() - indent * 2;
  44948. if (toolbarStyle == Toolbar::iconsWithText)
  44949. {
  44950. y = contentArea.getBottom() + indent / 2;
  44951. h -= contentArea.getHeight();
  44952. }
  44953. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44954. getButtonText(), *this);
  44955. }
  44956. if (! contentArea.isEmpty())
  44957. {
  44958. g.saveState();
  44959. g.reduceClipRegion (contentArea);
  44960. g.setOrigin (contentArea.getX(), contentArea.getY());
  44961. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44962. g.restoreState();
  44963. }
  44964. }
  44965. void ToolbarItemComponent::resized()
  44966. {
  44967. if (toolbarStyle != Toolbar::textOnly)
  44968. {
  44969. const int indent = jmin (proportionOfWidth (0.08f),
  44970. proportionOfHeight (0.08f));
  44971. contentArea = Rectangle<int> (indent, indent,
  44972. getWidth() - indent * 2,
  44973. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44974. : (getHeight() - indent * 2));
  44975. }
  44976. else
  44977. {
  44978. contentArea = Rectangle<int>();
  44979. }
  44980. contentAreaChanged (contentArea);
  44981. }
  44982. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44983. {
  44984. if (mode != newMode)
  44985. {
  44986. mode = newMode;
  44987. repaint();
  44988. if (mode == normalMode)
  44989. {
  44990. overlayComp = 0;
  44991. }
  44992. else if (overlayComp == 0)
  44993. {
  44994. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44995. overlayComp->parentSizeChanged();
  44996. }
  44997. resized();
  44998. }
  44999. }
  45000. END_JUCE_NAMESPACE
  45001. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45002. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45003. BEGIN_JUCE_NAMESPACE
  45004. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45005. Toolbar* const toolbar_)
  45006. : factory (factory_),
  45007. toolbar (toolbar_)
  45008. {
  45009. Component* const itemHolder = new Component();
  45010. viewport.setViewedComponent (itemHolder);
  45011. Array <int> allIds;
  45012. factory.getAllToolbarItemIds (allIds);
  45013. for (int i = 0; i < allIds.size(); ++i)
  45014. addComponent (allIds.getUnchecked (i), -1);
  45015. addAndMakeVisible (&viewport);
  45016. }
  45017. ToolbarItemPalette::~ToolbarItemPalette()
  45018. {
  45019. }
  45020. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  45021. {
  45022. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  45023. jassert (tc != 0);
  45024. if (tc != 0)
  45025. {
  45026. items.insert (index, tc);
  45027. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  45028. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45029. }
  45030. }
  45031. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45032. {
  45033. const int index = items.indexOf (comp);
  45034. jassert (index >= 0);
  45035. items.removeObject (comp, false);
  45036. addComponent (comp->getItemId(), index);
  45037. resized();
  45038. }
  45039. void ToolbarItemPalette::resized()
  45040. {
  45041. viewport.setBoundsInset (BorderSize (1));
  45042. Component* const itemHolder = viewport.getViewedComponent();
  45043. const int indent = 8;
  45044. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  45045. const int height = toolbar->getThickness();
  45046. int x = indent;
  45047. int y = indent;
  45048. int maxX = 0;
  45049. for (int i = 0; i < items.size(); ++i)
  45050. {
  45051. ToolbarItemComponent* const tc = items.getUnchecked(i);
  45052. tc->setStyle (toolbar->getStyle());
  45053. int preferredSize = 1, minSize = 1, maxSize = 1;
  45054. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45055. {
  45056. if (x + preferredSize > preferredWidth && x > indent)
  45057. {
  45058. x = indent;
  45059. y += height;
  45060. }
  45061. tc->setBounds (x, y, preferredSize, height);
  45062. x += preferredSize + 8;
  45063. maxX = jmax (maxX, x);
  45064. }
  45065. }
  45066. itemHolder->setSize (maxX, y + height + 8);
  45067. }
  45068. END_JUCE_NAMESPACE
  45069. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45070. /*** Start of inlined file: juce_TreeView.cpp ***/
  45071. BEGIN_JUCE_NAMESPACE
  45072. class TreeViewContentComponent : public Component,
  45073. public TooltipClient
  45074. {
  45075. public:
  45076. TreeViewContentComponent (TreeView& owner_)
  45077. : owner (owner_),
  45078. buttonUnderMouse (0),
  45079. isDragging (false)
  45080. {
  45081. }
  45082. ~TreeViewContentComponent()
  45083. {
  45084. }
  45085. void mouseDown (const MouseEvent& e)
  45086. {
  45087. updateButtonUnderMouse (e);
  45088. isDragging = false;
  45089. needSelectionOnMouseUp = false;
  45090. Rectangle<int> pos;
  45091. TreeViewItem* const item = findItemAt (e.y, pos);
  45092. if (item == 0)
  45093. return;
  45094. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45095. // as selection clicks)
  45096. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45097. {
  45098. if (e.x >= pos.getX() - owner.getIndentSize())
  45099. item->setOpen (! item->isOpen());
  45100. // (clicks to the left of an open/close button are ignored)
  45101. }
  45102. else
  45103. {
  45104. // mouse-down inside the body of the item..
  45105. if (! owner.isMultiSelectEnabled())
  45106. item->setSelected (true, true);
  45107. else if (item->isSelected())
  45108. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45109. else
  45110. selectBasedOnModifiers (item, e.mods);
  45111. if (e.x >= pos.getX())
  45112. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45113. }
  45114. }
  45115. void mouseUp (const MouseEvent& e)
  45116. {
  45117. updateButtonUnderMouse (e);
  45118. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45119. {
  45120. Rectangle<int> pos;
  45121. TreeViewItem* const item = findItemAt (e.y, pos);
  45122. if (item != 0)
  45123. selectBasedOnModifiers (item, e.mods);
  45124. }
  45125. }
  45126. void mouseDoubleClick (const MouseEvent& e)
  45127. {
  45128. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45129. {
  45130. Rectangle<int> pos;
  45131. TreeViewItem* const item = findItemAt (e.y, pos);
  45132. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45133. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45134. }
  45135. }
  45136. void mouseDrag (const MouseEvent& e)
  45137. {
  45138. if (isEnabled()
  45139. && ! (isDragging || e.mouseWasClicked()
  45140. || e.getDistanceFromDragStart() < 5
  45141. || e.mods.isPopupMenu()))
  45142. {
  45143. isDragging = true;
  45144. Rectangle<int> pos;
  45145. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45146. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45147. {
  45148. const String dragDescription (item->getDragSourceDescription());
  45149. if (dragDescription.isNotEmpty())
  45150. {
  45151. DragAndDropContainer* const dragContainer
  45152. = DragAndDropContainer::findParentDragContainerFor (this);
  45153. if (dragContainer != 0)
  45154. {
  45155. pos.setSize (pos.getWidth(), item->itemHeight);
  45156. Image dragImage (Component::createComponentSnapshot (pos, true));
  45157. dragImage.multiplyAllAlphas (0.6f);
  45158. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45159. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45160. }
  45161. else
  45162. {
  45163. // to be able to do a drag-and-drop operation, the treeview needs to
  45164. // be inside a component which is also a DragAndDropContainer.
  45165. jassertfalse;
  45166. }
  45167. }
  45168. }
  45169. }
  45170. }
  45171. void mouseMove (const MouseEvent& e)
  45172. {
  45173. updateButtonUnderMouse (e);
  45174. }
  45175. void mouseExit (const MouseEvent& e)
  45176. {
  45177. updateButtonUnderMouse (e);
  45178. }
  45179. void paint (Graphics& g)
  45180. {
  45181. if (owner.rootItem != 0)
  45182. {
  45183. owner.handleAsyncUpdate();
  45184. if (! owner.rootItemVisible)
  45185. g.setOrigin (0, -owner.rootItem->itemHeight);
  45186. owner.rootItem->paintRecursively (g, getWidth());
  45187. }
  45188. }
  45189. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45190. {
  45191. if (owner.rootItem != 0)
  45192. {
  45193. owner.handleAsyncUpdate();
  45194. if (! owner.rootItemVisible)
  45195. y += owner.rootItem->itemHeight;
  45196. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45197. if (ti != 0)
  45198. itemPosition = ti->getItemPosition (false);
  45199. return ti;
  45200. }
  45201. return 0;
  45202. }
  45203. void updateComponents()
  45204. {
  45205. const int visibleTop = -getY();
  45206. const int visibleBottom = visibleTop + getParentHeight();
  45207. {
  45208. for (int i = items.size(); --i >= 0;)
  45209. items.getUnchecked(i)->shouldKeep = false;
  45210. }
  45211. {
  45212. TreeViewItem* item = owner.rootItem;
  45213. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45214. while (item != 0 && y < visibleBottom)
  45215. {
  45216. y += item->itemHeight;
  45217. if (y >= visibleTop)
  45218. {
  45219. RowItem* const ri = findItem (item->uid);
  45220. if (ri != 0)
  45221. {
  45222. ri->shouldKeep = true;
  45223. }
  45224. else
  45225. {
  45226. Component* const comp = item->createItemComponent();
  45227. if (comp != 0)
  45228. {
  45229. items.add (new RowItem (item, comp, item->uid));
  45230. addAndMakeVisible (comp);
  45231. }
  45232. }
  45233. }
  45234. item = item->getNextVisibleItem (true);
  45235. }
  45236. }
  45237. for (int i = items.size(); --i >= 0;)
  45238. {
  45239. RowItem* const ri = items.getUnchecked(i);
  45240. bool keep = false;
  45241. if (isParentOf (ri->component))
  45242. {
  45243. if (ri->shouldKeep)
  45244. {
  45245. Rectangle<int> pos (ri->item->getItemPosition (false));
  45246. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  45247. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45248. {
  45249. keep = true;
  45250. ri->component->setBounds (pos);
  45251. }
  45252. }
  45253. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  45254. {
  45255. keep = true;
  45256. ri->component->setSize (0, 0);
  45257. }
  45258. }
  45259. if (! keep)
  45260. items.remove (i);
  45261. }
  45262. }
  45263. void updateButtonUnderMouse (const MouseEvent& e)
  45264. {
  45265. TreeViewItem* newItem = 0;
  45266. if (owner.openCloseButtonsVisible)
  45267. {
  45268. Rectangle<int> pos;
  45269. TreeViewItem* item = findItemAt (e.y, pos);
  45270. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45271. {
  45272. newItem = item;
  45273. if (! newItem->mightContainSubItems())
  45274. newItem = 0;
  45275. }
  45276. }
  45277. if (buttonUnderMouse != newItem)
  45278. {
  45279. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45280. {
  45281. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45282. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45283. }
  45284. buttonUnderMouse = newItem;
  45285. if (buttonUnderMouse != 0)
  45286. {
  45287. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45288. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45289. }
  45290. }
  45291. }
  45292. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45293. {
  45294. return item == buttonUnderMouse;
  45295. }
  45296. void resized()
  45297. {
  45298. owner.itemsChanged();
  45299. }
  45300. const String getTooltip()
  45301. {
  45302. Rectangle<int> pos;
  45303. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45304. if (item != 0)
  45305. return item->getTooltip();
  45306. return owner.getTooltip();
  45307. }
  45308. juce_UseDebuggingNewOperator
  45309. private:
  45310. TreeView& owner;
  45311. struct RowItem
  45312. {
  45313. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45314. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45315. {
  45316. }
  45317. ~RowItem()
  45318. {
  45319. component.deleteAndZero();
  45320. }
  45321. Component::SafePointer<Component> component;
  45322. TreeViewItem* item;
  45323. int uid;
  45324. bool shouldKeep;
  45325. };
  45326. OwnedArray <RowItem> items;
  45327. TreeViewItem* buttonUnderMouse;
  45328. bool isDragging, needSelectionOnMouseUp;
  45329. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45330. {
  45331. TreeViewItem* firstSelected = 0;
  45332. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45333. {
  45334. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45335. jassert (lastSelected != 0);
  45336. int rowStart = firstSelected->getRowNumberInTree();
  45337. int rowEnd = lastSelected->getRowNumberInTree();
  45338. if (rowStart > rowEnd)
  45339. swapVariables (rowStart, rowEnd);
  45340. int ourRow = item->getRowNumberInTree();
  45341. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45342. if (ourRow > otherEnd)
  45343. swapVariables (ourRow, otherEnd);
  45344. for (int i = ourRow; i <= otherEnd; ++i)
  45345. owner.getItemOnRow (i)->setSelected (true, false);
  45346. }
  45347. else
  45348. {
  45349. const bool cmd = modifiers.isCommandDown();
  45350. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45351. }
  45352. }
  45353. bool containsItem (TreeViewItem* const item) const throw()
  45354. {
  45355. for (int i = items.size(); --i >= 0;)
  45356. if (items.getUnchecked(i)->item == item)
  45357. return true;
  45358. return false;
  45359. }
  45360. RowItem* findItem (const int uid) const throw()
  45361. {
  45362. for (int i = items.size(); --i >= 0;)
  45363. {
  45364. RowItem* const ri = items.getUnchecked(i);
  45365. if (ri->uid == uid)
  45366. return ri;
  45367. }
  45368. return 0;
  45369. }
  45370. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45371. {
  45372. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45373. {
  45374. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45375. if (source->isDragging())
  45376. {
  45377. Component* const underMouse = source->getComponentUnderMouse();
  45378. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45379. return true;
  45380. }
  45381. }
  45382. return false;
  45383. }
  45384. TreeViewContentComponent (const TreeViewContentComponent&);
  45385. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  45386. };
  45387. class TreeView::TreeViewport : public Viewport
  45388. {
  45389. public:
  45390. TreeViewport() throw() : lastX (-1) {}
  45391. ~TreeViewport() throw() {}
  45392. void updateComponents (const bool triggerResize = false)
  45393. {
  45394. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45395. if (tvc != 0)
  45396. {
  45397. if (triggerResize)
  45398. tvc->resized();
  45399. else
  45400. tvc->updateComponents();
  45401. }
  45402. repaint();
  45403. }
  45404. void visibleAreaChanged (int x, int, int, int)
  45405. {
  45406. const bool hasScrolledSideways = (x != lastX);
  45407. lastX = x;
  45408. updateComponents (hasScrolledSideways);
  45409. }
  45410. juce_UseDebuggingNewOperator
  45411. private:
  45412. int lastX;
  45413. TreeViewport (const TreeViewport&);
  45414. TreeViewport& operator= (const TreeViewport&);
  45415. };
  45416. TreeView::TreeView (const String& componentName)
  45417. : Component (componentName),
  45418. rootItem (0),
  45419. indentSize (24),
  45420. defaultOpenness (false),
  45421. needsRecalculating (true),
  45422. rootItemVisible (true),
  45423. multiSelectEnabled (false),
  45424. openCloseButtonsVisible (true)
  45425. {
  45426. addAndMakeVisible (viewport = new TreeViewport());
  45427. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45428. viewport->setWantsKeyboardFocus (false);
  45429. setWantsKeyboardFocus (true);
  45430. }
  45431. TreeView::~TreeView()
  45432. {
  45433. if (rootItem != 0)
  45434. rootItem->setOwnerView (0);
  45435. }
  45436. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45437. {
  45438. if (rootItem != newRootItem)
  45439. {
  45440. if (newRootItem != 0)
  45441. {
  45442. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45443. if (newRootItem->ownerView != 0)
  45444. newRootItem->ownerView->setRootItem (0);
  45445. }
  45446. if (rootItem != 0)
  45447. rootItem->setOwnerView (0);
  45448. rootItem = newRootItem;
  45449. if (newRootItem != 0)
  45450. newRootItem->setOwnerView (this);
  45451. needsRecalculating = true;
  45452. handleAsyncUpdate();
  45453. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45454. {
  45455. rootItem->setOpen (false); // force a re-open
  45456. rootItem->setOpen (true);
  45457. }
  45458. }
  45459. }
  45460. void TreeView::deleteRootItem()
  45461. {
  45462. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45463. setRootItem (0);
  45464. }
  45465. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45466. {
  45467. rootItemVisible = shouldBeVisible;
  45468. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45469. {
  45470. rootItem->setOpen (false); // force a re-open
  45471. rootItem->setOpen (true);
  45472. }
  45473. itemsChanged();
  45474. }
  45475. void TreeView::colourChanged()
  45476. {
  45477. setOpaque (findColour (backgroundColourId).isOpaque());
  45478. repaint();
  45479. }
  45480. void TreeView::setIndentSize (const int newIndentSize)
  45481. {
  45482. if (indentSize != newIndentSize)
  45483. {
  45484. indentSize = newIndentSize;
  45485. resized();
  45486. }
  45487. }
  45488. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45489. {
  45490. if (defaultOpenness != isOpenByDefault)
  45491. {
  45492. defaultOpenness = isOpenByDefault;
  45493. itemsChanged();
  45494. }
  45495. }
  45496. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45497. {
  45498. multiSelectEnabled = canMultiSelect;
  45499. }
  45500. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45501. {
  45502. if (openCloseButtonsVisible != shouldBeVisible)
  45503. {
  45504. openCloseButtonsVisible = shouldBeVisible;
  45505. itemsChanged();
  45506. }
  45507. }
  45508. Viewport* TreeView::getViewport() const throw()
  45509. {
  45510. return viewport;
  45511. }
  45512. void TreeView::clearSelectedItems()
  45513. {
  45514. if (rootItem != 0)
  45515. rootItem->deselectAllRecursively();
  45516. }
  45517. int TreeView::getNumSelectedItems() const throw()
  45518. {
  45519. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45520. }
  45521. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45522. {
  45523. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45524. }
  45525. int TreeView::getNumRowsInTree() const
  45526. {
  45527. if (rootItem != 0)
  45528. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45529. return 0;
  45530. }
  45531. TreeViewItem* TreeView::getItemOnRow (int index) const
  45532. {
  45533. if (! rootItemVisible)
  45534. ++index;
  45535. if (rootItem != 0 && index >= 0)
  45536. return rootItem->getItemOnRow (index);
  45537. return 0;
  45538. }
  45539. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45540. {
  45541. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45542. Rectangle<int> pos;
  45543. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45544. }
  45545. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45546. {
  45547. if (rootItem == 0)
  45548. return 0;
  45549. return rootItem->findItemFromIdentifierString (identifierString);
  45550. }
  45551. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45552. {
  45553. XmlElement* e = 0;
  45554. if (rootItem != 0)
  45555. {
  45556. e = rootItem->getOpennessState();
  45557. if (e != 0 && alsoIncludeScrollPosition)
  45558. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45559. }
  45560. return e;
  45561. }
  45562. void TreeView::restoreOpennessState (const XmlElement& newState)
  45563. {
  45564. if (rootItem != 0)
  45565. {
  45566. rootItem->restoreOpennessState (newState);
  45567. if (newState.hasAttribute ("scrollPos"))
  45568. viewport->setViewPosition (viewport->getViewPositionX(),
  45569. newState.getIntAttribute ("scrollPos"));
  45570. }
  45571. }
  45572. void TreeView::paint (Graphics& g)
  45573. {
  45574. g.fillAll (findColour (backgroundColourId));
  45575. }
  45576. void TreeView::resized()
  45577. {
  45578. viewport->setBounds (getLocalBounds());
  45579. itemsChanged();
  45580. handleAsyncUpdate();
  45581. }
  45582. void TreeView::enablementChanged()
  45583. {
  45584. repaint();
  45585. }
  45586. void TreeView::moveSelectedRow (int delta)
  45587. {
  45588. if (delta == 0)
  45589. return;
  45590. int rowSelected = 0;
  45591. TreeViewItem* const firstSelected = getSelectedItem (0);
  45592. if (firstSelected != 0)
  45593. rowSelected = firstSelected->getRowNumberInTree();
  45594. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45595. for (;;)
  45596. {
  45597. TreeViewItem* item = getItemOnRow (rowSelected);
  45598. if (item != 0)
  45599. {
  45600. if (! item->canBeSelected())
  45601. {
  45602. // if the row we want to highlight doesn't allow it, try skipping
  45603. // to the next item..
  45604. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45605. rowSelected + (delta < 0 ? -1 : 1));
  45606. if (rowSelected != nextRowToTry)
  45607. {
  45608. rowSelected = nextRowToTry;
  45609. continue;
  45610. }
  45611. else
  45612. {
  45613. break;
  45614. }
  45615. }
  45616. item->setSelected (true, true);
  45617. scrollToKeepItemVisible (item);
  45618. }
  45619. break;
  45620. }
  45621. }
  45622. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45623. {
  45624. if (item != 0 && item->ownerView == this)
  45625. {
  45626. handleAsyncUpdate();
  45627. item = item->getDeepestOpenParentItem();
  45628. int y = item->y;
  45629. int viewTop = viewport->getViewPositionY();
  45630. if (y < viewTop)
  45631. {
  45632. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45633. }
  45634. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45635. {
  45636. viewport->setViewPosition (viewport->getViewPositionX(),
  45637. (y + item->itemHeight) - viewport->getViewHeight());
  45638. }
  45639. }
  45640. }
  45641. bool TreeView::keyPressed (const KeyPress& key)
  45642. {
  45643. if (key.isKeyCode (KeyPress::upKey))
  45644. {
  45645. moveSelectedRow (-1);
  45646. }
  45647. else if (key.isKeyCode (KeyPress::downKey))
  45648. {
  45649. moveSelectedRow (1);
  45650. }
  45651. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45652. {
  45653. if (rootItem != 0)
  45654. {
  45655. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45656. if (key.isKeyCode (KeyPress::pageUpKey))
  45657. rowsOnScreen = -rowsOnScreen;
  45658. moveSelectedRow (rowsOnScreen);
  45659. }
  45660. }
  45661. else if (key.isKeyCode (KeyPress::homeKey))
  45662. {
  45663. moveSelectedRow (-0x3fffffff);
  45664. }
  45665. else if (key.isKeyCode (KeyPress::endKey))
  45666. {
  45667. moveSelectedRow (0x3fffffff);
  45668. }
  45669. else if (key.isKeyCode (KeyPress::returnKey))
  45670. {
  45671. TreeViewItem* const firstSelected = getSelectedItem (0);
  45672. if (firstSelected != 0)
  45673. firstSelected->setOpen (! firstSelected->isOpen());
  45674. }
  45675. else if (key.isKeyCode (KeyPress::leftKey))
  45676. {
  45677. TreeViewItem* const firstSelected = getSelectedItem (0);
  45678. if (firstSelected != 0)
  45679. {
  45680. if (firstSelected->isOpen())
  45681. {
  45682. firstSelected->setOpen (false);
  45683. }
  45684. else
  45685. {
  45686. TreeViewItem* parent = firstSelected->parentItem;
  45687. if ((! rootItemVisible) && parent == rootItem)
  45688. parent = 0;
  45689. if (parent != 0)
  45690. {
  45691. parent->setSelected (true, true);
  45692. scrollToKeepItemVisible (parent);
  45693. }
  45694. }
  45695. }
  45696. }
  45697. else if (key.isKeyCode (KeyPress::rightKey))
  45698. {
  45699. TreeViewItem* const firstSelected = getSelectedItem (0);
  45700. if (firstSelected != 0)
  45701. {
  45702. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45703. moveSelectedRow (1);
  45704. else
  45705. firstSelected->setOpen (true);
  45706. }
  45707. }
  45708. else
  45709. {
  45710. return false;
  45711. }
  45712. return true;
  45713. }
  45714. void TreeView::itemsChanged() throw()
  45715. {
  45716. needsRecalculating = true;
  45717. repaint();
  45718. triggerAsyncUpdate();
  45719. }
  45720. void TreeView::handleAsyncUpdate()
  45721. {
  45722. if (needsRecalculating)
  45723. {
  45724. needsRecalculating = false;
  45725. const ScopedLock sl (nodeAlterationLock);
  45726. if (rootItem != 0)
  45727. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45728. viewport->updateComponents();
  45729. if (rootItem != 0)
  45730. {
  45731. viewport->getViewedComponent()
  45732. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45733. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45734. }
  45735. else
  45736. {
  45737. viewport->getViewedComponent()->setSize (0, 0);
  45738. }
  45739. }
  45740. }
  45741. class TreeView::InsertPointHighlight : public Component
  45742. {
  45743. public:
  45744. InsertPointHighlight()
  45745. : lastItem (0)
  45746. {
  45747. setSize (100, 12);
  45748. setAlwaysOnTop (true);
  45749. setInterceptsMouseClicks (false, false);
  45750. }
  45751. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45752. {
  45753. lastItem = item;
  45754. lastIndex = insertIndex;
  45755. const int offset = getHeight() / 2;
  45756. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45757. }
  45758. void paint (Graphics& g)
  45759. {
  45760. Path p;
  45761. const float h = (float) getHeight();
  45762. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45763. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45764. p.lineTo ((float) getWidth(), h / 2.0f);
  45765. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45766. g.strokePath (p, PathStrokeType (2.0f));
  45767. }
  45768. TreeViewItem* lastItem;
  45769. int lastIndex;
  45770. private:
  45771. InsertPointHighlight (const InsertPointHighlight&);
  45772. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45773. };
  45774. class TreeView::TargetGroupHighlight : public Component
  45775. {
  45776. public:
  45777. TargetGroupHighlight()
  45778. {
  45779. setAlwaysOnTop (true);
  45780. setInterceptsMouseClicks (false, false);
  45781. }
  45782. void setTargetPosition (TreeViewItem* const item) throw()
  45783. {
  45784. Rectangle<int> r (item->getItemPosition (true));
  45785. r.setHeight (item->getItemHeight());
  45786. setBounds (r);
  45787. }
  45788. void paint (Graphics& g)
  45789. {
  45790. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45791. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45792. }
  45793. private:
  45794. TargetGroupHighlight (const TargetGroupHighlight&);
  45795. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45796. };
  45797. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45798. {
  45799. beginDragAutoRepeat (100);
  45800. if (dragInsertPointHighlight == 0)
  45801. {
  45802. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45803. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45804. }
  45805. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45806. dragTargetGroupHighlight->setTargetPosition (item);
  45807. }
  45808. void TreeView::hideDragHighlight() throw()
  45809. {
  45810. dragInsertPointHighlight = 0;
  45811. dragTargetGroupHighlight = 0;
  45812. }
  45813. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45814. const StringArray& files, const String& sourceDescription,
  45815. Component* sourceComponent) const throw()
  45816. {
  45817. insertIndex = 0;
  45818. TreeViewItem* item = getItemAt (y);
  45819. if (item == 0)
  45820. return 0;
  45821. Rectangle<int> itemPos (item->getItemPosition (true));
  45822. insertIndex = item->getIndexInParent();
  45823. const int oldY = y;
  45824. y = itemPos.getY();
  45825. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45826. {
  45827. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45828. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45829. {
  45830. // Check if we're trying to drag into an empty group item..
  45831. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45832. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45833. {
  45834. insertIndex = 0;
  45835. x = itemPos.getX() + getIndentSize();
  45836. y = itemPos.getBottom();
  45837. return item;
  45838. }
  45839. }
  45840. }
  45841. if (oldY > itemPos.getCentreY())
  45842. {
  45843. y += item->getItemHeight();
  45844. while (item->isLastOfSiblings() && item->parentItem != 0
  45845. && item->parentItem->parentItem != 0)
  45846. {
  45847. if (x > itemPos.getX())
  45848. break;
  45849. item = item->parentItem;
  45850. itemPos = item->getItemPosition (true);
  45851. insertIndex = item->getIndexInParent();
  45852. }
  45853. ++insertIndex;
  45854. }
  45855. x = itemPos.getX();
  45856. return item->parentItem;
  45857. }
  45858. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45859. {
  45860. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45861. int insertIndex;
  45862. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45863. if (item != 0)
  45864. {
  45865. if (scrolled || dragInsertPointHighlight == 0
  45866. || dragInsertPointHighlight->lastItem != item
  45867. || dragInsertPointHighlight->lastIndex != insertIndex)
  45868. {
  45869. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45870. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45871. showDragHighlight (item, insertIndex, x, y);
  45872. else
  45873. hideDragHighlight();
  45874. }
  45875. }
  45876. else
  45877. {
  45878. hideDragHighlight();
  45879. }
  45880. }
  45881. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45882. {
  45883. hideDragHighlight();
  45884. int insertIndex;
  45885. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45886. if (item != 0)
  45887. {
  45888. if (files.size() > 0)
  45889. {
  45890. if (item->isInterestedInFileDrag (files))
  45891. item->filesDropped (files, insertIndex);
  45892. }
  45893. else
  45894. {
  45895. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45896. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45897. }
  45898. }
  45899. }
  45900. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45901. {
  45902. return true;
  45903. }
  45904. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45905. {
  45906. fileDragMove (files, x, y);
  45907. }
  45908. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45909. {
  45910. handleDrag (files, String::empty, 0, x, y);
  45911. }
  45912. void TreeView::fileDragExit (const StringArray&)
  45913. {
  45914. hideDragHighlight();
  45915. }
  45916. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45917. {
  45918. handleDrop (files, String::empty, 0, x, y);
  45919. }
  45920. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45921. {
  45922. return true;
  45923. }
  45924. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45925. {
  45926. itemDragMove (sourceDescription, sourceComponent, x, y);
  45927. }
  45928. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45929. {
  45930. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45931. }
  45932. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45933. {
  45934. hideDragHighlight();
  45935. }
  45936. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45937. {
  45938. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45939. }
  45940. enum TreeViewOpenness
  45941. {
  45942. opennessDefault = 0,
  45943. opennessClosed = 1,
  45944. opennessOpen = 2
  45945. };
  45946. TreeViewItem::TreeViewItem()
  45947. : ownerView (0),
  45948. parentItem (0),
  45949. y (0),
  45950. itemHeight (0),
  45951. totalHeight (0),
  45952. selected (false),
  45953. redrawNeeded (true),
  45954. drawLinesInside (true),
  45955. drawsInLeftMargin (false),
  45956. openness (opennessDefault)
  45957. {
  45958. static int nextUID = 0;
  45959. uid = nextUID++;
  45960. }
  45961. TreeViewItem::~TreeViewItem()
  45962. {
  45963. }
  45964. const String TreeViewItem::getUniqueName() const
  45965. {
  45966. return String::empty;
  45967. }
  45968. void TreeViewItem::itemOpennessChanged (bool)
  45969. {
  45970. }
  45971. int TreeViewItem::getNumSubItems() const throw()
  45972. {
  45973. return subItems.size();
  45974. }
  45975. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45976. {
  45977. return subItems [index];
  45978. }
  45979. void TreeViewItem::clearSubItems()
  45980. {
  45981. if (subItems.size() > 0)
  45982. {
  45983. if (ownerView != 0)
  45984. {
  45985. const ScopedLock sl (ownerView->nodeAlterationLock);
  45986. subItems.clear();
  45987. treeHasChanged();
  45988. }
  45989. else
  45990. {
  45991. subItems.clear();
  45992. }
  45993. }
  45994. }
  45995. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45996. {
  45997. if (newItem != 0)
  45998. {
  45999. newItem->parentItem = this;
  46000. newItem->setOwnerView (ownerView);
  46001. newItem->y = 0;
  46002. newItem->itemHeight = newItem->getItemHeight();
  46003. newItem->totalHeight = 0;
  46004. newItem->itemWidth = newItem->getItemWidth();
  46005. newItem->totalWidth = 0;
  46006. if (ownerView != 0)
  46007. {
  46008. const ScopedLock sl (ownerView->nodeAlterationLock);
  46009. subItems.insert (insertPosition, newItem);
  46010. treeHasChanged();
  46011. if (newItem->isOpen())
  46012. newItem->itemOpennessChanged (true);
  46013. }
  46014. else
  46015. {
  46016. subItems.insert (insertPosition, newItem);
  46017. if (newItem->isOpen())
  46018. newItem->itemOpennessChanged (true);
  46019. }
  46020. }
  46021. }
  46022. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46023. {
  46024. if (ownerView != 0)
  46025. {
  46026. const ScopedLock sl (ownerView->nodeAlterationLock);
  46027. if (((unsigned int) index) < (unsigned int) subItems.size())
  46028. {
  46029. subItems.remove (index, deleteItem);
  46030. treeHasChanged();
  46031. }
  46032. }
  46033. else
  46034. {
  46035. subItems.remove (index, deleteItem);
  46036. }
  46037. }
  46038. bool TreeViewItem::isOpen() const throw()
  46039. {
  46040. if (openness == opennessDefault)
  46041. return ownerView != 0 && ownerView->defaultOpenness;
  46042. else
  46043. return openness == opennessOpen;
  46044. }
  46045. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46046. {
  46047. if (isOpen() != shouldBeOpen)
  46048. {
  46049. openness = shouldBeOpen ? opennessOpen
  46050. : opennessClosed;
  46051. treeHasChanged();
  46052. itemOpennessChanged (isOpen());
  46053. }
  46054. }
  46055. bool TreeViewItem::isSelected() const throw()
  46056. {
  46057. return selected;
  46058. }
  46059. void TreeViewItem::deselectAllRecursively()
  46060. {
  46061. setSelected (false, false);
  46062. for (int i = 0; i < subItems.size(); ++i)
  46063. subItems.getUnchecked(i)->deselectAllRecursively();
  46064. }
  46065. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46066. const bool deselectOtherItemsFirst)
  46067. {
  46068. if (shouldBeSelected && ! canBeSelected())
  46069. return;
  46070. if (deselectOtherItemsFirst)
  46071. getTopLevelItem()->deselectAllRecursively();
  46072. if (shouldBeSelected != selected)
  46073. {
  46074. selected = shouldBeSelected;
  46075. if (ownerView != 0)
  46076. ownerView->repaint();
  46077. itemSelectionChanged (shouldBeSelected);
  46078. }
  46079. }
  46080. void TreeViewItem::paintItem (Graphics&, int, int)
  46081. {
  46082. }
  46083. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46084. {
  46085. ownerView->getLookAndFeel()
  46086. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46087. }
  46088. void TreeViewItem::itemClicked (const MouseEvent&)
  46089. {
  46090. }
  46091. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46092. {
  46093. if (mightContainSubItems())
  46094. setOpen (! isOpen());
  46095. }
  46096. void TreeViewItem::itemSelectionChanged (bool)
  46097. {
  46098. }
  46099. const String TreeViewItem::getTooltip()
  46100. {
  46101. return String::empty;
  46102. }
  46103. const String TreeViewItem::getDragSourceDescription()
  46104. {
  46105. return String::empty;
  46106. }
  46107. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46108. {
  46109. return false;
  46110. }
  46111. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46112. {
  46113. }
  46114. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46115. {
  46116. return false;
  46117. }
  46118. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46119. {
  46120. }
  46121. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46122. {
  46123. const int indentX = getIndentX();
  46124. int width = itemWidth;
  46125. if (ownerView != 0 && width < 0)
  46126. width = ownerView->viewport->getViewWidth() - indentX;
  46127. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46128. if (relativeToTreeViewTopLeft)
  46129. r -= ownerView->viewport->getViewPosition();
  46130. return r;
  46131. }
  46132. void TreeViewItem::treeHasChanged() const throw()
  46133. {
  46134. if (ownerView != 0)
  46135. ownerView->itemsChanged();
  46136. }
  46137. void TreeViewItem::repaintItem() const
  46138. {
  46139. if (ownerView != 0 && areAllParentsOpen())
  46140. {
  46141. Rectangle<int> r (getItemPosition (true));
  46142. r.setLeft (0);
  46143. ownerView->viewport->repaint (r);
  46144. }
  46145. }
  46146. bool TreeViewItem::areAllParentsOpen() const throw()
  46147. {
  46148. return parentItem == 0
  46149. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46150. }
  46151. void TreeViewItem::updatePositions (int newY)
  46152. {
  46153. y = newY;
  46154. itemHeight = getItemHeight();
  46155. totalHeight = itemHeight;
  46156. itemWidth = getItemWidth();
  46157. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46158. if (isOpen())
  46159. {
  46160. newY += totalHeight;
  46161. for (int i = 0; i < subItems.size(); ++i)
  46162. {
  46163. TreeViewItem* const ti = subItems.getUnchecked(i);
  46164. ti->updatePositions (newY);
  46165. newY += ti->totalHeight;
  46166. totalHeight += ti->totalHeight;
  46167. totalWidth = jmax (totalWidth, ti->totalWidth);
  46168. }
  46169. }
  46170. }
  46171. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46172. {
  46173. TreeViewItem* result = this;
  46174. TreeViewItem* item = this;
  46175. while (item->parentItem != 0)
  46176. {
  46177. item = item->parentItem;
  46178. if (! item->isOpen())
  46179. result = item;
  46180. }
  46181. return result;
  46182. }
  46183. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46184. {
  46185. ownerView = newOwner;
  46186. for (int i = subItems.size(); --i >= 0;)
  46187. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46188. }
  46189. int TreeViewItem::getIndentX() const throw()
  46190. {
  46191. const int indentWidth = ownerView->getIndentSize();
  46192. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46193. if (! ownerView->openCloseButtonsVisible)
  46194. x -= indentWidth;
  46195. TreeViewItem* p = parentItem;
  46196. while (p != 0)
  46197. {
  46198. x += indentWidth;
  46199. p = p->parentItem;
  46200. }
  46201. return x;
  46202. }
  46203. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46204. {
  46205. drawsInLeftMargin = canDrawInLeftMargin;
  46206. }
  46207. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46208. {
  46209. jassert (ownerView != 0);
  46210. if (ownerView == 0)
  46211. return;
  46212. const int indent = getIndentX();
  46213. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46214. {
  46215. g.saveState();
  46216. g.setOrigin (indent, 0);
  46217. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46218. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46219. paintItem (g, itemW, itemHeight);
  46220. g.restoreState();
  46221. }
  46222. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46223. const float halfH = itemHeight * 0.5f;
  46224. int depth = 0;
  46225. TreeViewItem* p = parentItem;
  46226. while (p != 0)
  46227. {
  46228. ++depth;
  46229. p = p->parentItem;
  46230. }
  46231. if (! ownerView->rootItemVisible)
  46232. --depth;
  46233. const int indentWidth = ownerView->getIndentSize();
  46234. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46235. {
  46236. float x = (depth + 0.5f) * indentWidth;
  46237. if (depth >= 0)
  46238. {
  46239. if (parentItem != 0 && parentItem->drawLinesInside)
  46240. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46241. if ((parentItem != 0 && parentItem->drawLinesInside)
  46242. || (parentItem == 0 && drawLinesInside))
  46243. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46244. }
  46245. p = parentItem;
  46246. int d = depth;
  46247. while (p != 0 && --d >= 0)
  46248. {
  46249. x -= (float) indentWidth;
  46250. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46251. && ! p->isLastOfSiblings())
  46252. {
  46253. g.drawLine (x, 0, x, (float) itemHeight);
  46254. }
  46255. p = p->parentItem;
  46256. }
  46257. if (mightContainSubItems())
  46258. {
  46259. g.saveState();
  46260. g.setOrigin (depth * indentWidth, 0);
  46261. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46262. paintOpenCloseButton (g, indentWidth, itemHeight,
  46263. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46264. ->isMouseOverButton (this));
  46265. g.restoreState();
  46266. }
  46267. }
  46268. if (isOpen())
  46269. {
  46270. const Rectangle<int> clip (g.getClipBounds());
  46271. for (int i = 0; i < subItems.size(); ++i)
  46272. {
  46273. TreeViewItem* const ti = subItems.getUnchecked(i);
  46274. const int relY = ti->y - y;
  46275. if (relY >= clip.getBottom())
  46276. break;
  46277. if (relY + ti->totalHeight >= clip.getY())
  46278. {
  46279. g.saveState();
  46280. g.setOrigin (0, relY);
  46281. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46282. ti->paintRecursively (g, width);
  46283. g.restoreState();
  46284. }
  46285. }
  46286. }
  46287. }
  46288. bool TreeViewItem::isLastOfSiblings() const throw()
  46289. {
  46290. return parentItem == 0
  46291. || parentItem->subItems.getLast() == this;
  46292. }
  46293. int TreeViewItem::getIndexInParent() const throw()
  46294. {
  46295. return parentItem == 0 ? 0
  46296. : parentItem->subItems.indexOf (this);
  46297. }
  46298. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46299. {
  46300. return parentItem == 0 ? this
  46301. : parentItem->getTopLevelItem();
  46302. }
  46303. int TreeViewItem::getNumRows() const throw()
  46304. {
  46305. int num = 1;
  46306. if (isOpen())
  46307. {
  46308. for (int i = subItems.size(); --i >= 0;)
  46309. num += subItems.getUnchecked(i)->getNumRows();
  46310. }
  46311. return num;
  46312. }
  46313. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46314. {
  46315. if (index == 0)
  46316. return this;
  46317. if (index > 0 && isOpen())
  46318. {
  46319. --index;
  46320. for (int i = 0; i < subItems.size(); ++i)
  46321. {
  46322. TreeViewItem* const item = subItems.getUnchecked(i);
  46323. if (index == 0)
  46324. return item;
  46325. const int numRows = item->getNumRows();
  46326. if (numRows > index)
  46327. return item->getItemOnRow (index);
  46328. index -= numRows;
  46329. }
  46330. }
  46331. return 0;
  46332. }
  46333. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46334. {
  46335. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46336. {
  46337. const int h = itemHeight;
  46338. if (targetY < h)
  46339. return this;
  46340. if (isOpen())
  46341. {
  46342. targetY -= h;
  46343. for (int i = 0; i < subItems.size(); ++i)
  46344. {
  46345. TreeViewItem* const ti = subItems.getUnchecked(i);
  46346. if (targetY < ti->totalHeight)
  46347. return ti->findItemRecursively (targetY);
  46348. targetY -= ti->totalHeight;
  46349. }
  46350. }
  46351. }
  46352. return 0;
  46353. }
  46354. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46355. {
  46356. int total = isSelected() ? 1 : 0;
  46357. for (int i = subItems.size(); --i >= 0;)
  46358. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46359. return total;
  46360. }
  46361. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46362. {
  46363. if (isSelected())
  46364. {
  46365. if (index == 0)
  46366. return this;
  46367. --index;
  46368. }
  46369. if (index >= 0)
  46370. {
  46371. for (int i = 0; i < subItems.size(); ++i)
  46372. {
  46373. TreeViewItem* const item = subItems.getUnchecked(i);
  46374. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46375. if (found != 0)
  46376. return found;
  46377. index -= item->countSelectedItemsRecursively();
  46378. }
  46379. }
  46380. return 0;
  46381. }
  46382. int TreeViewItem::getRowNumberInTree() const throw()
  46383. {
  46384. if (parentItem != 0 && ownerView != 0)
  46385. {
  46386. int n = 1 + parentItem->getRowNumberInTree();
  46387. int ourIndex = parentItem->subItems.indexOf (this);
  46388. jassert (ourIndex >= 0);
  46389. while (--ourIndex >= 0)
  46390. n += parentItem->subItems [ourIndex]->getNumRows();
  46391. if (parentItem->parentItem == 0
  46392. && ! ownerView->rootItemVisible)
  46393. --n;
  46394. return n;
  46395. }
  46396. else
  46397. {
  46398. return 0;
  46399. }
  46400. }
  46401. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46402. {
  46403. drawLinesInside = drawLines;
  46404. }
  46405. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46406. {
  46407. if (recurse && isOpen() && subItems.size() > 0)
  46408. return subItems [0];
  46409. if (parentItem != 0)
  46410. {
  46411. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46412. if (nextIndex >= parentItem->subItems.size())
  46413. return parentItem->getNextVisibleItem (false);
  46414. return parentItem->subItems [nextIndex];
  46415. }
  46416. return 0;
  46417. }
  46418. const String TreeViewItem::getItemIdentifierString() const
  46419. {
  46420. String s;
  46421. if (parentItem != 0)
  46422. s = parentItem->getItemIdentifierString();
  46423. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46424. }
  46425. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46426. {
  46427. const String thisId (getUniqueName());
  46428. if (thisId == identifierString)
  46429. return this;
  46430. if (identifierString.startsWith (thisId + "/"))
  46431. {
  46432. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46433. bool wasOpen = isOpen();
  46434. setOpen (true);
  46435. for (int i = subItems.size(); --i >= 0;)
  46436. {
  46437. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46438. if (item != 0)
  46439. return item;
  46440. }
  46441. setOpen (wasOpen);
  46442. }
  46443. return 0;
  46444. }
  46445. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46446. {
  46447. if (e.hasTagName ("CLOSED"))
  46448. {
  46449. setOpen (false);
  46450. }
  46451. else if (e.hasTagName ("OPEN"))
  46452. {
  46453. setOpen (true);
  46454. forEachXmlChildElement (e, n)
  46455. {
  46456. const String id (n->getStringAttribute ("id"));
  46457. for (int i = 0; i < subItems.size(); ++i)
  46458. {
  46459. TreeViewItem* const ti = subItems.getUnchecked(i);
  46460. if (ti->getUniqueName() == id)
  46461. {
  46462. ti->restoreOpennessState (*n);
  46463. break;
  46464. }
  46465. }
  46466. }
  46467. }
  46468. }
  46469. XmlElement* TreeViewItem::getOpennessState() const throw()
  46470. {
  46471. const String name (getUniqueName());
  46472. if (name.isNotEmpty())
  46473. {
  46474. XmlElement* e;
  46475. if (isOpen())
  46476. {
  46477. e = new XmlElement ("OPEN");
  46478. for (int i = 0; i < subItems.size(); ++i)
  46479. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46480. }
  46481. else
  46482. {
  46483. e = new XmlElement ("CLOSED");
  46484. }
  46485. e->setAttribute ("id", name);
  46486. return e;
  46487. }
  46488. else
  46489. {
  46490. // trying to save the openness for an element that has no name - this won't
  46491. // work because it needs the names to identify what to open.
  46492. jassertfalse;
  46493. }
  46494. return 0;
  46495. }
  46496. END_JUCE_NAMESPACE
  46497. /*** End of inlined file: juce_TreeView.cpp ***/
  46498. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46499. BEGIN_JUCE_NAMESPACE
  46500. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46501. : fileList (listToShow)
  46502. {
  46503. }
  46504. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46505. {
  46506. }
  46507. FileBrowserListener::~FileBrowserListener()
  46508. {
  46509. }
  46510. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46511. {
  46512. listeners.add (listener);
  46513. }
  46514. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46515. {
  46516. listeners.remove (listener);
  46517. }
  46518. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46519. {
  46520. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46521. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46522. }
  46523. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46524. {
  46525. if (fileList.getDirectory().exists())
  46526. {
  46527. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46528. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46529. }
  46530. }
  46531. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46532. {
  46533. if (fileList.getDirectory().exists())
  46534. {
  46535. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46536. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46537. }
  46538. }
  46539. END_JUCE_NAMESPACE
  46540. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46541. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46542. BEGIN_JUCE_NAMESPACE
  46543. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46544. TimeSliceThread& thread_)
  46545. : fileFilter (fileFilter_),
  46546. thread (thread_),
  46547. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46548. fileFindHandle (0),
  46549. shouldStop (true)
  46550. {
  46551. }
  46552. DirectoryContentsList::~DirectoryContentsList()
  46553. {
  46554. clear();
  46555. }
  46556. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46557. {
  46558. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46559. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46560. }
  46561. bool DirectoryContentsList::ignoresHiddenFiles() const
  46562. {
  46563. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46564. }
  46565. const File& DirectoryContentsList::getDirectory() const
  46566. {
  46567. return root;
  46568. }
  46569. void DirectoryContentsList::setDirectory (const File& directory,
  46570. const bool includeDirectories,
  46571. const bool includeFiles)
  46572. {
  46573. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46574. if (directory != root)
  46575. {
  46576. clear();
  46577. root = directory;
  46578. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46579. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46580. }
  46581. int newFlags = fileTypeFlags;
  46582. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46583. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46584. setTypeFlags (newFlags);
  46585. }
  46586. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46587. {
  46588. if (fileTypeFlags != newFlags)
  46589. {
  46590. fileTypeFlags = newFlags;
  46591. refresh();
  46592. }
  46593. }
  46594. void DirectoryContentsList::clear()
  46595. {
  46596. shouldStop = true;
  46597. thread.removeTimeSliceClient (this);
  46598. fileFindHandle = 0;
  46599. if (files.size() > 0)
  46600. {
  46601. files.clear();
  46602. changed();
  46603. }
  46604. }
  46605. void DirectoryContentsList::refresh()
  46606. {
  46607. clear();
  46608. if (root.isDirectory())
  46609. {
  46610. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46611. shouldStop = false;
  46612. thread.addTimeSliceClient (this);
  46613. }
  46614. }
  46615. int DirectoryContentsList::getNumFiles() const
  46616. {
  46617. return files.size();
  46618. }
  46619. bool DirectoryContentsList::getFileInfo (const int index,
  46620. FileInfo& result) const
  46621. {
  46622. const ScopedLock sl (fileListLock);
  46623. const FileInfo* const info = files [index];
  46624. if (info != 0)
  46625. {
  46626. result = *info;
  46627. return true;
  46628. }
  46629. return false;
  46630. }
  46631. const File DirectoryContentsList::getFile (const int index) const
  46632. {
  46633. const ScopedLock sl (fileListLock);
  46634. const FileInfo* const info = files [index];
  46635. if (info != 0)
  46636. return root.getChildFile (info->filename);
  46637. return File::nonexistent;
  46638. }
  46639. bool DirectoryContentsList::isStillLoading() const
  46640. {
  46641. return fileFindHandle != 0;
  46642. }
  46643. void DirectoryContentsList::changed()
  46644. {
  46645. sendChangeMessage();
  46646. }
  46647. bool DirectoryContentsList::useTimeSlice()
  46648. {
  46649. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46650. bool hasChanged = false;
  46651. for (int i = 100; --i >= 0;)
  46652. {
  46653. if (! checkNextFile (hasChanged))
  46654. {
  46655. if (hasChanged)
  46656. changed();
  46657. return false;
  46658. }
  46659. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46660. break;
  46661. }
  46662. if (hasChanged)
  46663. changed();
  46664. return true;
  46665. }
  46666. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46667. {
  46668. if (fileFindHandle != 0)
  46669. {
  46670. bool fileFoundIsDir, isHidden, isReadOnly;
  46671. int64 fileSize;
  46672. Time modTime, creationTime;
  46673. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46674. &modTime, &creationTime, &isReadOnly))
  46675. {
  46676. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46677. fileSize, modTime, creationTime, isReadOnly))
  46678. {
  46679. hasChanged = true;
  46680. }
  46681. return true;
  46682. }
  46683. else
  46684. {
  46685. fileFindHandle = 0;
  46686. }
  46687. }
  46688. return false;
  46689. }
  46690. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46691. const DirectoryContentsList::FileInfo* const second)
  46692. {
  46693. #if JUCE_WINDOWS
  46694. if (first->isDirectory != second->isDirectory)
  46695. return first->isDirectory ? -1 : 1;
  46696. #endif
  46697. return first->filename.compareIgnoreCase (second->filename);
  46698. }
  46699. bool DirectoryContentsList::addFile (const File& file,
  46700. const bool isDir,
  46701. const int64 fileSize,
  46702. const Time& modTime,
  46703. const Time& creationTime,
  46704. const bool isReadOnly)
  46705. {
  46706. if (fileFilter == 0
  46707. || ((! isDir) && fileFilter->isFileSuitable (file))
  46708. || (isDir && fileFilter->isDirectorySuitable (file)))
  46709. {
  46710. ScopedPointer <FileInfo> info (new FileInfo());
  46711. info->filename = file.getFileName();
  46712. info->fileSize = fileSize;
  46713. info->modificationTime = modTime;
  46714. info->creationTime = creationTime;
  46715. info->isDirectory = isDir;
  46716. info->isReadOnly = isReadOnly;
  46717. const ScopedLock sl (fileListLock);
  46718. for (int i = files.size(); --i >= 0;)
  46719. if (files.getUnchecked(i)->filename == info->filename)
  46720. return false;
  46721. files.addSorted (*this, info.release());
  46722. return true;
  46723. }
  46724. return false;
  46725. }
  46726. END_JUCE_NAMESPACE
  46727. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46728. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46729. BEGIN_JUCE_NAMESPACE
  46730. FileBrowserComponent::FileBrowserComponent (int flags_,
  46731. const File& initialFileOrDirectory,
  46732. const FileFilter* fileFilter_,
  46733. FilePreviewComponent* previewComp_)
  46734. : FileFilter (String::empty),
  46735. fileFilter (fileFilter_),
  46736. flags (flags_),
  46737. previewComp (previewComp_),
  46738. currentPathBox ("path"),
  46739. fileLabel ("f", TRANS ("file:")),
  46740. thread ("Juce FileBrowser")
  46741. {
  46742. // You need to specify one or other of the open/save flags..
  46743. jassert ((flags & (saveMode | openMode)) != 0);
  46744. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46745. // You need to specify at least one of these flags..
  46746. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46747. String filename;
  46748. if (initialFileOrDirectory == File::nonexistent)
  46749. {
  46750. currentRoot = File::getCurrentWorkingDirectory();
  46751. }
  46752. else if (initialFileOrDirectory.isDirectory())
  46753. {
  46754. currentRoot = initialFileOrDirectory;
  46755. }
  46756. else
  46757. {
  46758. chosenFiles.add (initialFileOrDirectory);
  46759. currentRoot = initialFileOrDirectory.getParentDirectory();
  46760. filename = initialFileOrDirectory.getFileName();
  46761. }
  46762. fileList = new DirectoryContentsList (this, thread);
  46763. if ((flags & useTreeView) != 0)
  46764. {
  46765. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46766. fileListComponent = tree;
  46767. if ((flags & canSelectMultipleItems) != 0)
  46768. tree->setMultiSelectEnabled (true);
  46769. addAndMakeVisible (tree);
  46770. }
  46771. else
  46772. {
  46773. FileListComponent* const list = new FileListComponent (*fileList);
  46774. fileListComponent = list;
  46775. list->setOutlineThickness (1);
  46776. if ((flags & canSelectMultipleItems) != 0)
  46777. list->setMultipleSelectionEnabled (true);
  46778. addAndMakeVisible (list);
  46779. }
  46780. fileListComponent->addListener (this);
  46781. addAndMakeVisible (&currentPathBox);
  46782. currentPathBox.setEditableText (true);
  46783. StringArray rootNames, rootPaths;
  46784. const BigInteger separators (getRoots (rootNames, rootPaths));
  46785. for (int i = 0; i < rootNames.size(); ++i)
  46786. {
  46787. if (separators [i])
  46788. currentPathBox.addSeparator();
  46789. currentPathBox.addItem (rootNames[i], i + 1);
  46790. }
  46791. currentPathBox.addSeparator();
  46792. currentPathBox.addListener (this);
  46793. addAndMakeVisible (&filenameBox);
  46794. filenameBox.setMultiLine (false);
  46795. filenameBox.setSelectAllWhenFocused (true);
  46796. filenameBox.setText (filename, false);
  46797. filenameBox.addListener (this);
  46798. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46799. addAndMakeVisible (&fileLabel);
  46800. fileLabel.attachToComponent (&filenameBox, true);
  46801. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46802. goUpButton->addButtonListener (this);
  46803. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46804. if (previewComp != 0)
  46805. addAndMakeVisible (previewComp);
  46806. setRoot (currentRoot);
  46807. thread.startThread (4);
  46808. }
  46809. FileBrowserComponent::~FileBrowserComponent()
  46810. {
  46811. fileListComponent = 0;
  46812. fileList = 0;
  46813. thread.stopThread (10000);
  46814. }
  46815. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46816. {
  46817. listeners.add (newListener);
  46818. }
  46819. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46820. {
  46821. listeners.remove (listener);
  46822. }
  46823. bool FileBrowserComponent::isSaveMode() const throw()
  46824. {
  46825. return (flags & saveMode) != 0;
  46826. }
  46827. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46828. {
  46829. if (chosenFiles.size() == 0 && currentFileIsValid())
  46830. return 1;
  46831. return chosenFiles.size();
  46832. }
  46833. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46834. {
  46835. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46836. return currentRoot;
  46837. if (! filenameBox.isReadOnly())
  46838. return currentRoot.getChildFile (filenameBox.getText());
  46839. return chosenFiles[index];
  46840. }
  46841. bool FileBrowserComponent::currentFileIsValid() const
  46842. {
  46843. if (isSaveMode())
  46844. return ! getSelectedFile (0).isDirectory();
  46845. else
  46846. return getSelectedFile (0).exists();
  46847. }
  46848. const File FileBrowserComponent::getHighlightedFile() const throw()
  46849. {
  46850. return fileListComponent->getSelectedFile (0);
  46851. }
  46852. void FileBrowserComponent::deselectAllFiles()
  46853. {
  46854. fileListComponent->deselectAllFiles();
  46855. }
  46856. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46857. {
  46858. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46859. }
  46860. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46861. {
  46862. return true;
  46863. }
  46864. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46865. {
  46866. if (f.isDirectory())
  46867. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46868. return (flags & canSelectFiles) != 0 && f.exists()
  46869. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46870. }
  46871. const File FileBrowserComponent::getRoot() const
  46872. {
  46873. return currentRoot;
  46874. }
  46875. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46876. {
  46877. if (currentRoot != newRootDirectory)
  46878. {
  46879. fileListComponent->scrollToTop();
  46880. String path (newRootDirectory.getFullPathName());
  46881. if (path.isEmpty())
  46882. path = File::separatorString;
  46883. StringArray rootNames, rootPaths;
  46884. getRoots (rootNames, rootPaths);
  46885. if (! rootPaths.contains (path, true))
  46886. {
  46887. bool alreadyListed = false;
  46888. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46889. {
  46890. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46891. {
  46892. alreadyListed = true;
  46893. break;
  46894. }
  46895. }
  46896. if (! alreadyListed)
  46897. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46898. }
  46899. }
  46900. currentRoot = newRootDirectory;
  46901. fileList->setDirectory (currentRoot, true, true);
  46902. String currentRootName (currentRoot.getFullPathName());
  46903. if (currentRootName.isEmpty())
  46904. currentRootName = File::separatorString;
  46905. currentPathBox.setText (currentRootName, true);
  46906. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46907. && currentRoot.getParentDirectory() != currentRoot);
  46908. }
  46909. void FileBrowserComponent::goUp()
  46910. {
  46911. setRoot (getRoot().getParentDirectory());
  46912. }
  46913. void FileBrowserComponent::refresh()
  46914. {
  46915. fileList->refresh();
  46916. }
  46917. const String FileBrowserComponent::getActionVerb() const
  46918. {
  46919. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46920. }
  46921. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46922. {
  46923. return previewComp;
  46924. }
  46925. void FileBrowserComponent::resized()
  46926. {
  46927. getLookAndFeel()
  46928. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46929. &currentPathBox, &filenameBox, goUpButton);
  46930. }
  46931. void FileBrowserComponent::sendListenerChangeMessage()
  46932. {
  46933. Component::BailOutChecker checker (this);
  46934. if (previewComp != 0)
  46935. previewComp->selectedFileChanged (getSelectedFile (0));
  46936. // You shouldn't delete the browser when the file gets changed!
  46937. jassert (! checker.shouldBailOut());
  46938. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46939. }
  46940. void FileBrowserComponent::selectionChanged()
  46941. {
  46942. StringArray newFilenames;
  46943. bool resetChosenFiles = true;
  46944. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46945. {
  46946. const File f (fileListComponent->getSelectedFile (i));
  46947. if (isFileOrDirSuitable (f))
  46948. {
  46949. if (resetChosenFiles)
  46950. {
  46951. chosenFiles.clear();
  46952. resetChosenFiles = false;
  46953. }
  46954. chosenFiles.add (f);
  46955. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46956. }
  46957. }
  46958. if (newFilenames.size() > 0)
  46959. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46960. sendListenerChangeMessage();
  46961. }
  46962. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46963. {
  46964. Component::BailOutChecker checker (this);
  46965. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46966. }
  46967. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46968. {
  46969. if (f.isDirectory())
  46970. {
  46971. setRoot (f);
  46972. if ((flags & canSelectDirectories) != 0)
  46973. filenameBox.setText (String::empty);
  46974. }
  46975. else
  46976. {
  46977. Component::BailOutChecker checker (this);
  46978. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46979. }
  46980. }
  46981. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46982. {
  46983. (void) key;
  46984. #if JUCE_LINUX || JUCE_WINDOWS
  46985. if (key.getModifiers().isCommandDown()
  46986. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46987. {
  46988. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46989. fileList->refresh();
  46990. return true;
  46991. }
  46992. #endif
  46993. return false;
  46994. }
  46995. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46996. {
  46997. sendListenerChangeMessage();
  46998. }
  46999. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47000. {
  47001. if (filenameBox.getText().containsChar (File::separator))
  47002. {
  47003. const File f (currentRoot.getChildFile (filenameBox.getText()));
  47004. if (f.isDirectory())
  47005. {
  47006. setRoot (f);
  47007. chosenFiles.clear();
  47008. filenameBox.setText (String::empty);
  47009. }
  47010. else
  47011. {
  47012. setRoot (f.getParentDirectory());
  47013. chosenFiles.clear();
  47014. chosenFiles.add (f);
  47015. filenameBox.setText (f.getFileName());
  47016. }
  47017. }
  47018. else
  47019. {
  47020. fileDoubleClicked (getSelectedFile (0));
  47021. }
  47022. }
  47023. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47024. {
  47025. }
  47026. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47027. {
  47028. if (! isSaveMode())
  47029. selectionChanged();
  47030. }
  47031. void FileBrowserComponent::buttonClicked (Button*)
  47032. {
  47033. goUp();
  47034. }
  47035. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47036. {
  47037. const String newText (currentPathBox.getText().trim().unquoted());
  47038. if (newText.isNotEmpty())
  47039. {
  47040. const int index = currentPathBox.getSelectedId() - 1;
  47041. StringArray rootNames, rootPaths;
  47042. getRoots (rootNames, rootPaths);
  47043. if (rootPaths [index].isNotEmpty())
  47044. {
  47045. setRoot (File (rootPaths [index]));
  47046. }
  47047. else
  47048. {
  47049. File f (newText);
  47050. for (;;)
  47051. {
  47052. if (f.isDirectory())
  47053. {
  47054. setRoot (f);
  47055. break;
  47056. }
  47057. if (f.getParentDirectory() == f)
  47058. break;
  47059. f = f.getParentDirectory();
  47060. }
  47061. }
  47062. }
  47063. }
  47064. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47065. {
  47066. BigInteger separators;
  47067. #if JUCE_WINDOWS
  47068. Array<File> roots;
  47069. File::findFileSystemRoots (roots);
  47070. rootPaths.clear();
  47071. for (int i = 0; i < roots.size(); ++i)
  47072. {
  47073. const File& drive = roots.getReference(i);
  47074. String name (drive.getFullPathName());
  47075. rootPaths.add (name);
  47076. if (drive.isOnHardDisk())
  47077. {
  47078. String volume (drive.getVolumeLabel());
  47079. if (volume.isEmpty())
  47080. volume = TRANS("Hard Drive");
  47081. name << " [" << volume << ']';
  47082. }
  47083. else if (drive.isOnCDRomDrive())
  47084. {
  47085. name << TRANS(" [CD/DVD drive]");
  47086. }
  47087. rootNames.add (name);
  47088. }
  47089. separators.setBit (rootPaths.size());
  47090. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47091. rootNames.add ("Documents");
  47092. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47093. rootNames.add ("Desktop");
  47094. #endif
  47095. #if JUCE_MAC
  47096. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47097. rootNames.add ("Home folder");
  47098. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47099. rootNames.add ("Documents");
  47100. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47101. rootNames.add ("Desktop");
  47102. separators.setBit (rootPaths.size());
  47103. Array <File> volumes;
  47104. File vol ("/Volumes");
  47105. vol.findChildFiles (volumes, File::findDirectories, false);
  47106. for (int i = 0; i < volumes.size(); ++i)
  47107. {
  47108. const File& volume = volumes.getReference(i);
  47109. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47110. {
  47111. rootPaths.add (volume.getFullPathName());
  47112. rootNames.add (volume.getFileName());
  47113. }
  47114. }
  47115. #endif
  47116. #if JUCE_LINUX
  47117. rootPaths.add ("/");
  47118. rootNames.add ("/");
  47119. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47120. rootNames.add ("Home folder");
  47121. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47122. rootNames.add ("Desktop");
  47123. #endif
  47124. return separators;
  47125. }
  47126. END_JUCE_NAMESPACE
  47127. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47128. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47129. BEGIN_JUCE_NAMESPACE
  47130. FileChooser::FileChooser (const String& chooserBoxTitle,
  47131. const File& currentFileOrDirectory,
  47132. const String& fileFilters,
  47133. const bool useNativeDialogBox_)
  47134. : title (chooserBoxTitle),
  47135. filters (fileFilters),
  47136. startingFile (currentFileOrDirectory),
  47137. useNativeDialogBox (useNativeDialogBox_)
  47138. {
  47139. #if JUCE_LINUX
  47140. useNativeDialogBox = false;
  47141. #endif
  47142. if (! fileFilters.containsNonWhitespaceChars())
  47143. filters = "*";
  47144. }
  47145. FileChooser::~FileChooser()
  47146. {
  47147. }
  47148. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47149. {
  47150. return showDialog (false, true, false, false, false, previewComponent);
  47151. }
  47152. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47153. {
  47154. return showDialog (false, true, false, false, true, previewComponent);
  47155. }
  47156. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47157. {
  47158. return showDialog (true, true, false, false, true, previewComponent);
  47159. }
  47160. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47161. {
  47162. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47163. }
  47164. bool FileChooser::browseForDirectory()
  47165. {
  47166. return showDialog (true, false, false, false, false, 0);
  47167. }
  47168. const File FileChooser::getResult() const
  47169. {
  47170. // if you've used a multiple-file select, you should use the getResults() method
  47171. // to retrieve all the files that were chosen.
  47172. jassert (results.size() <= 1);
  47173. return results.getFirst();
  47174. }
  47175. const Array<File>& FileChooser::getResults() const
  47176. {
  47177. return results;
  47178. }
  47179. bool FileChooser::showDialog (const bool selectsDirectories,
  47180. const bool selectsFiles,
  47181. const bool isSave,
  47182. const bool warnAboutOverwritingExistingFiles,
  47183. const bool selectMultipleFiles,
  47184. FilePreviewComponent* const previewComponent)
  47185. {
  47186. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47187. results.clear();
  47188. // the preview component needs to be the right size before you pass it in here..
  47189. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47190. && previewComponent->getHeight() > 10));
  47191. #if JUCE_WINDOWS
  47192. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47193. #elif JUCE_MAC
  47194. if (useNativeDialogBox && (previewComponent == 0))
  47195. #else
  47196. if (false)
  47197. #endif
  47198. {
  47199. showPlatformDialog (results, title, startingFile, filters,
  47200. selectsDirectories, selectsFiles, isSave,
  47201. warnAboutOverwritingExistingFiles,
  47202. selectMultipleFiles,
  47203. previewComponent);
  47204. }
  47205. else
  47206. {
  47207. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47208. selectsDirectories ? "*" : String::empty,
  47209. String::empty);
  47210. int flags = isSave ? FileBrowserComponent::saveMode
  47211. : FileBrowserComponent::openMode;
  47212. if (selectsFiles)
  47213. flags |= FileBrowserComponent::canSelectFiles;
  47214. if (selectsDirectories)
  47215. {
  47216. flags |= FileBrowserComponent::canSelectDirectories;
  47217. if (! isSave)
  47218. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47219. }
  47220. if (selectMultipleFiles)
  47221. flags |= FileBrowserComponent::canSelectMultipleItems;
  47222. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47223. FileChooserDialogBox box (title, String::empty,
  47224. browserComponent,
  47225. warnAboutOverwritingExistingFiles,
  47226. browserComponent.findColour (AlertWindow::backgroundColourId));
  47227. if (box.show())
  47228. {
  47229. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47230. results.add (browserComponent.getSelectedFile (i));
  47231. }
  47232. }
  47233. if (previouslyFocused != 0)
  47234. previouslyFocused->grabKeyboardFocus();
  47235. return results.size() > 0;
  47236. }
  47237. FilePreviewComponent::FilePreviewComponent()
  47238. {
  47239. }
  47240. FilePreviewComponent::~FilePreviewComponent()
  47241. {
  47242. }
  47243. END_JUCE_NAMESPACE
  47244. /*** End of inlined file: juce_FileChooser.cpp ***/
  47245. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47246. BEGIN_JUCE_NAMESPACE
  47247. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47248. const String& instructions,
  47249. FileBrowserComponent& chooserComponent,
  47250. const bool warnAboutOverwritingExistingFiles_,
  47251. const Colour& backgroundColour)
  47252. : ResizableWindow (name, backgroundColour, true),
  47253. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47254. {
  47255. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47256. setResizable (true, true);
  47257. setResizeLimits (300, 300, 1200, 1000);
  47258. content->okButton.addButtonListener (this);
  47259. content->cancelButton.addButtonListener (this);
  47260. content->chooserComponent.addListener (this);
  47261. }
  47262. FileChooserDialogBox::~FileChooserDialogBox()
  47263. {
  47264. content->chooserComponent.removeListener (this);
  47265. }
  47266. bool FileChooserDialogBox::show (int w, int h)
  47267. {
  47268. return showAt (-1, -1, w, h);
  47269. }
  47270. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47271. {
  47272. if (w <= 0)
  47273. {
  47274. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47275. if (previewComp != 0)
  47276. w = 400 + previewComp->getWidth();
  47277. else
  47278. w = 600;
  47279. }
  47280. if (h <= 0)
  47281. h = 500;
  47282. if (x < 0 || y < 0)
  47283. centreWithSize (w, h);
  47284. else
  47285. setBounds (x, y, w, h);
  47286. const bool ok = (runModalLoop() != 0);
  47287. setVisible (false);
  47288. return ok;
  47289. }
  47290. void FileChooserDialogBox::buttonClicked (Button* button)
  47291. {
  47292. if (button == &(content->okButton))
  47293. {
  47294. if (warnAboutOverwritingExistingFiles
  47295. && content->chooserComponent.isSaveMode()
  47296. && content->chooserComponent.getSelectedFile(0).exists())
  47297. {
  47298. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47299. TRANS("File already exists"),
  47300. TRANS("There's already a file called:")
  47301. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47302. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47303. TRANS("overwrite"),
  47304. TRANS("cancel")))
  47305. {
  47306. return;
  47307. }
  47308. }
  47309. exitModalState (1);
  47310. }
  47311. else if (button == &(content->cancelButton))
  47312. {
  47313. closeButtonPressed();
  47314. }
  47315. }
  47316. void FileChooserDialogBox::closeButtonPressed()
  47317. {
  47318. setVisible (false);
  47319. }
  47320. void FileChooserDialogBox::selectionChanged()
  47321. {
  47322. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47323. }
  47324. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47325. {
  47326. }
  47327. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47328. {
  47329. selectionChanged();
  47330. content->okButton.triggerClick();
  47331. }
  47332. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47333. : Component (name), instructions (instructions_),
  47334. chooserComponent (chooserComponent_),
  47335. okButton (chooserComponent_.getActionVerb()),
  47336. cancelButton (TRANS ("Cancel"))
  47337. {
  47338. addAndMakeVisible (&chooserComponent);
  47339. addAndMakeVisible (&okButton);
  47340. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47341. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47342. addAndMakeVisible (&cancelButton);
  47343. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47344. setInterceptsMouseClicks (false, true);
  47345. }
  47346. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47347. {
  47348. }
  47349. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47350. {
  47351. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47352. text.draw (g);
  47353. }
  47354. void FileChooserDialogBox::ContentComponent::resized()
  47355. {
  47356. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47357. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47358. const int y = roundToInt (bb.getBottom()) + 10;
  47359. const int buttonHeight = 26;
  47360. const int buttonY = getHeight() - buttonHeight - 8;
  47361. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47362. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47363. proportionOfWidth (0.2f), buttonHeight);
  47364. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47365. proportionOfWidth (0.2f), buttonHeight);
  47366. }
  47367. END_JUCE_NAMESPACE
  47368. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47369. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47370. BEGIN_JUCE_NAMESPACE
  47371. FileFilter::FileFilter (const String& filterDescription)
  47372. : description (filterDescription)
  47373. {
  47374. }
  47375. FileFilter::~FileFilter()
  47376. {
  47377. }
  47378. const String& FileFilter::getDescription() const throw()
  47379. {
  47380. return description;
  47381. }
  47382. END_JUCE_NAMESPACE
  47383. /*** End of inlined file: juce_FileFilter.cpp ***/
  47384. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47385. BEGIN_JUCE_NAMESPACE
  47386. const Image juce_createIconForFile (const File& file);
  47387. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47388. : ListBox (String::empty, 0),
  47389. DirectoryContentsDisplayComponent (listToShow)
  47390. {
  47391. setModel (this);
  47392. fileList.addChangeListener (this);
  47393. }
  47394. FileListComponent::~FileListComponent()
  47395. {
  47396. fileList.removeChangeListener (this);
  47397. }
  47398. int FileListComponent::getNumSelectedFiles() const
  47399. {
  47400. return getNumSelectedRows();
  47401. }
  47402. const File FileListComponent::getSelectedFile (int index) const
  47403. {
  47404. return fileList.getFile (getSelectedRow (index));
  47405. }
  47406. void FileListComponent::deselectAllFiles()
  47407. {
  47408. deselectAllRows();
  47409. }
  47410. void FileListComponent::scrollToTop()
  47411. {
  47412. getVerticalScrollBar()->setCurrentRangeStart (0);
  47413. }
  47414. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47415. {
  47416. updateContent();
  47417. if (lastDirectory != fileList.getDirectory())
  47418. {
  47419. lastDirectory = fileList.getDirectory();
  47420. deselectAllRows();
  47421. }
  47422. }
  47423. class FileListItemComponent : public Component,
  47424. public TimeSliceClient,
  47425. public AsyncUpdater
  47426. {
  47427. public:
  47428. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47429. : owner (owner_), thread (thread_),
  47430. highlighted (false), index (0), icon (0)
  47431. {
  47432. }
  47433. ~FileListItemComponent()
  47434. {
  47435. thread.removeTimeSliceClient (this);
  47436. clearIcon();
  47437. }
  47438. void paint (Graphics& g)
  47439. {
  47440. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47441. file.getFileName(),
  47442. &icon,
  47443. fileSize, modTime,
  47444. isDirectory, highlighted,
  47445. index, owner);
  47446. }
  47447. void mouseDown (const MouseEvent& e)
  47448. {
  47449. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47450. owner.sendMouseClickMessage (file, e);
  47451. }
  47452. void mouseDoubleClick (const MouseEvent&)
  47453. {
  47454. owner.sendDoubleClickMessage (file);
  47455. }
  47456. void update (const File& root,
  47457. const DirectoryContentsList::FileInfo* const fileInfo,
  47458. const int index_,
  47459. const bool highlighted_)
  47460. {
  47461. thread.removeTimeSliceClient (this);
  47462. if (highlighted_ != highlighted
  47463. || index_ != index)
  47464. {
  47465. index = index_;
  47466. highlighted = highlighted_;
  47467. repaint();
  47468. }
  47469. File newFile;
  47470. String newFileSize;
  47471. String newModTime;
  47472. if (fileInfo != 0)
  47473. {
  47474. newFile = root.getChildFile (fileInfo->filename);
  47475. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47476. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47477. }
  47478. if (newFile != file
  47479. || fileSize != newFileSize
  47480. || modTime != newModTime)
  47481. {
  47482. file = newFile;
  47483. fileSize = newFileSize;
  47484. modTime = newModTime;
  47485. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47486. repaint();
  47487. clearIcon();
  47488. }
  47489. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47490. {
  47491. updateIcon (true);
  47492. if (! icon.isValid())
  47493. thread.addTimeSliceClient (this);
  47494. }
  47495. }
  47496. bool useTimeSlice()
  47497. {
  47498. updateIcon (false);
  47499. return false;
  47500. }
  47501. void handleAsyncUpdate()
  47502. {
  47503. repaint();
  47504. }
  47505. juce_UseDebuggingNewOperator
  47506. private:
  47507. FileListComponent& owner;
  47508. TimeSliceThread& thread;
  47509. bool highlighted;
  47510. int index;
  47511. File file;
  47512. String fileSize;
  47513. String modTime;
  47514. Image icon;
  47515. bool isDirectory;
  47516. void clearIcon()
  47517. {
  47518. icon = Image::null;
  47519. }
  47520. void updateIcon (const bool onlyUpdateIfCached)
  47521. {
  47522. if (icon.isNull())
  47523. {
  47524. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47525. Image im (ImageCache::getFromHashCode (hashCode));
  47526. if (im.isNull() && ! onlyUpdateIfCached)
  47527. {
  47528. im = juce_createIconForFile (file);
  47529. if (im.isValid())
  47530. ImageCache::addImageToCache (im, hashCode);
  47531. }
  47532. if (im.isValid())
  47533. {
  47534. icon = im;
  47535. triggerAsyncUpdate();
  47536. }
  47537. }
  47538. }
  47539. };
  47540. int FileListComponent::getNumRows()
  47541. {
  47542. return fileList.getNumFiles();
  47543. }
  47544. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47545. {
  47546. }
  47547. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47548. {
  47549. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47550. if (comp == 0)
  47551. {
  47552. delete existingComponentToUpdate;
  47553. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47554. }
  47555. DirectoryContentsList::FileInfo fileInfo;
  47556. if (fileList.getFileInfo (row, fileInfo))
  47557. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47558. else
  47559. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47560. return comp;
  47561. }
  47562. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47563. {
  47564. sendSelectionChangeMessage();
  47565. }
  47566. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47567. {
  47568. }
  47569. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47570. {
  47571. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47572. }
  47573. END_JUCE_NAMESPACE
  47574. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47575. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47576. BEGIN_JUCE_NAMESPACE
  47577. FilenameComponent::FilenameComponent (const String& name,
  47578. const File& currentFile,
  47579. const bool canEditFilename,
  47580. const bool isDirectory,
  47581. const bool isForSaving,
  47582. const String& fileBrowserWildcard,
  47583. const String& enforcedSuffix_,
  47584. const String& textWhenNothingSelected)
  47585. : Component (name),
  47586. maxRecentFiles (30),
  47587. isDir (isDirectory),
  47588. isSaving (isForSaving),
  47589. isFileDragOver (false),
  47590. wildcard (fileBrowserWildcard),
  47591. enforcedSuffix (enforcedSuffix_)
  47592. {
  47593. addAndMakeVisible (&filenameBox);
  47594. filenameBox.setEditableText (canEditFilename);
  47595. filenameBox.addListener (this);
  47596. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47597. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47598. setBrowseButtonText ("...");
  47599. setCurrentFile (currentFile, true);
  47600. }
  47601. FilenameComponent::~FilenameComponent()
  47602. {
  47603. }
  47604. void FilenameComponent::paintOverChildren (Graphics& g)
  47605. {
  47606. if (isFileDragOver)
  47607. {
  47608. g.setColour (Colours::red.withAlpha (0.2f));
  47609. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47610. }
  47611. }
  47612. void FilenameComponent::resized()
  47613. {
  47614. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47615. }
  47616. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47617. {
  47618. browseButtonText = newBrowseButtonText;
  47619. lookAndFeelChanged();
  47620. }
  47621. void FilenameComponent::lookAndFeelChanged()
  47622. {
  47623. browseButton = 0;
  47624. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47625. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47626. resized();
  47627. browseButton->addButtonListener (this);
  47628. }
  47629. void FilenameComponent::setTooltip (const String& newTooltip)
  47630. {
  47631. SettableTooltipClient::setTooltip (newTooltip);
  47632. filenameBox.setTooltip (newTooltip);
  47633. }
  47634. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47635. {
  47636. defaultBrowseFile = newDefaultDirectory;
  47637. }
  47638. void FilenameComponent::buttonClicked (Button*)
  47639. {
  47640. FileChooser fc (TRANS("Choose a new file"),
  47641. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47642. : getCurrentFile(),
  47643. wildcard);
  47644. if (isDir ? fc.browseForDirectory()
  47645. : (isSaving ? fc.browseForFileToSave (false)
  47646. : fc.browseForFileToOpen()))
  47647. {
  47648. setCurrentFile (fc.getResult(), true);
  47649. }
  47650. }
  47651. void FilenameComponent::comboBoxChanged (ComboBox*)
  47652. {
  47653. setCurrentFile (getCurrentFile(), true);
  47654. }
  47655. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47656. {
  47657. return true;
  47658. }
  47659. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47660. {
  47661. isFileDragOver = false;
  47662. repaint();
  47663. const File f (filenames[0]);
  47664. if (f.exists() && (f.isDirectory() == isDir))
  47665. setCurrentFile (f, true);
  47666. }
  47667. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47668. {
  47669. isFileDragOver = true;
  47670. repaint();
  47671. }
  47672. void FilenameComponent::fileDragExit (const StringArray&)
  47673. {
  47674. isFileDragOver = false;
  47675. repaint();
  47676. }
  47677. const File FilenameComponent::getCurrentFile() const
  47678. {
  47679. File f (filenameBox.getText());
  47680. if (enforcedSuffix.isNotEmpty())
  47681. f = f.withFileExtension (enforcedSuffix);
  47682. return f;
  47683. }
  47684. void FilenameComponent::setCurrentFile (File newFile,
  47685. const bool addToRecentlyUsedList,
  47686. const bool sendChangeNotification)
  47687. {
  47688. if (enforcedSuffix.isNotEmpty())
  47689. newFile = newFile.withFileExtension (enforcedSuffix);
  47690. if (newFile.getFullPathName() != lastFilename)
  47691. {
  47692. lastFilename = newFile.getFullPathName();
  47693. if (addToRecentlyUsedList)
  47694. addRecentlyUsedFile (newFile);
  47695. filenameBox.setText (lastFilename, true);
  47696. if (sendChangeNotification)
  47697. triggerAsyncUpdate();
  47698. }
  47699. }
  47700. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47701. {
  47702. filenameBox.setEditableText (shouldBeEditable);
  47703. }
  47704. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47705. {
  47706. StringArray names;
  47707. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47708. names.add (filenameBox.getItemText (i));
  47709. return names;
  47710. }
  47711. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47712. {
  47713. if (filenames != getRecentlyUsedFilenames())
  47714. {
  47715. filenameBox.clear();
  47716. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47717. filenameBox.addItem (filenames[i], i + 1);
  47718. }
  47719. }
  47720. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47721. {
  47722. maxRecentFiles = jmax (1, newMaximum);
  47723. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47724. }
  47725. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47726. {
  47727. StringArray files (getRecentlyUsedFilenames());
  47728. if (file.getFullPathName().isNotEmpty())
  47729. {
  47730. files.removeString (file.getFullPathName(), true);
  47731. files.insert (0, file.getFullPathName());
  47732. setRecentlyUsedFilenames (files);
  47733. }
  47734. }
  47735. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47736. {
  47737. listeners.add (listener);
  47738. }
  47739. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47740. {
  47741. listeners.remove (listener);
  47742. }
  47743. void FilenameComponent::handleAsyncUpdate()
  47744. {
  47745. Component::BailOutChecker checker (this);
  47746. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47747. }
  47748. END_JUCE_NAMESPACE
  47749. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47750. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47751. BEGIN_JUCE_NAMESPACE
  47752. FileSearchPathListComponent::FileSearchPathListComponent()
  47753. : addButton ("+"),
  47754. removeButton ("-"),
  47755. changeButton (TRANS ("change...")),
  47756. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47757. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47758. {
  47759. listBox.setModel (this);
  47760. addAndMakeVisible (&listBox);
  47761. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47762. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47763. listBox.setOutlineThickness (1);
  47764. addAndMakeVisible (&addButton);
  47765. addButton.addButtonListener (this);
  47766. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47767. addAndMakeVisible (&removeButton);
  47768. removeButton.addButtonListener (this);
  47769. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47770. addAndMakeVisible (&changeButton);
  47771. changeButton.addButtonListener (this);
  47772. addAndMakeVisible (&upButton);
  47773. upButton.addButtonListener (this);
  47774. {
  47775. Path arrowPath;
  47776. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47777. DrawablePath arrowImage;
  47778. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47779. arrowImage.setPath (arrowPath);
  47780. upButton.setImages (&arrowImage);
  47781. }
  47782. addAndMakeVisible (&downButton);
  47783. downButton.addButtonListener (this);
  47784. {
  47785. Path arrowPath;
  47786. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47787. DrawablePath arrowImage;
  47788. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47789. arrowImage.setPath (arrowPath);
  47790. downButton.setImages (&arrowImage);
  47791. }
  47792. updateButtons();
  47793. }
  47794. FileSearchPathListComponent::~FileSearchPathListComponent()
  47795. {
  47796. }
  47797. void FileSearchPathListComponent::updateButtons()
  47798. {
  47799. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47800. removeButton.setEnabled (anythingSelected);
  47801. changeButton.setEnabled (anythingSelected);
  47802. upButton.setEnabled (anythingSelected);
  47803. downButton.setEnabled (anythingSelected);
  47804. }
  47805. void FileSearchPathListComponent::changed()
  47806. {
  47807. listBox.updateContent();
  47808. listBox.repaint();
  47809. updateButtons();
  47810. }
  47811. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47812. {
  47813. if (newPath.toString() != path.toString())
  47814. {
  47815. path = newPath;
  47816. changed();
  47817. }
  47818. }
  47819. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47820. {
  47821. defaultBrowseTarget = newDefaultDirectory;
  47822. }
  47823. int FileSearchPathListComponent::getNumRows()
  47824. {
  47825. return path.getNumPaths();
  47826. }
  47827. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47828. {
  47829. if (rowIsSelected)
  47830. g.fillAll (findColour (TextEditor::highlightColourId));
  47831. g.setColour (findColour (ListBox::textColourId));
  47832. Font f (height * 0.7f);
  47833. f.setHorizontalScale (0.9f);
  47834. g.setFont (f);
  47835. g.drawText (path [rowNumber].getFullPathName(),
  47836. 4, 0, width - 6, height,
  47837. Justification::centredLeft, true);
  47838. }
  47839. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47840. {
  47841. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47842. {
  47843. path.remove (row);
  47844. changed();
  47845. }
  47846. }
  47847. void FileSearchPathListComponent::returnKeyPressed (int row)
  47848. {
  47849. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47850. if (chooser.browseForDirectory())
  47851. {
  47852. path.remove (row);
  47853. path.add (chooser.getResult(), row);
  47854. changed();
  47855. }
  47856. }
  47857. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47858. {
  47859. returnKeyPressed (row);
  47860. }
  47861. void FileSearchPathListComponent::selectedRowsChanged (int)
  47862. {
  47863. updateButtons();
  47864. }
  47865. void FileSearchPathListComponent::paint (Graphics& g)
  47866. {
  47867. g.fillAll (findColour (backgroundColourId));
  47868. }
  47869. void FileSearchPathListComponent::resized()
  47870. {
  47871. const int buttonH = 22;
  47872. const int buttonY = getHeight() - buttonH - 4;
  47873. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47874. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47875. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47876. changeButton.changeWidthToFitText (buttonH);
  47877. downButton.setSize (buttonH * 2, buttonH);
  47878. upButton.setSize (buttonH * 2, buttonH);
  47879. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47880. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47881. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47882. }
  47883. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47884. {
  47885. return true;
  47886. }
  47887. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47888. {
  47889. for (int i = filenames.size(); --i >= 0;)
  47890. {
  47891. const File f (filenames[i]);
  47892. if (f.isDirectory())
  47893. {
  47894. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47895. path.add (f, row);
  47896. changed();
  47897. }
  47898. }
  47899. }
  47900. void FileSearchPathListComponent::buttonClicked (Button* button)
  47901. {
  47902. const int currentRow = listBox.getSelectedRow();
  47903. if (button == &removeButton)
  47904. {
  47905. deleteKeyPressed (currentRow);
  47906. }
  47907. else if (button == &addButton)
  47908. {
  47909. File start (defaultBrowseTarget);
  47910. if (start == File::nonexistent)
  47911. start = path [0];
  47912. if (start == File::nonexistent)
  47913. start = File::getCurrentWorkingDirectory();
  47914. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47915. if (chooser.browseForDirectory())
  47916. {
  47917. path.add (chooser.getResult(), currentRow);
  47918. }
  47919. }
  47920. else if (button == &changeButton)
  47921. {
  47922. returnKeyPressed (currentRow);
  47923. }
  47924. else if (button == &upButton)
  47925. {
  47926. if (currentRow > 0 && currentRow < path.getNumPaths())
  47927. {
  47928. const File f (path[currentRow]);
  47929. path.remove (currentRow);
  47930. path.add (f, currentRow - 1);
  47931. listBox.selectRow (currentRow - 1);
  47932. }
  47933. }
  47934. else if (button == &downButton)
  47935. {
  47936. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47937. {
  47938. const File f (path[currentRow]);
  47939. path.remove (currentRow);
  47940. path.add (f, currentRow + 1);
  47941. listBox.selectRow (currentRow + 1);
  47942. }
  47943. }
  47944. changed();
  47945. }
  47946. END_JUCE_NAMESPACE
  47947. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47948. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47949. BEGIN_JUCE_NAMESPACE
  47950. const Image juce_createIconForFile (const File& file);
  47951. class FileListTreeItem : public TreeViewItem,
  47952. public TimeSliceClient,
  47953. public AsyncUpdater,
  47954. public ChangeListener
  47955. {
  47956. public:
  47957. FileListTreeItem (FileTreeComponent& owner_,
  47958. DirectoryContentsList* const parentContentsList_,
  47959. const int indexInContentsList_,
  47960. const File& file_,
  47961. TimeSliceThread& thread_)
  47962. : file (file_),
  47963. owner (owner_),
  47964. parentContentsList (parentContentsList_),
  47965. indexInContentsList (indexInContentsList_),
  47966. subContentsList (0),
  47967. canDeleteSubContentsList (false),
  47968. thread (thread_),
  47969. icon (0)
  47970. {
  47971. DirectoryContentsList::FileInfo fileInfo;
  47972. if (parentContentsList_ != 0
  47973. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47974. {
  47975. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47976. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47977. isDirectory = fileInfo.isDirectory;
  47978. }
  47979. else
  47980. {
  47981. isDirectory = true;
  47982. }
  47983. }
  47984. ~FileListTreeItem()
  47985. {
  47986. thread.removeTimeSliceClient (this);
  47987. clearSubItems();
  47988. if (canDeleteSubContentsList)
  47989. delete subContentsList;
  47990. }
  47991. bool mightContainSubItems() { return isDirectory; }
  47992. const String getUniqueName() const { return file.getFullPathName(); }
  47993. int getItemHeight() const { return 22; }
  47994. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47995. void itemOpennessChanged (bool isNowOpen)
  47996. {
  47997. if (isNowOpen)
  47998. {
  47999. clearSubItems();
  48000. isDirectory = file.isDirectory();
  48001. if (isDirectory)
  48002. {
  48003. if (subContentsList == 0)
  48004. {
  48005. jassert (parentContentsList != 0);
  48006. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48007. l->setDirectory (file, true, true);
  48008. setSubContentsList (l);
  48009. canDeleteSubContentsList = true;
  48010. }
  48011. changeListenerCallback (0);
  48012. }
  48013. }
  48014. }
  48015. void setSubContentsList (DirectoryContentsList* newList)
  48016. {
  48017. jassert (subContentsList == 0);
  48018. subContentsList = newList;
  48019. newList->addChangeListener (this);
  48020. }
  48021. void changeListenerCallback (ChangeBroadcaster*)
  48022. {
  48023. clearSubItems();
  48024. if (isOpen() && subContentsList != 0)
  48025. {
  48026. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48027. {
  48028. FileListTreeItem* const item
  48029. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48030. addSubItem (item);
  48031. }
  48032. }
  48033. }
  48034. void paintItem (Graphics& g, int width, int height)
  48035. {
  48036. if (file != File::nonexistent)
  48037. {
  48038. updateIcon (true);
  48039. if (icon.isNull())
  48040. thread.addTimeSliceClient (this);
  48041. }
  48042. owner.getLookAndFeel()
  48043. .drawFileBrowserRow (g, width, height,
  48044. file.getFileName(),
  48045. &icon, fileSize, modTime,
  48046. isDirectory, isSelected(),
  48047. indexInContentsList, owner);
  48048. }
  48049. void itemClicked (const MouseEvent& e)
  48050. {
  48051. owner.sendMouseClickMessage (file, e);
  48052. }
  48053. void itemDoubleClicked (const MouseEvent& e)
  48054. {
  48055. TreeViewItem::itemDoubleClicked (e);
  48056. owner.sendDoubleClickMessage (file);
  48057. }
  48058. void itemSelectionChanged (bool)
  48059. {
  48060. owner.sendSelectionChangeMessage();
  48061. }
  48062. bool useTimeSlice()
  48063. {
  48064. updateIcon (false);
  48065. thread.removeTimeSliceClient (this);
  48066. return false;
  48067. }
  48068. void handleAsyncUpdate()
  48069. {
  48070. owner.repaint();
  48071. }
  48072. const File file;
  48073. juce_UseDebuggingNewOperator
  48074. private:
  48075. FileTreeComponent& owner;
  48076. DirectoryContentsList* parentContentsList;
  48077. int indexInContentsList;
  48078. DirectoryContentsList* subContentsList;
  48079. bool isDirectory, canDeleteSubContentsList;
  48080. TimeSliceThread& thread;
  48081. Image icon;
  48082. String fileSize;
  48083. String modTime;
  48084. void updateIcon (const bool onlyUpdateIfCached)
  48085. {
  48086. if (icon.isNull())
  48087. {
  48088. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48089. Image im (ImageCache::getFromHashCode (hashCode));
  48090. if (im.isNull() && ! onlyUpdateIfCached)
  48091. {
  48092. im = juce_createIconForFile (file);
  48093. if (im.isValid())
  48094. ImageCache::addImageToCache (im, hashCode);
  48095. }
  48096. if (im.isValid())
  48097. {
  48098. icon = im;
  48099. triggerAsyncUpdate();
  48100. }
  48101. }
  48102. }
  48103. };
  48104. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48105. : DirectoryContentsDisplayComponent (listToShow)
  48106. {
  48107. FileListTreeItem* const root
  48108. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48109. listToShow.getTimeSliceThread());
  48110. root->setSubContentsList (&listToShow);
  48111. setRootItemVisible (false);
  48112. setRootItem (root);
  48113. }
  48114. FileTreeComponent::~FileTreeComponent()
  48115. {
  48116. deleteRootItem();
  48117. }
  48118. const File FileTreeComponent::getSelectedFile (const int index) const
  48119. {
  48120. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48121. return item != 0 ? item->file
  48122. : File::nonexistent;
  48123. }
  48124. void FileTreeComponent::deselectAllFiles()
  48125. {
  48126. clearSelectedItems();
  48127. }
  48128. void FileTreeComponent::scrollToTop()
  48129. {
  48130. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48131. }
  48132. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48133. {
  48134. dragAndDropDescription = description;
  48135. }
  48136. END_JUCE_NAMESPACE
  48137. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48138. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48139. BEGIN_JUCE_NAMESPACE
  48140. ImagePreviewComponent::ImagePreviewComponent()
  48141. {
  48142. }
  48143. ImagePreviewComponent::~ImagePreviewComponent()
  48144. {
  48145. }
  48146. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48147. {
  48148. const int availableW = proportionOfWidth (0.97f);
  48149. const int availableH = getHeight() - 13 * 4;
  48150. const double scale = jmin (1.0,
  48151. availableW / (double) w,
  48152. availableH / (double) h);
  48153. w = roundToInt (scale * w);
  48154. h = roundToInt (scale * h);
  48155. }
  48156. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48157. {
  48158. if (fileToLoad != file)
  48159. {
  48160. fileToLoad = file;
  48161. startTimer (100);
  48162. }
  48163. }
  48164. void ImagePreviewComponent::timerCallback()
  48165. {
  48166. stopTimer();
  48167. currentThumbnail = Image::null;
  48168. currentDetails = String::empty;
  48169. repaint();
  48170. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48171. if (in != 0)
  48172. {
  48173. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48174. if (format != 0)
  48175. {
  48176. currentThumbnail = format->decodeImage (*in);
  48177. if (currentThumbnail.isValid())
  48178. {
  48179. int w = currentThumbnail.getWidth();
  48180. int h = currentThumbnail.getHeight();
  48181. currentDetails
  48182. << fileToLoad.getFileName() << "\n"
  48183. << format->getFormatName() << "\n"
  48184. << w << " x " << h << " pixels\n"
  48185. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48186. getThumbSize (w, h);
  48187. currentThumbnail = currentThumbnail.rescaled (w, h);
  48188. }
  48189. }
  48190. }
  48191. }
  48192. void ImagePreviewComponent::paint (Graphics& g)
  48193. {
  48194. if (currentThumbnail.isValid())
  48195. {
  48196. g.setFont (13.0f);
  48197. int w = currentThumbnail.getWidth();
  48198. int h = currentThumbnail.getHeight();
  48199. getThumbSize (w, h);
  48200. const int numLines = 4;
  48201. const int totalH = 13 * numLines + h + 4;
  48202. const int y = (getHeight() - totalH) / 2;
  48203. g.drawImageWithin (currentThumbnail,
  48204. (getWidth() - w) / 2, y, w, h,
  48205. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48206. false);
  48207. g.drawFittedText (currentDetails,
  48208. 0, y + h + 4, getWidth(), 100,
  48209. Justification::centredTop, numLines);
  48210. }
  48211. }
  48212. END_JUCE_NAMESPACE
  48213. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48214. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48215. BEGIN_JUCE_NAMESPACE
  48216. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48217. const String& directoryWildcardPatterns,
  48218. const String& description_)
  48219. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48220. : (description_ + " (" + fileWildcardPatterns + ")"))
  48221. {
  48222. parse (fileWildcardPatterns, fileWildcards);
  48223. parse (directoryWildcardPatterns, directoryWildcards);
  48224. }
  48225. WildcardFileFilter::~WildcardFileFilter()
  48226. {
  48227. }
  48228. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48229. {
  48230. return match (file, fileWildcards);
  48231. }
  48232. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48233. {
  48234. return match (file, directoryWildcards);
  48235. }
  48236. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48237. {
  48238. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48239. result.trim();
  48240. result.removeEmptyStrings();
  48241. // special case for *.*, because people use it to mean "any file", but it
  48242. // would actually ignore files with no extension.
  48243. for (int i = result.size(); --i >= 0;)
  48244. if (result[i] == "*.*")
  48245. result.set (i, "*");
  48246. }
  48247. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48248. {
  48249. const String filename (file.getFileName());
  48250. for (int i = wildcards.size(); --i >= 0;)
  48251. if (filename.matchesWildcard (wildcards[i], true))
  48252. return true;
  48253. return false;
  48254. }
  48255. END_JUCE_NAMESPACE
  48256. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48257. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48258. BEGIN_JUCE_NAMESPACE
  48259. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48260. {
  48261. }
  48262. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48263. {
  48264. }
  48265. namespace KeyboardFocusHelpers
  48266. {
  48267. // This will sort a set of components, so that they are ordered in terms of
  48268. // left-to-right and then top-to-bottom.
  48269. class ScreenPositionComparator
  48270. {
  48271. public:
  48272. ScreenPositionComparator() {}
  48273. static int compareElements (const Component* const first, const Component* const second)
  48274. {
  48275. int explicitOrder1 = first->getExplicitFocusOrder();
  48276. if (explicitOrder1 <= 0)
  48277. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48278. int explicitOrder2 = second->getExplicitFocusOrder();
  48279. if (explicitOrder2 <= 0)
  48280. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48281. if (explicitOrder1 != explicitOrder2)
  48282. return explicitOrder1 - explicitOrder2;
  48283. const int diff = first->getY() - second->getY();
  48284. return (diff == 0) ? first->getX() - second->getX()
  48285. : diff;
  48286. }
  48287. };
  48288. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48289. {
  48290. if (parent->getNumChildComponents() > 0)
  48291. {
  48292. Array <Component*> localComps;
  48293. ScreenPositionComparator comparator;
  48294. int i;
  48295. for (i = parent->getNumChildComponents(); --i >= 0;)
  48296. {
  48297. Component* const c = parent->getChildComponent (i);
  48298. if (c->isVisible() && c->isEnabled())
  48299. localComps.addSorted (comparator, c);
  48300. }
  48301. for (i = 0; i < localComps.size(); ++i)
  48302. {
  48303. Component* const c = localComps.getUnchecked (i);
  48304. if (c->getWantsKeyboardFocus())
  48305. comps.add (c);
  48306. if (! c->isFocusContainer())
  48307. findAllFocusableComponents (c, comps);
  48308. }
  48309. }
  48310. }
  48311. }
  48312. namespace KeyboardFocusHelpers
  48313. {
  48314. Component* getIncrementedComponent (Component* const current, const int delta)
  48315. {
  48316. Component* focusContainer = current->getParentComponent();
  48317. if (focusContainer != 0)
  48318. {
  48319. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48320. focusContainer = focusContainer->getParentComponent();
  48321. if (focusContainer != 0)
  48322. {
  48323. Array <Component*> comps;
  48324. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48325. if (comps.size() > 0)
  48326. {
  48327. const int index = comps.indexOf (current);
  48328. return comps [(index + comps.size() + delta) % comps.size()];
  48329. }
  48330. }
  48331. }
  48332. return 0;
  48333. }
  48334. }
  48335. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48336. {
  48337. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48338. }
  48339. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48340. {
  48341. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48342. }
  48343. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48344. {
  48345. Array <Component*> comps;
  48346. if (parentComponent != 0)
  48347. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48348. return comps.getFirst();
  48349. }
  48350. END_JUCE_NAMESPACE
  48351. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48352. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48353. BEGIN_JUCE_NAMESPACE
  48354. bool KeyListener::keyStateChanged (const bool, Component*)
  48355. {
  48356. return false;
  48357. }
  48358. END_JUCE_NAMESPACE
  48359. /*** End of inlined file: juce_KeyListener.cpp ***/
  48360. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48361. BEGIN_JUCE_NAMESPACE
  48362. // N.B. these two includes are put here deliberately to avoid problems with
  48363. // old GCCs failing on long include paths
  48364. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48365. {
  48366. public:
  48367. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48368. const CommandID commandID_,
  48369. const String& keyName,
  48370. const int keyNum_)
  48371. : Button (keyName),
  48372. owner (owner_),
  48373. commandID (commandID_),
  48374. keyNum (keyNum_)
  48375. {
  48376. setWantsKeyboardFocus (false);
  48377. setTriggeredOnMouseDown (keyNum >= 0);
  48378. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48379. : TRANS("click to change this key-mapping"));
  48380. }
  48381. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48382. {
  48383. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48384. keyNum >= 0 ? getName() : String::empty);
  48385. }
  48386. void clicked()
  48387. {
  48388. if (keyNum >= 0)
  48389. {
  48390. // existing key clicked..
  48391. PopupMenu m;
  48392. m.addItem (1, TRANS("change this key-mapping"));
  48393. m.addSeparator();
  48394. m.addItem (2, TRANS("remove this key-mapping"));
  48395. switch (m.show())
  48396. {
  48397. case 1: assignNewKey(); break;
  48398. case 2: owner.getMappings().removeKeyPress (commandID, keyNum); break;
  48399. default: break;
  48400. }
  48401. }
  48402. else
  48403. {
  48404. assignNewKey(); // + button pressed..
  48405. }
  48406. }
  48407. void fitToContent (const int h) throw()
  48408. {
  48409. if (keyNum < 0)
  48410. {
  48411. setSize (h, h);
  48412. }
  48413. else
  48414. {
  48415. Font f (h * 0.6f);
  48416. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48417. }
  48418. }
  48419. class KeyEntryWindow : public AlertWindow
  48420. {
  48421. public:
  48422. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48423. : AlertWindow (TRANS("New key-mapping"),
  48424. TRANS("Please press a key combination now..."),
  48425. AlertWindow::NoIcon),
  48426. owner (owner_)
  48427. {
  48428. addButton (TRANS("Ok"), 1);
  48429. addButton (TRANS("Cancel"), 0);
  48430. // (avoid return + escape keys getting processed by the buttons..)
  48431. for (int i = getNumChildComponents(); --i >= 0;)
  48432. getChildComponent (i)->setWantsKeyboardFocus (false);
  48433. setWantsKeyboardFocus (true);
  48434. grabKeyboardFocus();
  48435. }
  48436. bool keyPressed (const KeyPress& key)
  48437. {
  48438. lastPress = key;
  48439. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48440. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48441. if (previousCommand != 0)
  48442. message << "\n\n" << TRANS("(Currently assigned to \"")
  48443. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48444. setMessage (message);
  48445. return true;
  48446. }
  48447. bool keyStateChanged (bool)
  48448. {
  48449. return true;
  48450. }
  48451. KeyPress lastPress;
  48452. private:
  48453. KeyMappingEditorComponent& owner;
  48454. KeyEntryWindow (const KeyEntryWindow&);
  48455. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48456. };
  48457. void assignNewKey()
  48458. {
  48459. KeyEntryWindow entryWindow (owner);
  48460. if (entryWindow.runModalLoop() != 0)
  48461. {
  48462. entryWindow.setVisible (false);
  48463. if (entryWindow.lastPress.isValid())
  48464. {
  48465. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (entryWindow.lastPress);
  48466. if (previousCommand == 0
  48467. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48468. TRANS("Change key-mapping"),
  48469. TRANS("This key is already assigned to the command \"")
  48470. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48471. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48472. TRANS("Re-assign"),
  48473. TRANS("Cancel")))
  48474. {
  48475. owner.getMappings().removeKeyPress (entryWindow.lastPress);
  48476. if (keyNum >= 0)
  48477. owner.getMappings().removeKeyPress (commandID, keyNum);
  48478. owner.getMappings().addKeyPress (commandID, entryWindow.lastPress, keyNum);
  48479. }
  48480. }
  48481. }
  48482. }
  48483. juce_UseDebuggingNewOperator
  48484. private:
  48485. KeyMappingEditorComponent& owner;
  48486. const CommandID commandID;
  48487. const int keyNum;
  48488. ChangeKeyButton (const ChangeKeyButton&);
  48489. ChangeKeyButton& operator= (const ChangeKeyButton&);
  48490. };
  48491. class KeyMappingEditorComponent::ItemComponent : public Component
  48492. {
  48493. public:
  48494. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48495. : owner (owner_), commandID (commandID_)
  48496. {
  48497. setInterceptsMouseClicks (false, true);
  48498. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48499. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48500. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48501. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48502. addKeyPressButton (String::empty, -1, isReadOnly);
  48503. }
  48504. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48505. {
  48506. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48507. keyChangeButtons.add (b);
  48508. b->setEnabled (! isReadOnly);
  48509. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48510. addChildComponent (b);
  48511. }
  48512. void paint (Graphics& g)
  48513. {
  48514. g.setFont (getHeight() * 0.7f);
  48515. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48516. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48517. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48518. Justification::centredLeft, true);
  48519. }
  48520. void resized()
  48521. {
  48522. int x = getWidth() - 4;
  48523. for (int i = keyChangeButtons.size(); --i >= 0;)
  48524. {
  48525. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48526. b->fitToContent (getHeight() - 2);
  48527. b->setTopRightPosition (x, 1);
  48528. x = b->getX() - 5;
  48529. }
  48530. }
  48531. juce_UseDebuggingNewOperator
  48532. private:
  48533. KeyMappingEditorComponent& owner;
  48534. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48535. const CommandID commandID;
  48536. enum { maxNumAssignments = 3 };
  48537. ItemComponent (const ItemComponent&);
  48538. ItemComponent& operator= (const ItemComponent&);
  48539. };
  48540. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48541. {
  48542. public:
  48543. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48544. : owner (owner_), commandID (commandID_)
  48545. {
  48546. }
  48547. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48548. bool mightContainSubItems() { return false; }
  48549. int getItemHeight() const { return 20; }
  48550. Component* createItemComponent()
  48551. {
  48552. return new ItemComponent (owner, commandID);
  48553. }
  48554. juce_UseDebuggingNewOperator
  48555. private:
  48556. KeyMappingEditorComponent& owner;
  48557. const CommandID commandID;
  48558. MappingItem (const MappingItem&);
  48559. MappingItem& operator= (const MappingItem&);
  48560. };
  48561. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48562. {
  48563. public:
  48564. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48565. : owner (owner_), categoryName (name)
  48566. {
  48567. }
  48568. const String getUniqueName() const { return categoryName + "_cat"; }
  48569. bool mightContainSubItems() { return true; }
  48570. int getItemHeight() const { return 28; }
  48571. void paintItem (Graphics& g, int width, int height)
  48572. {
  48573. g.setFont (height * 0.6f, Font::bold);
  48574. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48575. g.drawText (categoryName,
  48576. 2, 0, width - 2, height,
  48577. Justification::centredLeft, true);
  48578. }
  48579. void itemOpennessChanged (bool isNowOpen)
  48580. {
  48581. if (isNowOpen)
  48582. {
  48583. if (getNumSubItems() == 0)
  48584. {
  48585. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48586. for (int i = 0; i < commands.size(); ++i)
  48587. {
  48588. if (owner.shouldCommandBeIncluded (commands[i]))
  48589. addSubItem (new MappingItem (owner, commands[i]));
  48590. }
  48591. }
  48592. }
  48593. else
  48594. {
  48595. clearSubItems();
  48596. }
  48597. }
  48598. juce_UseDebuggingNewOperator
  48599. private:
  48600. KeyMappingEditorComponent& owner;
  48601. String categoryName;
  48602. CategoryItem (const CategoryItem&);
  48603. CategoryItem& operator= (const CategoryItem&);
  48604. };
  48605. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48606. public ChangeListener,
  48607. public ButtonListener
  48608. {
  48609. public:
  48610. TopLevelItem (KeyMappingEditorComponent& owner_)
  48611. : owner (owner_)
  48612. {
  48613. setLinesDrawnForSubItems (false);
  48614. owner.getMappings().addChangeListener (this);
  48615. }
  48616. ~TopLevelItem()
  48617. {
  48618. owner.getMappings().removeChangeListener (this);
  48619. }
  48620. bool mightContainSubItems() { return true; }
  48621. const String getUniqueName() const { return "keys"; }
  48622. void changeListenerCallback (ChangeBroadcaster*)
  48623. {
  48624. const ScopedPointer <XmlElement> oldOpenness (owner.tree.getOpennessState (true));
  48625. clearSubItems();
  48626. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48627. for (int i = 0; i < categories.size(); ++i)
  48628. {
  48629. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48630. int count = 0;
  48631. for (int j = 0; j < commands.size(); ++j)
  48632. if (owner.shouldCommandBeIncluded (commands[j]))
  48633. ++count;
  48634. if (count > 0)
  48635. addSubItem (new CategoryItem (owner, categories[i]));
  48636. }
  48637. if (oldOpenness != 0)
  48638. owner.tree.restoreOpennessState (*oldOpenness);
  48639. }
  48640. void buttonClicked (Button*)
  48641. {
  48642. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48643. TRANS("Reset to defaults"),
  48644. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48645. TRANS("Reset")))
  48646. {
  48647. owner.getMappings().resetToDefaultMappings();
  48648. }
  48649. }
  48650. private:
  48651. KeyMappingEditorComponent& owner;
  48652. };
  48653. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48654. const bool showResetToDefaultButton)
  48655. : mappings (mappingManager),
  48656. resetButton (TRANS ("reset to defaults"))
  48657. {
  48658. treeItem = new TopLevelItem (*this);
  48659. if (showResetToDefaultButton)
  48660. {
  48661. addAndMakeVisible (&resetButton);
  48662. resetButton.addButtonListener (treeItem);
  48663. }
  48664. addAndMakeVisible (&tree);
  48665. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48666. tree.setRootItemVisible (false);
  48667. tree.setDefaultOpenness (true);
  48668. tree.setRootItem (treeItem);
  48669. }
  48670. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48671. {
  48672. tree.setRootItem (0);
  48673. }
  48674. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48675. const Colour& textColour)
  48676. {
  48677. setColour (backgroundColourId, mainBackground);
  48678. setColour (textColourId, textColour);
  48679. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48680. }
  48681. void KeyMappingEditorComponent::parentHierarchyChanged()
  48682. {
  48683. treeItem->changeListenerCallback (0);
  48684. }
  48685. void KeyMappingEditorComponent::resized()
  48686. {
  48687. int h = getHeight();
  48688. if (resetButton.isVisible())
  48689. {
  48690. const int buttonHeight = 20;
  48691. h -= buttonHeight + 8;
  48692. int x = getWidth() - 8;
  48693. resetButton.changeWidthToFitText (buttonHeight);
  48694. resetButton.setTopRightPosition (x, h + 6);
  48695. }
  48696. tree.setBounds (0, 0, getWidth(), h);
  48697. }
  48698. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48699. {
  48700. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48701. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48702. }
  48703. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48704. {
  48705. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48706. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48707. }
  48708. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48709. {
  48710. return key.getTextDescription();
  48711. }
  48712. END_JUCE_NAMESPACE
  48713. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48714. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48715. BEGIN_JUCE_NAMESPACE
  48716. KeyPress::KeyPress() throw()
  48717. : keyCode (0),
  48718. mods (0),
  48719. textCharacter (0)
  48720. {
  48721. }
  48722. KeyPress::KeyPress (const int keyCode_,
  48723. const ModifierKeys& mods_,
  48724. const juce_wchar textCharacter_) throw()
  48725. : keyCode (keyCode_),
  48726. mods (mods_),
  48727. textCharacter (textCharacter_)
  48728. {
  48729. }
  48730. KeyPress::KeyPress (const int keyCode_) throw()
  48731. : keyCode (keyCode_),
  48732. textCharacter (0)
  48733. {
  48734. }
  48735. KeyPress::KeyPress (const KeyPress& other) throw()
  48736. : keyCode (other.keyCode),
  48737. mods (other.mods),
  48738. textCharacter (other.textCharacter)
  48739. {
  48740. }
  48741. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48742. {
  48743. keyCode = other.keyCode;
  48744. mods = other.mods;
  48745. textCharacter = other.textCharacter;
  48746. return *this;
  48747. }
  48748. bool KeyPress::operator== (const KeyPress& other) const throw()
  48749. {
  48750. return mods.getRawFlags() == other.mods.getRawFlags()
  48751. && (textCharacter == other.textCharacter
  48752. || textCharacter == 0
  48753. || other.textCharacter == 0)
  48754. && (keyCode == other.keyCode
  48755. || (keyCode < 256
  48756. && other.keyCode < 256
  48757. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48758. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48759. }
  48760. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48761. {
  48762. return ! operator== (other);
  48763. }
  48764. bool KeyPress::isCurrentlyDown() const
  48765. {
  48766. return isKeyCurrentlyDown (keyCode)
  48767. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48768. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48769. }
  48770. namespace KeyPressHelpers
  48771. {
  48772. struct KeyNameAndCode
  48773. {
  48774. const char* name;
  48775. int code;
  48776. };
  48777. const KeyNameAndCode translations[] =
  48778. {
  48779. { "spacebar", KeyPress::spaceKey },
  48780. { "return", KeyPress::returnKey },
  48781. { "escape", KeyPress::escapeKey },
  48782. { "backspace", KeyPress::backspaceKey },
  48783. { "cursor left", KeyPress::leftKey },
  48784. { "cursor right", KeyPress::rightKey },
  48785. { "cursor up", KeyPress::upKey },
  48786. { "cursor down", KeyPress::downKey },
  48787. { "page up", KeyPress::pageUpKey },
  48788. { "page down", KeyPress::pageDownKey },
  48789. { "home", KeyPress::homeKey },
  48790. { "end", KeyPress::endKey },
  48791. { "delete", KeyPress::deleteKey },
  48792. { "insert", KeyPress::insertKey },
  48793. { "tab", KeyPress::tabKey },
  48794. { "play", KeyPress::playKey },
  48795. { "stop", KeyPress::stopKey },
  48796. { "fast forward", KeyPress::fastForwardKey },
  48797. { "rewind", KeyPress::rewindKey }
  48798. };
  48799. const String numberPadPrefix() { return "numpad "; }
  48800. }
  48801. const KeyPress KeyPress::createFromDescription (const String& desc)
  48802. {
  48803. int modifiers = 0;
  48804. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48805. || desc.containsWholeWordIgnoreCase ("control")
  48806. || desc.containsWholeWordIgnoreCase ("ctl"))
  48807. modifiers |= ModifierKeys::ctrlModifier;
  48808. if (desc.containsWholeWordIgnoreCase ("shift")
  48809. || desc.containsWholeWordIgnoreCase ("shft"))
  48810. modifiers |= ModifierKeys::shiftModifier;
  48811. if (desc.containsWholeWordIgnoreCase ("alt")
  48812. || desc.containsWholeWordIgnoreCase ("option"))
  48813. modifiers |= ModifierKeys::altModifier;
  48814. if (desc.containsWholeWordIgnoreCase ("command")
  48815. || desc.containsWholeWordIgnoreCase ("cmd"))
  48816. modifiers |= ModifierKeys::commandModifier;
  48817. int key = 0;
  48818. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48819. {
  48820. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48821. {
  48822. key = KeyPressHelpers::translations[i].code;
  48823. break;
  48824. }
  48825. }
  48826. if (key == 0)
  48827. {
  48828. // see if it's a numpad key..
  48829. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48830. {
  48831. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48832. if (lastChar >= '0' && lastChar <= '9')
  48833. key = numberPad0 + lastChar - '0';
  48834. else if (lastChar == '+')
  48835. key = numberPadAdd;
  48836. else if (lastChar == '-')
  48837. key = numberPadSubtract;
  48838. else if (lastChar == '*')
  48839. key = numberPadMultiply;
  48840. else if (lastChar == '/')
  48841. key = numberPadDivide;
  48842. else if (lastChar == '.')
  48843. key = numberPadDecimalPoint;
  48844. else if (lastChar == '=')
  48845. key = numberPadEquals;
  48846. else if (desc.endsWith ("separator"))
  48847. key = numberPadSeparator;
  48848. else if (desc.endsWith ("delete"))
  48849. key = numberPadDelete;
  48850. }
  48851. if (key == 0)
  48852. {
  48853. // see if it's a function key..
  48854. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48855. for (int i = 1; i <= 12; ++i)
  48856. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48857. key = F1Key + i - 1;
  48858. if (key == 0)
  48859. {
  48860. // give up and use the hex code..
  48861. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48862. .toLowerCase()
  48863. .retainCharacters ("0123456789abcdef")
  48864. .getHexValue32();
  48865. if (hexCode > 0)
  48866. key = hexCode;
  48867. else
  48868. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48869. }
  48870. }
  48871. }
  48872. return KeyPress (key, ModifierKeys (modifiers), 0);
  48873. }
  48874. const String KeyPress::getTextDescription() const
  48875. {
  48876. String desc;
  48877. if (keyCode > 0)
  48878. {
  48879. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48880. // want to store it as being a slash, not shift+whatever.
  48881. if (textCharacter == '/')
  48882. return "/";
  48883. if (mods.isCtrlDown())
  48884. desc << "ctrl + ";
  48885. if (mods.isShiftDown())
  48886. desc << "shift + ";
  48887. #if JUCE_MAC
  48888. // only do this on the mac, because on Windows ctrl and command are the same,
  48889. // and this would get confusing
  48890. if (mods.isCommandDown())
  48891. desc << "command + ";
  48892. if (mods.isAltDown())
  48893. desc << "option + ";
  48894. #else
  48895. if (mods.isAltDown())
  48896. desc << "alt + ";
  48897. #endif
  48898. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48899. if (keyCode == KeyPressHelpers::translations[i].code)
  48900. return desc + KeyPressHelpers::translations[i].name;
  48901. if (keyCode >= F1Key && keyCode <= F16Key)
  48902. desc << 'F' << (1 + keyCode - F1Key);
  48903. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48904. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48905. else if (keyCode >= 33 && keyCode < 176)
  48906. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48907. else if (keyCode == numberPadAdd)
  48908. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48909. else if (keyCode == numberPadSubtract)
  48910. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48911. else if (keyCode == numberPadMultiply)
  48912. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48913. else if (keyCode == numberPadDivide)
  48914. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48915. else if (keyCode == numberPadSeparator)
  48916. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48917. else if (keyCode == numberPadDecimalPoint)
  48918. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48919. else if (keyCode == numberPadDelete)
  48920. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48921. else
  48922. desc << '#' << String::toHexString (keyCode);
  48923. }
  48924. return desc;
  48925. }
  48926. END_JUCE_NAMESPACE
  48927. /*** End of inlined file: juce_KeyPress.cpp ***/
  48928. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48929. BEGIN_JUCE_NAMESPACE
  48930. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48931. : commandManager (commandManager_)
  48932. {
  48933. // A manager is needed to get the descriptions of commands, and will be called when
  48934. // a command is invoked. So you can't leave this null..
  48935. jassert (commandManager_ != 0);
  48936. Desktop::getInstance().addFocusChangeListener (this);
  48937. }
  48938. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48939. : commandManager (other.commandManager)
  48940. {
  48941. Desktop::getInstance().addFocusChangeListener (this);
  48942. }
  48943. KeyPressMappingSet::~KeyPressMappingSet()
  48944. {
  48945. Desktop::getInstance().removeFocusChangeListener (this);
  48946. }
  48947. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48948. {
  48949. for (int i = 0; i < mappings.size(); ++i)
  48950. if (mappings.getUnchecked(i)->commandID == commandID)
  48951. return mappings.getUnchecked (i)->keypresses;
  48952. return Array <KeyPress> ();
  48953. }
  48954. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48955. const KeyPress& newKeyPress,
  48956. int insertIndex)
  48957. {
  48958. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48959. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48960. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48961. && ! newKeyPress.getModifiers().isShiftDown()));
  48962. if (findCommandForKeyPress (newKeyPress) != commandID)
  48963. {
  48964. removeKeyPress (newKeyPress);
  48965. if (newKeyPress.isValid())
  48966. {
  48967. for (int i = mappings.size(); --i >= 0;)
  48968. {
  48969. if (mappings.getUnchecked(i)->commandID == commandID)
  48970. {
  48971. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48972. sendChangeMessage();
  48973. return;
  48974. }
  48975. }
  48976. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48977. if (ci != 0)
  48978. {
  48979. CommandMapping* const cm = new CommandMapping();
  48980. cm->commandID = commandID;
  48981. cm->keypresses.add (newKeyPress);
  48982. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48983. mappings.add (cm);
  48984. sendChangeMessage();
  48985. }
  48986. }
  48987. }
  48988. }
  48989. void KeyPressMappingSet::resetToDefaultMappings()
  48990. {
  48991. mappings.clear();
  48992. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48993. {
  48994. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48995. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48996. {
  48997. addKeyPress (ci->commandID,
  48998. ci->defaultKeypresses.getReference (j));
  48999. }
  49000. }
  49001. sendChangeMessage();
  49002. }
  49003. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49004. {
  49005. clearAllKeyPresses (commandID);
  49006. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49007. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49008. {
  49009. addKeyPress (ci->commandID,
  49010. ci->defaultKeypresses.getReference (j));
  49011. }
  49012. }
  49013. void KeyPressMappingSet::clearAllKeyPresses()
  49014. {
  49015. if (mappings.size() > 0)
  49016. {
  49017. sendChangeMessage();
  49018. mappings.clear();
  49019. }
  49020. }
  49021. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49022. {
  49023. for (int i = mappings.size(); --i >= 0;)
  49024. {
  49025. if (mappings.getUnchecked(i)->commandID == commandID)
  49026. {
  49027. mappings.remove (i);
  49028. sendChangeMessage();
  49029. }
  49030. }
  49031. }
  49032. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49033. {
  49034. if (keypress.isValid())
  49035. {
  49036. for (int i = mappings.size(); --i >= 0;)
  49037. {
  49038. CommandMapping* const cm = mappings.getUnchecked(i);
  49039. for (int j = cm->keypresses.size(); --j >= 0;)
  49040. {
  49041. if (keypress == cm->keypresses [j])
  49042. {
  49043. cm->keypresses.remove (j);
  49044. sendChangeMessage();
  49045. }
  49046. }
  49047. }
  49048. }
  49049. }
  49050. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49051. {
  49052. for (int i = mappings.size(); --i >= 0;)
  49053. {
  49054. if (mappings.getUnchecked(i)->commandID == commandID)
  49055. {
  49056. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49057. sendChangeMessage();
  49058. break;
  49059. }
  49060. }
  49061. }
  49062. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49063. {
  49064. for (int i = 0; i < mappings.size(); ++i)
  49065. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49066. return mappings.getUnchecked(i)->commandID;
  49067. return 0;
  49068. }
  49069. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49070. {
  49071. for (int i = mappings.size(); --i >= 0;)
  49072. if (mappings.getUnchecked(i)->commandID == commandID)
  49073. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49074. return false;
  49075. }
  49076. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49077. const KeyPress& key,
  49078. const bool isKeyDown,
  49079. const int millisecsSinceKeyPressed,
  49080. Component* const originatingComponent) const
  49081. {
  49082. ApplicationCommandTarget::InvocationInfo info (commandID);
  49083. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49084. info.isKeyDown = isKeyDown;
  49085. info.keyPress = key;
  49086. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49087. info.originatingComponent = originatingComponent;
  49088. commandManager->invoke (info, false);
  49089. }
  49090. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49091. {
  49092. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49093. {
  49094. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49095. {
  49096. // if the XML was created as a set of differences from the default mappings,
  49097. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49098. resetToDefaultMappings();
  49099. }
  49100. else
  49101. {
  49102. // if the XML was created calling createXml (false), then we need to clear all
  49103. // the keys and treat the xml as describing the entire set of mappings.
  49104. clearAllKeyPresses();
  49105. }
  49106. forEachXmlChildElement (xmlVersion, map)
  49107. {
  49108. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49109. if (commandId != 0)
  49110. {
  49111. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49112. if (map->hasTagName ("MAPPING"))
  49113. {
  49114. addKeyPress (commandId, key);
  49115. }
  49116. else if (map->hasTagName ("UNMAPPING"))
  49117. {
  49118. if (containsMapping (commandId, key))
  49119. removeKeyPress (key);
  49120. }
  49121. }
  49122. }
  49123. return true;
  49124. }
  49125. return false;
  49126. }
  49127. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49128. {
  49129. ScopedPointer <KeyPressMappingSet> defaultSet;
  49130. if (saveDifferencesFromDefaultSet)
  49131. {
  49132. defaultSet = new KeyPressMappingSet (commandManager);
  49133. defaultSet->resetToDefaultMappings();
  49134. }
  49135. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49136. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49137. int i;
  49138. for (i = 0; i < mappings.size(); ++i)
  49139. {
  49140. const CommandMapping* const cm = mappings.getUnchecked(i);
  49141. for (int j = 0; j < cm->keypresses.size(); ++j)
  49142. {
  49143. if (defaultSet == 0
  49144. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49145. {
  49146. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49147. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49148. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49149. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49150. }
  49151. }
  49152. }
  49153. if (defaultSet != 0)
  49154. {
  49155. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49156. {
  49157. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49158. for (int j = 0; j < cm->keypresses.size(); ++j)
  49159. {
  49160. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49161. {
  49162. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49163. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49164. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49165. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49166. }
  49167. }
  49168. }
  49169. }
  49170. return doc;
  49171. }
  49172. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49173. Component* originatingComponent)
  49174. {
  49175. bool used = false;
  49176. const CommandID commandID = findCommandForKeyPress (key);
  49177. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49178. if (ci != 0
  49179. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49180. {
  49181. ApplicationCommandInfo info (0);
  49182. if (commandManager->getTargetForCommand (commandID, info) != 0
  49183. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49184. {
  49185. invokeCommand (commandID, key, true, 0, originatingComponent);
  49186. used = true;
  49187. }
  49188. else
  49189. {
  49190. if (originatingComponent != 0)
  49191. originatingComponent->getLookAndFeel().playAlertSound();
  49192. }
  49193. }
  49194. return used;
  49195. }
  49196. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49197. {
  49198. bool used = false;
  49199. const uint32 now = Time::getMillisecondCounter();
  49200. for (int i = mappings.size(); --i >= 0;)
  49201. {
  49202. CommandMapping* const cm = mappings.getUnchecked(i);
  49203. if (cm->wantsKeyUpDownCallbacks)
  49204. {
  49205. for (int j = cm->keypresses.size(); --j >= 0;)
  49206. {
  49207. const KeyPress key (cm->keypresses.getReference (j));
  49208. const bool isDown = key.isCurrentlyDown();
  49209. int keyPressEntryIndex = 0;
  49210. bool wasDown = false;
  49211. for (int k = keysDown.size(); --k >= 0;)
  49212. {
  49213. if (key == keysDown.getUnchecked(k)->key)
  49214. {
  49215. keyPressEntryIndex = k;
  49216. wasDown = true;
  49217. used = true;
  49218. break;
  49219. }
  49220. }
  49221. if (isDown != wasDown)
  49222. {
  49223. int millisecs = 0;
  49224. if (isDown)
  49225. {
  49226. KeyPressTime* const k = new KeyPressTime();
  49227. k->key = key;
  49228. k->timeWhenPressed = now;
  49229. keysDown.add (k);
  49230. }
  49231. else
  49232. {
  49233. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49234. if (now > pressTime)
  49235. millisecs = now - pressTime;
  49236. keysDown.remove (keyPressEntryIndex);
  49237. }
  49238. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49239. used = true;
  49240. }
  49241. }
  49242. }
  49243. }
  49244. return used;
  49245. }
  49246. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49247. {
  49248. if (focusedComponent != 0)
  49249. focusedComponent->keyStateChanged (false);
  49250. }
  49251. END_JUCE_NAMESPACE
  49252. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49253. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49254. BEGIN_JUCE_NAMESPACE
  49255. ModifierKeys::ModifierKeys (const int flags_) throw()
  49256. : flags (flags_)
  49257. {
  49258. }
  49259. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49260. : flags (other.flags)
  49261. {
  49262. }
  49263. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49264. {
  49265. flags = other.flags;
  49266. return *this;
  49267. }
  49268. ModifierKeys ModifierKeys::currentModifiers;
  49269. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49270. {
  49271. return currentModifiers;
  49272. }
  49273. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49274. {
  49275. int num = 0;
  49276. if (isLeftButtonDown()) ++num;
  49277. if (isRightButtonDown()) ++num;
  49278. if (isMiddleButtonDown()) ++num;
  49279. return num;
  49280. }
  49281. END_JUCE_NAMESPACE
  49282. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49283. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49284. BEGIN_JUCE_NAMESPACE
  49285. class ComponentAnimator::AnimationTask
  49286. {
  49287. public:
  49288. AnimationTask (Component* const comp)
  49289. : component (comp)
  49290. {
  49291. }
  49292. void reset (const Rectangle<int>& finalBounds,
  49293. float finalAlpha,
  49294. int millisecondsToSpendMoving,
  49295. bool useProxyComponent,
  49296. double startSpeed_, double endSpeed_)
  49297. {
  49298. msElapsed = 0;
  49299. msTotal = jmax (1, millisecondsToSpendMoving);
  49300. lastProgress = 0;
  49301. destination = finalBounds;
  49302. destAlpha = finalAlpha;
  49303. isMoving = (finalBounds != component->getBounds());
  49304. isChangingAlpha = (finalAlpha != component->getAlpha());
  49305. left = component->getX();
  49306. top = component->getY();
  49307. right = component->getRight();
  49308. bottom = component->getBottom();
  49309. alpha = component->getAlpha();
  49310. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49311. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49312. midSpeed = invTotalDistance;
  49313. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49314. if (useProxyComponent)
  49315. proxy = new ProxyComponent (*component);
  49316. else
  49317. proxy = 0;
  49318. component->setVisible (! useProxyComponent);
  49319. }
  49320. bool useTimeslice (const int elapsed)
  49321. {
  49322. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49323. : static_cast <Component*> (component);
  49324. if (c != 0)
  49325. {
  49326. msElapsed += elapsed;
  49327. double newProgress = msElapsed / (double) msTotal;
  49328. if (newProgress >= 0 && newProgress < 1.0)
  49329. {
  49330. newProgress = timeToDistance (newProgress);
  49331. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49332. jassert (newProgress >= lastProgress);
  49333. lastProgress = newProgress;
  49334. if (delta < 1.0)
  49335. {
  49336. bool stillBusy = false;
  49337. if (isMoving)
  49338. {
  49339. left += (destination.getX() - left) * delta;
  49340. top += (destination.getY() - top) * delta;
  49341. right += (destination.getRight() - right) * delta;
  49342. bottom += (destination.getBottom() - bottom) * delta;
  49343. const Rectangle<int> newBounds (roundToInt (left),
  49344. roundToInt (top),
  49345. roundToInt (right - left),
  49346. roundToInt (bottom - top));
  49347. if (newBounds != destination)
  49348. {
  49349. c->setBounds (newBounds);
  49350. stillBusy = true;
  49351. }
  49352. }
  49353. if (isChangingAlpha)
  49354. {
  49355. alpha += (destAlpha - alpha) * delta;
  49356. c->setAlpha ((float) alpha);
  49357. stillBusy = true;
  49358. }
  49359. if (stillBusy)
  49360. return true;
  49361. }
  49362. }
  49363. }
  49364. moveToFinalDestination();
  49365. return false;
  49366. }
  49367. void moveToFinalDestination()
  49368. {
  49369. if (component != 0)
  49370. {
  49371. component->setAlpha ((float) destAlpha);
  49372. component->setBounds (destination);
  49373. }
  49374. }
  49375. class ProxyComponent : public Component
  49376. {
  49377. public:
  49378. ProxyComponent (Component& component)
  49379. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49380. {
  49381. setBounds (component.getBounds());
  49382. setAlpha (component.getAlpha());
  49383. setInterceptsMouseClicks (false, false);
  49384. Component* const parent = component.getParentComponent();
  49385. if (parent != 0)
  49386. parent->addAndMakeVisible (this);
  49387. else if (component.isOnDesktop() && component.getPeer() != 0)
  49388. addToDesktop (component.getPeer()->getStyleFlags());
  49389. else
  49390. jassertfalse; // seem to be trying to animate a component that's not visible..
  49391. setVisible (true);
  49392. toBehind (&component);
  49393. }
  49394. void paint (Graphics& g)
  49395. {
  49396. g.setOpacity (1.0f);
  49397. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49398. 0, 0, image.getWidth(), image.getHeight());
  49399. }
  49400. juce_UseDebuggingNewOperator
  49401. private:
  49402. Image image;
  49403. ProxyComponent (const ProxyComponent&);
  49404. ProxyComponent& operator= (const ProxyComponent&);
  49405. };
  49406. Component::SafePointer<Component> component;
  49407. ScopedPointer<Component> proxy;
  49408. Rectangle<int> destination;
  49409. double destAlpha;
  49410. int msElapsed, msTotal;
  49411. double startSpeed, midSpeed, endSpeed, lastProgress;
  49412. double left, top, right, bottom, alpha;
  49413. bool isMoving, isChangingAlpha;
  49414. private:
  49415. double timeToDistance (const double time) const throw()
  49416. {
  49417. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49418. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49419. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49420. }
  49421. };
  49422. ComponentAnimator::ComponentAnimator()
  49423. : lastTime (0)
  49424. {
  49425. }
  49426. ComponentAnimator::~ComponentAnimator()
  49427. {
  49428. }
  49429. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49430. {
  49431. for (int i = tasks.size(); --i >= 0;)
  49432. if (component == tasks.getUnchecked(i)->component.getComponent())
  49433. return tasks.getUnchecked(i);
  49434. return 0;
  49435. }
  49436. void ComponentAnimator::animateComponent (Component* const component,
  49437. const Rectangle<int>& finalBounds,
  49438. const float finalAlpha,
  49439. const int millisecondsToSpendMoving,
  49440. const bool useProxyComponent,
  49441. const double startSpeed,
  49442. const double endSpeed)
  49443. {
  49444. // the speeds must be 0 or greater!
  49445. jassert (startSpeed >= 0 && endSpeed >= 0)
  49446. if (component != 0)
  49447. {
  49448. AnimationTask* at = findTaskFor (component);
  49449. if (at == 0)
  49450. {
  49451. at = new AnimationTask (component);
  49452. tasks.add (at);
  49453. sendChangeMessage();
  49454. }
  49455. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49456. useProxyComponent, startSpeed, endSpeed);
  49457. if (! isTimerRunning())
  49458. {
  49459. lastTime = Time::getMillisecondCounter();
  49460. startTimer (1000 / 50);
  49461. }
  49462. }
  49463. }
  49464. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49465. {
  49466. if (component != 0)
  49467. {
  49468. if (component->isShowing() && millisecondsToTake > 0)
  49469. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49470. component->setVisible (false);
  49471. }
  49472. }
  49473. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49474. {
  49475. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49476. {
  49477. component->setAlpha (0.0f);
  49478. component->setVisible (true);
  49479. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49480. }
  49481. }
  49482. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49483. {
  49484. if (tasks.size() > 0)
  49485. {
  49486. if (moveComponentsToTheirFinalPositions)
  49487. for (int i = tasks.size(); --i >= 0;)
  49488. tasks.getUnchecked(i)->moveToFinalDestination();
  49489. tasks.clear();
  49490. sendChangeMessage();
  49491. }
  49492. }
  49493. void ComponentAnimator::cancelAnimation (Component* const component,
  49494. const bool moveComponentToItsFinalPosition)
  49495. {
  49496. AnimationTask* const at = findTaskFor (component);
  49497. if (at != 0)
  49498. {
  49499. if (moveComponentToItsFinalPosition)
  49500. at->moveToFinalDestination();
  49501. tasks.removeObject (at);
  49502. sendChangeMessage();
  49503. }
  49504. }
  49505. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49506. {
  49507. jassert (component != 0);
  49508. AnimationTask* const at = findTaskFor (component);
  49509. if (at != 0)
  49510. return at->destination;
  49511. return component->getBounds();
  49512. }
  49513. bool ComponentAnimator::isAnimating (Component* component) const
  49514. {
  49515. return findTaskFor (component) != 0;
  49516. }
  49517. void ComponentAnimator::timerCallback()
  49518. {
  49519. const uint32 timeNow = Time::getMillisecondCounter();
  49520. if (lastTime == 0 || lastTime == timeNow)
  49521. lastTime = timeNow;
  49522. const int elapsed = timeNow - lastTime;
  49523. for (int i = tasks.size(); --i >= 0;)
  49524. {
  49525. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49526. {
  49527. tasks.remove (i);
  49528. sendChangeMessage();
  49529. }
  49530. }
  49531. lastTime = timeNow;
  49532. if (tasks.size() == 0)
  49533. stopTimer();
  49534. }
  49535. END_JUCE_NAMESPACE
  49536. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49537. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49538. BEGIN_JUCE_NAMESPACE
  49539. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49540. : minW (0),
  49541. maxW (0x3fffffff),
  49542. minH (0),
  49543. maxH (0x3fffffff),
  49544. minOffTop (0),
  49545. minOffLeft (0),
  49546. minOffBottom (0),
  49547. minOffRight (0),
  49548. aspectRatio (0.0)
  49549. {
  49550. }
  49551. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49552. {
  49553. }
  49554. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49555. {
  49556. minW = minimumWidth;
  49557. }
  49558. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49559. {
  49560. maxW = maximumWidth;
  49561. }
  49562. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49563. {
  49564. minH = minimumHeight;
  49565. }
  49566. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49567. {
  49568. maxH = maximumHeight;
  49569. }
  49570. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49571. {
  49572. jassert (maxW >= minimumWidth);
  49573. jassert (maxH >= minimumHeight);
  49574. jassert (minimumWidth > 0 && minimumHeight > 0);
  49575. minW = minimumWidth;
  49576. minH = minimumHeight;
  49577. if (minW > maxW)
  49578. maxW = minW;
  49579. if (minH > maxH)
  49580. maxH = minH;
  49581. }
  49582. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49583. {
  49584. jassert (maximumWidth >= minW);
  49585. jassert (maximumHeight >= minH);
  49586. jassert (maximumWidth > 0 && maximumHeight > 0);
  49587. maxW = jmax (minW, maximumWidth);
  49588. maxH = jmax (minH, maximumHeight);
  49589. }
  49590. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49591. const int minimumHeight,
  49592. const int maximumWidth,
  49593. const int maximumHeight) throw()
  49594. {
  49595. jassert (maximumWidth >= minimumWidth);
  49596. jassert (maximumHeight >= minimumHeight);
  49597. jassert (maximumWidth > 0 && maximumHeight > 0);
  49598. jassert (minimumWidth > 0 && minimumHeight > 0);
  49599. minW = jmax (0, minimumWidth);
  49600. minH = jmax (0, minimumHeight);
  49601. maxW = jmax (minW, maximumWidth);
  49602. maxH = jmax (minH, maximumHeight);
  49603. }
  49604. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49605. const int minimumWhenOffTheLeft,
  49606. const int minimumWhenOffTheBottom,
  49607. const int minimumWhenOffTheRight) throw()
  49608. {
  49609. minOffTop = minimumWhenOffTheTop;
  49610. minOffLeft = minimumWhenOffTheLeft;
  49611. minOffBottom = minimumWhenOffTheBottom;
  49612. minOffRight = minimumWhenOffTheRight;
  49613. }
  49614. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49615. {
  49616. aspectRatio = jmax (0.0, widthOverHeight);
  49617. }
  49618. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49619. {
  49620. return aspectRatio;
  49621. }
  49622. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49623. const Rectangle<int>& targetBounds,
  49624. const bool isStretchingTop,
  49625. const bool isStretchingLeft,
  49626. const bool isStretchingBottom,
  49627. const bool isStretchingRight)
  49628. {
  49629. jassert (component != 0);
  49630. Rectangle<int> limits, bounds (targetBounds);
  49631. BorderSize border;
  49632. Component* const parent = component->getParentComponent();
  49633. if (parent == 0)
  49634. {
  49635. ComponentPeer* peer = component->getPeer();
  49636. if (peer != 0)
  49637. border = peer->getFrameSize();
  49638. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49639. }
  49640. else
  49641. {
  49642. limits.setSize (parent->getWidth(), parent->getHeight());
  49643. }
  49644. border.addTo (bounds);
  49645. checkBounds (bounds,
  49646. border.addedTo (component->getBounds()), limits,
  49647. isStretchingTop, isStretchingLeft,
  49648. isStretchingBottom, isStretchingRight);
  49649. border.subtractFrom (bounds);
  49650. applyBoundsToComponent (component, bounds);
  49651. }
  49652. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49653. {
  49654. setBoundsForComponent (component, component->getBounds(),
  49655. false, false, false, false);
  49656. }
  49657. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49658. const Rectangle<int>& bounds)
  49659. {
  49660. component->setBounds (bounds);
  49661. }
  49662. void ComponentBoundsConstrainer::resizeStart()
  49663. {
  49664. }
  49665. void ComponentBoundsConstrainer::resizeEnd()
  49666. {
  49667. }
  49668. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49669. const Rectangle<int>& old,
  49670. const Rectangle<int>& limits,
  49671. const bool isStretchingTop,
  49672. const bool isStretchingLeft,
  49673. const bool isStretchingBottom,
  49674. const bool isStretchingRight)
  49675. {
  49676. // constrain the size if it's being stretched..
  49677. if (isStretchingLeft)
  49678. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49679. if (isStretchingRight)
  49680. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49681. if (isStretchingTop)
  49682. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49683. if (isStretchingBottom)
  49684. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49685. if (bounds.isEmpty())
  49686. return;
  49687. if (minOffTop > 0)
  49688. {
  49689. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49690. if (bounds.getY() < limit)
  49691. {
  49692. if (isStretchingTop)
  49693. bounds.setTop (limits.getY());
  49694. else
  49695. bounds.setY (limit);
  49696. }
  49697. }
  49698. if (minOffLeft > 0)
  49699. {
  49700. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49701. if (bounds.getX() < limit)
  49702. {
  49703. if (isStretchingLeft)
  49704. bounds.setLeft (limits.getX());
  49705. else
  49706. bounds.setX (limit);
  49707. }
  49708. }
  49709. if (minOffBottom > 0)
  49710. {
  49711. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49712. if (bounds.getY() > limit)
  49713. {
  49714. if (isStretchingBottom)
  49715. bounds.setBottom (limits.getBottom());
  49716. else
  49717. bounds.setY (limit);
  49718. }
  49719. }
  49720. if (minOffRight > 0)
  49721. {
  49722. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49723. if (bounds.getX() > limit)
  49724. {
  49725. if (isStretchingRight)
  49726. bounds.setRight (limits.getRight());
  49727. else
  49728. bounds.setX (limit);
  49729. }
  49730. }
  49731. // constrain the aspect ratio if one has been specified..
  49732. if (aspectRatio > 0.0)
  49733. {
  49734. bool adjustWidth;
  49735. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49736. {
  49737. adjustWidth = true;
  49738. }
  49739. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49740. {
  49741. adjustWidth = false;
  49742. }
  49743. else
  49744. {
  49745. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49746. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49747. adjustWidth = (oldRatio > newRatio);
  49748. }
  49749. if (adjustWidth)
  49750. {
  49751. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49752. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49753. {
  49754. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49755. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49756. }
  49757. }
  49758. else
  49759. {
  49760. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49761. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49762. {
  49763. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49764. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49765. }
  49766. }
  49767. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49768. {
  49769. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49770. }
  49771. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49772. {
  49773. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49774. }
  49775. else
  49776. {
  49777. if (isStretchingLeft)
  49778. bounds.setX (old.getRight() - bounds.getWidth());
  49779. if (isStretchingTop)
  49780. bounds.setY (old.getBottom() - bounds.getHeight());
  49781. }
  49782. }
  49783. jassert (! bounds.isEmpty());
  49784. }
  49785. END_JUCE_NAMESPACE
  49786. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49787. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49788. BEGIN_JUCE_NAMESPACE
  49789. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49790. : component (component_),
  49791. lastPeer (0),
  49792. reentrant (false)
  49793. {
  49794. jassert (component != 0); // can't use this with a null pointer..
  49795. component->addComponentListener (this);
  49796. registerWithParentComps();
  49797. }
  49798. ComponentMovementWatcher::~ComponentMovementWatcher()
  49799. {
  49800. component->removeComponentListener (this);
  49801. unregister();
  49802. }
  49803. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49804. {
  49805. // agh! don't delete the target component without deleting this object first!
  49806. jassert (component != 0);
  49807. if (! reentrant)
  49808. {
  49809. reentrant = true;
  49810. ComponentPeer* const peer = component->getPeer();
  49811. if (peer != lastPeer)
  49812. {
  49813. componentPeerChanged();
  49814. if (component == 0)
  49815. return;
  49816. lastPeer = peer;
  49817. }
  49818. unregister();
  49819. registerWithParentComps();
  49820. reentrant = false;
  49821. componentMovedOrResized (*component, true, true);
  49822. }
  49823. }
  49824. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49825. {
  49826. // agh! don't delete the target component without deleting this object first!
  49827. jassert (component != 0);
  49828. if (wasMoved)
  49829. {
  49830. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49831. wasMoved = lastBounds.getPosition() != pos;
  49832. lastBounds.setPosition (pos);
  49833. }
  49834. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49835. lastBounds.setSize (component->getWidth(), component->getHeight());
  49836. if (wasMoved || wasResized)
  49837. componentMovedOrResized (wasMoved, wasResized);
  49838. }
  49839. void ComponentMovementWatcher::registerWithParentComps()
  49840. {
  49841. Component* p = component->getParentComponent();
  49842. while (p != 0)
  49843. {
  49844. p->addComponentListener (this);
  49845. registeredParentComps.add (p);
  49846. p = p->getParentComponent();
  49847. }
  49848. }
  49849. void ComponentMovementWatcher::unregister()
  49850. {
  49851. for (int i = registeredParentComps.size(); --i >= 0;)
  49852. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49853. registeredParentComps.clear();
  49854. }
  49855. END_JUCE_NAMESPACE
  49856. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49857. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49858. BEGIN_JUCE_NAMESPACE
  49859. GroupComponent::GroupComponent (const String& componentName,
  49860. const String& labelText)
  49861. : Component (componentName),
  49862. text (labelText),
  49863. justification (Justification::left)
  49864. {
  49865. setInterceptsMouseClicks (false, true);
  49866. }
  49867. GroupComponent::~GroupComponent()
  49868. {
  49869. }
  49870. void GroupComponent::setText (const String& newText)
  49871. {
  49872. if (text != newText)
  49873. {
  49874. text = newText;
  49875. repaint();
  49876. }
  49877. }
  49878. const String GroupComponent::getText() const
  49879. {
  49880. return text;
  49881. }
  49882. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49883. {
  49884. if (justification != newJustification)
  49885. {
  49886. justification = newJustification;
  49887. repaint();
  49888. }
  49889. }
  49890. void GroupComponent::paint (Graphics& g)
  49891. {
  49892. getLookAndFeel()
  49893. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49894. text, justification,
  49895. *this);
  49896. }
  49897. void GroupComponent::enablementChanged()
  49898. {
  49899. repaint();
  49900. }
  49901. void GroupComponent::colourChanged()
  49902. {
  49903. repaint();
  49904. }
  49905. END_JUCE_NAMESPACE
  49906. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49907. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49908. BEGIN_JUCE_NAMESPACE
  49909. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49910. : DocumentWindow (String::empty, backgroundColour,
  49911. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49912. {
  49913. }
  49914. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49915. {
  49916. }
  49917. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49918. {
  49919. MultiDocumentPanel* const owner = getOwner();
  49920. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49921. if (owner != 0)
  49922. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49923. }
  49924. void MultiDocumentPanelWindow::closeButtonPressed()
  49925. {
  49926. MultiDocumentPanel* const owner = getOwner();
  49927. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49928. if (owner != 0)
  49929. owner->closeDocument (getContentComponent(), true);
  49930. }
  49931. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49932. {
  49933. DocumentWindow::activeWindowStatusChanged();
  49934. updateOrder();
  49935. }
  49936. void MultiDocumentPanelWindow::broughtToFront()
  49937. {
  49938. DocumentWindow::broughtToFront();
  49939. updateOrder();
  49940. }
  49941. void MultiDocumentPanelWindow::updateOrder()
  49942. {
  49943. MultiDocumentPanel* const owner = getOwner();
  49944. if (owner != 0)
  49945. owner->updateOrder();
  49946. }
  49947. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49948. {
  49949. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49950. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49951. }
  49952. class MDITabbedComponentInternal : public TabbedComponent
  49953. {
  49954. public:
  49955. MDITabbedComponentInternal()
  49956. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49957. {
  49958. }
  49959. ~MDITabbedComponentInternal()
  49960. {
  49961. }
  49962. void currentTabChanged (int, const String&)
  49963. {
  49964. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49965. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49966. if (owner != 0)
  49967. owner->updateOrder();
  49968. }
  49969. };
  49970. MultiDocumentPanel::MultiDocumentPanel()
  49971. : mode (MaximisedWindowsWithTabs),
  49972. backgroundColour (Colours::lightblue),
  49973. maximumNumDocuments (0),
  49974. numDocsBeforeTabsUsed (0)
  49975. {
  49976. setOpaque (true);
  49977. }
  49978. MultiDocumentPanel::~MultiDocumentPanel()
  49979. {
  49980. closeAllDocuments (false);
  49981. }
  49982. namespace MultiDocHelpers
  49983. {
  49984. bool shouldDeleteComp (Component* const c)
  49985. {
  49986. return c->getProperties() ["mdiDocumentDelete_"];
  49987. }
  49988. }
  49989. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49990. {
  49991. while (components.size() > 0)
  49992. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49993. return false;
  49994. return true;
  49995. }
  49996. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49997. {
  49998. return new MultiDocumentPanelWindow (backgroundColour);
  49999. }
  50000. void MultiDocumentPanel::addWindow (Component* component)
  50001. {
  50002. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50003. dw->setResizable (true, false);
  50004. dw->setContentComponent (component, false, true);
  50005. dw->setName (component->getName());
  50006. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50007. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50008. int x = 4;
  50009. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50010. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50011. x += 16;
  50012. dw->setTopLeftPosition (x, x);
  50013. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50014. if (pos.toString().isNotEmpty())
  50015. dw->restoreWindowStateFromString (pos.toString());
  50016. addAndMakeVisible (dw);
  50017. dw->toFront (true);
  50018. }
  50019. bool MultiDocumentPanel::addDocument (Component* const component,
  50020. const Colour& docColour,
  50021. const bool deleteWhenRemoved)
  50022. {
  50023. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50024. // with a frame-within-a-frame! Just pass in the bare content component.
  50025. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50026. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50027. return false;
  50028. components.add (component);
  50029. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50030. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50031. component->addComponentListener (this);
  50032. if (mode == FloatingWindows)
  50033. {
  50034. if (isFullscreenWhenOneDocument())
  50035. {
  50036. if (components.size() == 1)
  50037. {
  50038. addAndMakeVisible (component);
  50039. }
  50040. else
  50041. {
  50042. if (components.size() == 2)
  50043. addWindow (components.getFirst());
  50044. addWindow (component);
  50045. }
  50046. }
  50047. else
  50048. {
  50049. addWindow (component);
  50050. }
  50051. }
  50052. else
  50053. {
  50054. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50055. {
  50056. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50057. Array <Component*> temp (components);
  50058. for (int i = 0; i < temp.size(); ++i)
  50059. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50060. resized();
  50061. }
  50062. else
  50063. {
  50064. if (tabComponent != 0)
  50065. tabComponent->addTab (component->getName(), docColour, component, false);
  50066. else
  50067. addAndMakeVisible (component);
  50068. }
  50069. setActiveDocument (component);
  50070. }
  50071. resized();
  50072. activeDocumentChanged();
  50073. return true;
  50074. }
  50075. bool MultiDocumentPanel::closeDocument (Component* component,
  50076. const bool checkItsOkToCloseFirst)
  50077. {
  50078. if (components.contains (component))
  50079. {
  50080. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50081. return false;
  50082. component->removeComponentListener (this);
  50083. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50084. component->getProperties().remove ("mdiDocumentDelete_");
  50085. component->getProperties().remove ("mdiDocumentBkg_");
  50086. if (mode == FloatingWindows)
  50087. {
  50088. for (int i = getNumChildComponents(); --i >= 0;)
  50089. {
  50090. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50091. if (dw != 0 && dw->getContentComponent() == component)
  50092. {
  50093. dw->setContentComponent (0, false);
  50094. delete dw;
  50095. break;
  50096. }
  50097. }
  50098. if (shouldDelete)
  50099. delete component;
  50100. components.removeValue (component);
  50101. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50102. {
  50103. for (int i = getNumChildComponents(); --i >= 0;)
  50104. {
  50105. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50106. if (dw != 0)
  50107. {
  50108. dw->setContentComponent (0, false);
  50109. delete dw;
  50110. }
  50111. }
  50112. addAndMakeVisible (components.getFirst());
  50113. }
  50114. }
  50115. else
  50116. {
  50117. jassert (components.indexOf (component) >= 0);
  50118. if (tabComponent != 0)
  50119. {
  50120. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50121. if (tabComponent->getTabContentComponent (i) == component)
  50122. tabComponent->removeTab (i);
  50123. }
  50124. else
  50125. {
  50126. removeChildComponent (component);
  50127. }
  50128. if (shouldDelete)
  50129. delete component;
  50130. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50131. tabComponent = 0;
  50132. components.removeValue (component);
  50133. if (components.size() > 0 && tabComponent == 0)
  50134. addAndMakeVisible (components.getFirst());
  50135. }
  50136. resized();
  50137. activeDocumentChanged();
  50138. }
  50139. else
  50140. {
  50141. jassertfalse;
  50142. }
  50143. return true;
  50144. }
  50145. int MultiDocumentPanel::getNumDocuments() const throw()
  50146. {
  50147. return components.size();
  50148. }
  50149. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50150. {
  50151. return components [index];
  50152. }
  50153. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50154. {
  50155. if (mode == FloatingWindows)
  50156. {
  50157. for (int i = getNumChildComponents(); --i >= 0;)
  50158. {
  50159. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50160. if (dw != 0 && dw->isActiveWindow())
  50161. return dw->getContentComponent();
  50162. }
  50163. }
  50164. return components.getLast();
  50165. }
  50166. void MultiDocumentPanel::setActiveDocument (Component* component)
  50167. {
  50168. if (mode == FloatingWindows)
  50169. {
  50170. component = getContainerComp (component);
  50171. if (component != 0)
  50172. component->toFront (true);
  50173. }
  50174. else if (tabComponent != 0)
  50175. {
  50176. jassert (components.indexOf (component) >= 0);
  50177. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50178. {
  50179. if (tabComponent->getTabContentComponent (i) == component)
  50180. {
  50181. tabComponent->setCurrentTabIndex (i);
  50182. break;
  50183. }
  50184. }
  50185. }
  50186. else
  50187. {
  50188. component->grabKeyboardFocus();
  50189. }
  50190. }
  50191. void MultiDocumentPanel::activeDocumentChanged()
  50192. {
  50193. }
  50194. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50195. {
  50196. maximumNumDocuments = newNumber;
  50197. }
  50198. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50199. {
  50200. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50201. }
  50202. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50203. {
  50204. return numDocsBeforeTabsUsed != 0;
  50205. }
  50206. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50207. {
  50208. if (mode != newLayoutMode)
  50209. {
  50210. mode = newLayoutMode;
  50211. if (mode == FloatingWindows)
  50212. {
  50213. tabComponent = 0;
  50214. }
  50215. else
  50216. {
  50217. for (int i = getNumChildComponents(); --i >= 0;)
  50218. {
  50219. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50220. if (dw != 0)
  50221. {
  50222. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50223. dw->setContentComponent (0, false);
  50224. delete dw;
  50225. }
  50226. }
  50227. }
  50228. resized();
  50229. const Array <Component*> tempComps (components);
  50230. components.clear();
  50231. for (int i = 0; i < tempComps.size(); ++i)
  50232. {
  50233. Component* const c = tempComps.getUnchecked(i);
  50234. addDocument (c,
  50235. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50236. MultiDocHelpers::shouldDeleteComp (c));
  50237. }
  50238. }
  50239. }
  50240. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50241. {
  50242. if (backgroundColour != newBackgroundColour)
  50243. {
  50244. backgroundColour = newBackgroundColour;
  50245. setOpaque (newBackgroundColour.isOpaque());
  50246. repaint();
  50247. }
  50248. }
  50249. void MultiDocumentPanel::paint (Graphics& g)
  50250. {
  50251. g.fillAll (backgroundColour);
  50252. }
  50253. void MultiDocumentPanel::resized()
  50254. {
  50255. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50256. {
  50257. for (int i = getNumChildComponents(); --i >= 0;)
  50258. getChildComponent (i)->setBounds (getLocalBounds());
  50259. }
  50260. setWantsKeyboardFocus (components.size() == 0);
  50261. }
  50262. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50263. {
  50264. if (mode == FloatingWindows)
  50265. {
  50266. for (int i = 0; i < getNumChildComponents(); ++i)
  50267. {
  50268. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50269. if (dw != 0 && dw->getContentComponent() == c)
  50270. {
  50271. c = dw;
  50272. break;
  50273. }
  50274. }
  50275. }
  50276. return c;
  50277. }
  50278. void MultiDocumentPanel::componentNameChanged (Component&)
  50279. {
  50280. if (mode == FloatingWindows)
  50281. {
  50282. for (int i = 0; i < getNumChildComponents(); ++i)
  50283. {
  50284. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50285. if (dw != 0)
  50286. dw->setName (dw->getContentComponent()->getName());
  50287. }
  50288. }
  50289. else if (tabComponent != 0)
  50290. {
  50291. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50292. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50293. }
  50294. }
  50295. void MultiDocumentPanel::updateOrder()
  50296. {
  50297. const Array <Component*> oldList (components);
  50298. if (mode == FloatingWindows)
  50299. {
  50300. components.clear();
  50301. for (int i = 0; i < getNumChildComponents(); ++i)
  50302. {
  50303. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50304. if (dw != 0)
  50305. components.add (dw->getContentComponent());
  50306. }
  50307. }
  50308. else
  50309. {
  50310. if (tabComponent != 0)
  50311. {
  50312. Component* const current = tabComponent->getCurrentContentComponent();
  50313. if (current != 0)
  50314. {
  50315. components.removeValue (current);
  50316. components.add (current);
  50317. }
  50318. }
  50319. }
  50320. if (components != oldList)
  50321. activeDocumentChanged();
  50322. }
  50323. END_JUCE_NAMESPACE
  50324. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50325. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50326. BEGIN_JUCE_NAMESPACE
  50327. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50328. : zone (zoneFlags)
  50329. {}
  50330. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50331. : zone (other.zone)
  50332. {}
  50333. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50334. {
  50335. zone = other.zone;
  50336. return *this;
  50337. }
  50338. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50339. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50340. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50341. const BorderSize& border,
  50342. const Point<int>& position)
  50343. {
  50344. int z = 0;
  50345. if (totalSize.contains (position)
  50346. && ! border.subtractedFrom (totalSize).contains (position))
  50347. {
  50348. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50349. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50350. z |= left;
  50351. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50352. z |= right;
  50353. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50354. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50355. z |= top;
  50356. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50357. z |= bottom;
  50358. }
  50359. return Zone (z);
  50360. }
  50361. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50362. {
  50363. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50364. switch (zone)
  50365. {
  50366. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50367. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50368. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50369. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50370. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50371. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50372. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50373. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50374. default: break;
  50375. }
  50376. return mc;
  50377. }
  50378. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50379. ComponentBoundsConstrainer* const constrainer_)
  50380. : component (componentToResize),
  50381. constrainer (constrainer_),
  50382. borderSize (5),
  50383. mouseZone (0)
  50384. {
  50385. }
  50386. ResizableBorderComponent::~ResizableBorderComponent()
  50387. {
  50388. }
  50389. void ResizableBorderComponent::paint (Graphics& g)
  50390. {
  50391. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50392. }
  50393. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50394. {
  50395. updateMouseZone (e);
  50396. }
  50397. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50398. {
  50399. updateMouseZone (e);
  50400. }
  50401. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50402. {
  50403. if (component == 0)
  50404. {
  50405. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50406. return;
  50407. }
  50408. updateMouseZone (e);
  50409. originalBounds = component->getBounds();
  50410. if (constrainer != 0)
  50411. constrainer->resizeStart();
  50412. }
  50413. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50414. {
  50415. if (component == 0)
  50416. {
  50417. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50418. return;
  50419. }
  50420. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50421. if (constrainer != 0)
  50422. constrainer->setBoundsForComponent (component, bounds,
  50423. mouseZone.isDraggingTopEdge(),
  50424. mouseZone.isDraggingLeftEdge(),
  50425. mouseZone.isDraggingBottomEdge(),
  50426. mouseZone.isDraggingRightEdge());
  50427. else
  50428. component->setBounds (bounds);
  50429. }
  50430. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50431. {
  50432. if (constrainer != 0)
  50433. constrainer->resizeEnd();
  50434. }
  50435. bool ResizableBorderComponent::hitTest (int x, int y)
  50436. {
  50437. return x < borderSize.getLeft()
  50438. || x >= getWidth() - borderSize.getRight()
  50439. || y < borderSize.getTop()
  50440. || y >= getHeight() - borderSize.getBottom();
  50441. }
  50442. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50443. {
  50444. if (borderSize != newBorderSize)
  50445. {
  50446. borderSize = newBorderSize;
  50447. repaint();
  50448. }
  50449. }
  50450. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50451. {
  50452. return borderSize;
  50453. }
  50454. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50455. {
  50456. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50457. if (mouseZone != newZone)
  50458. {
  50459. mouseZone = newZone;
  50460. setMouseCursor (newZone.getMouseCursor());
  50461. }
  50462. }
  50463. END_JUCE_NAMESPACE
  50464. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50465. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50466. BEGIN_JUCE_NAMESPACE
  50467. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50468. ComponentBoundsConstrainer* const constrainer_)
  50469. : component (componentToResize),
  50470. constrainer (constrainer_)
  50471. {
  50472. setRepaintsOnMouseActivity (true);
  50473. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50474. }
  50475. ResizableCornerComponent::~ResizableCornerComponent()
  50476. {
  50477. }
  50478. void ResizableCornerComponent::paint (Graphics& g)
  50479. {
  50480. getLookAndFeel()
  50481. .drawCornerResizer (g, getWidth(), getHeight(),
  50482. isMouseOverOrDragging(),
  50483. isMouseButtonDown());
  50484. }
  50485. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50486. {
  50487. if (component == 0)
  50488. {
  50489. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50490. return;
  50491. }
  50492. originalBounds = component->getBounds();
  50493. if (constrainer != 0)
  50494. constrainer->resizeStart();
  50495. }
  50496. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50497. {
  50498. if (component == 0)
  50499. {
  50500. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50501. return;
  50502. }
  50503. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50504. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50505. if (constrainer != 0)
  50506. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50507. else
  50508. component->setBounds (r);
  50509. }
  50510. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50511. {
  50512. if (constrainer != 0)
  50513. constrainer->resizeStart();
  50514. }
  50515. bool ResizableCornerComponent::hitTest (int x, int y)
  50516. {
  50517. if (getWidth() <= 0)
  50518. return false;
  50519. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50520. return y >= yAtX - getHeight() / 4;
  50521. }
  50522. END_JUCE_NAMESPACE
  50523. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50524. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50525. BEGIN_JUCE_NAMESPACE
  50526. class ScrollBar::ScrollbarButton : public Button
  50527. {
  50528. public:
  50529. int direction;
  50530. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50531. : Button (String::empty),
  50532. direction (direction_),
  50533. owner (owner_)
  50534. {
  50535. setWantsKeyboardFocus (false);
  50536. }
  50537. ~ScrollbarButton()
  50538. {
  50539. }
  50540. void paintButton (Graphics& g, bool over, bool down)
  50541. {
  50542. getLookAndFeel()
  50543. .drawScrollbarButton (g, owner,
  50544. getWidth(), getHeight(),
  50545. direction,
  50546. owner.isVertical(),
  50547. over, down);
  50548. }
  50549. void clicked()
  50550. {
  50551. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50552. }
  50553. juce_UseDebuggingNewOperator
  50554. private:
  50555. ScrollBar& owner;
  50556. ScrollbarButton (const ScrollbarButton&);
  50557. ScrollbarButton& operator= (const ScrollbarButton&);
  50558. };
  50559. ScrollBar::ScrollBar (const bool vertical_,
  50560. const bool buttonsAreVisible)
  50561. : totalRange (0.0, 1.0),
  50562. visibleRange (0.0, 0.1),
  50563. singleStepSize (0.1),
  50564. thumbAreaStart (0),
  50565. thumbAreaSize (0),
  50566. thumbStart (0),
  50567. thumbSize (0),
  50568. initialDelayInMillisecs (100),
  50569. repeatDelayInMillisecs (50),
  50570. minimumDelayInMillisecs (10),
  50571. vertical (vertical_),
  50572. isDraggingThumb (false),
  50573. autohides (true)
  50574. {
  50575. setButtonVisibility (buttonsAreVisible);
  50576. setRepaintsOnMouseActivity (true);
  50577. setFocusContainer (true);
  50578. }
  50579. ScrollBar::~ScrollBar()
  50580. {
  50581. upButton = 0;
  50582. downButton = 0;
  50583. }
  50584. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50585. {
  50586. if (totalRange != newRangeLimit)
  50587. {
  50588. totalRange = newRangeLimit;
  50589. setCurrentRange (visibleRange);
  50590. updateThumbPosition();
  50591. }
  50592. }
  50593. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50594. {
  50595. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50596. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50597. }
  50598. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50599. {
  50600. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50601. if (visibleRange != constrainedRange)
  50602. {
  50603. visibleRange = constrainedRange;
  50604. updateThumbPosition();
  50605. triggerAsyncUpdate();
  50606. }
  50607. }
  50608. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50609. {
  50610. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50611. }
  50612. void ScrollBar::setCurrentRangeStart (const double newStart)
  50613. {
  50614. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50615. }
  50616. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50617. {
  50618. singleStepSize = newSingleStepSize;
  50619. }
  50620. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50621. {
  50622. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50623. }
  50624. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50625. {
  50626. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50627. }
  50628. void ScrollBar::scrollToTop()
  50629. {
  50630. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50631. }
  50632. void ScrollBar::scrollToBottom()
  50633. {
  50634. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50635. }
  50636. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50637. const int repeatDelayInMillisecs_,
  50638. const int minimumDelayInMillisecs_)
  50639. {
  50640. initialDelayInMillisecs = initialDelayInMillisecs_;
  50641. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50642. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50643. if (upButton != 0)
  50644. {
  50645. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50646. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50647. }
  50648. }
  50649. void ScrollBar::addListener (Listener* const listener)
  50650. {
  50651. listeners.add (listener);
  50652. }
  50653. void ScrollBar::removeListener (Listener* const listener)
  50654. {
  50655. listeners.remove (listener);
  50656. }
  50657. void ScrollBar::handleAsyncUpdate()
  50658. {
  50659. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50660. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50661. }
  50662. void ScrollBar::updateThumbPosition()
  50663. {
  50664. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50665. : thumbAreaSize);
  50666. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50667. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50668. if (newThumbSize > thumbAreaSize)
  50669. newThumbSize = thumbAreaSize;
  50670. int newThumbStart = thumbAreaStart;
  50671. if (totalRange.getLength() > visibleRange.getLength())
  50672. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50673. / (totalRange.getLength() - visibleRange.getLength()));
  50674. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50675. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50676. {
  50677. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50678. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50679. if (vertical)
  50680. repaint (0, repaintStart, getWidth(), repaintSize);
  50681. else
  50682. repaint (repaintStart, 0, repaintSize, getHeight());
  50683. thumbStart = newThumbStart;
  50684. thumbSize = newThumbSize;
  50685. }
  50686. }
  50687. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50688. {
  50689. if (vertical != shouldBeVertical)
  50690. {
  50691. vertical = shouldBeVertical;
  50692. if (upButton != 0)
  50693. {
  50694. upButton->direction = vertical ? 0 : 3;
  50695. downButton->direction = vertical ? 2 : 1;
  50696. }
  50697. updateThumbPosition();
  50698. }
  50699. }
  50700. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50701. {
  50702. upButton = 0;
  50703. downButton = 0;
  50704. if (buttonsAreVisible)
  50705. {
  50706. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50707. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50708. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50709. }
  50710. updateThumbPosition();
  50711. }
  50712. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50713. {
  50714. autohides = shouldHideWhenFullRange;
  50715. updateThumbPosition();
  50716. }
  50717. bool ScrollBar::autoHides() const throw()
  50718. {
  50719. return autohides;
  50720. }
  50721. void ScrollBar::paint (Graphics& g)
  50722. {
  50723. if (thumbAreaSize > 0)
  50724. {
  50725. LookAndFeel& lf = getLookAndFeel();
  50726. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50727. ? thumbSize : 0;
  50728. if (vertical)
  50729. {
  50730. lf.drawScrollbar (g, *this,
  50731. 0, thumbAreaStart,
  50732. getWidth(), thumbAreaSize,
  50733. vertical,
  50734. thumbStart, thumb,
  50735. isMouseOver(), isMouseButtonDown());
  50736. }
  50737. else
  50738. {
  50739. lf.drawScrollbar (g, *this,
  50740. thumbAreaStart, 0,
  50741. thumbAreaSize, getHeight(),
  50742. vertical,
  50743. thumbStart, thumb,
  50744. isMouseOver(), isMouseButtonDown());
  50745. }
  50746. }
  50747. }
  50748. void ScrollBar::lookAndFeelChanged()
  50749. {
  50750. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50751. }
  50752. void ScrollBar::resized()
  50753. {
  50754. const int length = ((vertical) ? getHeight() : getWidth());
  50755. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50756. : 0;
  50757. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50758. {
  50759. thumbAreaStart = length >> 1;
  50760. thumbAreaSize = 0;
  50761. }
  50762. else
  50763. {
  50764. thumbAreaStart = buttonSize;
  50765. thumbAreaSize = length - (buttonSize << 1);
  50766. }
  50767. if (upButton != 0)
  50768. {
  50769. if (vertical)
  50770. {
  50771. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50772. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50773. }
  50774. else
  50775. {
  50776. upButton->setBounds (0, 0, buttonSize, getHeight());
  50777. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50778. }
  50779. }
  50780. updateThumbPosition();
  50781. }
  50782. void ScrollBar::mouseDown (const MouseEvent& e)
  50783. {
  50784. isDraggingThumb = false;
  50785. lastMousePos = vertical ? e.y : e.x;
  50786. dragStartMousePos = lastMousePos;
  50787. dragStartRange = visibleRange.getStart();
  50788. if (dragStartMousePos < thumbStart)
  50789. {
  50790. moveScrollbarInPages (-1);
  50791. startTimer (400);
  50792. }
  50793. else if (dragStartMousePos >= thumbStart + thumbSize)
  50794. {
  50795. moveScrollbarInPages (1);
  50796. startTimer (400);
  50797. }
  50798. else
  50799. {
  50800. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50801. && (thumbAreaSize > thumbSize);
  50802. }
  50803. }
  50804. void ScrollBar::mouseDrag (const MouseEvent& e)
  50805. {
  50806. if (isDraggingThumb)
  50807. {
  50808. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50809. setCurrentRangeStart (dragStartRange
  50810. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50811. / (thumbAreaSize - thumbSize));
  50812. }
  50813. else
  50814. {
  50815. lastMousePos = (vertical) ? e.y : e.x;
  50816. }
  50817. }
  50818. void ScrollBar::mouseUp (const MouseEvent&)
  50819. {
  50820. isDraggingThumb = false;
  50821. stopTimer();
  50822. repaint();
  50823. }
  50824. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50825. float wheelIncrementX,
  50826. float wheelIncrementY)
  50827. {
  50828. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50829. if (increment < 0)
  50830. increment = jmin (increment * 10.0f, -1.0f);
  50831. else if (increment > 0)
  50832. increment = jmax (increment * 10.0f, 1.0f);
  50833. setCurrentRange (visibleRange - singleStepSize * increment);
  50834. }
  50835. void ScrollBar::timerCallback()
  50836. {
  50837. if (isMouseButtonDown())
  50838. {
  50839. startTimer (40);
  50840. if (lastMousePos < thumbStart)
  50841. setCurrentRange (visibleRange - visibleRange.getLength());
  50842. else if (lastMousePos > thumbStart + thumbSize)
  50843. setCurrentRangeStart (visibleRange.getEnd());
  50844. }
  50845. else
  50846. {
  50847. stopTimer();
  50848. }
  50849. }
  50850. bool ScrollBar::keyPressed (const KeyPress& key)
  50851. {
  50852. if (! isVisible())
  50853. return false;
  50854. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50855. moveScrollbarInSteps (-1);
  50856. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50857. moveScrollbarInSteps (1);
  50858. else if (key.isKeyCode (KeyPress::pageUpKey))
  50859. moveScrollbarInPages (-1);
  50860. else if (key.isKeyCode (KeyPress::pageDownKey))
  50861. moveScrollbarInPages (1);
  50862. else if (key.isKeyCode (KeyPress::homeKey))
  50863. scrollToTop();
  50864. else if (key.isKeyCode (KeyPress::endKey))
  50865. scrollToBottom();
  50866. else
  50867. return false;
  50868. return true;
  50869. }
  50870. END_JUCE_NAMESPACE
  50871. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50872. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50873. BEGIN_JUCE_NAMESPACE
  50874. StretchableLayoutManager::StretchableLayoutManager()
  50875. : totalSize (0)
  50876. {
  50877. }
  50878. StretchableLayoutManager::~StretchableLayoutManager()
  50879. {
  50880. }
  50881. void StretchableLayoutManager::clearAllItems()
  50882. {
  50883. items.clear();
  50884. totalSize = 0;
  50885. }
  50886. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50887. const double minimumSize,
  50888. const double maximumSize,
  50889. const double preferredSize)
  50890. {
  50891. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50892. if (layout == 0)
  50893. {
  50894. layout = new ItemLayoutProperties();
  50895. layout->itemIndex = itemIndex;
  50896. int i;
  50897. for (i = 0; i < items.size(); ++i)
  50898. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50899. break;
  50900. items.insert (i, layout);
  50901. }
  50902. layout->minSize = minimumSize;
  50903. layout->maxSize = maximumSize;
  50904. layout->preferredSize = preferredSize;
  50905. layout->currentSize = 0;
  50906. }
  50907. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50908. double& minimumSize,
  50909. double& maximumSize,
  50910. double& preferredSize) const
  50911. {
  50912. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50913. if (layout != 0)
  50914. {
  50915. minimumSize = layout->minSize;
  50916. maximumSize = layout->maxSize;
  50917. preferredSize = layout->preferredSize;
  50918. return true;
  50919. }
  50920. return false;
  50921. }
  50922. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50923. {
  50924. totalSize = newTotalSize;
  50925. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50926. }
  50927. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50928. {
  50929. int pos = 0;
  50930. for (int i = 0; i < itemIndex; ++i)
  50931. {
  50932. const ItemLayoutProperties* const layout = getInfoFor (i);
  50933. if (layout != 0)
  50934. pos += layout->currentSize;
  50935. }
  50936. return pos;
  50937. }
  50938. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50939. {
  50940. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50941. if (layout != 0)
  50942. return layout->currentSize;
  50943. return 0;
  50944. }
  50945. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50946. {
  50947. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50948. if (layout != 0)
  50949. return -layout->currentSize / (double) totalSize;
  50950. return 0;
  50951. }
  50952. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50953. int newPosition)
  50954. {
  50955. for (int i = items.size(); --i >= 0;)
  50956. {
  50957. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50958. if (layout->itemIndex == itemIndex)
  50959. {
  50960. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50961. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50962. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50963. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50964. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50965. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50966. endPos += layout->currentSize;
  50967. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50968. updatePrefSizesToMatchCurrentPositions();
  50969. break;
  50970. }
  50971. }
  50972. }
  50973. void StretchableLayoutManager::layOutComponents (Component** const components,
  50974. int numComponents,
  50975. int x, int y, int w, int h,
  50976. const bool vertically,
  50977. const bool resizeOtherDimension)
  50978. {
  50979. setTotalSize (vertically ? h : w);
  50980. int pos = vertically ? y : x;
  50981. for (int i = 0; i < numComponents; ++i)
  50982. {
  50983. const ItemLayoutProperties* const layout = getInfoFor (i);
  50984. if (layout != 0)
  50985. {
  50986. Component* const c = components[i];
  50987. if (c != 0)
  50988. {
  50989. if (i == numComponents - 1)
  50990. {
  50991. // if it's the last item, crop it to exactly fit the available space..
  50992. if (resizeOtherDimension)
  50993. {
  50994. if (vertically)
  50995. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50996. else
  50997. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50998. }
  50999. else
  51000. {
  51001. if (vertically)
  51002. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51003. else
  51004. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51005. }
  51006. }
  51007. else
  51008. {
  51009. if (resizeOtherDimension)
  51010. {
  51011. if (vertically)
  51012. c->setBounds (x, pos, w, layout->currentSize);
  51013. else
  51014. c->setBounds (pos, y, layout->currentSize, h);
  51015. }
  51016. else
  51017. {
  51018. if (vertically)
  51019. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51020. else
  51021. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51022. }
  51023. }
  51024. }
  51025. pos += layout->currentSize;
  51026. }
  51027. }
  51028. }
  51029. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51030. {
  51031. for (int i = items.size(); --i >= 0;)
  51032. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51033. return items.getUnchecked(i);
  51034. return 0;
  51035. }
  51036. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51037. const int endIndex,
  51038. const int availableSpace,
  51039. int startPos)
  51040. {
  51041. // calculate the total sizes
  51042. int i;
  51043. double totalIdealSize = 0.0;
  51044. int totalMinimums = 0;
  51045. for (i = startIndex; i < endIndex; ++i)
  51046. {
  51047. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51048. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51049. totalMinimums += layout->currentSize;
  51050. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51051. }
  51052. if (totalIdealSize <= 0)
  51053. totalIdealSize = 1.0;
  51054. // now calc the best sizes..
  51055. int extraSpace = availableSpace - totalMinimums;
  51056. while (extraSpace > 0)
  51057. {
  51058. int numWantingMoreSpace = 0;
  51059. int numHavingTakenExtraSpace = 0;
  51060. // first figure out how many comps want a slice of the extra space..
  51061. for (i = startIndex; i < endIndex; ++i)
  51062. {
  51063. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51064. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51065. const int bestSize = jlimit (layout->currentSize,
  51066. jmax (layout->currentSize,
  51067. sizeToRealSize (layout->maxSize, totalSize)),
  51068. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51069. if (bestSize > layout->currentSize)
  51070. ++numWantingMoreSpace;
  51071. }
  51072. // ..share out the extra space..
  51073. for (i = startIndex; i < endIndex; ++i)
  51074. {
  51075. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51076. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51077. int bestSize = jlimit (layout->currentSize,
  51078. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51079. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51080. const int extraWanted = bestSize - layout->currentSize;
  51081. if (extraWanted > 0)
  51082. {
  51083. const int extraAllowed = jmin (extraWanted,
  51084. extraSpace / jmax (1, numWantingMoreSpace));
  51085. if (extraAllowed > 0)
  51086. {
  51087. ++numHavingTakenExtraSpace;
  51088. --numWantingMoreSpace;
  51089. layout->currentSize += extraAllowed;
  51090. extraSpace -= extraAllowed;
  51091. }
  51092. }
  51093. }
  51094. if (numHavingTakenExtraSpace <= 0)
  51095. break;
  51096. }
  51097. // ..and calculate the end position
  51098. for (i = startIndex; i < endIndex; ++i)
  51099. {
  51100. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51101. startPos += layout->currentSize;
  51102. }
  51103. return startPos;
  51104. }
  51105. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51106. const int endIndex) const
  51107. {
  51108. int totalMinimums = 0;
  51109. for (int i = startIndex; i < endIndex; ++i)
  51110. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51111. return totalMinimums;
  51112. }
  51113. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51114. {
  51115. int totalMaximums = 0;
  51116. for (int i = startIndex; i < endIndex; ++i)
  51117. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51118. return totalMaximums;
  51119. }
  51120. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51121. {
  51122. for (int i = 0; i < items.size(); ++i)
  51123. {
  51124. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51125. layout->preferredSize
  51126. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51127. : getItemCurrentAbsoluteSize (i);
  51128. }
  51129. }
  51130. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51131. {
  51132. if (size < 0)
  51133. size *= -totalSpace;
  51134. return roundToInt (size);
  51135. }
  51136. END_JUCE_NAMESPACE
  51137. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51138. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51139. BEGIN_JUCE_NAMESPACE
  51140. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51141. const int itemIndex_,
  51142. const bool isVertical_)
  51143. : layout (layout_),
  51144. itemIndex (itemIndex_),
  51145. isVertical (isVertical_)
  51146. {
  51147. setRepaintsOnMouseActivity (true);
  51148. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51149. : MouseCursor::UpDownResizeCursor));
  51150. }
  51151. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51152. {
  51153. }
  51154. void StretchableLayoutResizerBar::paint (Graphics& g)
  51155. {
  51156. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51157. getWidth(), getHeight(),
  51158. isVertical,
  51159. isMouseOver(),
  51160. isMouseButtonDown());
  51161. }
  51162. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51163. {
  51164. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51165. }
  51166. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51167. {
  51168. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51169. : e.getDistanceFromDragStartY());
  51170. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51171. {
  51172. layout->setItemPosition (itemIndex, desiredPos);
  51173. hasBeenMoved();
  51174. }
  51175. }
  51176. void StretchableLayoutResizerBar::hasBeenMoved()
  51177. {
  51178. if (getParentComponent() != 0)
  51179. getParentComponent()->resized();
  51180. }
  51181. END_JUCE_NAMESPACE
  51182. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51183. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51184. BEGIN_JUCE_NAMESPACE
  51185. StretchableObjectResizer::StretchableObjectResizer()
  51186. {
  51187. }
  51188. StretchableObjectResizer::~StretchableObjectResizer()
  51189. {
  51190. }
  51191. void StretchableObjectResizer::addItem (const double size,
  51192. const double minSize, const double maxSize,
  51193. const int order)
  51194. {
  51195. // the order must be >= 0 but less than the maximum integer value.
  51196. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51197. Item* const item = new Item();
  51198. item->size = size;
  51199. item->minSize = minSize;
  51200. item->maxSize = maxSize;
  51201. item->order = order;
  51202. items.add (item);
  51203. }
  51204. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51205. {
  51206. const Item* const it = items [index];
  51207. return it != 0 ? it->size : 0;
  51208. }
  51209. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51210. {
  51211. int order = 0;
  51212. for (;;)
  51213. {
  51214. double currentSize = 0;
  51215. double minSize = 0;
  51216. double maxSize = 0;
  51217. int nextHighestOrder = std::numeric_limits<int>::max();
  51218. for (int i = 0; i < items.size(); ++i)
  51219. {
  51220. const Item* const it = items.getUnchecked(i);
  51221. currentSize += it->size;
  51222. if (it->order <= order)
  51223. {
  51224. minSize += it->minSize;
  51225. maxSize += it->maxSize;
  51226. }
  51227. else
  51228. {
  51229. minSize += it->size;
  51230. maxSize += it->size;
  51231. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51232. }
  51233. }
  51234. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51235. if (thisIterationTarget >= currentSize)
  51236. {
  51237. const double availableExtraSpace = maxSize - currentSize;
  51238. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51239. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51240. for (int i = 0; i < items.size(); ++i)
  51241. {
  51242. Item* const it = items.getUnchecked(i);
  51243. if (it->order <= order)
  51244. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51245. }
  51246. }
  51247. else
  51248. {
  51249. const double amountOfSlack = currentSize - minSize;
  51250. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51251. const double scale = targetAmountOfSlack / amountOfSlack;
  51252. for (int i = 0; i < items.size(); ++i)
  51253. {
  51254. Item* const it = items.getUnchecked(i);
  51255. if (it->order <= order)
  51256. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51257. }
  51258. }
  51259. if (nextHighestOrder < std::numeric_limits<int>::max())
  51260. order = nextHighestOrder;
  51261. else
  51262. break;
  51263. }
  51264. }
  51265. END_JUCE_NAMESPACE
  51266. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51267. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51268. BEGIN_JUCE_NAMESPACE
  51269. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51270. : Button (name),
  51271. owner (owner_),
  51272. overlapPixels (0)
  51273. {
  51274. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51275. setComponentEffect (&shadow);
  51276. setWantsKeyboardFocus (false);
  51277. }
  51278. TabBarButton::~TabBarButton()
  51279. {
  51280. }
  51281. int TabBarButton::getIndex() const
  51282. {
  51283. return owner.indexOfTabButton (this);
  51284. }
  51285. void TabBarButton::paintButton (Graphics& g,
  51286. bool isMouseOverButton,
  51287. bool isButtonDown)
  51288. {
  51289. const Rectangle<int> area (getActiveArea());
  51290. g.setOrigin (area.getX(), area.getY());
  51291. getLookAndFeel()
  51292. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51293. owner.getTabBackgroundColour (getIndex()),
  51294. getIndex(), getButtonText(), *this,
  51295. owner.getOrientation(),
  51296. isMouseOverButton, isButtonDown,
  51297. getToggleState());
  51298. }
  51299. void TabBarButton::clicked (const ModifierKeys& mods)
  51300. {
  51301. if (mods.isPopupMenu())
  51302. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51303. else
  51304. owner.setCurrentTabIndex (getIndex());
  51305. }
  51306. bool TabBarButton::hitTest (int mx, int my)
  51307. {
  51308. const Rectangle<int> area (getActiveArea());
  51309. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51310. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51311. {
  51312. if (((unsigned int) mx) < (unsigned int) getWidth()
  51313. && my >= area.getY() + overlapPixels
  51314. && my < area.getBottom() - overlapPixels)
  51315. return true;
  51316. }
  51317. else
  51318. {
  51319. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51320. && ((unsigned int) my) < (unsigned int) getHeight())
  51321. return true;
  51322. }
  51323. Path p;
  51324. getLookAndFeel()
  51325. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51326. owner.getOrientation(), false, false, getToggleState());
  51327. return p.contains ((float) (mx - area.getX()),
  51328. (float) (my - area.getY()));
  51329. }
  51330. int TabBarButton::getBestTabLength (const int depth)
  51331. {
  51332. return jlimit (depth * 2,
  51333. depth * 7,
  51334. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51335. }
  51336. const Rectangle<int> TabBarButton::getActiveArea()
  51337. {
  51338. Rectangle<int> r (getLocalBounds());
  51339. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51340. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51341. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51342. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51343. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51344. return r;
  51345. }
  51346. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51347. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51348. {
  51349. public:
  51350. BehindFrontTabComp (TabbedButtonBar& owner_)
  51351. : owner (owner_)
  51352. {
  51353. setInterceptsMouseClicks (false, false);
  51354. }
  51355. void paint (Graphics& g)
  51356. {
  51357. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51358. owner, owner.getOrientation());
  51359. }
  51360. void enablementChanged()
  51361. {
  51362. repaint();
  51363. }
  51364. void buttonClicked (Button*)
  51365. {
  51366. owner.showExtraItemsMenu();
  51367. }
  51368. private:
  51369. TabbedButtonBar& owner;
  51370. BehindFrontTabComp (const BehindFrontTabComp&);
  51371. BehindFrontTabComp& operator= (const BehindFrontTabComp&);
  51372. };
  51373. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51374. : orientation (orientation_),
  51375. minimumScale (0.7),
  51376. currentTabIndex (-1)
  51377. {
  51378. setInterceptsMouseClicks (false, true);
  51379. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51380. setFocusContainer (true);
  51381. }
  51382. TabbedButtonBar::~TabbedButtonBar()
  51383. {
  51384. tabs.clear();
  51385. extraTabsButton = 0;
  51386. }
  51387. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51388. {
  51389. orientation = newOrientation;
  51390. for (int i = getNumChildComponents(); --i >= 0;)
  51391. getChildComponent (i)->resized();
  51392. resized();
  51393. }
  51394. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51395. {
  51396. return new TabBarButton (name, *this);
  51397. }
  51398. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51399. {
  51400. minimumScale = newMinimumScale;
  51401. resized();
  51402. }
  51403. void TabbedButtonBar::clearTabs()
  51404. {
  51405. tabs.clear();
  51406. extraTabsButton = 0;
  51407. setCurrentTabIndex (-1);
  51408. }
  51409. void TabbedButtonBar::addTab (const String& tabName,
  51410. const Colour& tabBackgroundColour,
  51411. int insertIndex)
  51412. {
  51413. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51414. if (tabName.isNotEmpty())
  51415. {
  51416. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51417. insertIndex = tabs.size();
  51418. TabInfo* newTab = new TabInfo();
  51419. newTab->name = tabName;
  51420. newTab->colour = tabBackgroundColour;
  51421. newTab->component = createTabButton (tabName, insertIndex);
  51422. jassert (newTab->component != 0);
  51423. tabs.insert (insertIndex, newTab);
  51424. addAndMakeVisible (newTab->component, insertIndex);
  51425. resized();
  51426. if (currentTabIndex < 0)
  51427. setCurrentTabIndex (0);
  51428. }
  51429. }
  51430. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51431. {
  51432. TabInfo* const tab = tabs [tabIndex];
  51433. if (tab != 0 && tab->name != newName)
  51434. {
  51435. tab->name = newName;
  51436. tab->component->setButtonText (newName);
  51437. resized();
  51438. }
  51439. }
  51440. void TabbedButtonBar::removeTab (const int tabIndex)
  51441. {
  51442. if (tabs [tabIndex] != 0)
  51443. {
  51444. const int oldTabIndex = currentTabIndex;
  51445. if (currentTabIndex == tabIndex)
  51446. currentTabIndex = -1;
  51447. tabs.remove (tabIndex);
  51448. resized();
  51449. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51450. }
  51451. }
  51452. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51453. {
  51454. tabs.move (currentIndex, newIndex);
  51455. resized();
  51456. }
  51457. int TabbedButtonBar::getNumTabs() const
  51458. {
  51459. return tabs.size();
  51460. }
  51461. const String TabbedButtonBar::getCurrentTabName() const
  51462. {
  51463. TabInfo* tab = tabs [currentTabIndex];
  51464. return tab == 0 ? String::empty : tab->name;
  51465. }
  51466. const StringArray TabbedButtonBar::getTabNames() const
  51467. {
  51468. StringArray names;
  51469. for (int i = 0; i < tabs.size(); ++i)
  51470. names.add (tabs.getUnchecked(i)->name);
  51471. return names;
  51472. }
  51473. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51474. {
  51475. if (currentTabIndex != newIndex)
  51476. {
  51477. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51478. newIndex = -1;
  51479. currentTabIndex = newIndex;
  51480. for (int i = 0; i < tabs.size(); ++i)
  51481. {
  51482. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51483. tb->setToggleState (i == newIndex, false);
  51484. }
  51485. resized();
  51486. if (sendChangeMessage_)
  51487. sendChangeMessage();
  51488. currentTabChanged (newIndex, getCurrentTabName());
  51489. }
  51490. }
  51491. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51492. {
  51493. TabInfo* const tab = tabs[index];
  51494. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51495. }
  51496. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51497. {
  51498. for (int i = tabs.size(); --i >= 0;)
  51499. if (tabs.getUnchecked(i)->component == button)
  51500. return i;
  51501. return -1;
  51502. }
  51503. void TabbedButtonBar::lookAndFeelChanged()
  51504. {
  51505. extraTabsButton = 0;
  51506. resized();
  51507. }
  51508. void TabbedButtonBar::resized()
  51509. {
  51510. int depth = getWidth();
  51511. int length = getHeight();
  51512. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51513. swapVariables (depth, length);
  51514. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51515. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51516. int i, totalLength = overlap;
  51517. int numVisibleButtons = tabs.size();
  51518. for (i = 0; i < tabs.size(); ++i)
  51519. {
  51520. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51521. totalLength += tb->getBestTabLength (depth) - overlap;
  51522. tb->overlapPixels = overlap / 2;
  51523. }
  51524. double scale = 1.0;
  51525. if (totalLength > length)
  51526. scale = jmax (minimumScale, length / (double) totalLength);
  51527. const bool isTooBig = totalLength * scale > length;
  51528. int tabsButtonPos = 0;
  51529. if (isTooBig)
  51530. {
  51531. if (extraTabsButton == 0)
  51532. {
  51533. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51534. extraTabsButton->addButtonListener (behindFrontTab);
  51535. extraTabsButton->setAlwaysOnTop (true);
  51536. extraTabsButton->setTriggeredOnMouseDown (true);
  51537. }
  51538. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51539. extraTabsButton->setSize (buttonSize, buttonSize);
  51540. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51541. {
  51542. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51543. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51544. }
  51545. else
  51546. {
  51547. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51548. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51549. }
  51550. totalLength = 0;
  51551. for (i = 0; i < tabs.size(); ++i)
  51552. {
  51553. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51554. const int newLength = totalLength + tb->getBestTabLength (depth);
  51555. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51556. {
  51557. totalLength += overlap;
  51558. break;
  51559. }
  51560. numVisibleButtons = i + 1;
  51561. totalLength = newLength - overlap;
  51562. }
  51563. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51564. }
  51565. else
  51566. {
  51567. extraTabsButton = 0;
  51568. }
  51569. int pos = 0;
  51570. TabBarButton* frontTab = 0;
  51571. for (i = 0; i < tabs.size(); ++i)
  51572. {
  51573. TabBarButton* const tb = getTabButton (i);
  51574. if (tb != 0)
  51575. {
  51576. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51577. if (i < numVisibleButtons)
  51578. {
  51579. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51580. tb->setBounds (pos, 0, bestLength, getHeight());
  51581. else
  51582. tb->setBounds (0, pos, getWidth(), bestLength);
  51583. tb->toBack();
  51584. if (i == currentTabIndex)
  51585. frontTab = tb;
  51586. tb->setVisible (true);
  51587. }
  51588. else
  51589. {
  51590. tb->setVisible (false);
  51591. }
  51592. pos += bestLength - overlap;
  51593. }
  51594. }
  51595. behindFrontTab->setBounds (getLocalBounds());
  51596. if (frontTab != 0)
  51597. {
  51598. frontTab->toFront (false);
  51599. behindFrontTab->toBehind (frontTab);
  51600. }
  51601. }
  51602. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51603. {
  51604. TabInfo* const tab = tabs [tabIndex];
  51605. return tab == 0 ? Colours::white : tab->colour;
  51606. }
  51607. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51608. {
  51609. TabInfo* const tab = tabs [tabIndex];
  51610. if (tab != 0 && tab->colour != newColour)
  51611. {
  51612. tab->colour = newColour;
  51613. repaint();
  51614. }
  51615. }
  51616. void TabbedButtonBar::showExtraItemsMenu()
  51617. {
  51618. PopupMenu m;
  51619. for (int i = 0; i < tabs.size(); ++i)
  51620. {
  51621. const TabInfo* const tab = tabs.getUnchecked(i);
  51622. if (! tab->component->isVisible())
  51623. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51624. }
  51625. const int res = m.showAt (extraTabsButton);
  51626. if (res != 0)
  51627. setCurrentTabIndex (res - 1);
  51628. }
  51629. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51630. {
  51631. }
  51632. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51633. {
  51634. }
  51635. END_JUCE_NAMESPACE
  51636. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51637. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51638. BEGIN_JUCE_NAMESPACE
  51639. class TabCompButtonBar : public TabbedButtonBar
  51640. {
  51641. public:
  51642. TabCompButtonBar (TabbedComponent& owner_,
  51643. const TabbedButtonBar::Orientation orientation_)
  51644. : TabbedButtonBar (orientation_),
  51645. owner (owner_)
  51646. {
  51647. }
  51648. ~TabCompButtonBar()
  51649. {
  51650. }
  51651. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51652. {
  51653. owner.changeCallback (newCurrentTabIndex, newTabName);
  51654. }
  51655. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51656. {
  51657. owner.popupMenuClickOnTab (tabIndex, tabName);
  51658. }
  51659. const Colour getTabBackgroundColour (const int tabIndex)
  51660. {
  51661. return owner.tabs->getTabBackgroundColour (tabIndex);
  51662. }
  51663. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51664. {
  51665. return owner.createTabButton (tabName, tabIndex);
  51666. }
  51667. juce_UseDebuggingNewOperator
  51668. private:
  51669. TabbedComponent& owner;
  51670. TabCompButtonBar (const TabCompButtonBar&);
  51671. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51672. };
  51673. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51674. : tabDepth (30),
  51675. outlineThickness (1),
  51676. edgeIndent (0)
  51677. {
  51678. addAndMakeVisible (tabs = new TabCompButtonBar (*this, orientation));
  51679. }
  51680. TabbedComponent::~TabbedComponent()
  51681. {
  51682. clearTabs();
  51683. tabs = 0;
  51684. }
  51685. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51686. {
  51687. tabs->setOrientation (orientation);
  51688. resized();
  51689. }
  51690. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51691. {
  51692. return tabs->getOrientation();
  51693. }
  51694. void TabbedComponent::setTabBarDepth (const int newDepth)
  51695. {
  51696. if (tabDepth != newDepth)
  51697. {
  51698. tabDepth = newDepth;
  51699. resized();
  51700. }
  51701. }
  51702. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51703. {
  51704. return new TabBarButton (tabName, *tabs);
  51705. }
  51706. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51707. void TabbedComponent::clearTabs()
  51708. {
  51709. if (panelComponent != 0)
  51710. {
  51711. panelComponent->setVisible (false);
  51712. removeChildComponent (panelComponent);
  51713. panelComponent = 0;
  51714. }
  51715. tabs->clearTabs();
  51716. for (int i = contentComponents.size(); --i >= 0;)
  51717. {
  51718. Component::SafePointer<Component>& c = *contentComponents.getUnchecked (i);
  51719. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51720. c.deleteAndZero();
  51721. }
  51722. contentComponents.clear();
  51723. }
  51724. void TabbedComponent::addTab (const String& tabName,
  51725. const Colour& tabBackgroundColour,
  51726. Component* const contentComponent,
  51727. const bool deleteComponentWhenNotNeeded,
  51728. const int insertIndex)
  51729. {
  51730. contentComponents.insert (insertIndex, new Component::SafePointer<Component> (contentComponent));
  51731. if (contentComponent != 0)
  51732. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51733. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51734. }
  51735. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51736. {
  51737. tabs->setTabName (tabIndex, newName);
  51738. }
  51739. void TabbedComponent::removeTab (const int tabIndex)
  51740. {
  51741. Component::SafePointer<Component>* c = contentComponents [tabIndex];
  51742. if (c != 0)
  51743. {
  51744. if ((bool) ((*c)->getProperties() [deleteComponentId]))
  51745. c->deleteAndZero();
  51746. contentComponents.remove (tabIndex);
  51747. tabs->removeTab (tabIndex);
  51748. }
  51749. }
  51750. int TabbedComponent::getNumTabs() const
  51751. {
  51752. return tabs->getNumTabs();
  51753. }
  51754. const StringArray TabbedComponent::getTabNames() const
  51755. {
  51756. return tabs->getTabNames();
  51757. }
  51758. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51759. {
  51760. Component::SafePointer<Component>* const c = contentComponents [tabIndex];
  51761. return c != 0 ? *c : 0;
  51762. }
  51763. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51764. {
  51765. return tabs->getTabBackgroundColour (tabIndex);
  51766. }
  51767. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51768. {
  51769. tabs->setTabBackgroundColour (tabIndex, newColour);
  51770. if (getCurrentTabIndex() == tabIndex)
  51771. repaint();
  51772. }
  51773. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51774. {
  51775. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51776. }
  51777. int TabbedComponent::getCurrentTabIndex() const
  51778. {
  51779. return tabs->getCurrentTabIndex();
  51780. }
  51781. const String TabbedComponent::getCurrentTabName() const
  51782. {
  51783. return tabs->getCurrentTabName();
  51784. }
  51785. void TabbedComponent::setOutline (int thickness)
  51786. {
  51787. outlineThickness = thickness;
  51788. repaint();
  51789. }
  51790. void TabbedComponent::setIndent (const int indentThickness)
  51791. {
  51792. edgeIndent = indentThickness;
  51793. }
  51794. void TabbedComponent::paint (Graphics& g)
  51795. {
  51796. g.fillAll (findColour (backgroundColourId));
  51797. const TabbedButtonBar::Orientation o = getOrientation();
  51798. int x = 0;
  51799. int y = 0;
  51800. int r = getWidth();
  51801. int b = getHeight();
  51802. if (o == TabbedButtonBar::TabsAtTop)
  51803. y += tabDepth;
  51804. else if (o == TabbedButtonBar::TabsAtBottom)
  51805. b -= tabDepth;
  51806. else if (o == TabbedButtonBar::TabsAtLeft)
  51807. x += tabDepth;
  51808. else if (o == TabbedButtonBar::TabsAtRight)
  51809. r -= tabDepth;
  51810. g.reduceClipRegion (x, y, r - x, b - y);
  51811. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51812. if (outlineThickness > 0)
  51813. {
  51814. if (o == TabbedButtonBar::TabsAtTop)
  51815. --y;
  51816. else if (o == TabbedButtonBar::TabsAtBottom)
  51817. ++b;
  51818. else if (o == TabbedButtonBar::TabsAtLeft)
  51819. --x;
  51820. else if (o == TabbedButtonBar::TabsAtRight)
  51821. ++r;
  51822. g.setColour (findColour (outlineColourId));
  51823. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51824. }
  51825. }
  51826. void TabbedComponent::resized()
  51827. {
  51828. const TabbedButtonBar::Orientation o = getOrientation();
  51829. const int indent = edgeIndent + outlineThickness;
  51830. BorderSize indents (indent);
  51831. if (o == TabbedButtonBar::TabsAtTop)
  51832. {
  51833. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51834. indents.setTop (tabDepth + edgeIndent);
  51835. }
  51836. else if (o == TabbedButtonBar::TabsAtBottom)
  51837. {
  51838. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51839. indents.setBottom (tabDepth + edgeIndent);
  51840. }
  51841. else if (o == TabbedButtonBar::TabsAtLeft)
  51842. {
  51843. tabs->setBounds (0, 0, tabDepth, getHeight());
  51844. indents.setLeft (tabDepth + edgeIndent);
  51845. }
  51846. else if (o == TabbedButtonBar::TabsAtRight)
  51847. {
  51848. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51849. indents.setRight (tabDepth + edgeIndent);
  51850. }
  51851. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51852. for (int i = contentComponents.size(); --i >= 0;)
  51853. if (*contentComponents.getUnchecked (i) != 0)
  51854. (*contentComponents.getUnchecked (i))->setBounds (bounds);
  51855. }
  51856. void TabbedComponent::lookAndFeelChanged()
  51857. {
  51858. for (int i = contentComponents.size(); --i >= 0;)
  51859. if (*contentComponents.getUnchecked (i) != 0)
  51860. (*contentComponents.getUnchecked (i))->lookAndFeelChanged();
  51861. }
  51862. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51863. const String& newTabName)
  51864. {
  51865. if (panelComponent != 0)
  51866. {
  51867. panelComponent->setVisible (false);
  51868. removeChildComponent (panelComponent);
  51869. panelComponent = 0;
  51870. }
  51871. if (getCurrentTabIndex() >= 0)
  51872. {
  51873. panelComponent = getTabContentComponent (getCurrentTabIndex());
  51874. if (panelComponent != 0)
  51875. {
  51876. // do these ops as two stages instead of addAndMakeVisible() so that the
  51877. // component has always got a parent when it gets the visibilityChanged() callback
  51878. addChildComponent (panelComponent);
  51879. panelComponent->setVisible (true);
  51880. panelComponent->toFront (true);
  51881. }
  51882. repaint();
  51883. }
  51884. resized();
  51885. currentTabChanged (newCurrentTabIndex, newTabName);
  51886. }
  51887. void TabbedComponent::currentTabChanged (const int, const String&)
  51888. {
  51889. }
  51890. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51891. {
  51892. }
  51893. END_JUCE_NAMESPACE
  51894. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51895. /*** Start of inlined file: juce_Viewport.cpp ***/
  51896. BEGIN_JUCE_NAMESPACE
  51897. Viewport::Viewport (const String& componentName)
  51898. : Component (componentName),
  51899. scrollBarThickness (0),
  51900. singleStepX (16),
  51901. singleStepY (16),
  51902. showHScrollbar (true),
  51903. showVScrollbar (true),
  51904. verticalScrollBar (true),
  51905. horizontalScrollBar (false)
  51906. {
  51907. // content holder is used to clip the contents so they don't overlap the scrollbars
  51908. addAndMakeVisible (&contentHolder);
  51909. contentHolder.setInterceptsMouseClicks (false, true);
  51910. addChildComponent (&verticalScrollBar);
  51911. addChildComponent (&horizontalScrollBar);
  51912. verticalScrollBar.addListener (this);
  51913. horizontalScrollBar.addListener (this);
  51914. setInterceptsMouseClicks (false, true);
  51915. setWantsKeyboardFocus (true);
  51916. }
  51917. Viewport::~Viewport()
  51918. {
  51919. deleteContentComp();
  51920. }
  51921. void Viewport::visibleAreaChanged (int, int, int, int)
  51922. {
  51923. }
  51924. void Viewport::deleteContentComp()
  51925. {
  51926. // This sets the content comp to a null pointer before deleting the old one, in case
  51927. // anything tries to use the old one while it's in mid-deletion..
  51928. ScopedPointer<Component> oldCompDeleter (contentComp);
  51929. contentComp = 0;
  51930. }
  51931. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51932. {
  51933. if (contentComp.getComponent() != newViewedComponent)
  51934. {
  51935. deleteContentComp();
  51936. contentComp = newViewedComponent;
  51937. if (contentComp != 0)
  51938. {
  51939. contentComp->setTopLeftPosition (0, 0);
  51940. contentHolder.addAndMakeVisible (contentComp);
  51941. contentComp->addComponentListener (this);
  51942. }
  51943. updateVisibleArea();
  51944. }
  51945. }
  51946. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  51947. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  51948. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51949. {
  51950. if (contentComp != 0)
  51951. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51952. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51953. }
  51954. void Viewport::setViewPosition (const Point<int>& newPosition)
  51955. {
  51956. setViewPosition (newPosition.getX(), newPosition.getY());
  51957. }
  51958. void Viewport::setViewPositionProportionately (const double x, const double y)
  51959. {
  51960. if (contentComp != 0)
  51961. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51962. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51963. }
  51964. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51965. {
  51966. if (contentComp != 0)
  51967. {
  51968. int dx = 0, dy = 0;
  51969. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51970. {
  51971. if (mouseX < activeBorderThickness)
  51972. dx = activeBorderThickness - mouseX;
  51973. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51974. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51975. if (dx < 0)
  51976. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51977. else
  51978. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51979. }
  51980. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51981. {
  51982. if (mouseY < activeBorderThickness)
  51983. dy = activeBorderThickness - mouseY;
  51984. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51985. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51986. if (dy < 0)
  51987. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51988. else
  51989. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51990. }
  51991. if (dx != 0 || dy != 0)
  51992. {
  51993. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51994. contentComp->getY() + dy);
  51995. return true;
  51996. }
  51997. }
  51998. return false;
  51999. }
  52000. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52001. {
  52002. updateVisibleArea();
  52003. }
  52004. void Viewport::resized()
  52005. {
  52006. updateVisibleArea();
  52007. }
  52008. void Viewport::updateVisibleArea()
  52009. {
  52010. const int scrollbarWidth = getScrollBarThickness();
  52011. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52012. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52013. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52014. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52015. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52016. Rectangle<int> contentArea (getLocalBounds());
  52017. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52018. {
  52019. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52020. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52021. if (vBarVisible)
  52022. contentArea.setWidth (getWidth() - scrollbarWidth);
  52023. if (hBarVisible)
  52024. contentArea.setHeight (getHeight() - scrollbarWidth);
  52025. if (! contentArea.contains (contentComp->getBounds()))
  52026. {
  52027. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52028. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52029. }
  52030. }
  52031. if (vBarVisible)
  52032. contentArea.setWidth (getWidth() - scrollbarWidth);
  52033. if (hBarVisible)
  52034. contentArea.setHeight (getHeight() - scrollbarWidth);
  52035. contentHolder.setBounds (contentArea);
  52036. Rectangle<int> contentBounds;
  52037. if (contentComp != 0)
  52038. contentBounds = contentComp->getBounds();
  52039. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52040. if (hBarVisible)
  52041. {
  52042. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52043. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52044. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52045. horizontalScrollBar.setSingleStepSize (singleStepX);
  52046. horizontalScrollBar.cancelPendingUpdate();
  52047. }
  52048. if (vBarVisible)
  52049. {
  52050. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52051. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52052. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52053. verticalScrollBar.setSingleStepSize (singleStepY);
  52054. verticalScrollBar.cancelPendingUpdate();
  52055. }
  52056. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52057. horizontalScrollBar.setVisible (hBarVisible);
  52058. verticalScrollBar.setVisible (vBarVisible);
  52059. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52060. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52061. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52062. if (lastVisibleArea != visibleArea)
  52063. {
  52064. lastVisibleArea = visibleArea;
  52065. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52066. }
  52067. horizontalScrollBar.handleUpdateNowIfNeeded();
  52068. verticalScrollBar.handleUpdateNowIfNeeded();
  52069. }
  52070. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52071. {
  52072. if (singleStepX != stepX || singleStepY != stepY)
  52073. {
  52074. singleStepX = stepX;
  52075. singleStepY = stepY;
  52076. updateVisibleArea();
  52077. }
  52078. }
  52079. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52080. const bool showHorizontalScrollbarIfNeeded)
  52081. {
  52082. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52083. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52084. {
  52085. showVScrollbar = showVerticalScrollbarIfNeeded;
  52086. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52087. updateVisibleArea();
  52088. }
  52089. }
  52090. void Viewport::setScrollBarThickness (const int thickness)
  52091. {
  52092. if (scrollBarThickness != thickness)
  52093. {
  52094. scrollBarThickness = thickness;
  52095. updateVisibleArea();
  52096. }
  52097. }
  52098. int Viewport::getScrollBarThickness() const
  52099. {
  52100. return scrollBarThickness > 0 ? scrollBarThickness
  52101. : getLookAndFeel().getDefaultScrollbarWidth();
  52102. }
  52103. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52104. {
  52105. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52106. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52107. }
  52108. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52109. {
  52110. const int newRangeStartInt = roundToInt (newRangeStart);
  52111. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52112. {
  52113. setViewPosition (newRangeStartInt, getViewPositionY());
  52114. }
  52115. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52116. {
  52117. setViewPosition (getViewPositionX(), newRangeStartInt);
  52118. }
  52119. }
  52120. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52121. {
  52122. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52123. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52124. }
  52125. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52126. {
  52127. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52128. {
  52129. const bool hasVertBar = verticalScrollBar.isVisible();
  52130. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52131. if (hasHorzBar || hasVertBar)
  52132. {
  52133. if (wheelIncrementX != 0)
  52134. {
  52135. wheelIncrementX *= 14.0f * singleStepX;
  52136. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52137. : jmax (wheelIncrementX, 1.0f);
  52138. }
  52139. if (wheelIncrementY != 0)
  52140. {
  52141. wheelIncrementY *= 14.0f * singleStepY;
  52142. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52143. : jmax (wheelIncrementY, 1.0f);
  52144. }
  52145. Point<int> pos (getViewPosition());
  52146. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52147. {
  52148. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52149. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52150. }
  52151. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52152. {
  52153. if (wheelIncrementX == 0 && ! hasVertBar)
  52154. wheelIncrementX = wheelIncrementY;
  52155. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52156. }
  52157. else if (hasVertBar && wheelIncrementY != 0)
  52158. {
  52159. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52160. }
  52161. if (pos != getViewPosition())
  52162. {
  52163. setViewPosition (pos);
  52164. return true;
  52165. }
  52166. }
  52167. }
  52168. return false;
  52169. }
  52170. bool Viewport::keyPressed (const KeyPress& key)
  52171. {
  52172. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52173. || key.isKeyCode (KeyPress::downKey)
  52174. || key.isKeyCode (KeyPress::pageUpKey)
  52175. || key.isKeyCode (KeyPress::pageDownKey)
  52176. || key.isKeyCode (KeyPress::homeKey)
  52177. || key.isKeyCode (KeyPress::endKey);
  52178. if (verticalScrollBar.isVisible() && isUpDownKey)
  52179. return verticalScrollBar.keyPressed (key);
  52180. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52181. || key.isKeyCode (KeyPress::rightKey);
  52182. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52183. return horizontalScrollBar.keyPressed (key);
  52184. return false;
  52185. }
  52186. END_JUCE_NAMESPACE
  52187. /*** End of inlined file: juce_Viewport.cpp ***/
  52188. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52189. BEGIN_JUCE_NAMESPACE
  52190. namespace LookAndFeelHelpers
  52191. {
  52192. void createRoundedPath (Path& p,
  52193. const float x, const float y,
  52194. const float w, const float h,
  52195. const float cs,
  52196. const bool curveTopLeft, const bool curveTopRight,
  52197. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52198. {
  52199. const float cs2 = 2.0f * cs;
  52200. if (curveTopLeft)
  52201. {
  52202. p.startNewSubPath (x, y + cs);
  52203. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52204. }
  52205. else
  52206. {
  52207. p.startNewSubPath (x, y);
  52208. }
  52209. if (curveTopRight)
  52210. {
  52211. p.lineTo (x + w - cs, y);
  52212. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52213. }
  52214. else
  52215. {
  52216. p.lineTo (x + w, y);
  52217. }
  52218. if (curveBottomRight)
  52219. {
  52220. p.lineTo (x + w, y + h - cs);
  52221. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52222. }
  52223. else
  52224. {
  52225. p.lineTo (x + w, y + h);
  52226. }
  52227. if (curveBottomLeft)
  52228. {
  52229. p.lineTo (x + cs, y + h);
  52230. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52231. }
  52232. else
  52233. {
  52234. p.lineTo (x, y + h);
  52235. }
  52236. p.closeSubPath();
  52237. }
  52238. const Colour createBaseColour (const Colour& buttonColour,
  52239. const bool hasKeyboardFocus,
  52240. const bool isMouseOverButton,
  52241. const bool isButtonDown) throw()
  52242. {
  52243. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52244. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52245. if (isButtonDown)
  52246. return baseColour.contrasting (0.2f);
  52247. else if (isMouseOverButton)
  52248. return baseColour.contrasting (0.1f);
  52249. return baseColour;
  52250. }
  52251. const TextLayout layoutTooltipText (const String& text) throw()
  52252. {
  52253. const float tooltipFontSize = 12.0f;
  52254. const int maxToolTipWidth = 400;
  52255. const Font f (tooltipFontSize, Font::bold);
  52256. TextLayout tl (text, f);
  52257. tl.layout (maxToolTipWidth, Justification::left, true);
  52258. return tl;
  52259. }
  52260. LookAndFeel* defaultLF = 0;
  52261. LookAndFeel* currentDefaultLF = 0;
  52262. }
  52263. LookAndFeel::LookAndFeel()
  52264. {
  52265. /* if this fails it means you're trying to create a LookAndFeel object before
  52266. the static Colours have been initialised. That ain't gonna work. It probably
  52267. means that you're using a static LookAndFeel object and that your compiler has
  52268. decided to intialise it before the Colours class.
  52269. */
  52270. jassert (Colours::white == Colour (0xffffffff));
  52271. // set up the standard set of colours..
  52272. const int textButtonColour = 0xffbbbbff;
  52273. const int textHighlightColour = 0x401111ee;
  52274. const int standardOutlineColour = 0xb2808080;
  52275. static const int standardColours[] =
  52276. {
  52277. TextButton::buttonColourId, textButtonColour,
  52278. TextButton::buttonOnColourId, 0xff4444ff,
  52279. TextButton::textColourOnId, 0xff000000,
  52280. TextButton::textColourOffId, 0xff000000,
  52281. ComboBox::buttonColourId, 0xffbbbbff,
  52282. ComboBox::outlineColourId, standardOutlineColour,
  52283. ToggleButton::textColourId, 0xff000000,
  52284. TextEditor::backgroundColourId, 0xffffffff,
  52285. TextEditor::textColourId, 0xff000000,
  52286. TextEditor::highlightColourId, textHighlightColour,
  52287. TextEditor::highlightedTextColourId, 0xff000000,
  52288. TextEditor::caretColourId, 0xff000000,
  52289. TextEditor::outlineColourId, 0x00000000,
  52290. TextEditor::focusedOutlineColourId, textButtonColour,
  52291. TextEditor::shadowColourId, 0x38000000,
  52292. Label::backgroundColourId, 0x00000000,
  52293. Label::textColourId, 0xff000000,
  52294. Label::outlineColourId, 0x00000000,
  52295. ScrollBar::backgroundColourId, 0x00000000,
  52296. ScrollBar::thumbColourId, 0xffffffff,
  52297. ScrollBar::trackColourId, 0xffffffff,
  52298. TreeView::linesColourId, 0x4c000000,
  52299. TreeView::backgroundColourId, 0x00000000,
  52300. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52301. PopupMenu::backgroundColourId, 0xffffffff,
  52302. PopupMenu::textColourId, 0xff000000,
  52303. PopupMenu::headerTextColourId, 0xff000000,
  52304. PopupMenu::highlightedTextColourId, 0xffffffff,
  52305. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52306. ComboBox::textColourId, 0xff000000,
  52307. ComboBox::backgroundColourId, 0xffffffff,
  52308. ComboBox::arrowColourId, 0x99000000,
  52309. ListBox::backgroundColourId, 0xffffffff,
  52310. ListBox::outlineColourId, standardOutlineColour,
  52311. ListBox::textColourId, 0xff000000,
  52312. Slider::backgroundColourId, 0x00000000,
  52313. Slider::thumbColourId, textButtonColour,
  52314. Slider::trackColourId, 0x7fffffff,
  52315. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52316. Slider::rotarySliderOutlineColourId, 0x66000000,
  52317. Slider::textBoxTextColourId, 0xff000000,
  52318. Slider::textBoxBackgroundColourId, 0xffffffff,
  52319. Slider::textBoxHighlightColourId, textHighlightColour,
  52320. Slider::textBoxOutlineColourId, standardOutlineColour,
  52321. ResizableWindow::backgroundColourId, 0xff777777,
  52322. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52323. AlertWindow::backgroundColourId, 0xffededed,
  52324. AlertWindow::textColourId, 0xff000000,
  52325. AlertWindow::outlineColourId, 0xff666666,
  52326. ProgressBar::backgroundColourId, 0xffeeeeee,
  52327. ProgressBar::foregroundColourId, 0xffaaaaee,
  52328. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52329. TooltipWindow::textColourId, 0xff000000,
  52330. TooltipWindow::outlineColourId, 0x4c000000,
  52331. TabbedComponent::backgroundColourId, 0x00000000,
  52332. TabbedComponent::outlineColourId, 0xff777777,
  52333. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52334. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52335. Toolbar::backgroundColourId, 0xfff6f8f9,
  52336. Toolbar::separatorColourId, 0x4c000000,
  52337. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52338. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52339. Toolbar::labelTextColourId, 0xff000000,
  52340. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52341. HyperlinkButton::textColourId, 0xcc1111ee,
  52342. GroupComponent::outlineColourId, 0x66000000,
  52343. GroupComponent::textColourId, 0xff000000,
  52344. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52345. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52346. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52347. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52348. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52349. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52350. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52351. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52352. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52353. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52354. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52355. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52356. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52357. CodeEditorComponent::caretColourId, 0xff000000,
  52358. CodeEditorComponent::highlightColourId, textHighlightColour,
  52359. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52360. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52361. ColourSelector::labelTextColourId, 0xff000000,
  52362. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52363. KeyMappingEditorComponent::textColourId, 0xff000000,
  52364. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52365. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52366. DrawableButton::textColourId, 0xff000000,
  52367. };
  52368. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52369. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52370. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52371. if (defaultSansName.isEmpty())
  52372. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52373. defaultSans = defaultSansName;
  52374. defaultSerif = defaultSerifName;
  52375. defaultFixed = defaultFixedName;
  52376. Font::setFallbackFontName (defaultFallback);
  52377. }
  52378. LookAndFeel::~LookAndFeel()
  52379. {
  52380. if (this == LookAndFeelHelpers::currentDefaultLF)
  52381. setDefaultLookAndFeel (0);
  52382. }
  52383. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52384. {
  52385. const int index = colourIds.indexOf (colourId);
  52386. if (index >= 0)
  52387. return colours [index];
  52388. jassertfalse;
  52389. return Colours::black;
  52390. }
  52391. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52392. {
  52393. const int index = colourIds.indexOf (colourId);
  52394. if (index >= 0)
  52395. {
  52396. colours.set (index, colour);
  52397. }
  52398. else
  52399. {
  52400. colourIds.add (colourId);
  52401. colours.add (colour);
  52402. }
  52403. }
  52404. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52405. {
  52406. return colourIds.contains (colourId);
  52407. }
  52408. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52409. {
  52410. // if this happens, your app hasn't initialised itself properly.. if you're
  52411. // trying to hack your own main() function, have a look at
  52412. // JUCEApplication::initialiseForGUI()
  52413. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52414. return *LookAndFeelHelpers::currentDefaultLF;
  52415. }
  52416. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52417. {
  52418. using namespace LookAndFeelHelpers;
  52419. if (newDefaultLookAndFeel == 0)
  52420. {
  52421. if (defaultLF == 0)
  52422. defaultLF = new LookAndFeel();
  52423. newDefaultLookAndFeel = defaultLF;
  52424. }
  52425. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52426. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52427. {
  52428. Component* const c = Desktop::getInstance().getComponent (i);
  52429. if (c != 0)
  52430. c->sendLookAndFeelChange();
  52431. }
  52432. }
  52433. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52434. {
  52435. using namespace LookAndFeelHelpers;
  52436. if (currentDefaultLF == defaultLF)
  52437. currentDefaultLF = 0;
  52438. deleteAndZero (defaultLF);
  52439. }
  52440. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52441. {
  52442. String faceName (font.getTypefaceName());
  52443. if (faceName == Font::getDefaultSansSerifFontName())
  52444. faceName = defaultSans;
  52445. else if (faceName == Font::getDefaultSerifFontName())
  52446. faceName = defaultSerif;
  52447. else if (faceName == Font::getDefaultMonospacedFontName())
  52448. faceName = defaultFixed;
  52449. Font f (font);
  52450. f.setTypefaceName (faceName);
  52451. return Typeface::createSystemTypefaceFor (f);
  52452. }
  52453. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52454. {
  52455. defaultSans = newName;
  52456. }
  52457. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52458. {
  52459. return component.getMouseCursor();
  52460. }
  52461. void LookAndFeel::drawButtonBackground (Graphics& g,
  52462. Button& button,
  52463. const Colour& backgroundColour,
  52464. bool isMouseOverButton,
  52465. bool isButtonDown)
  52466. {
  52467. const int width = button.getWidth();
  52468. const int height = button.getHeight();
  52469. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52470. const float halfThickness = outlineThickness * 0.5f;
  52471. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52472. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52473. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52474. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52475. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52476. button.hasKeyboardFocus (true),
  52477. isMouseOverButton, isButtonDown)
  52478. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52479. drawGlassLozenge (g,
  52480. indentL,
  52481. indentT,
  52482. width - indentL - indentR,
  52483. height - indentT - indentB,
  52484. baseColour, outlineThickness, -1.0f,
  52485. button.isConnectedOnLeft(),
  52486. button.isConnectedOnRight(),
  52487. button.isConnectedOnTop(),
  52488. button.isConnectedOnBottom());
  52489. }
  52490. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52491. {
  52492. return button.getFont();
  52493. }
  52494. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52495. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52496. {
  52497. Font font (getFontForTextButton (button));
  52498. g.setFont (font);
  52499. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52500. : TextButton::textColourOffId)
  52501. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52502. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52503. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52504. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52505. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52506. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52507. g.drawFittedText (button.getButtonText(),
  52508. leftIndent,
  52509. yIndent,
  52510. button.getWidth() - leftIndent - rightIndent,
  52511. button.getHeight() - yIndent * 2,
  52512. Justification::centred, 2);
  52513. }
  52514. void LookAndFeel::drawTickBox (Graphics& g,
  52515. Component& component,
  52516. float x, float y, float w, float h,
  52517. const bool ticked,
  52518. const bool isEnabled,
  52519. const bool isMouseOverButton,
  52520. const bool isButtonDown)
  52521. {
  52522. const float boxSize = w * 0.7f;
  52523. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52524. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52525. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52526. true, isMouseOverButton, isButtonDown),
  52527. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52528. if (ticked)
  52529. {
  52530. Path tick;
  52531. tick.startNewSubPath (1.5f, 3.0f);
  52532. tick.lineTo (3.0f, 6.0f);
  52533. tick.lineTo (6.0f, 0.0f);
  52534. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52535. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52536. .translated (x, y));
  52537. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52538. }
  52539. }
  52540. void LookAndFeel::drawToggleButton (Graphics& g,
  52541. ToggleButton& button,
  52542. bool isMouseOverButton,
  52543. bool isButtonDown)
  52544. {
  52545. if (button.hasKeyboardFocus (true))
  52546. {
  52547. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52548. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52549. }
  52550. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52551. const float tickWidth = fontSize * 1.1f;
  52552. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52553. tickWidth, tickWidth,
  52554. button.getToggleState(),
  52555. button.isEnabled(),
  52556. isMouseOverButton,
  52557. isButtonDown);
  52558. g.setColour (button.findColour (ToggleButton::textColourId));
  52559. g.setFont (fontSize);
  52560. if (! button.isEnabled())
  52561. g.setOpacity (0.5f);
  52562. const int textX = (int) tickWidth + 5;
  52563. g.drawFittedText (button.getButtonText(),
  52564. textX, 0,
  52565. button.getWidth() - textX - 2, button.getHeight(),
  52566. Justification::centredLeft, 10);
  52567. }
  52568. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52569. {
  52570. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52571. const int tickWidth = jmin (24, button.getHeight());
  52572. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52573. button.getHeight());
  52574. }
  52575. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52576. const String& message,
  52577. const String& button1,
  52578. const String& button2,
  52579. const String& button3,
  52580. AlertWindow::AlertIconType iconType,
  52581. int numButtons,
  52582. Component* associatedComponent)
  52583. {
  52584. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52585. if (numButtons == 1)
  52586. {
  52587. aw->addButton (button1, 0,
  52588. KeyPress (KeyPress::escapeKey, 0, 0),
  52589. KeyPress (KeyPress::returnKey, 0, 0));
  52590. }
  52591. else
  52592. {
  52593. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52594. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52595. if (button1ShortCut == button2ShortCut)
  52596. button2ShortCut = KeyPress();
  52597. if (numButtons == 2)
  52598. {
  52599. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52600. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52601. }
  52602. else if (numButtons == 3)
  52603. {
  52604. aw->addButton (button1, 1, button1ShortCut);
  52605. aw->addButton (button2, 2, button2ShortCut);
  52606. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52607. }
  52608. }
  52609. return aw;
  52610. }
  52611. void LookAndFeel::drawAlertBox (Graphics& g,
  52612. AlertWindow& alert,
  52613. const Rectangle<int>& textArea,
  52614. TextLayout& textLayout)
  52615. {
  52616. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52617. int iconSpaceUsed = 0;
  52618. Justification alignment (Justification::horizontallyCentred);
  52619. const int iconWidth = 80;
  52620. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52621. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52622. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52623. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52624. iconSize, iconSize);
  52625. if (alert.getAlertType() != AlertWindow::NoIcon)
  52626. {
  52627. Path icon;
  52628. uint32 colour;
  52629. char character;
  52630. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52631. {
  52632. colour = 0x55ff5555;
  52633. character = '!';
  52634. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52635. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52636. (float) iconRect.getX(), (float) iconRect.getBottom());
  52637. icon = icon.createPathWithRoundedCorners (5.0f);
  52638. }
  52639. else
  52640. {
  52641. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52642. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52643. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52644. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52645. }
  52646. GlyphArrangement ga;
  52647. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52648. String::charToString (character),
  52649. (float) iconRect.getX(), (float) iconRect.getY(),
  52650. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52651. Justification::centred, false);
  52652. ga.createPath (icon);
  52653. icon.setUsingNonZeroWinding (false);
  52654. g.setColour (Colour (colour));
  52655. g.fillPath (icon);
  52656. iconSpaceUsed = iconWidth;
  52657. alignment = Justification::left;
  52658. }
  52659. g.setColour (alert.findColour (AlertWindow::textColourId));
  52660. textLayout.drawWithin (g,
  52661. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52662. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52663. alignment.getFlags() | Justification::top);
  52664. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52665. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52666. }
  52667. int LookAndFeel::getAlertBoxWindowFlags()
  52668. {
  52669. return ComponentPeer::windowAppearsOnTaskbar
  52670. | ComponentPeer::windowHasDropShadow;
  52671. }
  52672. int LookAndFeel::getAlertWindowButtonHeight()
  52673. {
  52674. return 28;
  52675. }
  52676. const Font LookAndFeel::getAlertWindowFont()
  52677. {
  52678. return Font (12.0f);
  52679. }
  52680. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52681. int width, int height,
  52682. double progress, const String& textToShow)
  52683. {
  52684. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52685. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52686. g.fillAll (background);
  52687. if (progress >= 0.0f && progress < 1.0f)
  52688. {
  52689. drawGlassLozenge (g, 1.0f, 1.0f,
  52690. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52691. (float) (height - 2),
  52692. foreground,
  52693. 0.5f, 0.0f,
  52694. true, true, true, true);
  52695. }
  52696. else
  52697. {
  52698. // spinning bar..
  52699. g.setColour (foreground);
  52700. const int stripeWidth = height * 2;
  52701. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52702. Path p;
  52703. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52704. p.addQuadrilateral (x, 0.0f,
  52705. x + stripeWidth * 0.5f, 0.0f,
  52706. x, (float) height,
  52707. x - stripeWidth * 0.5f, (float) height);
  52708. Image im (Image::ARGB, width, height, true);
  52709. {
  52710. Graphics g2 (im);
  52711. drawGlassLozenge (g2, 1.0f, 1.0f,
  52712. (float) (width - 2),
  52713. (float) (height - 2),
  52714. foreground,
  52715. 0.5f, 0.0f,
  52716. true, true, true, true);
  52717. }
  52718. g.setTiledImageFill (im, 0, 0, 0.85f);
  52719. g.fillPath (p);
  52720. }
  52721. if (textToShow.isNotEmpty())
  52722. {
  52723. g.setColour (Colour::contrasting (background, foreground));
  52724. g.setFont (height * 0.6f);
  52725. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52726. }
  52727. }
  52728. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52729. {
  52730. const float radius = jmin (w, h) * 0.4f;
  52731. const float thickness = radius * 0.15f;
  52732. Path p;
  52733. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52734. radius * 0.6f, thickness,
  52735. thickness * 0.5f);
  52736. const float cx = x + w * 0.5f;
  52737. const float cy = y + h * 0.5f;
  52738. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52739. for (int i = 0; i < 12; ++i)
  52740. {
  52741. const int n = (i + 12 - animationIndex) % 12;
  52742. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52743. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52744. .translated (cx, cy));
  52745. }
  52746. }
  52747. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52748. ScrollBar& scrollbar,
  52749. int width, int height,
  52750. int buttonDirection,
  52751. bool /*isScrollbarVertical*/,
  52752. bool /*isMouseOverButton*/,
  52753. bool isButtonDown)
  52754. {
  52755. Path p;
  52756. if (buttonDirection == 0)
  52757. p.addTriangle (width * 0.5f, height * 0.2f,
  52758. width * 0.1f, height * 0.7f,
  52759. width * 0.9f, height * 0.7f);
  52760. else if (buttonDirection == 1)
  52761. p.addTriangle (width * 0.8f, height * 0.5f,
  52762. width * 0.3f, height * 0.1f,
  52763. width * 0.3f, height * 0.9f);
  52764. else if (buttonDirection == 2)
  52765. p.addTriangle (width * 0.5f, height * 0.8f,
  52766. width * 0.1f, height * 0.3f,
  52767. width * 0.9f, height * 0.3f);
  52768. else if (buttonDirection == 3)
  52769. p.addTriangle (width * 0.2f, height * 0.5f,
  52770. width * 0.7f, height * 0.1f,
  52771. width * 0.7f, height * 0.9f);
  52772. if (isButtonDown)
  52773. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52774. else
  52775. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52776. g.fillPath (p);
  52777. g.setColour (Colour (0x80000000));
  52778. g.strokePath (p, PathStrokeType (0.5f));
  52779. }
  52780. void LookAndFeel::drawScrollbar (Graphics& g,
  52781. ScrollBar& scrollbar,
  52782. int x, int y,
  52783. int width, int height,
  52784. bool isScrollbarVertical,
  52785. int thumbStartPosition,
  52786. int thumbSize,
  52787. bool /*isMouseOver*/,
  52788. bool /*isMouseDown*/)
  52789. {
  52790. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52791. Path slotPath, thumbPath;
  52792. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52793. const float slotIndentx2 = slotIndent * 2.0f;
  52794. const float thumbIndent = slotIndent + 1.0f;
  52795. const float thumbIndentx2 = thumbIndent * 2.0f;
  52796. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52797. if (isScrollbarVertical)
  52798. {
  52799. slotPath.addRoundedRectangle (x + slotIndent,
  52800. y + slotIndent,
  52801. width - slotIndentx2,
  52802. height - slotIndentx2,
  52803. (width - slotIndentx2) * 0.5f);
  52804. if (thumbSize > 0)
  52805. thumbPath.addRoundedRectangle (x + thumbIndent,
  52806. thumbStartPosition + thumbIndent,
  52807. width - thumbIndentx2,
  52808. thumbSize - thumbIndentx2,
  52809. (width - thumbIndentx2) * 0.5f);
  52810. gx1 = (float) x;
  52811. gx2 = x + width * 0.7f;
  52812. }
  52813. else
  52814. {
  52815. slotPath.addRoundedRectangle (x + slotIndent,
  52816. y + slotIndent,
  52817. width - slotIndentx2,
  52818. height - slotIndentx2,
  52819. (height - slotIndentx2) * 0.5f);
  52820. if (thumbSize > 0)
  52821. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52822. y + thumbIndent,
  52823. thumbSize - thumbIndentx2,
  52824. height - thumbIndentx2,
  52825. (height - thumbIndentx2) * 0.5f);
  52826. gy1 = (float) y;
  52827. gy2 = y + height * 0.7f;
  52828. }
  52829. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52830. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52831. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52832. g.fillPath (slotPath);
  52833. if (isScrollbarVertical)
  52834. {
  52835. gx1 = x + width * 0.6f;
  52836. gx2 = (float) x + width;
  52837. }
  52838. else
  52839. {
  52840. gy1 = y + height * 0.6f;
  52841. gy2 = (float) y + height;
  52842. }
  52843. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52844. Colour (0x19000000), gx2, gy2, false));
  52845. g.fillPath (slotPath);
  52846. g.setColour (thumbColour);
  52847. g.fillPath (thumbPath);
  52848. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52849. Colours::transparentBlack, gx2, gy2, false));
  52850. g.saveState();
  52851. if (isScrollbarVertical)
  52852. g.reduceClipRegion (x + width / 2, y, width, height);
  52853. else
  52854. g.reduceClipRegion (x, y + height / 2, width, height);
  52855. g.fillPath (thumbPath);
  52856. g.restoreState();
  52857. g.setColour (Colour (0x4c000000));
  52858. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52859. }
  52860. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52861. {
  52862. return 0;
  52863. }
  52864. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52865. {
  52866. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52867. }
  52868. int LookAndFeel::getDefaultScrollbarWidth()
  52869. {
  52870. return 18;
  52871. }
  52872. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52873. {
  52874. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52875. : scrollbar.getHeight());
  52876. }
  52877. const Path LookAndFeel::getTickShape (const float height)
  52878. {
  52879. static const unsigned char tickShapeData[] =
  52880. {
  52881. 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,
  52882. 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,
  52883. 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,
  52884. 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,
  52885. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52886. };
  52887. Path p;
  52888. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52889. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52890. return p;
  52891. }
  52892. const Path LookAndFeel::getCrossShape (const float height)
  52893. {
  52894. static const unsigned char crossShapeData[] =
  52895. {
  52896. 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,
  52897. 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,
  52898. 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,
  52899. 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,
  52900. 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,
  52901. 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,
  52902. 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
  52903. };
  52904. Path p;
  52905. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52906. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52907. return p;
  52908. }
  52909. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52910. {
  52911. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52912. x += (w - boxSize) >> 1;
  52913. y += (h - boxSize) >> 1;
  52914. w = boxSize;
  52915. h = boxSize;
  52916. g.setColour (Colour (0xe5ffffff));
  52917. g.fillRect (x, y, w, h);
  52918. g.setColour (Colour (0x80000000));
  52919. g.drawRect (x, y, w, h);
  52920. const float size = boxSize / 2 + 1.0f;
  52921. const float centre = (float) (boxSize / 2);
  52922. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52923. if (isPlus)
  52924. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52925. }
  52926. void LookAndFeel::drawBubble (Graphics& g,
  52927. float tipX, float tipY,
  52928. float boxX, float boxY,
  52929. float boxW, float boxH)
  52930. {
  52931. int side = 0;
  52932. if (tipX < boxX)
  52933. side = 1;
  52934. else if (tipX > boxX + boxW)
  52935. side = 3;
  52936. else if (tipY > boxY + boxH)
  52937. side = 2;
  52938. const float indent = 2.0f;
  52939. Path p;
  52940. p.addBubble (boxX + indent,
  52941. boxY + indent,
  52942. boxW - indent * 2.0f,
  52943. boxH - indent * 2.0f,
  52944. 5.0f,
  52945. tipX, tipY,
  52946. side,
  52947. 0.5f,
  52948. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52949. //xxx need to take comp as param for colour
  52950. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52951. g.fillPath (p);
  52952. //xxx as above
  52953. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52954. g.strokePath (p, PathStrokeType (1.33f));
  52955. }
  52956. const Font LookAndFeel::getPopupMenuFont()
  52957. {
  52958. return Font (17.0f);
  52959. }
  52960. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52961. const bool isSeparator,
  52962. int standardMenuItemHeight,
  52963. int& idealWidth,
  52964. int& idealHeight)
  52965. {
  52966. if (isSeparator)
  52967. {
  52968. idealWidth = 50;
  52969. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52970. }
  52971. else
  52972. {
  52973. Font font (getPopupMenuFont());
  52974. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52975. font.setHeight (standardMenuItemHeight / 1.3f);
  52976. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52977. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52978. }
  52979. }
  52980. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52981. {
  52982. const Colour background (findColour (PopupMenu::backgroundColourId));
  52983. g.fillAll (background);
  52984. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52985. for (int i = 0; i < height; i += 3)
  52986. g.fillRect (0, i, width, 1);
  52987. #if ! JUCE_MAC
  52988. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52989. g.drawRect (0, 0, width, height);
  52990. #endif
  52991. }
  52992. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52993. int width, int height,
  52994. bool isScrollUpArrow)
  52995. {
  52996. const Colour background (findColour (PopupMenu::backgroundColourId));
  52997. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52998. background.withAlpha (0.0f),
  52999. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53000. false));
  53001. g.fillRect (1, 1, width - 2, height - 2);
  53002. const float hw = width * 0.5f;
  53003. const float arrowW = height * 0.3f;
  53004. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53005. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53006. Path p;
  53007. p.addTriangle (hw - arrowW, y1,
  53008. hw + arrowW, y1,
  53009. hw, y2);
  53010. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53011. g.fillPath (p);
  53012. }
  53013. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53014. int width, int height,
  53015. const bool isSeparator,
  53016. const bool isActive,
  53017. const bool isHighlighted,
  53018. const bool isTicked,
  53019. const bool hasSubMenu,
  53020. const String& text,
  53021. const String& shortcutKeyText,
  53022. Image* image,
  53023. const Colour* const textColourToUse)
  53024. {
  53025. const float halfH = height * 0.5f;
  53026. if (isSeparator)
  53027. {
  53028. const float separatorIndent = 5.5f;
  53029. g.setColour (Colour (0x33000000));
  53030. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53031. g.setColour (Colour (0x66ffffff));
  53032. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53033. }
  53034. else
  53035. {
  53036. Colour textColour (findColour (PopupMenu::textColourId));
  53037. if (textColourToUse != 0)
  53038. textColour = *textColourToUse;
  53039. if (isHighlighted)
  53040. {
  53041. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53042. g.fillRect (1, 1, width - 2, height - 2);
  53043. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53044. }
  53045. else
  53046. {
  53047. g.setColour (textColour);
  53048. }
  53049. if (! isActive)
  53050. g.setOpacity (0.3f);
  53051. Font font (getPopupMenuFont());
  53052. if (font.getHeight() > height / 1.3f)
  53053. font.setHeight (height / 1.3f);
  53054. g.setFont (font);
  53055. const int leftBorder = (height * 5) / 4;
  53056. const int rightBorder = 4;
  53057. if (image != 0)
  53058. {
  53059. g.drawImageWithin (*image,
  53060. 2, 1, leftBorder - 4, height - 2,
  53061. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53062. }
  53063. else if (isTicked)
  53064. {
  53065. const Path tick (getTickShape (1.0f));
  53066. const float th = font.getAscent();
  53067. const float ty = halfH - th * 0.5f;
  53068. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53069. th, true));
  53070. }
  53071. g.drawFittedText (text,
  53072. leftBorder, 0,
  53073. width - (leftBorder + rightBorder), height,
  53074. Justification::centredLeft, 1);
  53075. if (shortcutKeyText.isNotEmpty())
  53076. {
  53077. Font f2 (font);
  53078. f2.setHeight (f2.getHeight() * 0.75f);
  53079. f2.setHorizontalScale (0.95f);
  53080. g.setFont (f2);
  53081. g.drawText (shortcutKeyText,
  53082. leftBorder,
  53083. 0,
  53084. width - (leftBorder + rightBorder + 4),
  53085. height,
  53086. Justification::centredRight,
  53087. true);
  53088. }
  53089. if (hasSubMenu)
  53090. {
  53091. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53092. const float x = width - height * 0.6f;
  53093. Path p;
  53094. p.addTriangle (x, halfH - arrowH * 0.5f,
  53095. x, halfH + arrowH * 0.5f,
  53096. x + arrowH * 0.6f, halfH);
  53097. g.fillPath (p);
  53098. }
  53099. }
  53100. }
  53101. int LookAndFeel::getMenuWindowFlags()
  53102. {
  53103. return ComponentPeer::windowHasDropShadow;
  53104. }
  53105. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53106. bool, MenuBarComponent& menuBar)
  53107. {
  53108. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53109. if (menuBar.isEnabled())
  53110. {
  53111. drawShinyButtonShape (g,
  53112. -4.0f, 0.0f,
  53113. width + 8.0f, (float) height,
  53114. 0.0f,
  53115. baseColour,
  53116. 0.4f,
  53117. true, true, true, true);
  53118. }
  53119. else
  53120. {
  53121. g.fillAll (baseColour);
  53122. }
  53123. }
  53124. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53125. {
  53126. return Font (menuBar.getHeight() * 0.7f);
  53127. }
  53128. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53129. {
  53130. return getMenuBarFont (menuBar, itemIndex, itemText)
  53131. .getStringWidth (itemText) + menuBar.getHeight();
  53132. }
  53133. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53134. int width, int height,
  53135. int itemIndex,
  53136. const String& itemText,
  53137. bool isMouseOverItem,
  53138. bool isMenuOpen,
  53139. bool /*isMouseOverBar*/,
  53140. MenuBarComponent& menuBar)
  53141. {
  53142. if (! menuBar.isEnabled())
  53143. {
  53144. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53145. .withMultipliedAlpha (0.5f));
  53146. }
  53147. else if (isMenuOpen || isMouseOverItem)
  53148. {
  53149. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53150. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53151. }
  53152. else
  53153. {
  53154. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53155. }
  53156. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53157. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53158. }
  53159. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53160. TextEditor& textEditor)
  53161. {
  53162. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53163. }
  53164. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53165. {
  53166. if (textEditor.isEnabled())
  53167. {
  53168. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53169. {
  53170. const int border = 2;
  53171. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53172. g.drawRect (0, 0, width, height, border);
  53173. g.setOpacity (1.0f);
  53174. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53175. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53176. }
  53177. else
  53178. {
  53179. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53180. g.drawRect (0, 0, width, height);
  53181. g.setOpacity (1.0f);
  53182. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53183. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53184. }
  53185. }
  53186. }
  53187. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53188. const bool isButtonDown,
  53189. int buttonX, int buttonY,
  53190. int buttonW, int buttonH,
  53191. ComboBox& box)
  53192. {
  53193. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53194. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53195. {
  53196. g.setColour (box.findColour (TextButton::buttonColourId));
  53197. g.drawRect (0, 0, width, height, 2);
  53198. }
  53199. else
  53200. {
  53201. g.setColour (box.findColour (ComboBox::outlineColourId));
  53202. g.drawRect (0, 0, width, height);
  53203. }
  53204. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53205. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53206. box.hasKeyboardFocus (true),
  53207. false, isButtonDown)
  53208. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53209. drawGlassLozenge (g,
  53210. buttonX + outlineThickness, buttonY + outlineThickness,
  53211. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53212. baseColour, outlineThickness, -1.0f,
  53213. true, true, true, true);
  53214. if (box.isEnabled())
  53215. {
  53216. const float arrowX = 0.3f;
  53217. const float arrowH = 0.2f;
  53218. Path p;
  53219. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53220. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53221. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53222. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53223. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53224. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53225. g.setColour (box.findColour (ComboBox::arrowColourId));
  53226. g.fillPath (p);
  53227. }
  53228. }
  53229. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53230. {
  53231. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53232. }
  53233. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53234. {
  53235. return new Label (String::empty, String::empty);
  53236. }
  53237. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53238. {
  53239. label.setBounds (1, 1,
  53240. box.getWidth() + 3 - box.getHeight(),
  53241. box.getHeight() - 2);
  53242. label.setFont (getComboBoxFont (box));
  53243. }
  53244. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53245. {
  53246. g.fillAll (label.findColour (Label::backgroundColourId));
  53247. if (! label.isBeingEdited())
  53248. {
  53249. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53250. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53251. g.setFont (label.getFont());
  53252. g.drawFittedText (label.getText(),
  53253. label.getHorizontalBorderSize(),
  53254. label.getVerticalBorderSize(),
  53255. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53256. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53257. label.getJustificationType(),
  53258. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53259. label.getMinimumHorizontalScale());
  53260. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53261. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53262. }
  53263. else if (label.isEnabled())
  53264. {
  53265. g.setColour (label.findColour (Label::outlineColourId));
  53266. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53267. }
  53268. }
  53269. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53270. int x, int y,
  53271. int width, int height,
  53272. float /*sliderPos*/,
  53273. float /*minSliderPos*/,
  53274. float /*maxSliderPos*/,
  53275. const Slider::SliderStyle /*style*/,
  53276. Slider& slider)
  53277. {
  53278. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53279. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53280. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53281. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53282. Path indent;
  53283. if (slider.isHorizontal())
  53284. {
  53285. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53286. const float ih = sliderRadius;
  53287. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53288. gradCol2, 0.0f, iy + ih, false));
  53289. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53290. width + sliderRadius, ih,
  53291. 5.0f);
  53292. g.fillPath (indent);
  53293. }
  53294. else
  53295. {
  53296. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53297. const float iw = sliderRadius;
  53298. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53299. gradCol2, ix + iw, 0.0f, false));
  53300. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53301. iw, height + sliderRadius,
  53302. 5.0f);
  53303. g.fillPath (indent);
  53304. }
  53305. g.setColour (Colour (0x4c000000));
  53306. g.strokePath (indent, PathStrokeType (0.5f));
  53307. }
  53308. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53309. int x, int y,
  53310. int width, int height,
  53311. float sliderPos,
  53312. float minSliderPos,
  53313. float maxSliderPos,
  53314. const Slider::SliderStyle style,
  53315. Slider& slider)
  53316. {
  53317. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53318. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53319. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53320. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53321. slider.isMouseButtonDown() && slider.isEnabled()));
  53322. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53323. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53324. {
  53325. float kx, ky;
  53326. if (style == Slider::LinearVertical)
  53327. {
  53328. kx = x + width * 0.5f;
  53329. ky = sliderPos;
  53330. }
  53331. else
  53332. {
  53333. kx = sliderPos;
  53334. ky = y + height * 0.5f;
  53335. }
  53336. drawGlassSphere (g,
  53337. kx - sliderRadius,
  53338. ky - sliderRadius,
  53339. sliderRadius * 2.0f,
  53340. knobColour, outlineThickness);
  53341. }
  53342. else
  53343. {
  53344. if (style == Slider::ThreeValueVertical)
  53345. {
  53346. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53347. sliderPos - sliderRadius,
  53348. sliderRadius * 2.0f,
  53349. knobColour, outlineThickness);
  53350. }
  53351. else if (style == Slider::ThreeValueHorizontal)
  53352. {
  53353. drawGlassSphere (g,sliderPos - sliderRadius,
  53354. y + height * 0.5f - sliderRadius,
  53355. sliderRadius * 2.0f,
  53356. knobColour, outlineThickness);
  53357. }
  53358. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53359. {
  53360. const float sr = jmin (sliderRadius, width * 0.4f);
  53361. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53362. minSliderPos - sliderRadius,
  53363. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53364. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53365. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53366. }
  53367. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53368. {
  53369. const float sr = jmin (sliderRadius, height * 0.4f);
  53370. drawGlassPointer (g, minSliderPos - sr,
  53371. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53372. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53373. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53374. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53375. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53376. }
  53377. }
  53378. }
  53379. void LookAndFeel::drawLinearSlider (Graphics& g,
  53380. int x, int y,
  53381. int width, int height,
  53382. float sliderPos,
  53383. float minSliderPos,
  53384. float maxSliderPos,
  53385. const Slider::SliderStyle style,
  53386. Slider& slider)
  53387. {
  53388. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53389. if (style == Slider::LinearBar)
  53390. {
  53391. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53392. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53393. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53394. false, isMouseOver,
  53395. isMouseOver || slider.isMouseButtonDown()));
  53396. drawShinyButtonShape (g,
  53397. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53398. baseColour,
  53399. slider.isEnabled() ? 0.9f : 0.3f,
  53400. true, true, true, true);
  53401. }
  53402. else
  53403. {
  53404. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53405. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53406. }
  53407. }
  53408. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53409. {
  53410. return jmin (7,
  53411. slider.getHeight() / 2,
  53412. slider.getWidth() / 2) + 2;
  53413. }
  53414. void LookAndFeel::drawRotarySlider (Graphics& g,
  53415. int x, int y,
  53416. int width, int height,
  53417. float sliderPos,
  53418. const float rotaryStartAngle,
  53419. const float rotaryEndAngle,
  53420. Slider& slider)
  53421. {
  53422. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53423. const float centreX = x + width * 0.5f;
  53424. const float centreY = y + height * 0.5f;
  53425. const float rx = centreX - radius;
  53426. const float ry = centreY - radius;
  53427. const float rw = radius * 2.0f;
  53428. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53429. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53430. if (radius > 12.0f)
  53431. {
  53432. if (slider.isEnabled())
  53433. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53434. else
  53435. g.setColour (Colour (0x80808080));
  53436. const float thickness = 0.7f;
  53437. {
  53438. Path filledArc;
  53439. filledArc.addPieSegment (rx, ry, rw, rw,
  53440. rotaryStartAngle,
  53441. angle,
  53442. thickness);
  53443. g.fillPath (filledArc);
  53444. }
  53445. if (thickness > 0)
  53446. {
  53447. const float innerRadius = radius * 0.2f;
  53448. Path p;
  53449. p.addTriangle (-innerRadius, 0.0f,
  53450. 0.0f, -radius * thickness * 1.1f,
  53451. innerRadius, 0.0f);
  53452. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53453. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53454. }
  53455. if (slider.isEnabled())
  53456. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53457. else
  53458. g.setColour (Colour (0x80808080));
  53459. Path outlineArc;
  53460. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53461. outlineArc.closeSubPath();
  53462. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53463. }
  53464. else
  53465. {
  53466. if (slider.isEnabled())
  53467. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53468. else
  53469. g.setColour (Colour (0x80808080));
  53470. Path p;
  53471. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53472. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53473. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53474. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53475. }
  53476. }
  53477. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53478. {
  53479. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53480. }
  53481. class SliderLabelComp : public Label
  53482. {
  53483. public:
  53484. SliderLabelComp() : Label (String::empty, String::empty) {}
  53485. ~SliderLabelComp() {}
  53486. void mouseWheelMove (const MouseEvent&, float, float) {}
  53487. };
  53488. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53489. {
  53490. Label* const l = new SliderLabelComp();
  53491. l->setJustificationType (Justification::centred);
  53492. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53493. l->setColour (Label::backgroundColourId,
  53494. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53495. : slider.findColour (Slider::textBoxBackgroundColourId));
  53496. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53497. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53498. l->setColour (TextEditor::backgroundColourId,
  53499. slider.findColour (Slider::textBoxBackgroundColourId)
  53500. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53501. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53502. return l;
  53503. }
  53504. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53505. {
  53506. return 0;
  53507. }
  53508. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53509. {
  53510. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53511. width = tl.getWidth() + 14;
  53512. height = tl.getHeight() + 6;
  53513. }
  53514. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53515. {
  53516. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53517. const Colour textCol (findColour (TooltipWindow::textColourId));
  53518. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53519. g.setColour (findColour (TooltipWindow::outlineColourId));
  53520. g.drawRect (0, 0, width, height, 1);
  53521. #endif
  53522. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53523. g.setColour (findColour (TooltipWindow::textColourId));
  53524. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53525. }
  53526. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53527. {
  53528. return new TextButton (text, TRANS("click to browse for a different file"));
  53529. }
  53530. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53531. ComboBox* filenameBox,
  53532. Button* browseButton)
  53533. {
  53534. browseButton->setSize (80, filenameComp.getHeight());
  53535. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53536. if (tb != 0)
  53537. tb->changeWidthToFitText();
  53538. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53539. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53540. }
  53541. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53542. int imageX, int imageY, int imageW, int imageH,
  53543. const Colour& overlayColour,
  53544. float imageOpacity,
  53545. ImageButton& button)
  53546. {
  53547. if (! button.isEnabled())
  53548. imageOpacity *= 0.3f;
  53549. if (! overlayColour.isOpaque())
  53550. {
  53551. g.setOpacity (imageOpacity);
  53552. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53553. 0, 0, image->getWidth(), image->getHeight(), false);
  53554. }
  53555. if (! overlayColour.isTransparent())
  53556. {
  53557. g.setColour (overlayColour);
  53558. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53559. 0, 0, image->getWidth(), image->getHeight(), true);
  53560. }
  53561. }
  53562. void LookAndFeel::drawCornerResizer (Graphics& g,
  53563. int w, int h,
  53564. bool /*isMouseOver*/,
  53565. bool /*isMouseDragging*/)
  53566. {
  53567. const float lineThickness = jmin (w, h) * 0.075f;
  53568. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53569. {
  53570. g.setColour (Colours::lightgrey);
  53571. g.drawLine (w * i,
  53572. h + 1.0f,
  53573. w + 1.0f,
  53574. h * i,
  53575. lineThickness);
  53576. g.setColour (Colours::darkgrey);
  53577. g.drawLine (w * i + lineThickness,
  53578. h + 1.0f,
  53579. w + 1.0f,
  53580. h * i + lineThickness,
  53581. lineThickness);
  53582. }
  53583. }
  53584. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53585. {
  53586. if (! border.isEmpty())
  53587. {
  53588. const Rectangle<int> fullSize (0, 0, w, h);
  53589. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53590. g.saveState();
  53591. g.excludeClipRegion (centreArea);
  53592. g.setColour (Colour (0x50000000));
  53593. g.drawRect (fullSize);
  53594. g.setColour (Colour (0x19000000));
  53595. g.drawRect (centreArea.expanded (1, 1));
  53596. g.restoreState();
  53597. }
  53598. }
  53599. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53600. const BorderSize& /*border*/, ResizableWindow& window)
  53601. {
  53602. g.fillAll (window.getBackgroundColour());
  53603. }
  53604. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53605. const BorderSize& /*border*/, ResizableWindow&)
  53606. {
  53607. }
  53608. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53609. Graphics& g, int w, int h,
  53610. int titleSpaceX, int titleSpaceW,
  53611. const Image* icon,
  53612. bool drawTitleTextOnLeft)
  53613. {
  53614. const bool isActive = window.isActiveWindow();
  53615. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53616. 0.0f, 0.0f,
  53617. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53618. 0.0f, (float) h, false));
  53619. g.fillAll();
  53620. Font font (h * 0.65f, Font::bold);
  53621. g.setFont (font);
  53622. int textW = font.getStringWidth (window.getName());
  53623. int iconW = 0;
  53624. int iconH = 0;
  53625. if (icon != 0)
  53626. {
  53627. iconH = (int) font.getHeight();
  53628. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53629. }
  53630. textW = jmin (titleSpaceW, textW + iconW);
  53631. int textX = drawTitleTextOnLeft ? titleSpaceX
  53632. : jmax (titleSpaceX, (w - textW) / 2);
  53633. if (textX + textW > titleSpaceX + titleSpaceW)
  53634. textX = titleSpaceX + titleSpaceW - textW;
  53635. if (icon != 0)
  53636. {
  53637. g.setOpacity (isActive ? 1.0f : 0.6f);
  53638. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53639. RectanglePlacement::centred, false);
  53640. textX += iconW;
  53641. textW -= iconW;
  53642. }
  53643. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53644. g.setColour (findColour (DocumentWindow::textColourId));
  53645. else
  53646. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53647. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53648. }
  53649. class GlassWindowButton : public Button
  53650. {
  53651. public:
  53652. GlassWindowButton (const String& name, const Colour& col,
  53653. const Path& normalShape_,
  53654. const Path& toggledShape_) throw()
  53655. : Button (name),
  53656. colour (col),
  53657. normalShape (normalShape_),
  53658. toggledShape (toggledShape_)
  53659. {
  53660. }
  53661. ~GlassWindowButton()
  53662. {
  53663. }
  53664. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53665. {
  53666. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53667. if (! isEnabled())
  53668. alpha *= 0.5f;
  53669. float x = 0, y = 0, diam;
  53670. if (getWidth() < getHeight())
  53671. {
  53672. diam = (float) getWidth();
  53673. y = (getHeight() - getWidth()) * 0.5f;
  53674. }
  53675. else
  53676. {
  53677. diam = (float) getHeight();
  53678. y = (getWidth() - getHeight()) * 0.5f;
  53679. }
  53680. x += diam * 0.05f;
  53681. y += diam * 0.05f;
  53682. diam *= 0.9f;
  53683. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53684. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53685. g.fillEllipse (x, y, diam, diam);
  53686. x += 2.0f;
  53687. y += 2.0f;
  53688. diam -= 4.0f;
  53689. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53690. Path& p = getToggleState() ? toggledShape : normalShape;
  53691. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53692. diam * 0.4f, diam * 0.4f, true));
  53693. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53694. g.fillPath (p, t);
  53695. }
  53696. juce_UseDebuggingNewOperator
  53697. private:
  53698. Colour colour;
  53699. Path normalShape, toggledShape;
  53700. GlassWindowButton (const GlassWindowButton&);
  53701. GlassWindowButton& operator= (const GlassWindowButton&);
  53702. };
  53703. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53704. {
  53705. Path shape;
  53706. const float crossThickness = 0.25f;
  53707. if (buttonType == DocumentWindow::closeButton)
  53708. {
  53709. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53710. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53711. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53712. }
  53713. else if (buttonType == DocumentWindow::minimiseButton)
  53714. {
  53715. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53716. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53717. }
  53718. else if (buttonType == DocumentWindow::maximiseButton)
  53719. {
  53720. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53721. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53722. Path fullscreenShape;
  53723. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53724. fullscreenShape.lineTo (0.0f, 100.0f);
  53725. fullscreenShape.lineTo (0.0f, 0.0f);
  53726. fullscreenShape.lineTo (100.0f, 0.0f);
  53727. fullscreenShape.lineTo (100.0f, 45.0f);
  53728. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53729. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53730. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53731. }
  53732. jassertfalse;
  53733. return 0;
  53734. }
  53735. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53736. int titleBarX,
  53737. int titleBarY,
  53738. int titleBarW,
  53739. int titleBarH,
  53740. Button* minimiseButton,
  53741. Button* maximiseButton,
  53742. Button* closeButton,
  53743. bool positionTitleBarButtonsOnLeft)
  53744. {
  53745. const int buttonW = titleBarH - titleBarH / 8;
  53746. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53747. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53748. if (closeButton != 0)
  53749. {
  53750. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53751. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53752. }
  53753. if (positionTitleBarButtonsOnLeft)
  53754. swapVariables (minimiseButton, maximiseButton);
  53755. if (maximiseButton != 0)
  53756. {
  53757. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53758. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53759. }
  53760. if (minimiseButton != 0)
  53761. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53762. }
  53763. int LookAndFeel::getDefaultMenuBarHeight()
  53764. {
  53765. return 24;
  53766. }
  53767. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53768. {
  53769. return new DropShadower (0.4f, 1, 5, 10);
  53770. }
  53771. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53772. int w, int h,
  53773. bool /*isVerticalBar*/,
  53774. bool isMouseOver,
  53775. bool isMouseDragging)
  53776. {
  53777. float alpha = 0.5f;
  53778. if (isMouseOver || isMouseDragging)
  53779. {
  53780. g.fillAll (Colour (0x190000ff));
  53781. alpha = 1.0f;
  53782. }
  53783. const float cx = w * 0.5f;
  53784. const float cy = h * 0.5f;
  53785. const float cr = jmin (w, h) * 0.4f;
  53786. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53787. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53788. true));
  53789. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53790. }
  53791. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53792. const String& text,
  53793. const Justification& position,
  53794. GroupComponent& group)
  53795. {
  53796. const float textH = 15.0f;
  53797. const float indent = 3.0f;
  53798. const float textEdgeGap = 4.0f;
  53799. float cs = 5.0f;
  53800. Font f (textH);
  53801. Path p;
  53802. float x = indent;
  53803. float y = f.getAscent() - 3.0f;
  53804. float w = jmax (0.0f, width - x * 2.0f);
  53805. float h = jmax (0.0f, height - y - indent);
  53806. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53807. const float cs2 = 2.0f * cs;
  53808. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53809. float textX = cs + textEdgeGap;
  53810. if (position.testFlags (Justification::horizontallyCentred))
  53811. textX = cs + (w - cs2 - textW) * 0.5f;
  53812. else if (position.testFlags (Justification::right))
  53813. textX = w - cs - textW - textEdgeGap;
  53814. p.startNewSubPath (x + textX + textW, y);
  53815. p.lineTo (x + w - cs, y);
  53816. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53817. p.lineTo (x + w, y + h - cs);
  53818. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53819. p.lineTo (x + cs, y + h);
  53820. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53821. p.lineTo (x, y + cs);
  53822. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53823. p.lineTo (x + textX, y);
  53824. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53825. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53826. .withMultipliedAlpha (alpha));
  53827. g.strokePath (p, PathStrokeType (2.0f));
  53828. g.setColour (group.findColour (GroupComponent::textColourId)
  53829. .withMultipliedAlpha (alpha));
  53830. g.setFont (f);
  53831. g.drawText (text,
  53832. roundToInt (x + textX), 0,
  53833. roundToInt (textW),
  53834. roundToInt (textH),
  53835. Justification::centred, true);
  53836. }
  53837. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53838. {
  53839. return 1 + tabDepth / 3;
  53840. }
  53841. int LookAndFeel::getTabButtonSpaceAroundImage()
  53842. {
  53843. return 4;
  53844. }
  53845. void LookAndFeel::createTabButtonShape (Path& p,
  53846. int width, int height,
  53847. int /*tabIndex*/,
  53848. const String& /*text*/,
  53849. Button& /*button*/,
  53850. TabbedButtonBar::Orientation orientation,
  53851. const bool /*isMouseOver*/,
  53852. const bool /*isMouseDown*/,
  53853. const bool /*isFrontTab*/)
  53854. {
  53855. const float w = (float) width;
  53856. const float h = (float) height;
  53857. float length = w;
  53858. float depth = h;
  53859. if (orientation == TabbedButtonBar::TabsAtLeft
  53860. || orientation == TabbedButtonBar::TabsAtRight)
  53861. {
  53862. swapVariables (length, depth);
  53863. }
  53864. const float indent = (float) getTabButtonOverlap ((int) depth);
  53865. const float overhang = 4.0f;
  53866. if (orientation == TabbedButtonBar::TabsAtLeft)
  53867. {
  53868. p.startNewSubPath (w, 0.0f);
  53869. p.lineTo (0.0f, indent);
  53870. p.lineTo (0.0f, h - indent);
  53871. p.lineTo (w, h);
  53872. p.lineTo (w + overhang, h + overhang);
  53873. p.lineTo (w + overhang, -overhang);
  53874. }
  53875. else if (orientation == TabbedButtonBar::TabsAtRight)
  53876. {
  53877. p.startNewSubPath (0.0f, 0.0f);
  53878. p.lineTo (w, indent);
  53879. p.lineTo (w, h - indent);
  53880. p.lineTo (0.0f, h);
  53881. p.lineTo (-overhang, h + overhang);
  53882. p.lineTo (-overhang, -overhang);
  53883. }
  53884. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53885. {
  53886. p.startNewSubPath (0.0f, 0.0f);
  53887. p.lineTo (indent, h);
  53888. p.lineTo (w - indent, h);
  53889. p.lineTo (w, 0.0f);
  53890. p.lineTo (w + overhang, -overhang);
  53891. p.lineTo (-overhang, -overhang);
  53892. }
  53893. else
  53894. {
  53895. p.startNewSubPath (0.0f, h);
  53896. p.lineTo (indent, 0.0f);
  53897. p.lineTo (w - indent, 0.0f);
  53898. p.lineTo (w, h);
  53899. p.lineTo (w + overhang, h + overhang);
  53900. p.lineTo (-overhang, h + overhang);
  53901. }
  53902. p.closeSubPath();
  53903. p = p.createPathWithRoundedCorners (3.0f);
  53904. }
  53905. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53906. const Path& path,
  53907. const Colour& preferredColour,
  53908. int /*tabIndex*/,
  53909. const String& /*text*/,
  53910. Button& button,
  53911. TabbedButtonBar::Orientation /*orientation*/,
  53912. const bool /*isMouseOver*/,
  53913. const bool /*isMouseDown*/,
  53914. const bool isFrontTab)
  53915. {
  53916. g.setColour (isFrontTab ? preferredColour
  53917. : preferredColour.withMultipliedAlpha (0.9f));
  53918. g.fillPath (path);
  53919. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53920. : TabbedButtonBar::tabOutlineColourId, false)
  53921. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53922. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53923. }
  53924. void LookAndFeel::drawTabButtonText (Graphics& g,
  53925. int x, int y, int w, int h,
  53926. const Colour& preferredBackgroundColour,
  53927. int /*tabIndex*/,
  53928. const String& text,
  53929. Button& button,
  53930. TabbedButtonBar::Orientation orientation,
  53931. const bool isMouseOver,
  53932. const bool isMouseDown,
  53933. const bool isFrontTab)
  53934. {
  53935. int length = w;
  53936. int depth = h;
  53937. if (orientation == TabbedButtonBar::TabsAtLeft
  53938. || orientation == TabbedButtonBar::TabsAtRight)
  53939. {
  53940. swapVariables (length, depth);
  53941. }
  53942. Font font (depth * 0.6f);
  53943. font.setUnderline (button.hasKeyboardFocus (false));
  53944. GlyphArrangement textLayout;
  53945. textLayout.addFittedText (font, text.trim(),
  53946. 0.0f, 0.0f, (float) length, (float) depth,
  53947. Justification::centred,
  53948. jmax (1, depth / 12));
  53949. AffineTransform transform;
  53950. if (orientation == TabbedButtonBar::TabsAtLeft)
  53951. {
  53952. transform = transform.rotated (float_Pi * -0.5f)
  53953. .translated ((float) x, (float) (y + h));
  53954. }
  53955. else if (orientation == TabbedButtonBar::TabsAtRight)
  53956. {
  53957. transform = transform.rotated (float_Pi * 0.5f)
  53958. .translated ((float) (x + w), (float) y);
  53959. }
  53960. else
  53961. {
  53962. transform = transform.translated ((float) x, (float) y);
  53963. }
  53964. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53965. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53966. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53967. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53968. else
  53969. g.setColour (preferredBackgroundColour.contrasting());
  53970. if (! (isMouseOver || isMouseDown))
  53971. g.setOpacity (0.8f);
  53972. if (! button.isEnabled())
  53973. g.setOpacity (0.3f);
  53974. textLayout.draw (g, transform);
  53975. }
  53976. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53977. const String& text,
  53978. int tabDepth,
  53979. Button&)
  53980. {
  53981. Font f (tabDepth * 0.6f);
  53982. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53983. }
  53984. void LookAndFeel::drawTabButton (Graphics& g,
  53985. int w, int h,
  53986. const Colour& preferredColour,
  53987. int tabIndex,
  53988. const String& text,
  53989. Button& button,
  53990. TabbedButtonBar::Orientation orientation,
  53991. const bool isMouseOver,
  53992. const bool isMouseDown,
  53993. const bool isFrontTab)
  53994. {
  53995. int length = w;
  53996. int depth = h;
  53997. if (orientation == TabbedButtonBar::TabsAtLeft
  53998. || orientation == TabbedButtonBar::TabsAtRight)
  53999. {
  54000. swapVariables (length, depth);
  54001. }
  54002. Path tabShape;
  54003. createTabButtonShape (tabShape, w, h,
  54004. tabIndex, text, button, orientation,
  54005. isMouseOver, isMouseDown, isFrontTab);
  54006. fillTabButtonShape (g, tabShape, preferredColour,
  54007. tabIndex, text, button, orientation,
  54008. isMouseOver, isMouseDown, isFrontTab);
  54009. const int indent = getTabButtonOverlap (depth);
  54010. int x = 0, y = 0;
  54011. if (orientation == TabbedButtonBar::TabsAtLeft
  54012. || orientation == TabbedButtonBar::TabsAtRight)
  54013. {
  54014. y += indent;
  54015. h -= indent * 2;
  54016. }
  54017. else
  54018. {
  54019. x += indent;
  54020. w -= indent * 2;
  54021. }
  54022. drawTabButtonText (g, x, y, w, h, preferredColour,
  54023. tabIndex, text, button, orientation,
  54024. isMouseOver, isMouseDown, isFrontTab);
  54025. }
  54026. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54027. int w, int h,
  54028. TabbedButtonBar& tabBar,
  54029. TabbedButtonBar::Orientation orientation)
  54030. {
  54031. const float shadowSize = 0.2f;
  54032. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54033. Rectangle<int> shadowRect;
  54034. if (orientation == TabbedButtonBar::TabsAtLeft)
  54035. {
  54036. x1 = (float) w;
  54037. x2 = w * (1.0f - shadowSize);
  54038. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54039. }
  54040. else if (orientation == TabbedButtonBar::TabsAtRight)
  54041. {
  54042. x2 = w * shadowSize;
  54043. shadowRect.setBounds (0, 0, (int) x2, h);
  54044. }
  54045. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54046. {
  54047. y2 = h * shadowSize;
  54048. shadowRect.setBounds (0, 0, w, (int) y2);
  54049. }
  54050. else
  54051. {
  54052. y1 = (float) h;
  54053. y2 = h * (1.0f - shadowSize);
  54054. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54055. }
  54056. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54057. Colours::transparentBlack, x2, y2, false));
  54058. shadowRect.expand (2, 2);
  54059. g.fillRect (shadowRect);
  54060. g.setColour (Colour (0x80000000));
  54061. if (orientation == TabbedButtonBar::TabsAtLeft)
  54062. {
  54063. g.fillRect (w - 1, 0, 1, h);
  54064. }
  54065. else if (orientation == TabbedButtonBar::TabsAtRight)
  54066. {
  54067. g.fillRect (0, 0, 1, h);
  54068. }
  54069. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54070. {
  54071. g.fillRect (0, 0, w, 1);
  54072. }
  54073. else
  54074. {
  54075. g.fillRect (0, h - 1, w, 1);
  54076. }
  54077. }
  54078. Button* LookAndFeel::createTabBarExtrasButton()
  54079. {
  54080. const float thickness = 7.0f;
  54081. const float indent = 22.0f;
  54082. Path p;
  54083. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54084. DrawablePath ellipse;
  54085. ellipse.setPath (p);
  54086. ellipse.setFill (Colour (0x99ffffff));
  54087. p.clear();
  54088. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54089. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54090. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54091. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54092. p.setUsingNonZeroWinding (false);
  54093. DrawablePath dp;
  54094. dp.setPath (p);
  54095. dp.setFill (Colour (0x59000000));
  54096. DrawableComposite normalImage;
  54097. normalImage.insertDrawable (ellipse);
  54098. normalImage.insertDrawable (dp);
  54099. dp.setFill (Colour (0xcc000000));
  54100. DrawableComposite overImage;
  54101. overImage.insertDrawable (ellipse);
  54102. overImage.insertDrawable (dp);
  54103. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54104. db->setImages (&normalImage, &overImage, 0);
  54105. return db;
  54106. }
  54107. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54108. {
  54109. g.fillAll (Colours::white);
  54110. const int w = header.getWidth();
  54111. const int h = header.getHeight();
  54112. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54113. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54114. false));
  54115. g.fillRect (0, h / 2, w, h);
  54116. g.setColour (Colour (0x33000000));
  54117. g.fillRect (0, h - 1, w, 1);
  54118. for (int i = header.getNumColumns (true); --i >= 0;)
  54119. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54120. }
  54121. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54122. int width, int height,
  54123. bool isMouseOver, bool isMouseDown,
  54124. int columnFlags)
  54125. {
  54126. if (isMouseDown)
  54127. g.fillAll (Colour (0x8899aadd));
  54128. else if (isMouseOver)
  54129. g.fillAll (Colour (0x5599aadd));
  54130. int rightOfText = width - 4;
  54131. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54132. {
  54133. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54134. const float bottom = height - top;
  54135. const float w = height * 0.5f;
  54136. const float x = rightOfText - (w * 1.25f);
  54137. rightOfText = (int) x;
  54138. Path sortArrow;
  54139. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54140. g.setColour (Colour (0x99000000));
  54141. g.fillPath (sortArrow);
  54142. }
  54143. g.setColour (Colours::black);
  54144. g.setFont (height * 0.5f, Font::bold);
  54145. const int textX = 4;
  54146. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54147. }
  54148. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54149. {
  54150. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54151. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54152. background.darker (0.1f),
  54153. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54154. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54155. false));
  54156. g.fillAll();
  54157. }
  54158. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54159. {
  54160. return createTabBarExtrasButton();
  54161. }
  54162. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54163. bool isMouseOver, bool isMouseDown,
  54164. ToolbarItemComponent& component)
  54165. {
  54166. if (isMouseDown)
  54167. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54168. else if (isMouseOver)
  54169. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54170. }
  54171. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54172. const String& text, ToolbarItemComponent& component)
  54173. {
  54174. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54175. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54176. const float fontHeight = jmin (14.0f, height * 0.85f);
  54177. g.setFont (fontHeight);
  54178. g.drawFittedText (text,
  54179. x, y, width, height,
  54180. Justification::centred,
  54181. jmax (1, height / (int) fontHeight));
  54182. }
  54183. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54184. bool isOpen, int width, int height)
  54185. {
  54186. const int buttonSize = (height * 3) / 4;
  54187. const int buttonIndent = (height - buttonSize) / 2;
  54188. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54189. const int textX = buttonIndent * 2 + buttonSize + 2;
  54190. g.setColour (Colours::black);
  54191. g.setFont (height * 0.7f, Font::bold);
  54192. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54193. }
  54194. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54195. PropertyComponent&)
  54196. {
  54197. g.setColour (Colour (0x66ffffff));
  54198. g.fillRect (0, 0, width, height - 1);
  54199. }
  54200. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54201. PropertyComponent& component)
  54202. {
  54203. g.setColour (Colours::black);
  54204. if (! component.isEnabled())
  54205. g.setOpacity (0.6f);
  54206. g.setFont (jmin (height, 24) * 0.65f);
  54207. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54208. g.drawFittedText (component.getName(),
  54209. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54210. Justification::centredLeft, 2);
  54211. }
  54212. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54213. {
  54214. return Rectangle<int> (component.getWidth() / 3, 1,
  54215. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54216. }
  54217. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54218. {
  54219. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54220. {
  54221. Graphics g2 (content);
  54222. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54223. g2.fillPath (path);
  54224. g2.setColour (Colours::white.withAlpha (0.8f));
  54225. g2.strokePath (path, PathStrokeType (2.0f));
  54226. }
  54227. DropShadowEffect shadow;
  54228. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54229. shadow.applyEffect (content, g, 1.0f);
  54230. }
  54231. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54232. const String& instructions,
  54233. GlyphArrangement& text,
  54234. int width)
  54235. {
  54236. text.clear();
  54237. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54238. 8.0f, 22.0f, width - 16.0f,
  54239. Justification::centred);
  54240. text.addJustifiedText (Font (14.0f), instructions,
  54241. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54242. Justification::centred);
  54243. }
  54244. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54245. const String& filename, Image* icon,
  54246. const String& fileSizeDescription,
  54247. const String& fileTimeDescription,
  54248. const bool isDirectory,
  54249. const bool isItemSelected,
  54250. const int /*itemIndex*/,
  54251. DirectoryContentsDisplayComponent&)
  54252. {
  54253. if (isItemSelected)
  54254. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54255. const int x = 32;
  54256. g.setColour (Colours::black);
  54257. if (icon != 0 && icon->isValid())
  54258. {
  54259. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54260. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54261. false);
  54262. }
  54263. else
  54264. {
  54265. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54266. : getDefaultDocumentFileImage();
  54267. if (d != 0)
  54268. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54269. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54270. }
  54271. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54272. g.setFont (height * 0.7f);
  54273. if (width > 450 && ! isDirectory)
  54274. {
  54275. const int sizeX = roundToInt (width * 0.7f);
  54276. const int dateX = roundToInt (width * 0.8f);
  54277. g.drawFittedText (filename,
  54278. x, 0, sizeX - x, height,
  54279. Justification::centredLeft, 1);
  54280. g.setFont (height * 0.5f);
  54281. g.setColour (Colours::darkgrey);
  54282. if (! isDirectory)
  54283. {
  54284. g.drawFittedText (fileSizeDescription,
  54285. sizeX, 0, dateX - sizeX - 8, height,
  54286. Justification::centredRight, 1);
  54287. g.drawFittedText (fileTimeDescription,
  54288. dateX, 0, width - 8 - dateX, height,
  54289. Justification::centredRight, 1);
  54290. }
  54291. }
  54292. else
  54293. {
  54294. g.drawFittedText (filename,
  54295. x, 0, width - x, height,
  54296. Justification::centredLeft, 1);
  54297. }
  54298. }
  54299. Button* LookAndFeel::createFileBrowserGoUpButton()
  54300. {
  54301. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54302. Path arrowPath;
  54303. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54304. DrawablePath arrowImage;
  54305. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54306. arrowImage.setPath (arrowPath);
  54307. goUpButton->setImages (&arrowImage);
  54308. return goUpButton;
  54309. }
  54310. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54311. DirectoryContentsDisplayComponent* fileListComponent,
  54312. FilePreviewComponent* previewComp,
  54313. ComboBox* currentPathBox,
  54314. TextEditor* filenameBox,
  54315. Button* goUpButton)
  54316. {
  54317. const int x = 8;
  54318. int w = browserComp.getWidth() - x - x;
  54319. if (previewComp != 0)
  54320. {
  54321. const int previewWidth = w / 3;
  54322. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54323. w -= previewWidth + 4;
  54324. }
  54325. int y = 4;
  54326. const int controlsHeight = 22;
  54327. const int bottomSectionHeight = controlsHeight + 8;
  54328. const int upButtonWidth = 50;
  54329. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54330. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54331. y += controlsHeight + 4;
  54332. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54333. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54334. y = listAsComp->getBottom() + 4;
  54335. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54336. }
  54337. // Pulls a drawable out of compressed valuetree data..
  54338. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54339. {
  54340. MemoryInputStream m (data, numBytes, false);
  54341. GZIPDecompressorInputStream gz (m);
  54342. ValueTree drawable (ValueTree::readFromStream (gz));
  54343. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54344. }
  54345. const Drawable* LookAndFeel::getDefaultFolderImage()
  54346. {
  54347. if (folderImage == 0)
  54348. {
  54349. static const unsigned char drawableData[] =
  54350. { 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,
  54351. 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,
  54352. 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,
  54353. 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,
  54354. 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,
  54355. 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,
  54356. 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,
  54357. 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,
  54358. 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,
  54359. 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,
  54360. 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,
  54361. 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,
  54362. 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,
  54363. 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,
  54364. 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 };
  54365. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54366. }
  54367. return folderImage;
  54368. }
  54369. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54370. {
  54371. if (documentImage == 0)
  54372. {
  54373. static const unsigned char drawableData[] =
  54374. { 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,
  54375. 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,
  54376. 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,
  54377. 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,
  54378. 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,
  54379. 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,
  54380. 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,
  54381. 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,
  54382. 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,
  54383. 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,
  54384. 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,
  54385. 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,
  54386. 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,
  54387. 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,
  54388. 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,
  54389. 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,
  54390. 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,
  54391. 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,
  54392. 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,
  54393. 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,
  54394. 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,
  54395. 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,
  54396. 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 };
  54397. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54398. }
  54399. return documentImage;
  54400. }
  54401. void LookAndFeel::playAlertSound()
  54402. {
  54403. PlatformUtilities::beep();
  54404. }
  54405. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54406. {
  54407. g.setColour (Colours::white.withAlpha (0.7f));
  54408. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54409. g.setColour (Colours::black.withAlpha (0.2f));
  54410. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54411. const int totalBlocks = 7;
  54412. const int numBlocks = roundToInt (totalBlocks * level);
  54413. const float w = (width - 6.0f) / (float) totalBlocks;
  54414. for (int i = 0; i < totalBlocks; ++i)
  54415. {
  54416. if (i >= numBlocks)
  54417. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54418. else
  54419. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54420. : Colours::red);
  54421. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54422. }
  54423. }
  54424. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54425. {
  54426. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54427. if (keyDescription.isNotEmpty())
  54428. {
  54429. if (button.isEnabled())
  54430. {
  54431. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54432. g.fillAll (textColour.withAlpha (alpha));
  54433. g.setOpacity (0.3f);
  54434. g.drawBevel (0, 0, width, height, 2);
  54435. }
  54436. g.setColour (textColour);
  54437. g.setFont (height * 0.6f);
  54438. g.drawFittedText (keyDescription,
  54439. 3, 0, width - 6, height,
  54440. Justification::centred, 1);
  54441. }
  54442. else
  54443. {
  54444. const float thickness = 7.0f;
  54445. const float indent = 22.0f;
  54446. Path p;
  54447. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54448. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54449. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54450. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54451. p.setUsingNonZeroWinding (false);
  54452. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54453. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54454. }
  54455. if (button.hasKeyboardFocus (false))
  54456. {
  54457. g.setColour (textColour.withAlpha (0.4f));
  54458. g.drawRect (0, 0, width, height);
  54459. }
  54460. }
  54461. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54462. float x, float y, float w, float h,
  54463. float maxCornerSize,
  54464. const Colour& baseColour,
  54465. const float strokeWidth,
  54466. const bool flatOnLeft,
  54467. const bool flatOnRight,
  54468. const bool flatOnTop,
  54469. const bool flatOnBottom) throw()
  54470. {
  54471. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54472. return;
  54473. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54474. Path outline;
  54475. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54476. ! (flatOnLeft || flatOnTop),
  54477. ! (flatOnRight || flatOnTop),
  54478. ! (flatOnLeft || flatOnBottom),
  54479. ! (flatOnRight || flatOnBottom));
  54480. ColourGradient cg (baseColour, 0.0f, y,
  54481. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54482. false);
  54483. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54484. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54485. g.setGradientFill (cg);
  54486. g.fillPath (outline);
  54487. g.setColour (Colour (0x80000000));
  54488. g.strokePath (outline, PathStrokeType (strokeWidth));
  54489. }
  54490. void LookAndFeel::drawGlassSphere (Graphics& g,
  54491. const float x, const float y,
  54492. const float diameter,
  54493. const Colour& colour,
  54494. const float outlineThickness) throw()
  54495. {
  54496. if (diameter <= outlineThickness)
  54497. return;
  54498. Path p;
  54499. p.addEllipse (x, y, diameter, diameter);
  54500. {
  54501. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54502. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54503. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54504. g.setGradientFill (cg);
  54505. g.fillPath (p);
  54506. }
  54507. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54508. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54509. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54510. ColourGradient cg (Colours::transparentBlack,
  54511. x + diameter * 0.5f, y + diameter * 0.5f,
  54512. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54513. x, y + diameter * 0.5f, true);
  54514. cg.addColour (0.7, Colours::transparentBlack);
  54515. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54516. g.setGradientFill (cg);
  54517. g.fillPath (p);
  54518. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54519. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54520. }
  54521. void LookAndFeel::drawGlassPointer (Graphics& g,
  54522. const float x, const float y,
  54523. const float diameter,
  54524. const Colour& colour, const float outlineThickness,
  54525. const int direction) throw()
  54526. {
  54527. if (diameter <= outlineThickness)
  54528. return;
  54529. Path p;
  54530. p.startNewSubPath (x + diameter * 0.5f, y);
  54531. p.lineTo (x + diameter, y + diameter * 0.6f);
  54532. p.lineTo (x + diameter, y + diameter);
  54533. p.lineTo (x, y + diameter);
  54534. p.lineTo (x, y + diameter * 0.6f);
  54535. p.closeSubPath();
  54536. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54537. {
  54538. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54539. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54540. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54541. g.setGradientFill (cg);
  54542. g.fillPath (p);
  54543. }
  54544. ColourGradient cg (Colours::transparentBlack,
  54545. x + diameter * 0.5f, y + diameter * 0.5f,
  54546. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54547. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54548. cg.addColour (0.5, Colours::transparentBlack);
  54549. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54550. g.setGradientFill (cg);
  54551. g.fillPath (p);
  54552. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54553. g.strokePath (p, PathStrokeType (outlineThickness));
  54554. }
  54555. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54556. const float x, const float y,
  54557. const float width, const float height,
  54558. const Colour& colour,
  54559. const float outlineThickness,
  54560. const float cornerSize,
  54561. const bool flatOnLeft,
  54562. const bool flatOnRight,
  54563. const bool flatOnTop,
  54564. const bool flatOnBottom) throw()
  54565. {
  54566. if (width <= outlineThickness || height <= outlineThickness)
  54567. return;
  54568. const int intX = (int) x;
  54569. const int intY = (int) y;
  54570. const int intW = (int) width;
  54571. const int intH = (int) height;
  54572. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54573. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54574. const int intEdge = (int) edgeBlurRadius;
  54575. Path outline;
  54576. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54577. ! (flatOnLeft || flatOnTop),
  54578. ! (flatOnRight || flatOnTop),
  54579. ! (flatOnLeft || flatOnBottom),
  54580. ! (flatOnRight || flatOnBottom));
  54581. {
  54582. ColourGradient cg (colour.darker (0.2f), 0, y,
  54583. colour.darker (0.2f), 0, y + height, false);
  54584. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54585. cg.addColour (0.4, colour);
  54586. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54587. g.setGradientFill (cg);
  54588. g.fillPath (outline);
  54589. }
  54590. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54591. colour.darker (0.2f), x, y + height * 0.5f, true);
  54592. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54593. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54594. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54595. {
  54596. g.saveState();
  54597. g.setGradientFill (cg);
  54598. g.reduceClipRegion (intX, intY, intEdge, intH);
  54599. g.fillPath (outline);
  54600. g.restoreState();
  54601. }
  54602. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54603. {
  54604. cg.point1.setX (x + width - edgeBlurRadius);
  54605. cg.point2.setX (x + width);
  54606. g.saveState();
  54607. g.setGradientFill (cg);
  54608. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54609. g.fillPath (outline);
  54610. g.restoreState();
  54611. }
  54612. {
  54613. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54614. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54615. Path highlight;
  54616. LookAndFeelHelpers::createRoundedPath (highlight,
  54617. x + leftIndent,
  54618. y + cs * 0.1f,
  54619. width - (leftIndent + rightIndent),
  54620. height * 0.4f, cs * 0.4f,
  54621. ! (flatOnLeft || flatOnTop),
  54622. ! (flatOnRight || flatOnTop),
  54623. ! (flatOnLeft || flatOnBottom),
  54624. ! (flatOnRight || flatOnBottom));
  54625. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54626. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54627. g.fillPath (highlight);
  54628. }
  54629. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54630. g.strokePath (outline, PathStrokeType (outlineThickness));
  54631. }
  54632. END_JUCE_NAMESPACE
  54633. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54634. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54635. BEGIN_JUCE_NAMESPACE
  54636. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54637. {
  54638. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54639. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54640. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54641. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54642. setColour (Slider::thumbColourId, Colours::white);
  54643. setColour (Slider::trackColourId, Colour (0x7f000000));
  54644. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54645. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54646. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54647. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54648. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54649. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54650. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54651. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54652. }
  54653. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54654. {
  54655. }
  54656. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54657. Button& button,
  54658. const Colour& backgroundColour,
  54659. bool isMouseOverButton,
  54660. bool isButtonDown)
  54661. {
  54662. const int width = button.getWidth();
  54663. const int height = button.getHeight();
  54664. const float indent = 2.0f;
  54665. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54666. roundToInt (height * 0.4f));
  54667. Path p;
  54668. p.addRoundedRectangle (indent, indent,
  54669. width - indent * 2.0f,
  54670. height - indent * 2.0f,
  54671. (float) cornerSize);
  54672. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54673. if (isMouseOverButton)
  54674. {
  54675. if (isButtonDown)
  54676. bc = bc.brighter();
  54677. else if (bc.getBrightness() > 0.5f)
  54678. bc = bc.darker (0.1f);
  54679. else
  54680. bc = bc.brighter (0.1f);
  54681. }
  54682. g.setColour (bc);
  54683. g.fillPath (p);
  54684. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54685. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54686. }
  54687. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54688. Component& /*component*/,
  54689. float x, float y, float w, float h,
  54690. const bool ticked,
  54691. const bool isEnabled,
  54692. const bool /*isMouseOverButton*/,
  54693. const bool isButtonDown)
  54694. {
  54695. Path box;
  54696. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54697. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54698. : Colours::lightgrey.withAlpha (0.1f));
  54699. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54700. g.fillPath (box, trans);
  54701. g.setColour (Colours::black.withAlpha (0.6f));
  54702. g.strokePath (box, PathStrokeType (0.9f), trans);
  54703. if (ticked)
  54704. {
  54705. Path tick;
  54706. tick.startNewSubPath (1.5f, 3.0f);
  54707. tick.lineTo (3.0f, 6.0f);
  54708. tick.lineTo (6.0f, 0.0f);
  54709. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54710. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54711. }
  54712. }
  54713. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54714. ToggleButton& button,
  54715. bool isMouseOverButton,
  54716. bool isButtonDown)
  54717. {
  54718. if (button.hasKeyboardFocus (true))
  54719. {
  54720. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54721. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54722. }
  54723. const int tickWidth = jmin (20, button.getHeight() - 4);
  54724. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54725. (float) tickWidth, (float) tickWidth,
  54726. button.getToggleState(),
  54727. button.isEnabled(),
  54728. isMouseOverButton,
  54729. isButtonDown);
  54730. g.setColour (button.findColour (ToggleButton::textColourId));
  54731. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54732. if (! button.isEnabled())
  54733. g.setOpacity (0.5f);
  54734. const int textX = tickWidth + 5;
  54735. g.drawFittedText (button.getButtonText(),
  54736. textX, 4,
  54737. button.getWidth() - textX - 2, button.getHeight() - 8,
  54738. Justification::centredLeft, 10);
  54739. }
  54740. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54741. int width, int height,
  54742. double progress, const String& textToShow)
  54743. {
  54744. if (progress < 0 || progress >= 1.0)
  54745. {
  54746. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54747. }
  54748. else
  54749. {
  54750. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54751. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54752. g.fillAll (background);
  54753. g.setColour (foreground);
  54754. g.fillRect (1, 1,
  54755. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54756. height - 2);
  54757. if (textToShow.isNotEmpty())
  54758. {
  54759. g.setColour (Colour::contrasting (background, foreground));
  54760. g.setFont (height * 0.6f);
  54761. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54762. }
  54763. }
  54764. }
  54765. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54766. ScrollBar& bar,
  54767. int width, int height,
  54768. int buttonDirection,
  54769. bool isScrollbarVertical,
  54770. bool isMouseOverButton,
  54771. bool isButtonDown)
  54772. {
  54773. if (isScrollbarVertical)
  54774. width -= 2;
  54775. else
  54776. height -= 2;
  54777. Path p;
  54778. if (buttonDirection == 0)
  54779. p.addTriangle (width * 0.5f, height * 0.2f,
  54780. width * 0.1f, height * 0.7f,
  54781. width * 0.9f, height * 0.7f);
  54782. else if (buttonDirection == 1)
  54783. p.addTriangle (width * 0.8f, height * 0.5f,
  54784. width * 0.3f, height * 0.1f,
  54785. width * 0.3f, height * 0.9f);
  54786. else if (buttonDirection == 2)
  54787. p.addTriangle (width * 0.5f, height * 0.8f,
  54788. width * 0.1f, height * 0.3f,
  54789. width * 0.9f, height * 0.3f);
  54790. else if (buttonDirection == 3)
  54791. p.addTriangle (width * 0.2f, height * 0.5f,
  54792. width * 0.7f, height * 0.1f,
  54793. width * 0.7f, height * 0.9f);
  54794. if (isButtonDown)
  54795. g.setColour (Colours::white);
  54796. else if (isMouseOverButton)
  54797. g.setColour (Colours::white.withAlpha (0.7f));
  54798. else
  54799. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54800. g.fillPath (p);
  54801. g.setColour (Colours::black.withAlpha (0.5f));
  54802. g.strokePath (p, PathStrokeType (0.5f));
  54803. }
  54804. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54805. ScrollBar& bar,
  54806. int x, int y,
  54807. int width, int height,
  54808. bool isScrollbarVertical,
  54809. int thumbStartPosition,
  54810. int thumbSize,
  54811. bool isMouseOver,
  54812. bool isMouseDown)
  54813. {
  54814. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54815. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54816. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54817. if (thumbSize > 0.0f)
  54818. {
  54819. Rectangle<int> thumb;
  54820. if (isScrollbarVertical)
  54821. {
  54822. width -= 2;
  54823. g.fillRect (x + roundToInt (width * 0.35f), y,
  54824. roundToInt (width * 0.3f), height);
  54825. thumb.setBounds (x + 1, thumbStartPosition,
  54826. width - 2, thumbSize);
  54827. }
  54828. else
  54829. {
  54830. height -= 2;
  54831. g.fillRect (x, y + roundToInt (height * 0.35f),
  54832. width, roundToInt (height * 0.3f));
  54833. thumb.setBounds (thumbStartPosition, y + 1,
  54834. thumbSize, height - 2);
  54835. }
  54836. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54837. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54838. g.fillRect (thumb);
  54839. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54840. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54841. if (thumbSize > 16)
  54842. {
  54843. for (int i = 3; --i >= 0;)
  54844. {
  54845. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54846. g.setColour (Colours::black.withAlpha (0.15f));
  54847. if (isScrollbarVertical)
  54848. {
  54849. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54850. g.setColour (Colours::white.withAlpha (0.15f));
  54851. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54852. }
  54853. else
  54854. {
  54855. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54856. g.setColour (Colours::white.withAlpha (0.15f));
  54857. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54858. }
  54859. }
  54860. }
  54861. }
  54862. }
  54863. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54864. {
  54865. return &scrollbarShadow;
  54866. }
  54867. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54868. {
  54869. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54870. g.setColour (Colours::black.withAlpha (0.6f));
  54871. g.drawRect (0, 0, width, height);
  54872. }
  54873. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54874. bool, MenuBarComponent& menuBar)
  54875. {
  54876. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54877. }
  54878. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54879. {
  54880. if (textEditor.isEnabled())
  54881. {
  54882. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54883. g.drawRect (0, 0, width, height);
  54884. }
  54885. }
  54886. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54887. const bool isButtonDown,
  54888. int buttonX, int buttonY,
  54889. int buttonW, int buttonH,
  54890. ComboBox& box)
  54891. {
  54892. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54893. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54894. : ComboBox::backgroundColourId));
  54895. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54896. g.setColour (box.findColour (ComboBox::outlineColourId));
  54897. g.drawRect (0, 0, width, height);
  54898. const float arrowX = 0.2f;
  54899. const float arrowH = 0.3f;
  54900. if (box.isEnabled())
  54901. {
  54902. Path p;
  54903. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54904. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54905. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54906. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54907. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54908. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54909. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54910. : ComboBox::buttonColourId));
  54911. g.fillPath (p);
  54912. }
  54913. }
  54914. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54915. {
  54916. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54917. f.setHorizontalScale (0.9f);
  54918. return f;
  54919. }
  54920. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54921. {
  54922. Path p;
  54923. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54924. g.setColour (fill);
  54925. g.fillPath (p);
  54926. g.setColour (outline);
  54927. g.strokePath (p, PathStrokeType (0.3f));
  54928. }
  54929. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54930. int x, int y,
  54931. int w, int h,
  54932. float sliderPos,
  54933. float minSliderPos,
  54934. float maxSliderPos,
  54935. const Slider::SliderStyle style,
  54936. Slider& slider)
  54937. {
  54938. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54939. if (style == Slider::LinearBar)
  54940. {
  54941. g.setColour (slider.findColour (Slider::thumbColourId));
  54942. g.fillRect (x, y, (int) sliderPos - x, h);
  54943. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54944. g.drawRect (x, y, (int) sliderPos - x, h);
  54945. }
  54946. else
  54947. {
  54948. g.setColour (slider.findColour (Slider::trackColourId)
  54949. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54950. if (slider.isHorizontal())
  54951. {
  54952. g.fillRect (x, y + roundToInt (h * 0.6f),
  54953. w, roundToInt (h * 0.2f));
  54954. }
  54955. else
  54956. {
  54957. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54958. jmin (4, roundToInt (w * 0.2f)), h);
  54959. }
  54960. float alpha = 0.35f;
  54961. if (slider.isEnabled())
  54962. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54963. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54964. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54965. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54966. {
  54967. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54968. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54969. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54970. fill, outline);
  54971. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54972. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54973. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54974. fill, outline);
  54975. }
  54976. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54977. {
  54978. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54979. minSliderPos - 7.0f, y + h * 0.9f ,
  54980. minSliderPos, y + h * 0.9f,
  54981. fill, outline);
  54982. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54983. maxSliderPos, y + h * 0.9f,
  54984. maxSliderPos + 7.0f, y + h * 0.9f,
  54985. fill, outline);
  54986. }
  54987. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54988. {
  54989. drawTriangle (g, sliderPos, y + h * 0.9f,
  54990. sliderPos - 7.0f, y + h * 0.2f,
  54991. sliderPos + 7.0f, y + h * 0.2f,
  54992. fill, outline);
  54993. }
  54994. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54995. {
  54996. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54997. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54998. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54999. fill, outline);
  55000. }
  55001. }
  55002. }
  55003. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55004. {
  55005. if (isIncrement)
  55006. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55007. else
  55008. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55009. }
  55010. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55011. {
  55012. return &scrollbarShadow;
  55013. }
  55014. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55015. {
  55016. return 8;
  55017. }
  55018. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55019. int w, int h,
  55020. bool isMouseOver,
  55021. bool isMouseDragging)
  55022. {
  55023. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55024. : Colours::darkgrey);
  55025. const float lineThickness = jmin (w, h) * 0.1f;
  55026. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55027. {
  55028. g.drawLine (w * i,
  55029. h + 1.0f,
  55030. w + 1.0f,
  55031. h * i,
  55032. lineThickness);
  55033. }
  55034. }
  55035. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55036. {
  55037. Path shape;
  55038. if (buttonType == DocumentWindow::closeButton)
  55039. {
  55040. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55041. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55042. ShapeButton* const b = new ShapeButton ("close",
  55043. Colour (0x7fff3333),
  55044. Colour (0xd7ff3333),
  55045. Colour (0xf7ff3333));
  55046. b->setShape (shape, true, true, true);
  55047. return b;
  55048. }
  55049. else if (buttonType == DocumentWindow::minimiseButton)
  55050. {
  55051. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55052. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55053. DrawablePath dp;
  55054. dp.setPath (shape);
  55055. dp.setFill (Colours::black.withAlpha (0.3f));
  55056. b->setImages (&dp);
  55057. return b;
  55058. }
  55059. else if (buttonType == DocumentWindow::maximiseButton)
  55060. {
  55061. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55062. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55063. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55064. DrawablePath dp;
  55065. dp.setPath (shape);
  55066. dp.setFill (Colours::black.withAlpha (0.3f));
  55067. b->setImages (&dp);
  55068. return b;
  55069. }
  55070. jassertfalse;
  55071. return 0;
  55072. }
  55073. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55074. int titleBarX,
  55075. int titleBarY,
  55076. int titleBarW,
  55077. int titleBarH,
  55078. Button* minimiseButton,
  55079. Button* maximiseButton,
  55080. Button* closeButton,
  55081. bool positionTitleBarButtonsOnLeft)
  55082. {
  55083. titleBarY += titleBarH / 8;
  55084. titleBarH -= titleBarH / 4;
  55085. const int buttonW = titleBarH;
  55086. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55087. : titleBarX + titleBarW - buttonW - 4;
  55088. if (closeButton != 0)
  55089. {
  55090. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55091. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55092. : -(buttonW + buttonW / 5);
  55093. }
  55094. if (positionTitleBarButtonsOnLeft)
  55095. swapVariables (minimiseButton, maximiseButton);
  55096. if (maximiseButton != 0)
  55097. {
  55098. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55099. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55100. }
  55101. if (minimiseButton != 0)
  55102. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55103. }
  55104. END_JUCE_NAMESPACE
  55105. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55106. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55107. BEGIN_JUCE_NAMESPACE
  55108. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55109. : model (0),
  55110. itemUnderMouse (-1),
  55111. currentPopupIndex (-1),
  55112. topLevelIndexClicked (0),
  55113. lastMouseX (0),
  55114. lastMouseY (0)
  55115. {
  55116. setRepaintsOnMouseActivity (true);
  55117. setWantsKeyboardFocus (false);
  55118. setMouseClickGrabsKeyboardFocus (false);
  55119. setModel (model_);
  55120. }
  55121. MenuBarComponent::~MenuBarComponent()
  55122. {
  55123. setModel (0);
  55124. Desktop::getInstance().removeGlobalMouseListener (this);
  55125. }
  55126. MenuBarModel* MenuBarComponent::getModel() const throw()
  55127. {
  55128. return model;
  55129. }
  55130. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55131. {
  55132. if (model != newModel)
  55133. {
  55134. if (model != 0)
  55135. model->removeListener (this);
  55136. model = newModel;
  55137. if (model != 0)
  55138. model->addListener (this);
  55139. repaint();
  55140. menuBarItemsChanged (0);
  55141. }
  55142. }
  55143. void MenuBarComponent::paint (Graphics& g)
  55144. {
  55145. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55146. getLookAndFeel().drawMenuBarBackground (g,
  55147. getWidth(),
  55148. getHeight(),
  55149. isMouseOverBar,
  55150. *this);
  55151. if (model != 0)
  55152. {
  55153. for (int i = 0; i < menuNames.size(); ++i)
  55154. {
  55155. g.saveState();
  55156. g.setOrigin (xPositions [i], 0);
  55157. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55158. getLookAndFeel().drawMenuBarItem (g,
  55159. xPositions[i + 1] - xPositions[i],
  55160. getHeight(),
  55161. i,
  55162. menuNames[i],
  55163. i == itemUnderMouse,
  55164. i == currentPopupIndex,
  55165. isMouseOverBar,
  55166. *this);
  55167. g.restoreState();
  55168. }
  55169. }
  55170. }
  55171. void MenuBarComponent::resized()
  55172. {
  55173. xPositions.clear();
  55174. int x = 0;
  55175. xPositions.add (x);
  55176. for (int i = 0; i < menuNames.size(); ++i)
  55177. {
  55178. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55179. xPositions.add (x);
  55180. }
  55181. }
  55182. int MenuBarComponent::getItemAt (const int x, const int y)
  55183. {
  55184. for (int i = 0; i < xPositions.size(); ++i)
  55185. if (x >= xPositions[i] && x < xPositions[i + 1])
  55186. return reallyContains (x, y, true) ? i : -1;
  55187. return -1;
  55188. }
  55189. void MenuBarComponent::repaintMenuItem (int index)
  55190. {
  55191. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55192. {
  55193. const int x1 = xPositions [index];
  55194. const int x2 = xPositions [index + 1];
  55195. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55196. }
  55197. }
  55198. void MenuBarComponent::setItemUnderMouse (const int index)
  55199. {
  55200. if (itemUnderMouse != index)
  55201. {
  55202. repaintMenuItem (itemUnderMouse);
  55203. itemUnderMouse = index;
  55204. repaintMenuItem (itemUnderMouse);
  55205. }
  55206. }
  55207. void MenuBarComponent::setOpenItem (int index)
  55208. {
  55209. if (currentPopupIndex != index)
  55210. {
  55211. repaintMenuItem (currentPopupIndex);
  55212. currentPopupIndex = index;
  55213. repaintMenuItem (currentPopupIndex);
  55214. if (index >= 0)
  55215. Desktop::getInstance().addGlobalMouseListener (this);
  55216. else
  55217. Desktop::getInstance().removeGlobalMouseListener (this);
  55218. }
  55219. }
  55220. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55221. {
  55222. setItemUnderMouse (getItemAt (x, y));
  55223. }
  55224. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55225. {
  55226. public:
  55227. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55228. : bar (bar_), topLevelIndex (topLevelIndex_)
  55229. {
  55230. }
  55231. void modalStateFinished (int returnValue)
  55232. {
  55233. if (bar != 0)
  55234. bar->menuDismissed (topLevelIndex, returnValue);
  55235. }
  55236. private:
  55237. Component::SafePointer<MenuBarComponent> bar;
  55238. const int topLevelIndex;
  55239. AsyncCallback (const AsyncCallback&);
  55240. AsyncCallback& operator= (const AsyncCallback&);
  55241. };
  55242. void MenuBarComponent::showMenu (int index)
  55243. {
  55244. if (index != currentPopupIndex)
  55245. {
  55246. PopupMenu::dismissAllActiveMenus();
  55247. menuBarItemsChanged (0);
  55248. setOpenItem (index);
  55249. setItemUnderMouse (index);
  55250. if (index >= 0)
  55251. {
  55252. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55253. menuNames [itemUnderMouse]));
  55254. if (m.lookAndFeel == 0)
  55255. m.setLookAndFeel (&getLookAndFeel());
  55256. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55257. m.showMenu (itemPos + getScreenPosition(),
  55258. 0, itemPos.getWidth(), 0, 0, true, this,
  55259. new AsyncCallback (this, index));
  55260. }
  55261. }
  55262. }
  55263. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55264. {
  55265. topLevelIndexClicked = topLevelIndex;
  55266. postCommandMessage (itemId);
  55267. }
  55268. void MenuBarComponent::handleCommandMessage (int commandId)
  55269. {
  55270. const Point<int> mousePos (getMouseXYRelative());
  55271. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55272. if (currentPopupIndex == topLevelIndexClicked)
  55273. setOpenItem (-1);
  55274. if (commandId != 0 && model != 0)
  55275. model->menuItemSelected (commandId, topLevelIndexClicked);
  55276. }
  55277. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55278. {
  55279. if (e.eventComponent == this)
  55280. updateItemUnderMouse (e.x, e.y);
  55281. }
  55282. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55283. {
  55284. if (e.eventComponent == this)
  55285. updateItemUnderMouse (e.x, e.y);
  55286. }
  55287. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55288. {
  55289. if (currentPopupIndex < 0)
  55290. {
  55291. const MouseEvent e2 (e.getEventRelativeTo (this));
  55292. updateItemUnderMouse (e2.x, e2.y);
  55293. currentPopupIndex = -2;
  55294. showMenu (itemUnderMouse);
  55295. }
  55296. }
  55297. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55298. {
  55299. const MouseEvent e2 (e.getEventRelativeTo (this));
  55300. const int item = getItemAt (e2.x, e2.y);
  55301. if (item >= 0)
  55302. showMenu (item);
  55303. }
  55304. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55305. {
  55306. const MouseEvent e2 (e.getEventRelativeTo (this));
  55307. updateItemUnderMouse (e2.x, e2.y);
  55308. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55309. {
  55310. setOpenItem (-1);
  55311. PopupMenu::dismissAllActiveMenus();
  55312. }
  55313. }
  55314. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55315. {
  55316. const MouseEvent e2 (e.getEventRelativeTo (this));
  55317. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55318. {
  55319. if (currentPopupIndex >= 0)
  55320. {
  55321. const int item = getItemAt (e2.x, e2.y);
  55322. if (item >= 0)
  55323. showMenu (item);
  55324. }
  55325. else
  55326. {
  55327. updateItemUnderMouse (e2.x, e2.y);
  55328. }
  55329. lastMouseX = e2.x;
  55330. lastMouseY = e2.y;
  55331. }
  55332. }
  55333. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55334. {
  55335. bool used = false;
  55336. const int numMenus = menuNames.size();
  55337. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55338. if (key.isKeyCode (KeyPress::leftKey))
  55339. {
  55340. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55341. used = true;
  55342. }
  55343. else if (key.isKeyCode (KeyPress::rightKey))
  55344. {
  55345. showMenu ((currentIndex + 1) % numMenus);
  55346. used = true;
  55347. }
  55348. return used;
  55349. }
  55350. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55351. {
  55352. StringArray newNames;
  55353. if (model != 0)
  55354. newNames = model->getMenuBarNames();
  55355. if (newNames != menuNames)
  55356. {
  55357. menuNames = newNames;
  55358. repaint();
  55359. resized();
  55360. }
  55361. }
  55362. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55363. const ApplicationCommandTarget::InvocationInfo& info)
  55364. {
  55365. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55366. return;
  55367. for (int i = 0; i < menuNames.size(); ++i)
  55368. {
  55369. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55370. if (menu.containsCommandItem (info.commandID))
  55371. {
  55372. setItemUnderMouse (i);
  55373. startTimer (200);
  55374. break;
  55375. }
  55376. }
  55377. }
  55378. void MenuBarComponent::timerCallback()
  55379. {
  55380. stopTimer();
  55381. const Point<int> mousePos (getMouseXYRelative());
  55382. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55383. }
  55384. END_JUCE_NAMESPACE
  55385. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55386. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55387. BEGIN_JUCE_NAMESPACE
  55388. MenuBarModel::MenuBarModel() throw()
  55389. : manager (0)
  55390. {
  55391. }
  55392. MenuBarModel::~MenuBarModel()
  55393. {
  55394. setApplicationCommandManagerToWatch (0);
  55395. }
  55396. void MenuBarModel::menuItemsChanged()
  55397. {
  55398. triggerAsyncUpdate();
  55399. }
  55400. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55401. {
  55402. if (manager != newManager)
  55403. {
  55404. if (manager != 0)
  55405. manager->removeListener (this);
  55406. manager = newManager;
  55407. if (manager != 0)
  55408. manager->addListener (this);
  55409. }
  55410. }
  55411. void MenuBarModel::addListener (Listener* const newListener) throw()
  55412. {
  55413. listeners.add (newListener);
  55414. }
  55415. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55416. {
  55417. // Trying to remove a listener that isn't on the list!
  55418. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55419. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55420. jassert (listeners.contains (listenerToRemove));
  55421. listeners.remove (listenerToRemove);
  55422. }
  55423. void MenuBarModel::handleAsyncUpdate()
  55424. {
  55425. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55426. }
  55427. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55428. {
  55429. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55430. }
  55431. void MenuBarModel::applicationCommandListChanged()
  55432. {
  55433. menuItemsChanged();
  55434. }
  55435. END_JUCE_NAMESPACE
  55436. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55437. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55438. BEGIN_JUCE_NAMESPACE
  55439. class PopupMenu::Item
  55440. {
  55441. public:
  55442. Item()
  55443. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55444. usesColour (false), customComp (0), commandManager (0)
  55445. {
  55446. }
  55447. Item (const int itemId_,
  55448. const String& text_,
  55449. const bool active_,
  55450. const bool isTicked_,
  55451. const Image& im,
  55452. const Colour& textColour_,
  55453. const bool usesColour_,
  55454. PopupMenuCustomComponent* const customComp_,
  55455. const PopupMenu* const subMenu_,
  55456. ApplicationCommandManager* const commandManager_)
  55457. : itemId (itemId_), text (text_), textColour (textColour_),
  55458. active (active_), isSeparator (false), isTicked (isTicked_),
  55459. usesColour (usesColour_), image (im), customComp (customComp_),
  55460. commandManager (commandManager_)
  55461. {
  55462. if (subMenu_ != 0)
  55463. subMenu = new PopupMenu (*subMenu_);
  55464. if (commandManager_ != 0 && itemId_ != 0)
  55465. {
  55466. String shortcutKey;
  55467. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55468. ->getKeyPressesAssignedToCommand (itemId_));
  55469. for (int i = 0; i < keyPresses.size(); ++i)
  55470. {
  55471. const String key (keyPresses.getReference(i).getTextDescription());
  55472. if (shortcutKey.isNotEmpty())
  55473. shortcutKey << ", ";
  55474. if (key.length() == 1)
  55475. shortcutKey << "shortcut: '" << key << '\'';
  55476. else
  55477. shortcutKey << key;
  55478. }
  55479. shortcutKey = shortcutKey.trim();
  55480. if (shortcutKey.isNotEmpty())
  55481. text << "<end>" << shortcutKey;
  55482. }
  55483. }
  55484. Item (const Item& other)
  55485. : itemId (other.itemId),
  55486. text (other.text),
  55487. textColour (other.textColour),
  55488. active (other.active),
  55489. isSeparator (other.isSeparator),
  55490. isTicked (other.isTicked),
  55491. usesColour (other.usesColour),
  55492. image (other.image),
  55493. customComp (other.customComp),
  55494. commandManager (other.commandManager)
  55495. {
  55496. if (other.subMenu != 0)
  55497. subMenu = new PopupMenu (*(other.subMenu));
  55498. }
  55499. ~Item()
  55500. {
  55501. customComp = 0;
  55502. }
  55503. bool canBeTriggered() const throw()
  55504. {
  55505. return active && ! (isSeparator || (subMenu != 0));
  55506. }
  55507. bool hasActiveSubMenu() const throw()
  55508. {
  55509. return active && (subMenu != 0);
  55510. }
  55511. const int itemId;
  55512. String text;
  55513. const Colour textColour;
  55514. const bool active, isSeparator, isTicked, usesColour;
  55515. Image image;
  55516. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55517. ScopedPointer <PopupMenu> subMenu;
  55518. ApplicationCommandManager* const commandManager;
  55519. juce_UseDebuggingNewOperator
  55520. private:
  55521. Item& operator= (const Item&);
  55522. };
  55523. class PopupMenu::ItemComponent : public Component
  55524. {
  55525. public:
  55526. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight)
  55527. : itemInfo (itemInfo_),
  55528. isHighlighted (false)
  55529. {
  55530. if (itemInfo.customComp != 0)
  55531. addAndMakeVisible (itemInfo.customComp);
  55532. int itemW = 80;
  55533. int itemH = 16;
  55534. getIdealSize (itemW, itemH, standardItemHeight);
  55535. setSize (itemW, jlimit (2, 600, itemH));
  55536. }
  55537. ~ItemComponent()
  55538. {
  55539. if (itemInfo.customComp != 0)
  55540. removeChildComponent (itemInfo.customComp);
  55541. }
  55542. void getIdealSize (int& idealWidth,
  55543. int& idealHeight,
  55544. const int standardItemHeight)
  55545. {
  55546. if (itemInfo.customComp != 0)
  55547. {
  55548. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55549. }
  55550. else
  55551. {
  55552. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55553. itemInfo.isSeparator,
  55554. standardItemHeight,
  55555. idealWidth,
  55556. idealHeight);
  55557. }
  55558. }
  55559. void paint (Graphics& g)
  55560. {
  55561. if (itemInfo.customComp == 0)
  55562. {
  55563. String mainText (itemInfo.text);
  55564. String endText;
  55565. const int endIndex = mainText.indexOf ("<end>");
  55566. if (endIndex >= 0)
  55567. {
  55568. endText = mainText.substring (endIndex + 5).trim();
  55569. mainText = mainText.substring (0, endIndex);
  55570. }
  55571. getLookAndFeel()
  55572. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55573. itemInfo.isSeparator,
  55574. itemInfo.active,
  55575. isHighlighted,
  55576. itemInfo.isTicked,
  55577. itemInfo.subMenu != 0,
  55578. mainText, endText,
  55579. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55580. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55581. }
  55582. }
  55583. void resized()
  55584. {
  55585. if (getNumChildComponents() > 0)
  55586. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55587. }
  55588. void setHighlighted (bool shouldBeHighlighted)
  55589. {
  55590. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55591. if (isHighlighted != shouldBeHighlighted)
  55592. {
  55593. isHighlighted = shouldBeHighlighted;
  55594. if (itemInfo.customComp != 0)
  55595. {
  55596. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55597. itemInfo.customComp->repaint();
  55598. }
  55599. repaint();
  55600. }
  55601. }
  55602. PopupMenu::Item itemInfo;
  55603. juce_UseDebuggingNewOperator
  55604. private:
  55605. bool isHighlighted;
  55606. ItemComponent (const ItemComponent&);
  55607. ItemComponent& operator= (const ItemComponent&);
  55608. };
  55609. namespace PopupMenuSettings
  55610. {
  55611. const int scrollZone = 24;
  55612. const int borderSize = 2;
  55613. const int timerInterval = 50;
  55614. const int dismissCommandId = 0x6287345f;
  55615. }
  55616. class PopupMenu::Window : public Component,
  55617. private Timer
  55618. {
  55619. public:
  55620. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55621. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55622. const int minimumWidth_, const int maximumNumColumns_,
  55623. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55624. ApplicationCommandManager** const managerOfChosenCommand_,
  55625. Component* const componentAttachedTo_)
  55626. : Component ("menu"),
  55627. owner (owner_),
  55628. activeSubMenu (0),
  55629. managerOfChosenCommand (managerOfChosenCommand_),
  55630. componentAttachedTo (componentAttachedTo_),
  55631. componentAttachedToOriginal (componentAttachedTo_),
  55632. minimumWidth (minimumWidth_),
  55633. maximumNumColumns (maximumNumColumns_),
  55634. standardItemHeight (standardItemHeight_),
  55635. isOver (false),
  55636. hasBeenOver (false),
  55637. isDown (false),
  55638. needsToScroll (false),
  55639. dismissOnMouseUp (dismissOnMouseUp_),
  55640. hideOnExit (false),
  55641. disableMouseMoves (false),
  55642. hasAnyJuceCompHadFocus (false),
  55643. numColumns (0),
  55644. contentHeight (0),
  55645. childYOffset (0),
  55646. menuCreationTime (Time::getMillisecondCounter()),
  55647. timeEnteredCurrentChildComp (0),
  55648. scrollAcceleration (1.0)
  55649. {
  55650. lastFocused = lastScroll = menuCreationTime;
  55651. setWantsKeyboardFocus (false);
  55652. setMouseClickGrabsKeyboardFocus (false);
  55653. setAlwaysOnTop (true);
  55654. setLookAndFeel (menu.lookAndFeel);
  55655. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55656. for (int i = 0; i < menu.items.size(); ++i)
  55657. {
  55658. PopupMenu::ItemComponent* const itemComp = new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight);
  55659. items.add (itemComp);
  55660. addAndMakeVisible (itemComp);
  55661. itemComp->addMouseListener (this, false);
  55662. }
  55663. calculateWindowPos (target, alignToRectangle);
  55664. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55665. updateYPositions();
  55666. if (itemIdThatMustBeVisible != 0)
  55667. {
  55668. const int y = target.getY() - windowPos.getY();
  55669. ensureItemIsVisible (itemIdThatMustBeVisible,
  55670. (((unsigned int) y) < (unsigned int) windowPos.getHeight()) ? y : -1);
  55671. }
  55672. resizeToBestWindowPos();
  55673. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55674. getActiveWindows().add (this);
  55675. Desktop::getInstance().addGlobalMouseListener (this);
  55676. }
  55677. ~Window()
  55678. {
  55679. getActiveWindows().removeValue (this);
  55680. Desktop::getInstance().removeGlobalMouseListener (this);
  55681. activeSubMenu = 0;
  55682. items.clear();
  55683. }
  55684. static Window* create (const PopupMenu& menu,
  55685. bool dismissOnMouseUp,
  55686. Window* const owner_,
  55687. const Rectangle<int>& target,
  55688. int minimumWidth,
  55689. int maximumNumColumns,
  55690. int standardItemHeight,
  55691. bool alignToRectangle,
  55692. int itemIdThatMustBeVisible,
  55693. ApplicationCommandManager** managerOfChosenCommand,
  55694. Component* componentAttachedTo)
  55695. {
  55696. if (menu.items.size() > 0)
  55697. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55698. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55699. managerOfChosenCommand, componentAttachedTo);
  55700. return 0;
  55701. }
  55702. void paint (Graphics& g)
  55703. {
  55704. if (isOpaque())
  55705. g.fillAll (Colours::white);
  55706. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55707. }
  55708. void paintOverChildren (Graphics& g)
  55709. {
  55710. if (isScrolling())
  55711. {
  55712. LookAndFeel& lf = getLookAndFeel();
  55713. if (isScrollZoneActive (false))
  55714. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55715. if (isScrollZoneActive (true))
  55716. {
  55717. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55718. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55719. }
  55720. }
  55721. }
  55722. bool isScrollZoneActive (bool bottomOne) const
  55723. {
  55724. return isScrolling()
  55725. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55726. : childYOffset > 0);
  55727. }
  55728. // hide this and all sub-comps
  55729. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55730. {
  55731. if (isVisible())
  55732. {
  55733. activeSubMenu = 0;
  55734. currentChild = 0;
  55735. exitModalState (item != 0 ? item->itemId : 0);
  55736. if (makeInvisible)
  55737. setVisible (false);
  55738. if (item != 0
  55739. && item->commandManager != 0
  55740. && item->itemId != 0)
  55741. {
  55742. *managerOfChosenCommand = item->commandManager;
  55743. }
  55744. }
  55745. }
  55746. void dismissMenu (const PopupMenu::Item* const item)
  55747. {
  55748. if (owner != 0)
  55749. {
  55750. owner->dismissMenu (item);
  55751. }
  55752. else
  55753. {
  55754. if (item != 0)
  55755. {
  55756. // need a copy of this on the stack as the one passed in will get deleted during this call
  55757. const PopupMenu::Item mi (*item);
  55758. hide (&mi, false);
  55759. }
  55760. else
  55761. {
  55762. hide (0, false);
  55763. }
  55764. }
  55765. }
  55766. void mouseMove (const MouseEvent&) { timerCallback(); }
  55767. void mouseDown (const MouseEvent&) { timerCallback(); }
  55768. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55769. void mouseUp (const MouseEvent&) { timerCallback(); }
  55770. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55771. {
  55772. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55773. lastMouse = Point<int> (-1, -1);
  55774. }
  55775. bool keyPressed (const KeyPress& key)
  55776. {
  55777. if (key.isKeyCode (KeyPress::downKey))
  55778. {
  55779. selectNextItem (1);
  55780. }
  55781. else if (key.isKeyCode (KeyPress::upKey))
  55782. {
  55783. selectNextItem (-1);
  55784. }
  55785. else if (key.isKeyCode (KeyPress::leftKey))
  55786. {
  55787. if (owner != 0)
  55788. {
  55789. Component::SafePointer<Window> parentWindow (owner);
  55790. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55791. hide (0, true);
  55792. if (parentWindow != 0)
  55793. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55794. disableTimerUntilMouseMoves();
  55795. }
  55796. else if (componentAttachedTo != 0)
  55797. {
  55798. componentAttachedTo->keyPressed (key);
  55799. }
  55800. }
  55801. else if (key.isKeyCode (KeyPress::rightKey))
  55802. {
  55803. disableTimerUntilMouseMoves();
  55804. if (showSubMenuFor (currentChild))
  55805. {
  55806. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55807. activeSubMenu->selectNextItem (1);
  55808. }
  55809. else if (componentAttachedTo != 0)
  55810. {
  55811. componentAttachedTo->keyPressed (key);
  55812. }
  55813. }
  55814. else if (key.isKeyCode (KeyPress::returnKey))
  55815. {
  55816. triggerCurrentlyHighlightedItem();
  55817. }
  55818. else if (key.isKeyCode (KeyPress::escapeKey))
  55819. {
  55820. dismissMenu (0);
  55821. }
  55822. else
  55823. {
  55824. return false;
  55825. }
  55826. return true;
  55827. }
  55828. void inputAttemptWhenModal()
  55829. {
  55830. Component::SafePointer<Component> deletionChecker (this);
  55831. timerCallback();
  55832. if (deletionChecker != 0 && ! isOverAnyMenu())
  55833. {
  55834. if (componentAttachedTo != 0)
  55835. {
  55836. // we want to dismiss the menu, but if we do it synchronously, then
  55837. // the mouse-click will be allowed to pass through. That's good, except
  55838. // when the user clicks on the button that orginally popped the menu up,
  55839. // as they'll expect the menu to go away, and in fact it'll just
  55840. // come back. So only dismiss synchronously if they're not on the original
  55841. // comp that we're attached to.
  55842. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55843. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55844. {
  55845. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55846. return;
  55847. }
  55848. }
  55849. dismissMenu (0);
  55850. }
  55851. }
  55852. void handleCommandMessage (int commandId)
  55853. {
  55854. Component::handleCommandMessage (commandId);
  55855. if (commandId == PopupMenuSettings::dismissCommandId)
  55856. dismissMenu (0);
  55857. }
  55858. void timerCallback()
  55859. {
  55860. if (! isVisible())
  55861. return;
  55862. if (componentAttachedTo != componentAttachedToOriginal)
  55863. {
  55864. dismissMenu (0);
  55865. return;
  55866. }
  55867. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55868. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55869. return;
  55870. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55871. // move rather than a real timer callback
  55872. const Point<int> globalMousePos (Desktop::getMousePosition());
  55873. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  55874. const uint32 now = Time::getMillisecondCounter();
  55875. if (now > timeEnteredCurrentChildComp + 100
  55876. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55877. && currentChild != 0
  55878. && (! disableMouseMoves)
  55879. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55880. {
  55881. showSubMenuFor (currentChild);
  55882. }
  55883. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55884. {
  55885. highlightItemUnderMouse (globalMousePos, localMousePos);
  55886. }
  55887. bool overScrollArea = false;
  55888. if (isScrolling()
  55889. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55890. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55891. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55892. {
  55893. if (now > lastScroll + 20)
  55894. {
  55895. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55896. int amount = 0;
  55897. for (int i = 0; i < items.size() && amount == 0; ++i)
  55898. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  55899. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55900. lastScroll = now;
  55901. }
  55902. overScrollArea = true;
  55903. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55904. }
  55905. else
  55906. {
  55907. scrollAcceleration = 1.0;
  55908. }
  55909. const bool wasDown = isDown;
  55910. bool isOverAny = isOverAnyMenu();
  55911. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55912. {
  55913. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55914. isOverAny = isOverAnyMenu();
  55915. }
  55916. if (hideOnExit && hasBeenOver && ! isOverAny)
  55917. {
  55918. hide (0, true);
  55919. }
  55920. else
  55921. {
  55922. isDown = hasBeenOver
  55923. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55924. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55925. bool anyFocused = Process::isForegroundProcess();
  55926. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55927. {
  55928. // because no component at all may have focus, our test here will
  55929. // only be triggered when something has focus and then loses it.
  55930. anyFocused = ! hasAnyJuceCompHadFocus;
  55931. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55932. {
  55933. if (ComponentPeer::getPeer (i)->isFocused())
  55934. {
  55935. anyFocused = true;
  55936. hasAnyJuceCompHadFocus = true;
  55937. break;
  55938. }
  55939. }
  55940. }
  55941. if (! anyFocused)
  55942. {
  55943. if (now > lastFocused + 10)
  55944. {
  55945. wasHiddenBecauseOfAppChange() = true;
  55946. dismissMenu (0);
  55947. return; // may have been deleted by the previous call..
  55948. }
  55949. }
  55950. else if (wasDown && now > menuCreationTime + 250
  55951. && ! (isDown || overScrollArea))
  55952. {
  55953. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55954. if (isOver)
  55955. {
  55956. triggerCurrentlyHighlightedItem();
  55957. }
  55958. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55959. {
  55960. dismissMenu (0);
  55961. }
  55962. return; // may have been deleted by the previous calls..
  55963. }
  55964. else
  55965. {
  55966. lastFocused = now;
  55967. }
  55968. }
  55969. }
  55970. static Array<Window*>& getActiveWindows()
  55971. {
  55972. static Array<Window*> activeMenuWindows;
  55973. return activeMenuWindows;
  55974. }
  55975. static bool& wasHiddenBecauseOfAppChange() throw()
  55976. {
  55977. static bool b = false;
  55978. return b;
  55979. }
  55980. juce_UseDebuggingNewOperator
  55981. private:
  55982. Window* owner;
  55983. OwnedArray <PopupMenu::ItemComponent> items;
  55984. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  55985. ScopedPointer <Window> activeSubMenu;
  55986. ApplicationCommandManager** managerOfChosenCommand;
  55987. Component::SafePointer<Component> componentAttachedTo;
  55988. Component* componentAttachedToOriginal;
  55989. Rectangle<int> windowPos;
  55990. Point<int> lastMouse;
  55991. int minimumWidth, maximumNumColumns, standardItemHeight;
  55992. bool isOver, hasBeenOver, isDown, needsToScroll;
  55993. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55994. int numColumns, contentHeight, childYOffset;
  55995. Array <int> columnWidths;
  55996. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55997. double scrollAcceleration;
  55998. bool overlaps (const Rectangle<int>& r) const
  55999. {
  56000. return r.intersects (getBounds())
  56001. || (owner != 0 && owner->overlaps (r));
  56002. }
  56003. bool isOverAnyMenu() const
  56004. {
  56005. return (owner != 0) ? owner->isOverAnyMenu()
  56006. : isOverChildren();
  56007. }
  56008. bool isOverChildren() const
  56009. {
  56010. return isVisible()
  56011. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56012. }
  56013. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56014. {
  56015. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  56016. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56017. if (activeSubMenu != 0)
  56018. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56019. }
  56020. bool treeContains (const Window* const window) const throw()
  56021. {
  56022. const Window* mw = this;
  56023. while (mw->owner != 0)
  56024. mw = mw->owner;
  56025. while (mw != 0)
  56026. {
  56027. if (mw == window)
  56028. return true;
  56029. mw = mw->activeSubMenu;
  56030. }
  56031. return false;
  56032. }
  56033. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56034. {
  56035. const Rectangle<int> mon (Desktop::getInstance()
  56036. .getMonitorAreaContaining (target.getCentre(),
  56037. #if JUCE_MAC
  56038. true));
  56039. #else
  56040. false)); // on windows, don't stop the menu overlapping the taskbar
  56041. #endif
  56042. int x, y, widthToUse, heightToUse;
  56043. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56044. if (alignToRectangle)
  56045. {
  56046. x = target.getX();
  56047. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56048. const int spaceOver = target.getY() - mon.getY();
  56049. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56050. y = target.getBottom();
  56051. else
  56052. y = target.getY() - heightToUse;
  56053. }
  56054. else
  56055. {
  56056. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56057. if (owner != 0)
  56058. {
  56059. if (owner->owner != 0)
  56060. {
  56061. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56062. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56063. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56064. tendTowardsRight = true;
  56065. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56066. tendTowardsRight = false;
  56067. }
  56068. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56069. {
  56070. tendTowardsRight = true;
  56071. }
  56072. }
  56073. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56074. target.getX() - mon.getX()) - 32;
  56075. if (biggestSpace < widthToUse)
  56076. {
  56077. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56078. if (numColumns > 1)
  56079. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56080. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56081. }
  56082. if (tendTowardsRight)
  56083. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56084. else
  56085. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56086. y = target.getY();
  56087. if (target.getCentreY() > mon.getCentreY())
  56088. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56089. }
  56090. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56091. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56092. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56093. // sets this flag if it's big enough to obscure any of its parent menus
  56094. hideOnExit = (owner != 0)
  56095. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56096. }
  56097. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56098. {
  56099. numColumns = 0;
  56100. contentHeight = 0;
  56101. const int maxMenuH = getParentHeight() - 24;
  56102. int totalW;
  56103. do
  56104. {
  56105. ++numColumns;
  56106. totalW = workOutBestSize (maxMenuW);
  56107. if (totalW > maxMenuW)
  56108. {
  56109. numColumns = jmax (1, numColumns - 1);
  56110. totalW = workOutBestSize (maxMenuW); // to update col widths
  56111. break;
  56112. }
  56113. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56114. {
  56115. break;
  56116. }
  56117. } while (numColumns < maximumNumColumns);
  56118. const int actualH = jmin (contentHeight, maxMenuH);
  56119. needsToScroll = contentHeight > actualH;
  56120. width = updateYPositions();
  56121. height = actualH + PopupMenuSettings::borderSize * 2;
  56122. }
  56123. int workOutBestSize (const int maxMenuW)
  56124. {
  56125. int totalW = 0;
  56126. contentHeight = 0;
  56127. int childNum = 0;
  56128. for (int col = 0; col < numColumns; ++col)
  56129. {
  56130. int i, colW = 50, colH = 0;
  56131. const int numChildren = jmin (items.size() - childNum,
  56132. (items.size() + numColumns - 1) / numColumns);
  56133. for (i = numChildren; --i >= 0;)
  56134. {
  56135. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56136. colH += items.getUnchecked (childNum + i)->getHeight();
  56137. }
  56138. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56139. columnWidths.set (col, colW);
  56140. totalW += colW;
  56141. contentHeight = jmax (contentHeight, colH);
  56142. childNum += numChildren;
  56143. }
  56144. if (totalW < minimumWidth)
  56145. {
  56146. totalW = minimumWidth;
  56147. for (int col = 0; col < numColumns; ++col)
  56148. columnWidths.set (0, totalW / numColumns);
  56149. }
  56150. return totalW;
  56151. }
  56152. void ensureItemIsVisible (const int itemId, int wantedY)
  56153. {
  56154. jassert (itemId != 0)
  56155. for (int i = items.size(); --i >= 0;)
  56156. {
  56157. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56158. if (m != 0
  56159. && m->itemInfo.itemId == itemId
  56160. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56161. {
  56162. const int currentY = m->getY();
  56163. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56164. {
  56165. if (wantedY < 0)
  56166. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56167. jmax (PopupMenuSettings::scrollZone,
  56168. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56169. currentY);
  56170. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56171. int deltaY = wantedY - currentY;
  56172. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56173. jmin (windowPos.getHeight(), mon.getHeight()));
  56174. const int newY = jlimit (mon.getY(),
  56175. mon.getBottom() - windowPos.getHeight(),
  56176. windowPos.getY() + deltaY);
  56177. deltaY -= newY - windowPos.getY();
  56178. childYOffset -= deltaY;
  56179. windowPos.setPosition (windowPos.getX(), newY);
  56180. updateYPositions();
  56181. }
  56182. break;
  56183. }
  56184. }
  56185. }
  56186. void resizeToBestWindowPos()
  56187. {
  56188. Rectangle<int> r (windowPos);
  56189. if (childYOffset < 0)
  56190. {
  56191. r.setBounds (r.getX(), r.getY() - childYOffset,
  56192. r.getWidth(), r.getHeight() + childYOffset);
  56193. }
  56194. else if (childYOffset > 0)
  56195. {
  56196. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56197. if (spaceAtBottom > 0)
  56198. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56199. }
  56200. setBounds (r);
  56201. updateYPositions();
  56202. }
  56203. void alterChildYPos (const int delta)
  56204. {
  56205. if (isScrolling())
  56206. {
  56207. childYOffset += delta;
  56208. if (delta < 0)
  56209. {
  56210. childYOffset = jmax (childYOffset, 0);
  56211. }
  56212. else if (delta > 0)
  56213. {
  56214. childYOffset = jmin (childYOffset,
  56215. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56216. }
  56217. updateYPositions();
  56218. }
  56219. else
  56220. {
  56221. childYOffset = 0;
  56222. }
  56223. resizeToBestWindowPos();
  56224. repaint();
  56225. }
  56226. int updateYPositions()
  56227. {
  56228. int x = 0;
  56229. int childNum = 0;
  56230. for (int col = 0; col < numColumns; ++col)
  56231. {
  56232. const int numChildren = jmin (items.size() - childNum,
  56233. (items.size() + numColumns - 1) / numColumns);
  56234. const int colW = columnWidths [col];
  56235. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56236. for (int i = 0; i < numChildren; ++i)
  56237. {
  56238. Component* const c = items.getUnchecked (childNum + i);
  56239. c->setBounds (x, y, colW, c->getHeight());
  56240. y += c->getHeight();
  56241. }
  56242. x += colW;
  56243. childNum += numChildren;
  56244. }
  56245. return x;
  56246. }
  56247. bool isScrolling() const throw()
  56248. {
  56249. return childYOffset != 0 || needsToScroll;
  56250. }
  56251. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56252. {
  56253. if (currentChild != 0)
  56254. currentChild->setHighlighted (false);
  56255. currentChild = child;
  56256. if (currentChild != 0)
  56257. {
  56258. currentChild->setHighlighted (true);
  56259. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56260. }
  56261. }
  56262. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56263. {
  56264. activeSubMenu = 0;
  56265. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56266. {
  56267. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56268. dismissOnMouseUp,
  56269. this,
  56270. childComp->getScreenBounds(),
  56271. 0, maximumNumColumns,
  56272. standardItemHeight,
  56273. false, 0, managerOfChosenCommand,
  56274. componentAttachedTo);
  56275. if (activeSubMenu != 0)
  56276. {
  56277. activeSubMenu->setVisible (true);
  56278. activeSubMenu->enterModalState (false);
  56279. activeSubMenu->toFront (false);
  56280. return true;
  56281. }
  56282. }
  56283. return false;
  56284. }
  56285. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56286. {
  56287. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56288. if (isOver)
  56289. hasBeenOver = true;
  56290. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56291. {
  56292. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56293. if (disableMouseMoves && isOver)
  56294. disableMouseMoves = false;
  56295. }
  56296. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56297. return;
  56298. bool isMovingTowardsMenu = false;
  56299. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56300. {
  56301. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56302. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56303. // extends from the last mouse pos to the submenu's rectangle..
  56304. float subX = (float) activeSubMenu->getScreenX();
  56305. if (activeSubMenu->getX() > getX())
  56306. {
  56307. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56308. }
  56309. else
  56310. {
  56311. lastMouse += Point<int> (2, 0);
  56312. subX += activeSubMenu->getWidth();
  56313. }
  56314. Path areaTowardsSubMenu;
  56315. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56316. subX, (float) activeSubMenu->getScreenY(),
  56317. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56318. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56319. }
  56320. lastMouse = globalMousePos;
  56321. if (! isMovingTowardsMenu)
  56322. {
  56323. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56324. if (c == this)
  56325. c = 0;
  56326. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56327. if (mic == 0 && c != 0)
  56328. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56329. if (mic != currentChild
  56330. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56331. {
  56332. if (isOver && (c != 0) && (activeSubMenu != 0))
  56333. {
  56334. activeSubMenu->hide (0, true);
  56335. }
  56336. if (! isOver)
  56337. mic = 0;
  56338. setCurrentlyHighlightedChild (mic);
  56339. }
  56340. }
  56341. }
  56342. void triggerCurrentlyHighlightedItem()
  56343. {
  56344. if (currentChild != 0
  56345. && currentChild->itemInfo.canBeTriggered()
  56346. && (currentChild->itemInfo.customComp == 0
  56347. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56348. {
  56349. dismissMenu (&currentChild->itemInfo);
  56350. }
  56351. }
  56352. void selectNextItem (const int delta)
  56353. {
  56354. disableTimerUntilMouseMoves();
  56355. PopupMenu::ItemComponent* mic = 0;
  56356. bool wasLastOne = (currentChild == 0);
  56357. const int numItems = items.size();
  56358. for (int i = 0; i < numItems + 1; ++i)
  56359. {
  56360. int index = (delta > 0) ? i : (numItems - 1 - i);
  56361. index = (index + numItems) % numItems;
  56362. mic = items.getUnchecked (index);
  56363. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56364. && wasLastOne)
  56365. break;
  56366. if (mic == currentChild)
  56367. wasLastOne = true;
  56368. }
  56369. setCurrentlyHighlightedChild (mic);
  56370. }
  56371. void disableTimerUntilMouseMoves()
  56372. {
  56373. disableMouseMoves = true;
  56374. if (owner != 0)
  56375. owner->disableTimerUntilMouseMoves();
  56376. }
  56377. Window (const Window&);
  56378. Window& operator= (const Window&);
  56379. };
  56380. PopupMenu::PopupMenu()
  56381. : lookAndFeel (0),
  56382. separatorPending (false)
  56383. {
  56384. }
  56385. PopupMenu::PopupMenu (const PopupMenu& other)
  56386. : lookAndFeel (other.lookAndFeel),
  56387. separatorPending (false)
  56388. {
  56389. items.addCopiesOf (other.items);
  56390. }
  56391. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56392. {
  56393. if (this != &other)
  56394. {
  56395. lookAndFeel = other.lookAndFeel;
  56396. clear();
  56397. items.addCopiesOf (other.items);
  56398. }
  56399. return *this;
  56400. }
  56401. PopupMenu::~PopupMenu()
  56402. {
  56403. clear();
  56404. }
  56405. void PopupMenu::clear()
  56406. {
  56407. items.clear();
  56408. separatorPending = false;
  56409. }
  56410. void PopupMenu::addSeparatorIfPending()
  56411. {
  56412. if (separatorPending)
  56413. {
  56414. separatorPending = false;
  56415. if (items.size() > 0)
  56416. items.add (new Item());
  56417. }
  56418. }
  56419. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56420. const bool isActive, const bool isTicked, const Image& iconToUse)
  56421. {
  56422. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56423. // didn't pick anything, so you shouldn't use it as the id
  56424. // for an item..
  56425. addSeparatorIfPending();
  56426. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56427. Colours::black, false, 0, 0, 0));
  56428. }
  56429. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56430. const int commandID,
  56431. const String& displayName)
  56432. {
  56433. jassert (commandManager != 0 && commandID != 0);
  56434. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56435. if (registeredInfo != 0)
  56436. {
  56437. ApplicationCommandInfo info (*registeredInfo);
  56438. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56439. addSeparatorIfPending();
  56440. items.add (new Item (commandID,
  56441. displayName.isNotEmpty() ? displayName
  56442. : info.shortName,
  56443. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56444. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56445. Image::null,
  56446. Colours::black,
  56447. false,
  56448. 0, 0,
  56449. commandManager));
  56450. }
  56451. }
  56452. void PopupMenu::addColouredItem (const int itemResultId,
  56453. const String& itemText,
  56454. const Colour& itemTextColour,
  56455. const bool isActive,
  56456. const bool isTicked,
  56457. const Image& iconToUse)
  56458. {
  56459. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56460. // didn't pick anything, so you shouldn't use it as the id
  56461. // for an item..
  56462. addSeparatorIfPending();
  56463. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56464. itemTextColour, true, 0, 0, 0));
  56465. }
  56466. void PopupMenu::addCustomItem (const int itemResultId,
  56467. PopupMenuCustomComponent* const customComponent)
  56468. {
  56469. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56470. // didn't pick anything, so you shouldn't use it as the id
  56471. // for an item..
  56472. addSeparatorIfPending();
  56473. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56474. Colours::black, false, customComponent, 0, 0));
  56475. }
  56476. class NormalComponentWrapper : public PopupMenuCustomComponent
  56477. {
  56478. public:
  56479. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56480. const bool triggerMenuItemAutomaticallyWhenClicked)
  56481. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56482. width (w), height (h)
  56483. {
  56484. addAndMakeVisible (comp);
  56485. }
  56486. ~NormalComponentWrapper() {}
  56487. void getIdealSize (int& idealWidth, int& idealHeight)
  56488. {
  56489. idealWidth = width;
  56490. idealHeight = height;
  56491. }
  56492. void resized()
  56493. {
  56494. if (getChildComponent(0) != 0)
  56495. getChildComponent(0)->setBounds (getLocalBounds());
  56496. }
  56497. juce_UseDebuggingNewOperator
  56498. private:
  56499. const int width, height;
  56500. NormalComponentWrapper (const NormalComponentWrapper&);
  56501. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56502. };
  56503. void PopupMenu::addCustomItem (const int itemResultId,
  56504. Component* customComponent,
  56505. int idealWidth, int idealHeight,
  56506. const bool triggerMenuItemAutomaticallyWhenClicked)
  56507. {
  56508. addCustomItem (itemResultId,
  56509. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56510. triggerMenuItemAutomaticallyWhenClicked));
  56511. }
  56512. void PopupMenu::addSubMenu (const String& subMenuName,
  56513. const PopupMenu& subMenu,
  56514. const bool isActive,
  56515. const Image& iconToUse,
  56516. const bool isTicked)
  56517. {
  56518. addSeparatorIfPending();
  56519. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56520. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56521. }
  56522. void PopupMenu::addSeparator()
  56523. {
  56524. separatorPending = true;
  56525. }
  56526. class HeaderItemComponent : public PopupMenuCustomComponent
  56527. {
  56528. public:
  56529. HeaderItemComponent (const String& name)
  56530. : PopupMenuCustomComponent (false)
  56531. {
  56532. setName (name);
  56533. }
  56534. ~HeaderItemComponent()
  56535. {
  56536. }
  56537. void paint (Graphics& g)
  56538. {
  56539. Font f (getLookAndFeel().getPopupMenuFont());
  56540. f.setBold (true);
  56541. g.setFont (f);
  56542. g.setColour (findColour (PopupMenu::headerTextColourId));
  56543. g.drawFittedText (getName(),
  56544. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56545. Justification::bottomLeft, 1);
  56546. }
  56547. void getIdealSize (int& idealWidth,
  56548. int& idealHeight)
  56549. {
  56550. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56551. idealHeight += idealHeight / 2;
  56552. idealWidth += idealWidth / 4;
  56553. }
  56554. juce_UseDebuggingNewOperator
  56555. };
  56556. void PopupMenu::addSectionHeader (const String& title)
  56557. {
  56558. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56559. }
  56560. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56561. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56562. {
  56563. public:
  56564. PopupMenuCompletionCallback()
  56565. : managerOfChosenCommand (0)
  56566. {
  56567. }
  56568. void modalStateFinished (int result)
  56569. {
  56570. if (managerOfChosenCommand != 0 && result != 0)
  56571. {
  56572. ApplicationCommandTarget::InvocationInfo info (result);
  56573. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56574. managerOfChosenCommand->invoke (info, true);
  56575. }
  56576. // (this would be the place to fade out the component, if that's what's required)
  56577. component = 0;
  56578. }
  56579. ApplicationCommandManager* managerOfChosenCommand;
  56580. ScopedPointer<Component> component;
  56581. private:
  56582. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  56583. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  56584. };
  56585. int PopupMenu::showMenu (const Rectangle<int>& target,
  56586. const int itemIdThatMustBeVisible,
  56587. const int minimumWidth,
  56588. const int maximumNumColumns,
  56589. const int standardItemHeight,
  56590. const bool alignToRectangle,
  56591. Component* const componentAttachedTo,
  56592. ModalComponentManager::Callback* userCallback)
  56593. {
  56594. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56595. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56596. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56597. Window::wasHiddenBecauseOfAppChange() = false;
  56598. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56599. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56600. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56601. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56602. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56603. &callback->managerOfChosenCommand, componentAttachedTo);
  56604. if (callback->component == 0)
  56605. return 0;
  56606. callback->component->enterModalState (false, userCallbackDeleter.release());
  56607. callback->component->toFront (false); // need to do this after making it modal, or it could
  56608. // be stuck behind other comps that are already modal..
  56609. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56610. callbackDeleter.release();
  56611. if (userCallback != 0)
  56612. return 0;
  56613. const int result = callback->component->runModalLoop();
  56614. if (! Window::wasHiddenBecauseOfAppChange())
  56615. {
  56616. if (prevTopLevel != 0)
  56617. prevTopLevel->toFront (true);
  56618. if (prevFocused != 0)
  56619. prevFocused->grabKeyboardFocus();
  56620. }
  56621. return result;
  56622. }
  56623. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56624. const int minimumWidth, const int maximumNumColumns,
  56625. const int standardItemHeight,
  56626. ModalComponentManager::Callback* callback)
  56627. {
  56628. const Point<int> mousePos (Desktop::getMousePosition());
  56629. return showAt (mousePos.getX(), mousePos.getY(),
  56630. itemIdThatMustBeVisible,
  56631. minimumWidth, maximumNumColumns,
  56632. standardItemHeight, callback);
  56633. }
  56634. int PopupMenu::showAt (const int screenX, const int screenY,
  56635. const int itemIdThatMustBeVisible,
  56636. const int minimumWidth, const int maximumNumColumns,
  56637. const int standardItemHeight,
  56638. ModalComponentManager::Callback* callback)
  56639. {
  56640. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56641. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56642. standardItemHeight, false, 0, callback);
  56643. }
  56644. int PopupMenu::showAt (Component* componentToAttachTo,
  56645. const int itemIdThatMustBeVisible,
  56646. const int minimumWidth, const int maximumNumColumns,
  56647. const int standardItemHeight,
  56648. ModalComponentManager::Callback* callback)
  56649. {
  56650. if (componentToAttachTo != 0)
  56651. {
  56652. return showMenu (componentToAttachTo->getScreenBounds(),
  56653. itemIdThatMustBeVisible,
  56654. minimumWidth,
  56655. maximumNumColumns,
  56656. standardItemHeight,
  56657. true, componentToAttachTo, callback);
  56658. }
  56659. else
  56660. {
  56661. return show (itemIdThatMustBeVisible,
  56662. minimumWidth, maximumNumColumns,
  56663. standardItemHeight, callback);
  56664. }
  56665. }
  56666. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56667. {
  56668. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56669. {
  56670. Window* const pmw = Window::getActiveWindows()[i];
  56671. if (pmw != 0)
  56672. pmw->dismissMenu (0);
  56673. }
  56674. }
  56675. int PopupMenu::getNumItems() const throw()
  56676. {
  56677. int num = 0;
  56678. for (int i = items.size(); --i >= 0;)
  56679. if (! (items.getUnchecked(i))->isSeparator)
  56680. ++num;
  56681. return num;
  56682. }
  56683. bool PopupMenu::containsCommandItem (const int commandID) const
  56684. {
  56685. for (int i = items.size(); --i >= 0;)
  56686. {
  56687. const Item* mi = items.getUnchecked (i);
  56688. if ((mi->itemId == commandID && mi->commandManager != 0)
  56689. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56690. {
  56691. return true;
  56692. }
  56693. }
  56694. return false;
  56695. }
  56696. bool PopupMenu::containsAnyActiveItems() const throw()
  56697. {
  56698. for (int i = items.size(); --i >= 0;)
  56699. {
  56700. const Item* const mi = items.getUnchecked (i);
  56701. if (mi->subMenu != 0)
  56702. {
  56703. if (mi->subMenu->containsAnyActiveItems())
  56704. return true;
  56705. }
  56706. else if (mi->active)
  56707. {
  56708. return true;
  56709. }
  56710. }
  56711. return false;
  56712. }
  56713. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56714. {
  56715. lookAndFeel = newLookAndFeel;
  56716. }
  56717. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56718. : isHighlighted (false),
  56719. isTriggeredAutomatically (isTriggeredAutomatically_)
  56720. {
  56721. }
  56722. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56723. {
  56724. }
  56725. void PopupMenuCustomComponent::triggerMenuItem()
  56726. {
  56727. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56728. if (mic != 0)
  56729. {
  56730. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56731. if (pmw != 0)
  56732. {
  56733. pmw->dismissMenu (&mic->itemInfo);
  56734. }
  56735. else
  56736. {
  56737. // something must have gone wrong with the component hierarchy if this happens..
  56738. jassertfalse;
  56739. }
  56740. }
  56741. else
  56742. {
  56743. // why isn't this component inside a menu? Not much point triggering the item if
  56744. // there's no menu.
  56745. jassertfalse;
  56746. }
  56747. }
  56748. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56749. : subMenu (0),
  56750. itemId (0),
  56751. isSeparator (false),
  56752. isTicked (false),
  56753. isEnabled (false),
  56754. isCustomComponent (false),
  56755. isSectionHeader (false),
  56756. customColour (0),
  56757. customImage (0),
  56758. menu (menu_),
  56759. index (0)
  56760. {
  56761. }
  56762. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56763. {
  56764. }
  56765. bool PopupMenu::MenuItemIterator::next()
  56766. {
  56767. if (index >= menu.items.size())
  56768. return false;
  56769. const Item* const item = menu.items.getUnchecked (index);
  56770. ++index;
  56771. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56772. subMenu = item->subMenu;
  56773. itemId = item->itemId;
  56774. isSeparator = item->isSeparator;
  56775. isTicked = item->isTicked;
  56776. isEnabled = item->active;
  56777. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <PopupMenuCustomComponent*> (item->customComp)) != 0;
  56778. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56779. customColour = item->usesColour ? &(item->textColour) : 0;
  56780. customImage = item->image;
  56781. commandManager = item->commandManager;
  56782. return true;
  56783. }
  56784. END_JUCE_NAMESPACE
  56785. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56786. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56787. BEGIN_JUCE_NAMESPACE
  56788. ComponentDragger::ComponentDragger()
  56789. : constrainer (0)
  56790. {
  56791. }
  56792. ComponentDragger::~ComponentDragger()
  56793. {
  56794. }
  56795. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56796. ComponentBoundsConstrainer* const constrainer_)
  56797. {
  56798. jassert (componentToDrag != 0);
  56799. if (componentToDrag != 0)
  56800. {
  56801. constrainer = constrainer_;
  56802. originalPos = componentToDrag->localPointToGlobal (Point<int>());
  56803. }
  56804. }
  56805. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56806. {
  56807. jassert (componentToDrag != 0);
  56808. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56809. if (componentToDrag != 0)
  56810. {
  56811. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56812. const Component* const parentComp = componentToDrag->getParentComponent();
  56813. if (parentComp != 0)
  56814. bounds.setPosition (parentComp->getLocalPoint (0, originalPos));
  56815. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56816. if (constrainer != 0)
  56817. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56818. else
  56819. componentToDrag->setBounds (bounds);
  56820. }
  56821. }
  56822. END_JUCE_NAMESPACE
  56823. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56824. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56825. BEGIN_JUCE_NAMESPACE
  56826. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56827. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56828. class DragImageComponent : public Component,
  56829. public Timer
  56830. {
  56831. public:
  56832. DragImageComponent (const Image& im,
  56833. const String& desc,
  56834. Component* const sourceComponent,
  56835. Component* const mouseDragSource_,
  56836. DragAndDropContainer* const o,
  56837. const Point<int>& imageOffset_)
  56838. : image (im),
  56839. source (sourceComponent),
  56840. mouseDragSource (mouseDragSource_),
  56841. owner (o),
  56842. dragDesc (desc),
  56843. imageOffset (imageOffset_),
  56844. hasCheckedForExternalDrag (false),
  56845. drawImage (true)
  56846. {
  56847. setSize (im.getWidth(), im.getHeight());
  56848. if (mouseDragSource == 0)
  56849. mouseDragSource = source;
  56850. mouseDragSource->addMouseListener (this, false);
  56851. startTimer (200);
  56852. setInterceptsMouseClicks (false, false);
  56853. setAlwaysOnTop (true);
  56854. }
  56855. ~DragImageComponent()
  56856. {
  56857. if (owner->dragImageComponent == this)
  56858. owner->dragImageComponent.release();
  56859. if (mouseDragSource != 0)
  56860. {
  56861. mouseDragSource->removeMouseListener (this);
  56862. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56863. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56864. }
  56865. }
  56866. void paint (Graphics& g)
  56867. {
  56868. if (isOpaque())
  56869. g.fillAll (Colours::white);
  56870. if (drawImage)
  56871. {
  56872. g.setOpacity (1.0f);
  56873. g.drawImageAt (image, 0, 0);
  56874. }
  56875. }
  56876. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56877. {
  56878. Component* hit = getParentComponent();
  56879. if (hit == 0)
  56880. {
  56881. hit = Desktop::getInstance().findComponentAt (screenPos);
  56882. }
  56883. else
  56884. {
  56885. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  56886. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56887. }
  56888. // (note: use a local copy of the dragDesc member in case the callback runs
  56889. // a modal loop and deletes this object before the method completes)
  56890. const String dragDescLocal (dragDesc);
  56891. while (hit != 0)
  56892. {
  56893. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56894. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56895. {
  56896. relativePos = hit->getLocalPoint (0, screenPos);
  56897. return ddt;
  56898. }
  56899. hit = hit->getParentComponent();
  56900. }
  56901. return 0;
  56902. }
  56903. void mouseUp (const MouseEvent& e)
  56904. {
  56905. if (e.originalComponent != this)
  56906. {
  56907. if (mouseDragSource != 0)
  56908. mouseDragSource->removeMouseListener (this);
  56909. bool dropAccepted = false;
  56910. DragAndDropTarget* ddt = 0;
  56911. Point<int> relPos;
  56912. if (isVisible())
  56913. {
  56914. setVisible (false);
  56915. ddt = findTarget (e.getScreenPosition(), relPos);
  56916. // fade this component and remove it - it'll be deleted later by the timer callback
  56917. dropAccepted = ddt != 0;
  56918. setVisible (true);
  56919. if (dropAccepted || source == 0)
  56920. {
  56921. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  56922. }
  56923. else
  56924. {
  56925. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  56926. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  56927. Desktop::getInstance().getAnimator().animateComponent (this,
  56928. getBounds() + (target - ourCentre),
  56929. 0.0f, 120,
  56930. true, 1.0, 1.0);
  56931. }
  56932. }
  56933. if (getParentComponent() != 0)
  56934. getParentComponent()->removeChildComponent (this);
  56935. if (dropAccepted && ddt != 0)
  56936. {
  56937. // (note: use a local copy of the dragDesc member in case the callback runs
  56938. // a modal loop and deletes this object before the method completes)
  56939. const String dragDescLocal (dragDesc);
  56940. currentlyOverComp = 0;
  56941. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56942. }
  56943. // careful - this object could now be deleted..
  56944. }
  56945. }
  56946. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56947. {
  56948. // (note: use a local copy of the dragDesc member in case the callback runs
  56949. // a modal loop and deletes this object before it returns)
  56950. const String dragDescLocal (dragDesc);
  56951. Point<int> newPos (screenPos + imageOffset);
  56952. if (getParentComponent() != 0)
  56953. newPos = getParentComponent()->getLocalPoint (0, newPos);
  56954. //if (newX != getX() || newY != getY())
  56955. {
  56956. setTopLeftPosition (newPos.getX(), newPos.getY());
  56957. Point<int> relPos;
  56958. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56959. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56960. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56961. if (ddtComp != currentlyOverComp)
  56962. {
  56963. if (currentlyOverComp != 0 && source != 0
  56964. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56965. {
  56966. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56967. }
  56968. currentlyOverComp = ddtComp;
  56969. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56970. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56971. }
  56972. DragAndDropTarget* target = getCurrentlyOver();
  56973. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56974. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56975. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56976. {
  56977. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56978. {
  56979. hasCheckedForExternalDrag = true;
  56980. StringArray files;
  56981. bool canMoveFiles = false;
  56982. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56983. && files.size() > 0)
  56984. {
  56985. Component::SafePointer<Component> cdw (this);
  56986. setVisible (false);
  56987. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56988. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56989. if (cdw != 0)
  56990. delete this;
  56991. return;
  56992. }
  56993. }
  56994. }
  56995. }
  56996. }
  56997. void mouseDrag (const MouseEvent& e)
  56998. {
  56999. if (e.originalComponent != this)
  57000. updateLocation (true, e.getScreenPosition());
  57001. }
  57002. void timerCallback()
  57003. {
  57004. if (source == 0)
  57005. {
  57006. delete this;
  57007. }
  57008. else if (! isMouseButtonDownAnywhere())
  57009. {
  57010. if (mouseDragSource != 0)
  57011. mouseDragSource->removeMouseListener (this);
  57012. delete this;
  57013. }
  57014. }
  57015. private:
  57016. Image image;
  57017. Component::SafePointer<Component> source;
  57018. Component::SafePointer<Component> mouseDragSource;
  57019. DragAndDropContainer* const owner;
  57020. Component::SafePointer<Component> currentlyOverComp;
  57021. DragAndDropTarget* getCurrentlyOver()
  57022. {
  57023. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57024. }
  57025. String dragDesc;
  57026. const Point<int> imageOffset;
  57027. bool hasCheckedForExternalDrag, drawImage;
  57028. DragImageComponent (const DragImageComponent&);
  57029. DragImageComponent& operator= (const DragImageComponent&);
  57030. };
  57031. DragAndDropContainer::DragAndDropContainer()
  57032. {
  57033. }
  57034. DragAndDropContainer::~DragAndDropContainer()
  57035. {
  57036. dragImageComponent = 0;
  57037. }
  57038. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57039. Component* sourceComponent,
  57040. const Image& dragImage_,
  57041. const bool allowDraggingToExternalWindows,
  57042. const Point<int>* imageOffsetFromMouse)
  57043. {
  57044. Image dragImage (dragImage_);
  57045. if (dragImageComponent == 0)
  57046. {
  57047. Component* const thisComp = dynamic_cast <Component*> (this);
  57048. if (thisComp == 0)
  57049. {
  57050. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57051. return;
  57052. }
  57053. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57054. if (draggingSource == 0 || ! draggingSource->isDragging())
  57055. {
  57056. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57057. return;
  57058. }
  57059. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57060. Point<int> imageOffset;
  57061. if (dragImage.isNull())
  57062. {
  57063. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57064. .convertedToFormat (Image::ARGB);
  57065. dragImage.multiplyAllAlphas (0.6f);
  57066. const int lo = 150;
  57067. const int hi = 400;
  57068. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  57069. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57070. for (int y = dragImage.getHeight(); --y >= 0;)
  57071. {
  57072. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57073. for (int x = dragImage.getWidth(); --x >= 0;)
  57074. {
  57075. const int dx = x - clipped.getX();
  57076. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57077. if (distance > lo)
  57078. {
  57079. const float alpha = (distance > hi) ? 0
  57080. : (hi - distance) / (float) (hi - lo)
  57081. + Random::getSystemRandom().nextFloat() * 0.008f;
  57082. dragImage.multiplyAlphaAt (x, y, alpha);
  57083. }
  57084. }
  57085. }
  57086. imageOffset = -clipped;
  57087. }
  57088. else
  57089. {
  57090. if (imageOffsetFromMouse == 0)
  57091. imageOffset = -dragImage.getBounds().getCentre();
  57092. else
  57093. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57094. }
  57095. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57096. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57097. currentDragDesc = sourceDescription;
  57098. if (allowDraggingToExternalWindows)
  57099. {
  57100. if (! Desktop::canUseSemiTransparentWindows())
  57101. dragImageComponent->setOpaque (true);
  57102. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57103. | ComponentPeer::windowIsTemporary
  57104. | ComponentPeer::windowIgnoresKeyPresses);
  57105. }
  57106. else
  57107. thisComp->addChildComponent (dragImageComponent);
  57108. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57109. dragImageComponent->setVisible (true);
  57110. }
  57111. }
  57112. bool DragAndDropContainer::isDragAndDropActive() const
  57113. {
  57114. return dragImageComponent != 0;
  57115. }
  57116. const String DragAndDropContainer::getCurrentDragDescription() const
  57117. {
  57118. return (dragImageComponent != 0) ? currentDragDesc
  57119. : String::empty;
  57120. }
  57121. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57122. {
  57123. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57124. }
  57125. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57126. {
  57127. return false;
  57128. }
  57129. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57130. {
  57131. }
  57132. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57133. {
  57134. }
  57135. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57136. {
  57137. }
  57138. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57139. {
  57140. return true;
  57141. }
  57142. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57143. {
  57144. }
  57145. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57146. {
  57147. }
  57148. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57149. {
  57150. }
  57151. END_JUCE_NAMESPACE
  57152. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57153. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57154. BEGIN_JUCE_NAMESPACE
  57155. class MouseCursor::SharedCursorHandle
  57156. {
  57157. public:
  57158. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57159. : handle (createStandardMouseCursor (type)),
  57160. refCount (1),
  57161. standardType (type),
  57162. isStandard (true)
  57163. {
  57164. }
  57165. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57166. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57167. refCount (1),
  57168. standardType (MouseCursor::NormalCursor),
  57169. isStandard (false)
  57170. {
  57171. }
  57172. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57173. {
  57174. const ScopedLock sl (getLock());
  57175. for (int i = 0; i < getCursors().size(); ++i)
  57176. {
  57177. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57178. if (sc->standardType == type)
  57179. return sc->retain();
  57180. }
  57181. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57182. getCursors().add (sc);
  57183. return sc;
  57184. }
  57185. SharedCursorHandle* retain() throw()
  57186. {
  57187. ++refCount;
  57188. return this;
  57189. }
  57190. void release()
  57191. {
  57192. if (--refCount == 0)
  57193. {
  57194. if (isStandard)
  57195. {
  57196. const ScopedLock sl (getLock());
  57197. getCursors().removeValue (this);
  57198. }
  57199. delete this;
  57200. }
  57201. }
  57202. void* getHandle() const throw() { return handle; }
  57203. juce_UseDebuggingNewOperator
  57204. private:
  57205. void* const handle;
  57206. Atomic <int> refCount;
  57207. const MouseCursor::StandardCursorType standardType;
  57208. const bool isStandard;
  57209. static CriticalSection& getLock()
  57210. {
  57211. static CriticalSection lock;
  57212. return lock;
  57213. }
  57214. static Array <SharedCursorHandle*>& getCursors()
  57215. {
  57216. static Array <SharedCursorHandle*> cursors;
  57217. return cursors;
  57218. }
  57219. ~SharedCursorHandle()
  57220. {
  57221. deleteMouseCursor (handle, isStandard);
  57222. }
  57223. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57224. };
  57225. MouseCursor::MouseCursor()
  57226. : cursorHandle (0)
  57227. {
  57228. }
  57229. MouseCursor::MouseCursor (const StandardCursorType type)
  57230. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57231. {
  57232. }
  57233. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57234. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57235. {
  57236. }
  57237. MouseCursor::MouseCursor (const MouseCursor& other)
  57238. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57239. {
  57240. }
  57241. MouseCursor::~MouseCursor()
  57242. {
  57243. if (cursorHandle != 0)
  57244. cursorHandle->release();
  57245. }
  57246. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57247. {
  57248. if (other.cursorHandle != 0)
  57249. other.cursorHandle->retain();
  57250. if (cursorHandle != 0)
  57251. cursorHandle->release();
  57252. cursorHandle = other.cursorHandle;
  57253. return *this;
  57254. }
  57255. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57256. {
  57257. return getHandle() == other.getHandle();
  57258. }
  57259. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57260. {
  57261. return getHandle() != other.getHandle();
  57262. }
  57263. void* MouseCursor::getHandle() const throw()
  57264. {
  57265. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57266. }
  57267. void MouseCursor::showWaitCursor()
  57268. {
  57269. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57270. }
  57271. void MouseCursor::hideWaitCursor()
  57272. {
  57273. Desktop::getInstance().getMainMouseSource().revealCursor();
  57274. }
  57275. END_JUCE_NAMESPACE
  57276. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57277. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57278. BEGIN_JUCE_NAMESPACE
  57279. MouseEvent::MouseEvent (MouseInputSource& source_,
  57280. const Point<int>& position,
  57281. const ModifierKeys& mods_,
  57282. Component* const eventComponent_,
  57283. Component* const originator,
  57284. const Time& eventTime_,
  57285. const Point<int> mouseDownPos_,
  57286. const Time& mouseDownTime_,
  57287. const int numberOfClicks_,
  57288. const bool mouseWasDragged) throw()
  57289. : x (position.getX()),
  57290. y (position.getY()),
  57291. mods (mods_),
  57292. eventComponent (eventComponent_),
  57293. originalComponent (originator),
  57294. eventTime (eventTime_),
  57295. source (source_),
  57296. mouseDownPos (mouseDownPos_),
  57297. mouseDownTime (mouseDownTime_),
  57298. numberOfClicks (numberOfClicks_),
  57299. wasMovedSinceMouseDown (mouseWasDragged)
  57300. {
  57301. }
  57302. MouseEvent::~MouseEvent() throw()
  57303. {
  57304. }
  57305. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57306. {
  57307. if (otherComponent == 0)
  57308. {
  57309. jassertfalse;
  57310. return *this;
  57311. }
  57312. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57313. mods, otherComponent, originalComponent, eventTime,
  57314. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57315. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57316. }
  57317. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57318. {
  57319. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57320. eventTime, mouseDownPos, mouseDownTime,
  57321. numberOfClicks, wasMovedSinceMouseDown);
  57322. }
  57323. bool MouseEvent::mouseWasClicked() const throw()
  57324. {
  57325. return ! wasMovedSinceMouseDown;
  57326. }
  57327. int MouseEvent::getMouseDownX() const throw()
  57328. {
  57329. return mouseDownPos.getX();
  57330. }
  57331. int MouseEvent::getMouseDownY() const throw()
  57332. {
  57333. return mouseDownPos.getY();
  57334. }
  57335. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57336. {
  57337. return mouseDownPos;
  57338. }
  57339. int MouseEvent::getDistanceFromDragStartX() const throw()
  57340. {
  57341. return x - mouseDownPos.getX();
  57342. }
  57343. int MouseEvent::getDistanceFromDragStartY() const throw()
  57344. {
  57345. return y - mouseDownPos.getY();
  57346. }
  57347. int MouseEvent::getDistanceFromDragStart() const throw()
  57348. {
  57349. return mouseDownPos.getDistanceFrom (getPosition());
  57350. }
  57351. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57352. {
  57353. return getPosition() - mouseDownPos;
  57354. }
  57355. int MouseEvent::getLengthOfMousePress() const throw()
  57356. {
  57357. if (mouseDownTime.toMilliseconds() > 0)
  57358. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57359. return 0;
  57360. }
  57361. const Point<int> MouseEvent::getPosition() const throw()
  57362. {
  57363. return Point<int> (x, y);
  57364. }
  57365. int MouseEvent::getScreenX() const
  57366. {
  57367. return getScreenPosition().getX();
  57368. }
  57369. int MouseEvent::getScreenY() const
  57370. {
  57371. return getScreenPosition().getY();
  57372. }
  57373. const Point<int> MouseEvent::getScreenPosition() const
  57374. {
  57375. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57376. }
  57377. int MouseEvent::getMouseDownScreenX() const
  57378. {
  57379. return getMouseDownScreenPosition().getX();
  57380. }
  57381. int MouseEvent::getMouseDownScreenY() const
  57382. {
  57383. return getMouseDownScreenPosition().getY();
  57384. }
  57385. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57386. {
  57387. return eventComponent->localPointToGlobal (mouseDownPos);
  57388. }
  57389. int MouseEvent::doubleClickTimeOutMs = 400;
  57390. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57391. {
  57392. doubleClickTimeOutMs = newTime;
  57393. }
  57394. int MouseEvent::getDoubleClickTimeout() throw()
  57395. {
  57396. return doubleClickTimeOutMs;
  57397. }
  57398. END_JUCE_NAMESPACE
  57399. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57400. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57401. BEGIN_JUCE_NAMESPACE
  57402. class MouseInputSourceInternal : public AsyncUpdater
  57403. {
  57404. public:
  57405. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57406. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57407. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57408. mouseEventCounter (0), lastTime (0)
  57409. {
  57410. }
  57411. ~MouseInputSourceInternal()
  57412. {
  57413. }
  57414. bool isDragging() const throw()
  57415. {
  57416. return buttonState.isAnyMouseButtonDown();
  57417. }
  57418. Component* getComponentUnderMouse() const
  57419. {
  57420. return static_cast <Component*> (componentUnderMouse);
  57421. }
  57422. const ModifierKeys getCurrentModifiers() const
  57423. {
  57424. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57425. }
  57426. ComponentPeer* getPeer()
  57427. {
  57428. if (! ComponentPeer::isValidPeer (lastPeer))
  57429. lastPeer = 0;
  57430. return lastPeer;
  57431. }
  57432. Component* findComponentAt (const Point<int>& screenPos)
  57433. {
  57434. ComponentPeer* const peer = getPeer();
  57435. if (peer != 0)
  57436. {
  57437. Component* const comp = peer->getComponent();
  57438. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57439. // (the contains() call is needed to test for overlapping desktop windows)
  57440. if (comp->contains (relativePos))
  57441. return comp->getComponentAt (relativePos);
  57442. }
  57443. return 0;
  57444. }
  57445. const Point<int> getScreenPosition() const throw()
  57446. {
  57447. return lastScreenPos + unboundedMouseOffset;
  57448. }
  57449. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57450. {
  57451. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57452. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57453. }
  57454. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57455. {
  57456. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57457. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57458. }
  57459. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57460. {
  57461. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57462. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57463. }
  57464. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57465. {
  57466. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57467. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57468. }
  57469. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57470. {
  57471. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57472. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57473. }
  57474. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57475. {
  57476. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57477. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57478. }
  57479. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57480. {
  57481. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57482. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57483. }
  57484. // (returns true if the button change caused a modal event loop)
  57485. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57486. {
  57487. if (buttonState == newButtonState)
  57488. return false;
  57489. setScreenPos (screenPos, time, false);
  57490. // (ignore secondary clicks when there's already a button down)
  57491. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57492. {
  57493. buttonState = newButtonState;
  57494. return false;
  57495. }
  57496. const int lastCounter = mouseEventCounter;
  57497. if (buttonState.isAnyMouseButtonDown())
  57498. {
  57499. Component* const current = getComponentUnderMouse();
  57500. if (current != 0)
  57501. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57502. enableUnboundedMouseMovement (false, false);
  57503. }
  57504. buttonState = newButtonState;
  57505. if (buttonState.isAnyMouseButtonDown())
  57506. {
  57507. Desktop::getInstance().incrementMouseClickCounter();
  57508. Component* const current = getComponentUnderMouse();
  57509. if (current != 0)
  57510. {
  57511. registerMouseDown (screenPos, time, current, buttonState);
  57512. sendMouseDown (current, screenPos, time);
  57513. }
  57514. }
  57515. return lastCounter != mouseEventCounter;
  57516. }
  57517. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57518. {
  57519. Component* current = getComponentUnderMouse();
  57520. if (newComponent != current)
  57521. {
  57522. Component::SafePointer<Component> safeNewComp (newComponent);
  57523. const ModifierKeys originalButtonState (buttonState);
  57524. if (current != 0)
  57525. {
  57526. setButtons (screenPos, time, ModifierKeys());
  57527. sendMouseExit (current, screenPos, time);
  57528. buttonState = originalButtonState;
  57529. }
  57530. componentUnderMouse = safeNewComp;
  57531. current = getComponentUnderMouse();
  57532. if (current != 0)
  57533. sendMouseEnter (current, screenPos, time);
  57534. revealCursor (false);
  57535. setButtons (screenPos, time, originalButtonState);
  57536. }
  57537. }
  57538. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57539. {
  57540. ModifierKeys::updateCurrentModifiers();
  57541. if (newPeer != lastPeer)
  57542. {
  57543. setComponentUnderMouse (0, screenPos, time);
  57544. lastPeer = newPeer;
  57545. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57546. }
  57547. }
  57548. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57549. {
  57550. if (! isDragging())
  57551. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57552. if (newScreenPos != lastScreenPos || forceUpdate)
  57553. {
  57554. cancelPendingUpdate();
  57555. lastScreenPos = newScreenPos;
  57556. Component* const current = getComponentUnderMouse();
  57557. if (current != 0)
  57558. {
  57559. if (isDragging())
  57560. {
  57561. registerMouseDrag (newScreenPos);
  57562. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57563. if (isUnboundedMouseModeOn)
  57564. handleUnboundedDrag (current);
  57565. }
  57566. else
  57567. {
  57568. sendMouseMove (current, newScreenPos, time);
  57569. }
  57570. }
  57571. revealCursor (false);
  57572. }
  57573. }
  57574. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57575. {
  57576. jassert (newPeer != 0);
  57577. lastTime = time;
  57578. ++mouseEventCounter;
  57579. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57580. if (isDragging() && newMods.isAnyMouseButtonDown())
  57581. {
  57582. setScreenPos (screenPos, time, false);
  57583. }
  57584. else
  57585. {
  57586. setPeer (newPeer, screenPos, time);
  57587. ComponentPeer* peer = getPeer();
  57588. if (peer != 0)
  57589. {
  57590. if (setButtons (screenPos, time, newMods))
  57591. return; // some modal events have been dispatched, so the current event is now out-of-date
  57592. peer = getPeer();
  57593. if (peer != 0)
  57594. setScreenPos (screenPos, time, false);
  57595. }
  57596. }
  57597. }
  57598. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57599. {
  57600. jassert (peer != 0);
  57601. lastTime = time;
  57602. ++mouseEventCounter;
  57603. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57604. setPeer (peer, screenPos, time);
  57605. setScreenPos (screenPos, time, false);
  57606. triggerFakeMove();
  57607. if (! isDragging())
  57608. {
  57609. Component* current = getComponentUnderMouse();
  57610. if (current != 0)
  57611. sendMouseWheel (current, screenPos, time, x, y);
  57612. }
  57613. }
  57614. const Time getLastMouseDownTime() const throw()
  57615. {
  57616. return Time (mouseDowns[0].time);
  57617. }
  57618. const Point<int> getLastMouseDownPosition() const throw()
  57619. {
  57620. return mouseDowns[0].position;
  57621. }
  57622. int getNumberOfMultipleClicks() const throw()
  57623. {
  57624. int numClicks = 0;
  57625. if (mouseDowns[0].time != 0)
  57626. {
  57627. if (! mouseMovedSignificantlySincePressed)
  57628. ++numClicks;
  57629. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57630. {
  57631. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57632. ++numClicks;
  57633. else
  57634. break;
  57635. }
  57636. }
  57637. return numClicks;
  57638. }
  57639. bool hasMouseMovedSignificantlySincePressed() const throw()
  57640. {
  57641. return mouseMovedSignificantlySincePressed
  57642. || lastTime > mouseDowns[0].time + 300;
  57643. }
  57644. void triggerFakeMove()
  57645. {
  57646. triggerAsyncUpdate();
  57647. }
  57648. void handleAsyncUpdate()
  57649. {
  57650. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57651. }
  57652. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57653. {
  57654. enable = enable && isDragging();
  57655. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57656. if (enable != isUnboundedMouseModeOn)
  57657. {
  57658. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57659. {
  57660. // when released, return the mouse to within the component's bounds
  57661. Component* current = getComponentUnderMouse();
  57662. if (current != 0)
  57663. Desktop::setMousePosition (current->getScreenBounds()
  57664. .getConstrainedPoint (lastScreenPos));
  57665. }
  57666. isUnboundedMouseModeOn = enable;
  57667. unboundedMouseOffset = Point<int>();
  57668. revealCursor (true);
  57669. }
  57670. }
  57671. void handleUnboundedDrag (Component* current)
  57672. {
  57673. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57674. if (! screenArea.contains (lastScreenPos))
  57675. {
  57676. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57677. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57678. Desktop::setMousePosition (componentCentre);
  57679. }
  57680. else if (isCursorVisibleUntilOffscreen
  57681. && (! unboundedMouseOffset.isOrigin())
  57682. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57683. {
  57684. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57685. unboundedMouseOffset = Point<int>();
  57686. }
  57687. }
  57688. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57689. {
  57690. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57691. {
  57692. cursor = MouseCursor::NoCursor;
  57693. forcedUpdate = true;
  57694. }
  57695. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57696. {
  57697. currentCursorHandle = cursor.getHandle();
  57698. cursor.showInWindow (getPeer());
  57699. }
  57700. }
  57701. void hideCursor()
  57702. {
  57703. showMouseCursor (MouseCursor::NoCursor, true);
  57704. }
  57705. void revealCursor (bool forcedUpdate)
  57706. {
  57707. MouseCursor mc (MouseCursor::NormalCursor);
  57708. Component* current = getComponentUnderMouse();
  57709. if (current != 0)
  57710. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57711. showMouseCursor (mc, forcedUpdate);
  57712. }
  57713. int index;
  57714. bool isMouseDevice;
  57715. Point<int> lastScreenPos;
  57716. ModifierKeys buttonState;
  57717. private:
  57718. MouseInputSource& source;
  57719. Component::SafePointer<Component> componentUnderMouse;
  57720. ComponentPeer* lastPeer;
  57721. Point<int> unboundedMouseOffset;
  57722. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57723. void* currentCursorHandle;
  57724. int mouseEventCounter;
  57725. struct RecentMouseDown
  57726. {
  57727. RecentMouseDown()
  57728. : time (0), component (0)
  57729. {
  57730. }
  57731. Point<int> position;
  57732. int64 time;
  57733. Component* component;
  57734. ModifierKeys buttons;
  57735. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, int maxTimeBetween) const
  57736. {
  57737. return time - other.time < maxTimeBetween
  57738. && abs (position.getX() - other.position.getX()) < 8
  57739. && abs (position.getY() - other.position.getY()) < 8
  57740. && buttons == other.buttons;;
  57741. }
  57742. };
  57743. RecentMouseDown mouseDowns[4];
  57744. bool mouseMovedSignificantlySincePressed;
  57745. int64 lastTime;
  57746. void registerMouseDown (const Point<int>& screenPos, const int64 time,
  57747. Component* const component, const ModifierKeys& modifiers) throw()
  57748. {
  57749. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57750. mouseDowns[i] = mouseDowns[i - 1];
  57751. mouseDowns[0].position = screenPos;
  57752. mouseDowns[0].time = time;
  57753. mouseDowns[0].component = component;
  57754. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57755. mouseMovedSignificantlySincePressed = false;
  57756. }
  57757. void registerMouseDrag (const Point<int>& screenPos) throw()
  57758. {
  57759. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57760. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57761. }
  57762. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57763. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57764. };
  57765. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57766. {
  57767. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57768. }
  57769. MouseInputSource::~MouseInputSource()
  57770. {
  57771. }
  57772. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57773. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57774. bool MouseInputSource::canHover() const { return isMouse(); }
  57775. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57776. int MouseInputSource::getIndex() const { return pimpl->index; }
  57777. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57778. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57779. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57780. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57781. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57782. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57783. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57784. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57785. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57786. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57787. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57788. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57789. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57790. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57791. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57792. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57793. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57794. {
  57795. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57796. }
  57797. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57798. {
  57799. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57800. }
  57801. END_JUCE_NAMESPACE
  57802. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57803. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57804. BEGIN_JUCE_NAMESPACE
  57805. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57806. : source (0),
  57807. hoverTimeMillisecs (hoverTimeMillisecs_),
  57808. hasJustHovered (false)
  57809. {
  57810. internalTimer.owner = this;
  57811. }
  57812. MouseHoverDetector::~MouseHoverDetector()
  57813. {
  57814. setHoverComponent (0);
  57815. }
  57816. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57817. {
  57818. hoverTimeMillisecs = newTimeInMillisecs;
  57819. }
  57820. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57821. {
  57822. if (source != newSourceComponent)
  57823. {
  57824. internalTimer.stopTimer();
  57825. hasJustHovered = false;
  57826. if (source != 0)
  57827. source->removeMouseListener (&internalTimer);
  57828. source = newSourceComponent;
  57829. if (newSourceComponent != 0)
  57830. newSourceComponent->addMouseListener (&internalTimer, false);
  57831. }
  57832. }
  57833. void MouseHoverDetector::hoverTimerCallback()
  57834. {
  57835. internalTimer.stopTimer();
  57836. if (source != 0)
  57837. {
  57838. const Point<int> pos (source->getMouseXYRelative());
  57839. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57840. {
  57841. hasJustHovered = true;
  57842. mouseHovered (pos.getX(), pos.getY());
  57843. }
  57844. }
  57845. }
  57846. void MouseHoverDetector::checkJustHoveredCallback()
  57847. {
  57848. if (hasJustHovered)
  57849. {
  57850. hasJustHovered = false;
  57851. mouseMovedAfterHover();
  57852. }
  57853. }
  57854. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57855. {
  57856. owner->hoverTimerCallback();
  57857. }
  57858. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57859. {
  57860. stopTimer();
  57861. owner->checkJustHoveredCallback();
  57862. }
  57863. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57864. {
  57865. stopTimer();
  57866. owner->checkJustHoveredCallback();
  57867. }
  57868. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57869. {
  57870. stopTimer();
  57871. owner->checkJustHoveredCallback();
  57872. }
  57873. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57874. {
  57875. stopTimer();
  57876. owner->checkJustHoveredCallback();
  57877. }
  57878. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57879. {
  57880. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57881. {
  57882. lastX = e.x;
  57883. lastY = e.y;
  57884. if (owner->source != 0)
  57885. startTimer (owner->hoverTimeMillisecs);
  57886. owner->checkJustHoveredCallback();
  57887. }
  57888. }
  57889. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57890. {
  57891. stopTimer();
  57892. owner->checkJustHoveredCallback();
  57893. }
  57894. END_JUCE_NAMESPACE
  57895. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57896. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57897. BEGIN_JUCE_NAMESPACE
  57898. void MouseListener::mouseEnter (const MouseEvent&)
  57899. {
  57900. }
  57901. void MouseListener::mouseExit (const MouseEvent&)
  57902. {
  57903. }
  57904. void MouseListener::mouseDown (const MouseEvent&)
  57905. {
  57906. }
  57907. void MouseListener::mouseUp (const MouseEvent&)
  57908. {
  57909. }
  57910. void MouseListener::mouseDrag (const MouseEvent&)
  57911. {
  57912. }
  57913. void MouseListener::mouseMove (const MouseEvent&)
  57914. {
  57915. }
  57916. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57917. {
  57918. }
  57919. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57920. {
  57921. }
  57922. END_JUCE_NAMESPACE
  57923. /*** End of inlined file: juce_MouseListener.cpp ***/
  57924. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57925. BEGIN_JUCE_NAMESPACE
  57926. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57927. const String& buttonTextWhenTrue,
  57928. const String& buttonTextWhenFalse)
  57929. : PropertyComponent (name),
  57930. onText (buttonTextWhenTrue),
  57931. offText (buttonTextWhenFalse)
  57932. {
  57933. addAndMakeVisible (&button);
  57934. button.setClickingTogglesState (false);
  57935. button.addButtonListener (this);
  57936. }
  57937. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57938. const String& name,
  57939. const String& buttonText)
  57940. : PropertyComponent (name),
  57941. onText (buttonText),
  57942. offText (buttonText)
  57943. {
  57944. addAndMakeVisible (&button);
  57945. button.setClickingTogglesState (false);
  57946. button.setButtonText (buttonText);
  57947. button.getToggleStateValue().referTo (valueToControl);
  57948. button.setClickingTogglesState (true);
  57949. }
  57950. BooleanPropertyComponent::~BooleanPropertyComponent()
  57951. {
  57952. }
  57953. void BooleanPropertyComponent::setState (const bool newState)
  57954. {
  57955. button.setToggleState (newState, true);
  57956. }
  57957. bool BooleanPropertyComponent::getState() const
  57958. {
  57959. return button.getToggleState();
  57960. }
  57961. void BooleanPropertyComponent::paint (Graphics& g)
  57962. {
  57963. PropertyComponent::paint (g);
  57964. g.setColour (Colours::white);
  57965. g.fillRect (button.getBounds());
  57966. g.setColour (findColour (ComboBox::outlineColourId));
  57967. g.drawRect (button.getBounds());
  57968. }
  57969. void BooleanPropertyComponent::refresh()
  57970. {
  57971. button.setToggleState (getState(), false);
  57972. button.setButtonText (button.getToggleState() ? onText : offText);
  57973. }
  57974. void BooleanPropertyComponent::buttonClicked (Button*)
  57975. {
  57976. setState (! getState());
  57977. }
  57978. END_JUCE_NAMESPACE
  57979. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57980. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57981. BEGIN_JUCE_NAMESPACE
  57982. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57983. const bool triggerOnMouseDown)
  57984. : PropertyComponent (name)
  57985. {
  57986. addAndMakeVisible (&button);
  57987. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57988. button.addButtonListener (this);
  57989. }
  57990. ButtonPropertyComponent::~ButtonPropertyComponent()
  57991. {
  57992. }
  57993. void ButtonPropertyComponent::refresh()
  57994. {
  57995. button.setButtonText (getButtonText());
  57996. }
  57997. void ButtonPropertyComponent::buttonClicked (Button*)
  57998. {
  57999. buttonClicked();
  58000. }
  58001. END_JUCE_NAMESPACE
  58002. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58003. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58004. BEGIN_JUCE_NAMESPACE
  58005. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58006. public ValueListener
  58007. {
  58008. public:
  58009. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58010. : sourceValue (sourceValue_),
  58011. mappings (mappings_)
  58012. {
  58013. sourceValue.addListener (this);
  58014. }
  58015. ~RemapperValueSource() {}
  58016. const var getValue() const
  58017. {
  58018. return mappings.indexOf (sourceValue.getValue()) + 1;
  58019. }
  58020. void setValue (const var& newValue)
  58021. {
  58022. const var remappedVal (mappings [(int) newValue - 1]);
  58023. if (remappedVal != sourceValue)
  58024. sourceValue = remappedVal;
  58025. }
  58026. void valueChanged (Value&)
  58027. {
  58028. sendChangeMessage (true);
  58029. }
  58030. juce_UseDebuggingNewOperator
  58031. protected:
  58032. Value sourceValue;
  58033. Array<var> mappings;
  58034. RemapperValueSource (const RemapperValueSource&);
  58035. const RemapperValueSource& operator= (const RemapperValueSource&);
  58036. };
  58037. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58038. : PropertyComponent (name),
  58039. isCustomClass (true)
  58040. {
  58041. }
  58042. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58043. const String& name,
  58044. const StringArray& choices_,
  58045. const Array <var>& correspondingValues)
  58046. : PropertyComponent (name),
  58047. choices (choices_),
  58048. isCustomClass (false)
  58049. {
  58050. // The array of corresponding values must contain one value for each of the items in
  58051. // the choices array!
  58052. jassert (correspondingValues.size() == choices.size());
  58053. createComboBox();
  58054. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58055. }
  58056. ChoicePropertyComponent::~ChoicePropertyComponent()
  58057. {
  58058. }
  58059. void ChoicePropertyComponent::createComboBox()
  58060. {
  58061. addAndMakeVisible (&comboBox);
  58062. for (int i = 0; i < choices.size(); ++i)
  58063. {
  58064. if (choices[i].isNotEmpty())
  58065. comboBox.addItem (choices[i], i + 1);
  58066. else
  58067. comboBox.addSeparator();
  58068. }
  58069. comboBox.setEditableText (false);
  58070. }
  58071. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58072. {
  58073. jassertfalse; // you need to override this method in your subclass!
  58074. }
  58075. int ChoicePropertyComponent::getIndex() const
  58076. {
  58077. jassertfalse; // you need to override this method in your subclass!
  58078. return -1;
  58079. }
  58080. const StringArray& ChoicePropertyComponent::getChoices() const
  58081. {
  58082. return choices;
  58083. }
  58084. void ChoicePropertyComponent::refresh()
  58085. {
  58086. if (isCustomClass)
  58087. {
  58088. if (! comboBox.isVisible())
  58089. {
  58090. createComboBox();
  58091. comboBox.addListener (this);
  58092. }
  58093. comboBox.setSelectedId (getIndex() + 1, true);
  58094. }
  58095. }
  58096. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58097. {
  58098. if (isCustomClass)
  58099. {
  58100. const int newIndex = comboBox.getSelectedId() - 1;
  58101. if (newIndex != getIndex())
  58102. setIndex (newIndex);
  58103. }
  58104. }
  58105. END_JUCE_NAMESPACE
  58106. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58107. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58108. BEGIN_JUCE_NAMESPACE
  58109. PropertyComponent::PropertyComponent (const String& name,
  58110. const int preferredHeight_)
  58111. : Component (name),
  58112. preferredHeight (preferredHeight_)
  58113. {
  58114. jassert (name.isNotEmpty());
  58115. }
  58116. PropertyComponent::~PropertyComponent()
  58117. {
  58118. }
  58119. void PropertyComponent::paint (Graphics& g)
  58120. {
  58121. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58122. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58123. }
  58124. void PropertyComponent::resized()
  58125. {
  58126. if (getNumChildComponents() > 0)
  58127. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58128. }
  58129. void PropertyComponent::enablementChanged()
  58130. {
  58131. repaint();
  58132. }
  58133. END_JUCE_NAMESPACE
  58134. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58135. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58136. BEGIN_JUCE_NAMESPACE
  58137. class PropertySectionComponent : public Component
  58138. {
  58139. public:
  58140. PropertySectionComponent (const String& sectionTitle,
  58141. const Array <PropertyComponent*>& newProperties,
  58142. const bool sectionIsOpen_)
  58143. : Component (sectionTitle),
  58144. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58145. sectionIsOpen (sectionIsOpen_)
  58146. {
  58147. propertyComps.addArray (newProperties);
  58148. for (int i = propertyComps.size(); --i >= 0;)
  58149. {
  58150. addAndMakeVisible (propertyComps.getUnchecked(i));
  58151. propertyComps.getUnchecked(i)->refresh();
  58152. }
  58153. }
  58154. ~PropertySectionComponent()
  58155. {
  58156. propertyComps.clear();
  58157. }
  58158. void paint (Graphics& g)
  58159. {
  58160. if (titleHeight > 0)
  58161. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58162. }
  58163. void resized()
  58164. {
  58165. int y = titleHeight;
  58166. for (int i = 0; i < propertyComps.size(); ++i)
  58167. {
  58168. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  58169. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  58170. y = pec->getBottom();
  58171. }
  58172. }
  58173. int getPreferredHeight() const
  58174. {
  58175. int y = titleHeight;
  58176. if (isOpen())
  58177. {
  58178. for (int i = propertyComps.size(); --i >= 0;)
  58179. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  58180. }
  58181. return y;
  58182. }
  58183. void setOpen (const bool open)
  58184. {
  58185. if (sectionIsOpen != open)
  58186. {
  58187. sectionIsOpen = open;
  58188. for (int i = propertyComps.size(); --i >= 0;)
  58189. propertyComps.getUnchecked(i)->setVisible (open);
  58190. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58191. if (pp != 0)
  58192. pp->resized();
  58193. }
  58194. }
  58195. bool isOpen() const
  58196. {
  58197. return sectionIsOpen;
  58198. }
  58199. void refreshAll() const
  58200. {
  58201. for (int i = propertyComps.size(); --i >= 0;)
  58202. propertyComps.getUnchecked (i)->refresh();
  58203. }
  58204. void mouseUp (const MouseEvent& e)
  58205. {
  58206. if (e.getMouseDownX() < titleHeight
  58207. && e.x < titleHeight
  58208. && e.y < titleHeight
  58209. && e.getNumberOfClicks() != 2)
  58210. {
  58211. setOpen (! isOpen());
  58212. }
  58213. }
  58214. void mouseDoubleClick (const MouseEvent& e)
  58215. {
  58216. if (e.y < titleHeight)
  58217. setOpen (! isOpen());
  58218. }
  58219. private:
  58220. OwnedArray <PropertyComponent> propertyComps;
  58221. int titleHeight;
  58222. bool sectionIsOpen;
  58223. PropertySectionComponent (const PropertySectionComponent&);
  58224. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58225. };
  58226. class PropertyPanel::PropertyHolderComponent : public Component
  58227. {
  58228. public:
  58229. PropertyHolderComponent() {}
  58230. void paint (Graphics&) {}
  58231. void updateLayout (int width)
  58232. {
  58233. int y = 0;
  58234. for (int i = 0; i < sections.size(); ++i)
  58235. {
  58236. PropertySectionComponent* const section = sections.getUnchecked(i);
  58237. section->setBounds (0, y, width, section->getPreferredHeight());
  58238. y = section->getBottom();
  58239. }
  58240. setSize (width, y);
  58241. repaint();
  58242. }
  58243. void refreshAll() const
  58244. {
  58245. for (int i = 0; i < sections.size(); ++i)
  58246. sections.getUnchecked(i)->refreshAll();
  58247. }
  58248. void clear()
  58249. {
  58250. sections.clear();
  58251. }
  58252. void addSection (PropertySectionComponent* newSection)
  58253. {
  58254. sections.add (newSection);
  58255. addAndMakeVisible (newSection, 0);
  58256. }
  58257. int getNumSections() const throw() { return sections.size(); }
  58258. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58259. private:
  58260. OwnedArray<PropertySectionComponent> sections;
  58261. PropertyHolderComponent (const PropertyHolderComponent&);
  58262. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58263. };
  58264. PropertyPanel::PropertyPanel()
  58265. {
  58266. messageWhenEmpty = TRANS("(nothing selected)");
  58267. addAndMakeVisible (&viewport);
  58268. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58269. viewport.setFocusContainer (true);
  58270. }
  58271. PropertyPanel::~PropertyPanel()
  58272. {
  58273. clear();
  58274. }
  58275. void PropertyPanel::paint (Graphics& g)
  58276. {
  58277. if (propertyHolderComponent->getNumSections() == 0)
  58278. {
  58279. g.setColour (Colours::black.withAlpha (0.5f));
  58280. g.setFont (14.0f);
  58281. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58282. Justification::centred, true);
  58283. }
  58284. }
  58285. void PropertyPanel::resized()
  58286. {
  58287. viewport.setBounds (getLocalBounds());
  58288. updatePropHolderLayout();
  58289. }
  58290. void PropertyPanel::clear()
  58291. {
  58292. if (propertyHolderComponent->getNumSections() > 0)
  58293. {
  58294. propertyHolderComponent->clear();
  58295. repaint();
  58296. }
  58297. }
  58298. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58299. {
  58300. if (propertyHolderComponent->getNumSections() == 0)
  58301. repaint();
  58302. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58303. updatePropHolderLayout();
  58304. }
  58305. void PropertyPanel::addSection (const String& sectionTitle,
  58306. const Array <PropertyComponent*>& newProperties,
  58307. const bool shouldBeOpen)
  58308. {
  58309. jassert (sectionTitle.isNotEmpty());
  58310. if (propertyHolderComponent->getNumSections() == 0)
  58311. repaint();
  58312. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58313. updatePropHolderLayout();
  58314. }
  58315. void PropertyPanel::updatePropHolderLayout() const
  58316. {
  58317. const int maxWidth = viewport.getMaximumVisibleWidth();
  58318. propertyHolderComponent->updateLayout (maxWidth);
  58319. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58320. if (maxWidth != newMaxWidth)
  58321. {
  58322. // need to do this twice because of scrollbars changing the size, etc.
  58323. propertyHolderComponent->updateLayout (newMaxWidth);
  58324. }
  58325. }
  58326. void PropertyPanel::refreshAll() const
  58327. {
  58328. propertyHolderComponent->refreshAll();
  58329. }
  58330. const StringArray PropertyPanel::getSectionNames() const
  58331. {
  58332. StringArray s;
  58333. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58334. {
  58335. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58336. if (section->getName().isNotEmpty())
  58337. s.add (section->getName());
  58338. }
  58339. return s;
  58340. }
  58341. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58342. {
  58343. int index = 0;
  58344. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58345. {
  58346. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58347. if (section->getName().isNotEmpty())
  58348. {
  58349. if (index == sectionIndex)
  58350. return section->isOpen();
  58351. ++index;
  58352. }
  58353. }
  58354. return false;
  58355. }
  58356. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58357. {
  58358. int index = 0;
  58359. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58360. {
  58361. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58362. if (section->getName().isNotEmpty())
  58363. {
  58364. if (index == sectionIndex)
  58365. {
  58366. section->setOpen (shouldBeOpen);
  58367. break;
  58368. }
  58369. ++index;
  58370. }
  58371. }
  58372. }
  58373. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58374. {
  58375. int index = 0;
  58376. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58377. {
  58378. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58379. if (section->getName().isNotEmpty())
  58380. {
  58381. if (index == sectionIndex)
  58382. {
  58383. section->setEnabled (shouldBeEnabled);
  58384. break;
  58385. }
  58386. ++index;
  58387. }
  58388. }
  58389. }
  58390. XmlElement* PropertyPanel::getOpennessState() const
  58391. {
  58392. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58393. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58394. const StringArray sections (getSectionNames());
  58395. for (int i = 0; i < sections.size(); ++i)
  58396. {
  58397. if (sections[i].isNotEmpty())
  58398. {
  58399. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58400. e->setAttribute ("name", sections[i]);
  58401. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58402. }
  58403. }
  58404. return xml;
  58405. }
  58406. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58407. {
  58408. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58409. {
  58410. const StringArray sections (getSectionNames());
  58411. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58412. {
  58413. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58414. e->getBoolAttribute ("open"));
  58415. }
  58416. viewport.setViewPosition (viewport.getViewPositionX(),
  58417. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58418. }
  58419. }
  58420. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58421. {
  58422. if (messageWhenEmpty != newMessage)
  58423. {
  58424. messageWhenEmpty = newMessage;
  58425. repaint();
  58426. }
  58427. }
  58428. const String& PropertyPanel::getMessageWhenEmpty() const
  58429. {
  58430. return messageWhenEmpty;
  58431. }
  58432. END_JUCE_NAMESPACE
  58433. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58434. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58435. BEGIN_JUCE_NAMESPACE
  58436. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58437. const double rangeMin,
  58438. const double rangeMax,
  58439. const double interval,
  58440. const double skewFactor)
  58441. : PropertyComponent (name)
  58442. {
  58443. addAndMakeVisible (&slider);
  58444. slider.setRange (rangeMin, rangeMax, interval);
  58445. slider.setSkewFactor (skewFactor);
  58446. slider.setSliderStyle (Slider::LinearBar);
  58447. slider.addListener (this);
  58448. }
  58449. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58450. const String& name,
  58451. const double rangeMin,
  58452. const double rangeMax,
  58453. const double interval,
  58454. const double skewFactor)
  58455. : PropertyComponent (name)
  58456. {
  58457. addAndMakeVisible (&slider);
  58458. slider.setRange (rangeMin, rangeMax, interval);
  58459. slider.setSkewFactor (skewFactor);
  58460. slider.setSliderStyle (Slider::LinearBar);
  58461. slider.getValueObject().referTo (valueToControl);
  58462. }
  58463. SliderPropertyComponent::~SliderPropertyComponent()
  58464. {
  58465. }
  58466. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58467. {
  58468. }
  58469. double SliderPropertyComponent::getValue() const
  58470. {
  58471. return slider.getValue();
  58472. }
  58473. void SliderPropertyComponent::refresh()
  58474. {
  58475. slider.setValue (getValue(), false);
  58476. }
  58477. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58478. {
  58479. if (getValue() != slider.getValue())
  58480. setValue (slider.getValue());
  58481. }
  58482. END_JUCE_NAMESPACE
  58483. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58484. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58485. BEGIN_JUCE_NAMESPACE
  58486. class TextPropLabel : public Label
  58487. {
  58488. public:
  58489. TextPropLabel (TextPropertyComponent& owner_,
  58490. const int maxChars_, const bool isMultiline_)
  58491. : Label (String::empty, String::empty),
  58492. owner (owner_),
  58493. maxChars (maxChars_),
  58494. isMultiline (isMultiline_)
  58495. {
  58496. setEditable (true, true, false);
  58497. setColour (backgroundColourId, Colours::white);
  58498. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58499. }
  58500. TextEditor* createEditorComponent()
  58501. {
  58502. TextEditor* const textEditor = Label::createEditorComponent();
  58503. textEditor->setInputRestrictions (maxChars);
  58504. if (isMultiline)
  58505. {
  58506. textEditor->setMultiLine (true, true);
  58507. textEditor->setReturnKeyStartsNewLine (true);
  58508. }
  58509. return textEditor;
  58510. }
  58511. void textWasEdited()
  58512. {
  58513. owner.textWasEdited();
  58514. }
  58515. private:
  58516. TextPropertyComponent& owner;
  58517. int maxChars;
  58518. bool isMultiline;
  58519. };
  58520. TextPropertyComponent::TextPropertyComponent (const String& name,
  58521. const int maxNumChars,
  58522. const bool isMultiLine)
  58523. : PropertyComponent (name)
  58524. {
  58525. createEditor (maxNumChars, isMultiLine);
  58526. }
  58527. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58528. const String& name,
  58529. const int maxNumChars,
  58530. const bool isMultiLine)
  58531. : PropertyComponent (name)
  58532. {
  58533. createEditor (maxNumChars, isMultiLine);
  58534. textEditor->getTextValue().referTo (valueToControl);
  58535. }
  58536. TextPropertyComponent::~TextPropertyComponent()
  58537. {
  58538. }
  58539. void TextPropertyComponent::setText (const String& newText)
  58540. {
  58541. textEditor->setText (newText, true);
  58542. }
  58543. const String TextPropertyComponent::getText() const
  58544. {
  58545. return textEditor->getText();
  58546. }
  58547. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58548. {
  58549. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58550. if (isMultiLine)
  58551. {
  58552. textEditor->setJustificationType (Justification::topLeft);
  58553. preferredHeight = 120;
  58554. }
  58555. }
  58556. void TextPropertyComponent::refresh()
  58557. {
  58558. textEditor->setText (getText(), false);
  58559. }
  58560. void TextPropertyComponent::textWasEdited()
  58561. {
  58562. const String newText (textEditor->getText());
  58563. if (getText() != newText)
  58564. setText (newText);
  58565. }
  58566. END_JUCE_NAMESPACE
  58567. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58568. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58569. BEGIN_JUCE_NAMESPACE
  58570. class SimpleDeviceManagerInputLevelMeter : public Component,
  58571. public Timer
  58572. {
  58573. public:
  58574. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58575. : manager (manager_),
  58576. level (0)
  58577. {
  58578. startTimer (50);
  58579. manager->enableInputLevelMeasurement (true);
  58580. }
  58581. ~SimpleDeviceManagerInputLevelMeter()
  58582. {
  58583. manager->enableInputLevelMeasurement (false);
  58584. }
  58585. void timerCallback()
  58586. {
  58587. const float newLevel = (float) manager->getCurrentInputLevel();
  58588. if (std::abs (level - newLevel) > 0.005f)
  58589. {
  58590. level = newLevel;
  58591. repaint();
  58592. }
  58593. }
  58594. void paint (Graphics& g)
  58595. {
  58596. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58597. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58598. }
  58599. private:
  58600. AudioDeviceManager* const manager;
  58601. float level;
  58602. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58603. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58604. };
  58605. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58606. public ListBoxModel
  58607. {
  58608. public:
  58609. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58610. const String& noItemsMessage_,
  58611. const int minNumber_,
  58612. const int maxNumber_)
  58613. : ListBox (String::empty, 0),
  58614. deviceManager (deviceManager_),
  58615. noItemsMessage (noItemsMessage_),
  58616. minNumber (minNumber_),
  58617. maxNumber (maxNumber_)
  58618. {
  58619. items = MidiInput::getDevices();
  58620. setModel (this);
  58621. setOutlineThickness (1);
  58622. }
  58623. ~MidiInputSelectorComponentListBox()
  58624. {
  58625. }
  58626. int getNumRows()
  58627. {
  58628. return items.size();
  58629. }
  58630. void paintListBoxItem (int row,
  58631. Graphics& g,
  58632. int width, int height,
  58633. bool rowIsSelected)
  58634. {
  58635. if (((unsigned int) row) < (unsigned int) items.size())
  58636. {
  58637. if (rowIsSelected)
  58638. g.fillAll (findColour (TextEditor::highlightColourId)
  58639. .withMultipliedAlpha (0.3f));
  58640. const String item (items [row]);
  58641. bool enabled = deviceManager.isMidiInputEnabled (item);
  58642. const int x = getTickX();
  58643. const float tickW = height * 0.75f;
  58644. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58645. enabled, true, true, false);
  58646. g.setFont (height * 0.6f);
  58647. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58648. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58649. }
  58650. }
  58651. void listBoxItemClicked (int row, const MouseEvent& e)
  58652. {
  58653. selectRow (row);
  58654. if (e.x < getTickX())
  58655. flipEnablement (row);
  58656. }
  58657. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58658. {
  58659. flipEnablement (row);
  58660. }
  58661. void returnKeyPressed (int row)
  58662. {
  58663. flipEnablement (row);
  58664. }
  58665. void paint (Graphics& g)
  58666. {
  58667. ListBox::paint (g);
  58668. if (items.size() == 0)
  58669. {
  58670. g.setColour (Colours::grey);
  58671. g.setFont (13.0f);
  58672. g.drawText (noItemsMessage,
  58673. 0, 0, getWidth(), getHeight() / 2,
  58674. Justification::centred, true);
  58675. }
  58676. }
  58677. int getBestHeight (const int preferredHeight)
  58678. {
  58679. const int extra = getOutlineThickness() * 2;
  58680. return jmax (getRowHeight() * 2 + extra,
  58681. jmin (getRowHeight() * getNumRows() + extra,
  58682. preferredHeight));
  58683. }
  58684. juce_UseDebuggingNewOperator
  58685. private:
  58686. AudioDeviceManager& deviceManager;
  58687. const String noItemsMessage;
  58688. StringArray items;
  58689. int minNumber, maxNumber;
  58690. void flipEnablement (const int row)
  58691. {
  58692. if (((unsigned int) row) < (unsigned int) items.size())
  58693. {
  58694. const String item (items [row]);
  58695. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58696. }
  58697. }
  58698. int getTickX() const
  58699. {
  58700. return getRowHeight() + 5;
  58701. }
  58702. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58703. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58704. };
  58705. class AudioDeviceSettingsPanel : public Component,
  58706. public ChangeListener,
  58707. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58708. public ButtonListener
  58709. {
  58710. public:
  58711. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58712. AudioIODeviceType::DeviceSetupDetails& setup_,
  58713. const bool hideAdvancedOptionsWithButton)
  58714. : type (type_),
  58715. setup (setup_)
  58716. {
  58717. if (hideAdvancedOptionsWithButton)
  58718. {
  58719. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58720. showAdvancedSettingsButton->addButtonListener (this);
  58721. }
  58722. type->scanForDevices();
  58723. setup.manager->addChangeListener (this);
  58724. changeListenerCallback (0);
  58725. }
  58726. ~AudioDeviceSettingsPanel()
  58727. {
  58728. setup.manager->removeChangeListener (this);
  58729. }
  58730. void resized()
  58731. {
  58732. const int lx = proportionOfWidth (0.35f);
  58733. const int w = proportionOfWidth (0.4f);
  58734. const int h = 24;
  58735. const int space = 6;
  58736. const int dh = h + space;
  58737. int y = 0;
  58738. if (outputDeviceDropDown != 0)
  58739. {
  58740. outputDeviceDropDown->setBounds (lx, y, w, h);
  58741. if (testButton != 0)
  58742. testButton->setBounds (proportionOfWidth (0.77f),
  58743. outputDeviceDropDown->getY(),
  58744. proportionOfWidth (0.18f),
  58745. h);
  58746. y += dh;
  58747. }
  58748. if (inputDeviceDropDown != 0)
  58749. {
  58750. inputDeviceDropDown->setBounds (lx, y, w, h);
  58751. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58752. inputDeviceDropDown->getY(),
  58753. proportionOfWidth (0.18f),
  58754. h);
  58755. y += dh;
  58756. }
  58757. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58758. if (outputChanList != 0)
  58759. {
  58760. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58761. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58762. y += bh + space;
  58763. }
  58764. if (inputChanList != 0)
  58765. {
  58766. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58767. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58768. y += bh + space;
  58769. }
  58770. y += space * 2;
  58771. if (showAdvancedSettingsButton != 0)
  58772. {
  58773. showAdvancedSettingsButton->changeWidthToFitText (h);
  58774. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58775. }
  58776. if (sampleRateDropDown != 0)
  58777. {
  58778. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58779. || ! showAdvancedSettingsButton->isVisible());
  58780. sampleRateDropDown->setBounds (lx, y, w, h);
  58781. y += dh;
  58782. }
  58783. if (bufferSizeDropDown != 0)
  58784. {
  58785. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58786. || ! showAdvancedSettingsButton->isVisible());
  58787. bufferSizeDropDown->setBounds (lx, y, w, h);
  58788. y += dh;
  58789. }
  58790. if (showUIButton != 0)
  58791. {
  58792. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58793. || ! showAdvancedSettingsButton->isVisible());
  58794. showUIButton->changeWidthToFitText (h);
  58795. showUIButton->setTopLeftPosition (lx, y);
  58796. }
  58797. }
  58798. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58799. {
  58800. if (comboBoxThatHasChanged == 0)
  58801. return;
  58802. AudioDeviceManager::AudioDeviceSetup config;
  58803. setup.manager->getAudioDeviceSetup (config);
  58804. String error;
  58805. if (comboBoxThatHasChanged == outputDeviceDropDown
  58806. || comboBoxThatHasChanged == inputDeviceDropDown)
  58807. {
  58808. if (outputDeviceDropDown != 0)
  58809. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58810. : outputDeviceDropDown->getText();
  58811. if (inputDeviceDropDown != 0)
  58812. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58813. : inputDeviceDropDown->getText();
  58814. if (! type->hasSeparateInputsAndOutputs())
  58815. config.inputDeviceName = config.outputDeviceName;
  58816. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58817. config.useDefaultInputChannels = true;
  58818. else
  58819. config.useDefaultOutputChannels = true;
  58820. error = setup.manager->setAudioDeviceSetup (config, true);
  58821. showCorrectDeviceName (inputDeviceDropDown, true);
  58822. showCorrectDeviceName (outputDeviceDropDown, false);
  58823. updateControlPanelButton();
  58824. resized();
  58825. }
  58826. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58827. {
  58828. if (sampleRateDropDown->getSelectedId() > 0)
  58829. {
  58830. config.sampleRate = sampleRateDropDown->getSelectedId();
  58831. error = setup.manager->setAudioDeviceSetup (config, true);
  58832. }
  58833. }
  58834. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58835. {
  58836. if (bufferSizeDropDown->getSelectedId() > 0)
  58837. {
  58838. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58839. error = setup.manager->setAudioDeviceSetup (config, true);
  58840. }
  58841. }
  58842. if (error.isNotEmpty())
  58843. {
  58844. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58845. "Error when trying to open audio device!",
  58846. error);
  58847. }
  58848. }
  58849. void buttonClicked (Button* button)
  58850. {
  58851. if (button == showAdvancedSettingsButton)
  58852. {
  58853. showAdvancedSettingsButton->setVisible (false);
  58854. resized();
  58855. }
  58856. else if (button == showUIButton)
  58857. {
  58858. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58859. if (device != 0 && device->showControlPanel())
  58860. {
  58861. setup.manager->closeAudioDevice();
  58862. setup.manager->restartLastAudioDevice();
  58863. getTopLevelComponent()->toFront (true);
  58864. }
  58865. }
  58866. else if (button == testButton && testButton != 0)
  58867. {
  58868. setup.manager->playTestSound();
  58869. }
  58870. }
  58871. void updateControlPanelButton()
  58872. {
  58873. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58874. showUIButton = 0;
  58875. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58876. {
  58877. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58878. TRANS ("opens the device's own control panel")));
  58879. showUIButton->addButtonListener (this);
  58880. }
  58881. resized();
  58882. }
  58883. void changeListenerCallback (ChangeBroadcaster*)
  58884. {
  58885. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58886. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58887. {
  58888. if (outputDeviceDropDown == 0)
  58889. {
  58890. outputDeviceDropDown = new ComboBox (String::empty);
  58891. outputDeviceDropDown->addListener (this);
  58892. addAndMakeVisible (outputDeviceDropDown);
  58893. outputDeviceLabel = new Label (String::empty,
  58894. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58895. : TRANS ("device:"));
  58896. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58897. if (setup.maxNumOutputChannels > 0)
  58898. {
  58899. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58900. testButton->addButtonListener (this);
  58901. }
  58902. }
  58903. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58904. }
  58905. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58906. {
  58907. if (inputDeviceDropDown == 0)
  58908. {
  58909. inputDeviceDropDown = new ComboBox (String::empty);
  58910. inputDeviceDropDown->addListener (this);
  58911. addAndMakeVisible (inputDeviceDropDown);
  58912. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58913. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58914. addAndMakeVisible (inputLevelMeter
  58915. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58916. }
  58917. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58918. }
  58919. updateControlPanelButton();
  58920. showCorrectDeviceName (inputDeviceDropDown, true);
  58921. showCorrectDeviceName (outputDeviceDropDown, false);
  58922. if (currentDevice != 0)
  58923. {
  58924. if (setup.maxNumOutputChannels > 0
  58925. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58926. {
  58927. if (outputChanList == 0)
  58928. {
  58929. addAndMakeVisible (outputChanList
  58930. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58931. TRANS ("(no audio output channels found)")));
  58932. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58933. outputChanLabel->attachToComponent (outputChanList, true);
  58934. }
  58935. outputChanList->refresh();
  58936. }
  58937. else
  58938. {
  58939. outputChanLabel = 0;
  58940. outputChanList = 0;
  58941. }
  58942. if (setup.maxNumInputChannels > 0
  58943. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58944. {
  58945. if (inputChanList == 0)
  58946. {
  58947. addAndMakeVisible (inputChanList
  58948. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58949. TRANS ("(no audio input channels found)")));
  58950. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58951. inputChanLabel->attachToComponent (inputChanList, true);
  58952. }
  58953. inputChanList->refresh();
  58954. }
  58955. else
  58956. {
  58957. inputChanLabel = 0;
  58958. inputChanList = 0;
  58959. }
  58960. // sample rate..
  58961. {
  58962. if (sampleRateDropDown == 0)
  58963. {
  58964. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58965. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58966. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58967. }
  58968. else
  58969. {
  58970. sampleRateDropDown->clear();
  58971. sampleRateDropDown->removeListener (this);
  58972. }
  58973. const int numRates = currentDevice->getNumSampleRates();
  58974. for (int i = 0; i < numRates; ++i)
  58975. {
  58976. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58977. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58978. }
  58979. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58980. sampleRateDropDown->addListener (this);
  58981. }
  58982. // buffer size
  58983. {
  58984. if (bufferSizeDropDown == 0)
  58985. {
  58986. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58987. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58988. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58989. }
  58990. else
  58991. {
  58992. bufferSizeDropDown->clear();
  58993. bufferSizeDropDown->removeListener (this);
  58994. }
  58995. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58996. double currentRate = currentDevice->getCurrentSampleRate();
  58997. if (currentRate == 0)
  58998. currentRate = 48000.0;
  58999. for (int i = 0; i < numBufferSizes; ++i)
  59000. {
  59001. const int bs = currentDevice->getBufferSizeSamples (i);
  59002. bufferSizeDropDown->addItem (String (bs)
  59003. + " samples ("
  59004. + String (bs * 1000.0 / currentRate, 1)
  59005. + " ms)",
  59006. bs);
  59007. }
  59008. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59009. bufferSizeDropDown->addListener (this);
  59010. }
  59011. }
  59012. else
  59013. {
  59014. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59015. sampleRateLabel = 0;
  59016. bufferSizeLabel = 0;
  59017. sampleRateDropDown = 0;
  59018. bufferSizeDropDown = 0;
  59019. if (outputDeviceDropDown != 0)
  59020. outputDeviceDropDown->setSelectedId (-1, true);
  59021. if (inputDeviceDropDown != 0)
  59022. inputDeviceDropDown->setSelectedId (-1, true);
  59023. }
  59024. resized();
  59025. setSize (getWidth(), getLowestY() + 4);
  59026. }
  59027. private:
  59028. AudioIODeviceType* const type;
  59029. const AudioIODeviceType::DeviceSetupDetails setup;
  59030. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59031. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59032. ScopedPointer<TextButton> testButton;
  59033. ScopedPointer<Component> inputLevelMeter;
  59034. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59035. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59036. {
  59037. if (box != 0)
  59038. {
  59039. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59040. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59041. box->setSelectedId (index + 1, true);
  59042. if (testButton != 0 && ! isInput)
  59043. testButton->setEnabled (index >= 0);
  59044. }
  59045. }
  59046. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59047. {
  59048. const StringArray devs (type->getDeviceNames (isInputs));
  59049. combo.clear (true);
  59050. for (int i = 0; i < devs.size(); ++i)
  59051. combo.addItem (devs[i], i + 1);
  59052. combo.addItem (TRANS("<< none >>"), -1);
  59053. combo.setSelectedId (-1, true);
  59054. }
  59055. int getLowestY() const
  59056. {
  59057. int y = 0;
  59058. for (int i = getNumChildComponents(); --i >= 0;)
  59059. y = jmax (y, getChildComponent (i)->getBottom());
  59060. return y;
  59061. }
  59062. public:
  59063. class ChannelSelectorListBox : public ListBox,
  59064. public ListBoxModel
  59065. {
  59066. public:
  59067. enum BoxType
  59068. {
  59069. audioInputType,
  59070. audioOutputType
  59071. };
  59072. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59073. const BoxType type_,
  59074. const String& noItemsMessage_)
  59075. : ListBox (String::empty, 0),
  59076. setup (setup_),
  59077. type (type_),
  59078. noItemsMessage (noItemsMessage_)
  59079. {
  59080. refresh();
  59081. setModel (this);
  59082. setOutlineThickness (1);
  59083. }
  59084. ~ChannelSelectorListBox()
  59085. {
  59086. }
  59087. void refresh()
  59088. {
  59089. items.clear();
  59090. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59091. if (currentDevice != 0)
  59092. {
  59093. if (type == audioInputType)
  59094. items = currentDevice->getInputChannelNames();
  59095. else if (type == audioOutputType)
  59096. items = currentDevice->getOutputChannelNames();
  59097. if (setup.useStereoPairs)
  59098. {
  59099. StringArray pairs;
  59100. for (int i = 0; i < items.size(); i += 2)
  59101. {
  59102. const String name (items[i]);
  59103. const String name2 (items[i + 1]);
  59104. String commonBit;
  59105. for (int j = 0; j < name.length(); ++j)
  59106. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59107. commonBit = name.substring (0, j);
  59108. // Make sure we only split the name at a space, because otherwise, things
  59109. // like "input 11" + "input 12" would become "input 11 + 2"
  59110. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59111. commonBit = commonBit.dropLastCharacters (1);
  59112. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59113. }
  59114. items = pairs;
  59115. }
  59116. }
  59117. updateContent();
  59118. repaint();
  59119. }
  59120. int getNumRows()
  59121. {
  59122. return items.size();
  59123. }
  59124. void paintListBoxItem (int row,
  59125. Graphics& g,
  59126. int width, int height,
  59127. bool rowIsSelected)
  59128. {
  59129. if (((unsigned int) row) < (unsigned int) items.size())
  59130. {
  59131. if (rowIsSelected)
  59132. g.fillAll (findColour (TextEditor::highlightColourId)
  59133. .withMultipliedAlpha (0.3f));
  59134. const String item (items [row]);
  59135. bool enabled = false;
  59136. AudioDeviceManager::AudioDeviceSetup config;
  59137. setup.manager->getAudioDeviceSetup (config);
  59138. if (setup.useStereoPairs)
  59139. {
  59140. if (type == audioInputType)
  59141. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59142. else if (type == audioOutputType)
  59143. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59144. }
  59145. else
  59146. {
  59147. if (type == audioInputType)
  59148. enabled = config.inputChannels [row];
  59149. else if (type == audioOutputType)
  59150. enabled = config.outputChannels [row];
  59151. }
  59152. const int x = getTickX();
  59153. const float tickW = height * 0.75f;
  59154. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59155. enabled, true, true, false);
  59156. g.setFont (height * 0.6f);
  59157. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59158. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59159. }
  59160. }
  59161. void listBoxItemClicked (int row, const MouseEvent& e)
  59162. {
  59163. selectRow (row);
  59164. if (e.x < getTickX())
  59165. flipEnablement (row);
  59166. }
  59167. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59168. {
  59169. flipEnablement (row);
  59170. }
  59171. void returnKeyPressed (int row)
  59172. {
  59173. flipEnablement (row);
  59174. }
  59175. void paint (Graphics& g)
  59176. {
  59177. ListBox::paint (g);
  59178. if (items.size() == 0)
  59179. {
  59180. g.setColour (Colours::grey);
  59181. g.setFont (13.0f);
  59182. g.drawText (noItemsMessage,
  59183. 0, 0, getWidth(), getHeight() / 2,
  59184. Justification::centred, true);
  59185. }
  59186. }
  59187. int getBestHeight (int maxHeight)
  59188. {
  59189. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59190. getNumRows())
  59191. + getOutlineThickness() * 2;
  59192. }
  59193. juce_UseDebuggingNewOperator
  59194. private:
  59195. const AudioIODeviceType::DeviceSetupDetails setup;
  59196. const BoxType type;
  59197. const String noItemsMessage;
  59198. StringArray items;
  59199. void flipEnablement (const int row)
  59200. {
  59201. jassert (type == audioInputType || type == audioOutputType);
  59202. if (((unsigned int) row) < (unsigned int) items.size())
  59203. {
  59204. AudioDeviceManager::AudioDeviceSetup config;
  59205. setup.manager->getAudioDeviceSetup (config);
  59206. if (setup.useStereoPairs)
  59207. {
  59208. BigInteger bits;
  59209. BigInteger& original = (type == audioInputType ? config.inputChannels
  59210. : config.outputChannels);
  59211. int i;
  59212. for (i = 0; i < 256; i += 2)
  59213. bits.setBit (i / 2, original [i] || original [i + 1]);
  59214. if (type == audioInputType)
  59215. {
  59216. config.useDefaultInputChannels = false;
  59217. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59218. }
  59219. else
  59220. {
  59221. config.useDefaultOutputChannels = false;
  59222. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59223. }
  59224. for (i = 0; i < 256; ++i)
  59225. original.setBit (i, bits [i / 2]);
  59226. }
  59227. else
  59228. {
  59229. if (type == audioInputType)
  59230. {
  59231. config.useDefaultInputChannels = false;
  59232. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59233. }
  59234. else
  59235. {
  59236. config.useDefaultOutputChannels = false;
  59237. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59238. }
  59239. }
  59240. String error (setup.manager->setAudioDeviceSetup (config, true));
  59241. if (! error.isEmpty())
  59242. {
  59243. //xxx
  59244. }
  59245. }
  59246. }
  59247. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59248. {
  59249. const int numActive = chans.countNumberOfSetBits();
  59250. if (chans [index])
  59251. {
  59252. if (numActive > minNumber)
  59253. chans.setBit (index, false);
  59254. }
  59255. else
  59256. {
  59257. if (numActive >= maxNumber)
  59258. {
  59259. const int firstActiveChan = chans.findNextSetBit();
  59260. chans.setBit (index > firstActiveChan
  59261. ? firstActiveChan : chans.getHighestBit(),
  59262. false);
  59263. }
  59264. chans.setBit (index, true);
  59265. }
  59266. }
  59267. int getTickX() const
  59268. {
  59269. return getRowHeight() + 5;
  59270. }
  59271. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59272. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59273. };
  59274. private:
  59275. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59276. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59277. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59278. };
  59279. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59280. const int minInputChannels_,
  59281. const int maxInputChannels_,
  59282. const int minOutputChannels_,
  59283. const int maxOutputChannels_,
  59284. const bool showMidiInputOptions,
  59285. const bool showMidiOutputSelector,
  59286. const bool showChannelsAsStereoPairs_,
  59287. const bool hideAdvancedOptionsWithButton_)
  59288. : deviceManager (deviceManager_),
  59289. deviceTypeDropDown (0),
  59290. deviceTypeDropDownLabel (0),
  59291. minOutputChannels (minOutputChannels_),
  59292. maxOutputChannels (maxOutputChannels_),
  59293. minInputChannels (minInputChannels_),
  59294. maxInputChannels (maxInputChannels_),
  59295. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59296. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59297. {
  59298. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59299. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59300. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59301. {
  59302. deviceTypeDropDown = new ComboBox (String::empty);
  59303. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59304. {
  59305. deviceTypeDropDown
  59306. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59307. i + 1);
  59308. }
  59309. addAndMakeVisible (deviceTypeDropDown);
  59310. deviceTypeDropDown->addListener (this);
  59311. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59312. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59313. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59314. }
  59315. if (showMidiInputOptions)
  59316. {
  59317. addAndMakeVisible (midiInputsList
  59318. = new MidiInputSelectorComponentListBox (deviceManager,
  59319. TRANS("(no midi inputs available)"),
  59320. 0, 0));
  59321. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59322. midiInputsLabel->setJustificationType (Justification::topRight);
  59323. midiInputsLabel->attachToComponent (midiInputsList, true);
  59324. }
  59325. else
  59326. {
  59327. midiInputsList = 0;
  59328. midiInputsLabel = 0;
  59329. }
  59330. if (showMidiOutputSelector)
  59331. {
  59332. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59333. midiOutputSelector->addListener (this);
  59334. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59335. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59336. }
  59337. else
  59338. {
  59339. midiOutputSelector = 0;
  59340. midiOutputLabel = 0;
  59341. }
  59342. deviceManager_.addChangeListener (this);
  59343. changeListenerCallback (0);
  59344. }
  59345. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59346. {
  59347. deviceManager.removeChangeListener (this);
  59348. }
  59349. void AudioDeviceSelectorComponent::resized()
  59350. {
  59351. const int lx = proportionOfWidth (0.35f);
  59352. const int w = proportionOfWidth (0.4f);
  59353. const int h = 24;
  59354. const int space = 6;
  59355. const int dh = h + space;
  59356. int y = 15;
  59357. if (deviceTypeDropDown != 0)
  59358. {
  59359. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59360. y += dh + space * 2;
  59361. }
  59362. if (audioDeviceSettingsComp != 0)
  59363. {
  59364. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59365. y += audioDeviceSettingsComp->getHeight() + space;
  59366. }
  59367. if (midiInputsList != 0)
  59368. {
  59369. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59370. midiInputsList->setBounds (lx, y, w, bh);
  59371. y += bh + space;
  59372. }
  59373. if (midiOutputSelector != 0)
  59374. midiOutputSelector->setBounds (lx, y, w, h);
  59375. }
  59376. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59377. {
  59378. if (child == audioDeviceSettingsComp)
  59379. resized();
  59380. }
  59381. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59382. {
  59383. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59384. if (device != 0 && device->hasControlPanel())
  59385. {
  59386. if (device->showControlPanel())
  59387. deviceManager.restartLastAudioDevice();
  59388. getTopLevelComponent()->toFront (true);
  59389. }
  59390. }
  59391. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59392. {
  59393. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59394. {
  59395. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59396. if (type != 0)
  59397. {
  59398. audioDeviceSettingsComp = 0;
  59399. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59400. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59401. }
  59402. }
  59403. else if (comboBoxThatHasChanged == midiOutputSelector)
  59404. {
  59405. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59406. }
  59407. }
  59408. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59409. {
  59410. if (deviceTypeDropDown != 0)
  59411. {
  59412. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59413. }
  59414. if (audioDeviceSettingsComp == 0
  59415. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59416. {
  59417. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59418. audioDeviceSettingsComp = 0;
  59419. AudioIODeviceType* const type
  59420. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59421. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59422. if (type != 0)
  59423. {
  59424. AudioIODeviceType::DeviceSetupDetails details;
  59425. details.manager = &deviceManager;
  59426. details.minNumInputChannels = minInputChannels;
  59427. details.maxNumInputChannels = maxInputChannels;
  59428. details.minNumOutputChannels = minOutputChannels;
  59429. details.maxNumOutputChannels = maxOutputChannels;
  59430. details.useStereoPairs = showChannelsAsStereoPairs;
  59431. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59432. if (audioDeviceSettingsComp != 0)
  59433. {
  59434. addAndMakeVisible (audioDeviceSettingsComp);
  59435. audioDeviceSettingsComp->resized();
  59436. }
  59437. }
  59438. }
  59439. if (midiInputsList != 0)
  59440. {
  59441. midiInputsList->updateContent();
  59442. midiInputsList->repaint();
  59443. }
  59444. if (midiOutputSelector != 0)
  59445. {
  59446. midiOutputSelector->clear();
  59447. const StringArray midiOuts (MidiOutput::getDevices());
  59448. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59449. midiOutputSelector->addSeparator();
  59450. for (int i = 0; i < midiOuts.size(); ++i)
  59451. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59452. int current = -1;
  59453. if (deviceManager.getDefaultMidiOutput() != 0)
  59454. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59455. midiOutputSelector->setSelectedId (current, true);
  59456. }
  59457. resized();
  59458. }
  59459. END_JUCE_NAMESPACE
  59460. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59461. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59462. BEGIN_JUCE_NAMESPACE
  59463. BubbleComponent::BubbleComponent()
  59464. : side (0),
  59465. allowablePlacements (above | below | left | right),
  59466. arrowTipX (0.0f),
  59467. arrowTipY (0.0f)
  59468. {
  59469. setInterceptsMouseClicks (false, false);
  59470. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59471. setComponentEffect (&shadow);
  59472. }
  59473. BubbleComponent::~BubbleComponent()
  59474. {
  59475. }
  59476. void BubbleComponent::paint (Graphics& g)
  59477. {
  59478. int x = content.getX();
  59479. int y = content.getY();
  59480. int w = content.getWidth();
  59481. int h = content.getHeight();
  59482. int cw, ch;
  59483. getContentSize (cw, ch);
  59484. if (side == 3)
  59485. x += w - cw;
  59486. else if (side != 1)
  59487. x += (w - cw) / 2;
  59488. w = cw;
  59489. if (side == 2)
  59490. y += h - ch;
  59491. else if (side != 0)
  59492. y += (h - ch) / 2;
  59493. h = ch;
  59494. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59495. (float) x, (float) y,
  59496. (float) w, (float) h);
  59497. const int cx = x + (w - cw) / 2;
  59498. const int cy = y + (h - ch) / 2;
  59499. const int indent = 3;
  59500. g.setOrigin (cx + indent, cy + indent);
  59501. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59502. paintContent (g, cw - indent * 2, ch - indent * 2);
  59503. }
  59504. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59505. {
  59506. allowablePlacements = newPlacement;
  59507. }
  59508. void BubbleComponent::setPosition (Component* componentToPointTo)
  59509. {
  59510. jassert (componentToPointTo != 0);
  59511. Point<int> pos;
  59512. if (getParentComponent() != 0)
  59513. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59514. else
  59515. pos = componentToPointTo->localPointToGlobal (pos);
  59516. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59517. }
  59518. void BubbleComponent::setPosition (const int arrowTipX_,
  59519. const int arrowTipY_)
  59520. {
  59521. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59522. }
  59523. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59524. {
  59525. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59526. : getParentMonitorArea());
  59527. int x = 0;
  59528. int y = 0;
  59529. int w = 150;
  59530. int h = 30;
  59531. getContentSize (w, h);
  59532. w += 30;
  59533. h += 30;
  59534. const float edgeIndent = 2.0f;
  59535. const int arrowLength = jmin (10, h / 3, w / 3);
  59536. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59537. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59538. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59539. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59540. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59541. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59542. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59543. {
  59544. spaceLeft = spaceRight = 0;
  59545. }
  59546. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59547. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59548. {
  59549. spaceAbove = spaceBelow = 0;
  59550. }
  59551. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59552. {
  59553. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59554. arrowTipX = w * 0.5f;
  59555. content.setSize (w, h - arrowLength);
  59556. if (spaceAbove >= spaceBelow)
  59557. {
  59558. // above
  59559. y = rectangleToPointTo.getY() - h;
  59560. content.setPosition (0, 0);
  59561. arrowTipY = h - edgeIndent;
  59562. side = 2;
  59563. }
  59564. else
  59565. {
  59566. // below
  59567. y = rectangleToPointTo.getBottom();
  59568. content.setPosition (0, arrowLength);
  59569. arrowTipY = edgeIndent;
  59570. side = 0;
  59571. }
  59572. }
  59573. else
  59574. {
  59575. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59576. arrowTipY = h * 0.5f;
  59577. content.setSize (w - arrowLength, h);
  59578. if (spaceLeft > spaceRight)
  59579. {
  59580. // on the left
  59581. x = rectangleToPointTo.getX() - w;
  59582. content.setPosition (0, 0);
  59583. arrowTipX = w - edgeIndent;
  59584. side = 3;
  59585. }
  59586. else
  59587. {
  59588. // on the right
  59589. x = rectangleToPointTo.getRight();
  59590. content.setPosition (arrowLength, 0);
  59591. arrowTipX = edgeIndent;
  59592. side = 1;
  59593. }
  59594. }
  59595. setBounds (x, y, w, h);
  59596. }
  59597. END_JUCE_NAMESPACE
  59598. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59599. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59600. BEGIN_JUCE_NAMESPACE
  59601. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59602. : fadeOutLength (fadeOutLengthMs),
  59603. deleteAfterUse (false)
  59604. {
  59605. }
  59606. BubbleMessageComponent::~BubbleMessageComponent()
  59607. {
  59608. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59609. }
  59610. void BubbleMessageComponent::showAt (int x, int y,
  59611. const String& text,
  59612. const int numMillisecondsBeforeRemoving,
  59613. const bool removeWhenMouseClicked,
  59614. const bool deleteSelfAfterUse)
  59615. {
  59616. textLayout.clear();
  59617. textLayout.setText (text, Font (14.0f));
  59618. textLayout.layout (256, Justification::centredLeft, true);
  59619. setPosition (x, y);
  59620. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59621. }
  59622. void BubbleMessageComponent::showAt (Component* const component,
  59623. const String& text,
  59624. const int numMillisecondsBeforeRemoving,
  59625. const bool removeWhenMouseClicked,
  59626. const bool deleteSelfAfterUse)
  59627. {
  59628. textLayout.clear();
  59629. textLayout.setText (text, Font (14.0f));
  59630. textLayout.layout (256, Justification::centredLeft, true);
  59631. setPosition (component);
  59632. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59633. }
  59634. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59635. const bool removeWhenMouseClicked,
  59636. const bool deleteSelfAfterUse)
  59637. {
  59638. setVisible (true);
  59639. deleteAfterUse = deleteSelfAfterUse;
  59640. if (numMillisecondsBeforeRemoving > 0)
  59641. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59642. else
  59643. expiryTime = 0;
  59644. startTimer (77);
  59645. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59646. if (! (removeWhenMouseClicked && isShowing()))
  59647. mouseClickCounter += 0xfffff;
  59648. repaint();
  59649. }
  59650. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59651. {
  59652. w = textLayout.getWidth() + 16;
  59653. h = textLayout.getHeight() + 16;
  59654. }
  59655. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59656. {
  59657. g.setColour (findColour (TooltipWindow::textColourId));
  59658. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59659. }
  59660. void BubbleMessageComponent::timerCallback()
  59661. {
  59662. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59663. {
  59664. stopTimer();
  59665. setVisible (false);
  59666. if (deleteAfterUse)
  59667. delete this;
  59668. }
  59669. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59670. {
  59671. stopTimer();
  59672. if (deleteAfterUse)
  59673. delete this;
  59674. else
  59675. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59676. }
  59677. }
  59678. END_JUCE_NAMESPACE
  59679. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59680. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59681. BEGIN_JUCE_NAMESPACE
  59682. class ColourComponentSlider : public Slider
  59683. {
  59684. public:
  59685. ColourComponentSlider (const String& name)
  59686. : Slider (name)
  59687. {
  59688. setRange (0.0, 255.0, 1.0);
  59689. }
  59690. const String getTextFromValue (double value)
  59691. {
  59692. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59693. }
  59694. double getValueFromText (const String& text)
  59695. {
  59696. return (double) text.getHexValue32();
  59697. }
  59698. private:
  59699. ColourComponentSlider (const ColourComponentSlider&);
  59700. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59701. };
  59702. class ColourSpaceMarker : public Component
  59703. {
  59704. public:
  59705. ColourSpaceMarker()
  59706. {
  59707. setInterceptsMouseClicks (false, false);
  59708. }
  59709. void paint (Graphics& g)
  59710. {
  59711. g.setColour (Colour::greyLevel (0.1f));
  59712. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59713. g.setColour (Colour::greyLevel (0.9f));
  59714. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59715. }
  59716. private:
  59717. ColourSpaceMarker (const ColourSpaceMarker&);
  59718. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59719. };
  59720. class ColourSelector::ColourSpaceView : public Component
  59721. {
  59722. public:
  59723. ColourSpaceView (ColourSelector& owner_,
  59724. float& h_, float& s_, float& v_,
  59725. const int edgeSize)
  59726. : owner (owner_),
  59727. h (h_), s (s_), v (v_),
  59728. lastHue (0.0f),
  59729. edge (edgeSize)
  59730. {
  59731. addAndMakeVisible (&marker);
  59732. setMouseCursor (MouseCursor::CrosshairCursor);
  59733. }
  59734. void paint (Graphics& g)
  59735. {
  59736. if (colours.isNull())
  59737. {
  59738. const int width = getWidth() / 2;
  59739. const int height = getHeight() / 2;
  59740. colours = Image (Image::RGB, width, height, false);
  59741. Image::BitmapData pixels (colours, true);
  59742. for (int y = 0; y < height; ++y)
  59743. {
  59744. const float val = 1.0f - y / (float) height;
  59745. for (int x = 0; x < width; ++x)
  59746. {
  59747. const float sat = x / (float) width;
  59748. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59749. }
  59750. }
  59751. }
  59752. g.setOpacity (1.0f);
  59753. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59754. 0, 0, colours.getWidth(), colours.getHeight());
  59755. }
  59756. void mouseDown (const MouseEvent& e)
  59757. {
  59758. mouseDrag (e);
  59759. }
  59760. void mouseDrag (const MouseEvent& e)
  59761. {
  59762. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59763. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59764. owner.setSV (sat, val);
  59765. }
  59766. void updateIfNeeded()
  59767. {
  59768. if (lastHue != h)
  59769. {
  59770. lastHue = h;
  59771. colours = Image::null;
  59772. repaint();
  59773. }
  59774. updateMarker();
  59775. }
  59776. void resized()
  59777. {
  59778. colours = Image::null;
  59779. updateMarker();
  59780. }
  59781. private:
  59782. ColourSelector& owner;
  59783. float& h;
  59784. float& s;
  59785. float& v;
  59786. float lastHue;
  59787. ColourSpaceMarker marker;
  59788. const int edge;
  59789. Image colours;
  59790. void updateMarker()
  59791. {
  59792. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59793. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59794. edge * 2, edge * 2);
  59795. }
  59796. ColourSpaceView (const ColourSpaceView&);
  59797. ColourSpaceView& operator= (const ColourSpaceView&);
  59798. };
  59799. class HueSelectorMarker : public Component
  59800. {
  59801. public:
  59802. HueSelectorMarker()
  59803. {
  59804. setInterceptsMouseClicks (false, false);
  59805. }
  59806. void paint (Graphics& g)
  59807. {
  59808. Path p;
  59809. p.addTriangle (1.0f, 1.0f,
  59810. getWidth() * 0.3f, getHeight() * 0.5f,
  59811. 1.0f, getHeight() - 1.0f);
  59812. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59813. getWidth() * 0.7f, getHeight() * 0.5f,
  59814. getWidth() - 1.0f, getHeight() - 1.0f);
  59815. g.setColour (Colours::white.withAlpha (0.75f));
  59816. g.fillPath (p);
  59817. g.setColour (Colours::black.withAlpha (0.75f));
  59818. g.strokePath (p, PathStrokeType (1.2f));
  59819. }
  59820. private:
  59821. HueSelectorMarker (const HueSelectorMarker&);
  59822. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59823. };
  59824. class ColourSelector::HueSelectorComp : public Component
  59825. {
  59826. public:
  59827. HueSelectorComp (ColourSelector& owner_,
  59828. float& h_, float& s_, float& v_,
  59829. const int edgeSize)
  59830. : owner (owner_),
  59831. h (h_), s (s_), v (v_),
  59832. lastHue (0.0f),
  59833. edge (edgeSize)
  59834. {
  59835. addAndMakeVisible (&marker);
  59836. }
  59837. void paint (Graphics& g)
  59838. {
  59839. const float yScale = 1.0f / (getHeight() - edge * 2);
  59840. const Rectangle<int> clip (g.getClipBounds());
  59841. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59842. {
  59843. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59844. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59845. }
  59846. }
  59847. void resized()
  59848. {
  59849. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59850. getWidth(), edge * 2);
  59851. }
  59852. void mouseDown (const MouseEvent& e)
  59853. {
  59854. mouseDrag (e);
  59855. }
  59856. void mouseDrag (const MouseEvent& e)
  59857. {
  59858. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59859. }
  59860. void updateIfNeeded()
  59861. {
  59862. resized();
  59863. }
  59864. private:
  59865. ColourSelector& owner;
  59866. float& h;
  59867. float& s;
  59868. float& v;
  59869. float lastHue;
  59870. HueSelectorMarker marker;
  59871. const int edge;
  59872. HueSelectorComp (const HueSelectorComp&);
  59873. HueSelectorComp& operator= (const HueSelectorComp&);
  59874. };
  59875. class ColourSelector::SwatchComponent : public Component
  59876. {
  59877. public:
  59878. SwatchComponent (ColourSelector& owner_, int index_)
  59879. : owner (owner_), index (index_)
  59880. {
  59881. }
  59882. void paint (Graphics& g)
  59883. {
  59884. const Colour colour (owner.getSwatchColour (index));
  59885. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59886. Colour (0xffdddddd).overlaidWith (colour),
  59887. Colour (0xffffffff).overlaidWith (colour));
  59888. }
  59889. void mouseDown (const MouseEvent&)
  59890. {
  59891. PopupMenu m;
  59892. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59893. m.addSeparator();
  59894. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59895. const int r = m.showAt (this);
  59896. if (r == 1)
  59897. {
  59898. owner.setCurrentColour (owner.getSwatchColour (index));
  59899. }
  59900. else if (r == 2)
  59901. {
  59902. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  59903. {
  59904. owner.setSwatchColour (index, owner.getCurrentColour());
  59905. repaint();
  59906. }
  59907. }
  59908. }
  59909. private:
  59910. ColourSelector& owner;
  59911. const int index;
  59912. SwatchComponent (const SwatchComponent&);
  59913. SwatchComponent& operator= (const SwatchComponent&);
  59914. };
  59915. ColourSelector::ColourSelector (const int flags_,
  59916. const int edgeGap_,
  59917. const int gapAroundColourSpaceComponent)
  59918. : colour (Colours::white),
  59919. flags (flags_),
  59920. edgeGap (edgeGap_)
  59921. {
  59922. // not much point having a selector with no components in it!
  59923. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59924. updateHSV();
  59925. if ((flags & showSliders) != 0)
  59926. {
  59927. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59928. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59929. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59930. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59931. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59932. for (int i = 4; --i >= 0;)
  59933. sliders[i]->addListener (this);
  59934. }
  59935. if ((flags & showColourspace) != 0)
  59936. {
  59937. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  59938. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  59939. }
  59940. update();
  59941. }
  59942. ColourSelector::~ColourSelector()
  59943. {
  59944. dispatchPendingMessages();
  59945. swatchComponents.clear();
  59946. }
  59947. const Colour ColourSelector::getCurrentColour() const
  59948. {
  59949. return ((flags & showAlphaChannel) != 0) ? colour
  59950. : colour.withAlpha ((uint8) 0xff);
  59951. }
  59952. void ColourSelector::setCurrentColour (const Colour& c)
  59953. {
  59954. if (c != colour)
  59955. {
  59956. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59957. updateHSV();
  59958. update();
  59959. }
  59960. }
  59961. void ColourSelector::setHue (float newH)
  59962. {
  59963. newH = jlimit (0.0f, 1.0f, newH);
  59964. if (h != newH)
  59965. {
  59966. h = newH;
  59967. colour = Colour (h, s, v, colour.getFloatAlpha());
  59968. update();
  59969. }
  59970. }
  59971. void ColourSelector::setSV (float newS, float newV)
  59972. {
  59973. newS = jlimit (0.0f, 1.0f, newS);
  59974. newV = jlimit (0.0f, 1.0f, newV);
  59975. if (s != newS || v != newV)
  59976. {
  59977. s = newS;
  59978. v = newV;
  59979. colour = Colour (h, s, v, colour.getFloatAlpha());
  59980. update();
  59981. }
  59982. }
  59983. void ColourSelector::updateHSV()
  59984. {
  59985. colour.getHSB (h, s, v);
  59986. }
  59987. void ColourSelector::update()
  59988. {
  59989. if (sliders[0] != 0)
  59990. {
  59991. sliders[0]->setValue ((int) colour.getRed());
  59992. sliders[1]->setValue ((int) colour.getGreen());
  59993. sliders[2]->setValue ((int) colour.getBlue());
  59994. sliders[3]->setValue ((int) colour.getAlpha());
  59995. }
  59996. if (colourSpace != 0)
  59997. {
  59998. colourSpace->updateIfNeeded();
  59999. hueSelector->updateIfNeeded();
  60000. }
  60001. if ((flags & showColourAtTop) != 0)
  60002. repaint (previewArea);
  60003. sendChangeMessage();
  60004. }
  60005. void ColourSelector::paint (Graphics& g)
  60006. {
  60007. g.fillAll (findColour (backgroundColourId));
  60008. if ((flags & showColourAtTop) != 0)
  60009. {
  60010. const Colour currentColour (getCurrentColour());
  60011. g.fillCheckerBoard (previewArea, 10, 10,
  60012. Colour (0xffdddddd).overlaidWith (currentColour),
  60013. Colour (0xffffffff).overlaidWith (currentColour));
  60014. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60015. g.setFont (14.0f, true);
  60016. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60017. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60018. Justification::centred, false);
  60019. }
  60020. if ((flags & showSliders) != 0)
  60021. {
  60022. g.setColour (findColour (labelTextColourId));
  60023. g.setFont (11.0f);
  60024. for (int i = 4; --i >= 0;)
  60025. {
  60026. if (sliders[i]->isVisible())
  60027. g.drawText (sliders[i]->getName() + ":",
  60028. 0, sliders[i]->getY(),
  60029. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60030. Justification::centredRight, false);
  60031. }
  60032. }
  60033. }
  60034. void ColourSelector::resized()
  60035. {
  60036. const int swatchesPerRow = 8;
  60037. const int swatchHeight = 22;
  60038. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60039. const int numSwatches = getNumSwatches();
  60040. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60041. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60042. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60043. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60044. int y = topSpace;
  60045. if ((flags & showColourspace) != 0)
  60046. {
  60047. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60048. colourSpace->setBounds (edgeGap, y,
  60049. getWidth() - hueWidth - edgeGap - 4,
  60050. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60051. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60052. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60053. colourSpace->getHeight());
  60054. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60055. }
  60056. if ((flags & showSliders) != 0)
  60057. {
  60058. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60059. for (int i = 0; i < numSliders; ++i)
  60060. {
  60061. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60062. proportionOfWidth (0.72f), sliderHeight - 2);
  60063. y += sliderHeight;
  60064. }
  60065. }
  60066. if (numSwatches > 0)
  60067. {
  60068. const int startX = 8;
  60069. const int xGap = 4;
  60070. const int yGap = 4;
  60071. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60072. y += edgeGap;
  60073. if (swatchComponents.size() != numSwatches)
  60074. {
  60075. swatchComponents.clear();
  60076. for (int i = 0; i < numSwatches; ++i)
  60077. {
  60078. SwatchComponent* const sc = new SwatchComponent (*this, i);
  60079. swatchComponents.add (sc);
  60080. addAndMakeVisible (sc);
  60081. }
  60082. }
  60083. int x = startX;
  60084. for (int i = 0; i < swatchComponents.size(); ++i)
  60085. {
  60086. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60087. sc->setBounds (x + xGap / 2,
  60088. y + yGap / 2,
  60089. swatchWidth - xGap,
  60090. swatchHeight - yGap);
  60091. if (((i + 1) % swatchesPerRow) == 0)
  60092. {
  60093. x = startX;
  60094. y += swatchHeight;
  60095. }
  60096. else
  60097. {
  60098. x += swatchWidth;
  60099. }
  60100. }
  60101. }
  60102. }
  60103. void ColourSelector::sliderValueChanged (Slider*)
  60104. {
  60105. if (sliders[0] != 0)
  60106. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60107. (uint8) sliders[1]->getValue(),
  60108. (uint8) sliders[2]->getValue(),
  60109. (uint8) sliders[3]->getValue()));
  60110. }
  60111. int ColourSelector::getNumSwatches() const
  60112. {
  60113. return 0;
  60114. }
  60115. const Colour ColourSelector::getSwatchColour (const int) const
  60116. {
  60117. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60118. return Colours::black;
  60119. }
  60120. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60121. {
  60122. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60123. }
  60124. END_JUCE_NAMESPACE
  60125. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60126. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60127. BEGIN_JUCE_NAMESPACE
  60128. class ShadowWindow : public Component
  60129. {
  60130. Component* owner;
  60131. Image shadowImageSections [12];
  60132. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60133. public:
  60134. ShadowWindow (Component* const owner_,
  60135. const int type_,
  60136. const Image shadowImageSections_ [12])
  60137. : owner (owner_),
  60138. type (type_)
  60139. {
  60140. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60141. shadowImageSections [i] = shadowImageSections_ [i];
  60142. setInterceptsMouseClicks (false, false);
  60143. if (owner_->isOnDesktop())
  60144. {
  60145. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60146. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60147. | ComponentPeer::windowIsTemporary
  60148. | ComponentPeer::windowIgnoresKeyPresses);
  60149. }
  60150. else if (owner_->getParentComponent() != 0)
  60151. {
  60152. owner_->getParentComponent()->addChildComponent (this);
  60153. }
  60154. }
  60155. ~ShadowWindow()
  60156. {
  60157. }
  60158. void paint (Graphics& g)
  60159. {
  60160. const Image& topLeft = shadowImageSections [type * 3];
  60161. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60162. const Image& filler = shadowImageSections [type * 3 + 2];
  60163. g.setOpacity (1.0f);
  60164. if (type < 2)
  60165. {
  60166. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60167. g.drawImage (topLeft,
  60168. 0, 0, topLeft.getWidth(), imH,
  60169. 0, 0, topLeft.getWidth(), imH);
  60170. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60171. g.drawImage (bottomRight,
  60172. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60173. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60174. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60175. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60176. }
  60177. else
  60178. {
  60179. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60180. g.drawImage (topLeft,
  60181. 0, 0, imW, topLeft.getHeight(),
  60182. 0, 0, imW, topLeft.getHeight());
  60183. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60184. g.drawImage (bottomRight,
  60185. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60186. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60187. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60188. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60189. }
  60190. }
  60191. void resized()
  60192. {
  60193. repaint(); // (needed for correct repainting)
  60194. }
  60195. private:
  60196. ShadowWindow (const ShadowWindow&);
  60197. ShadowWindow& operator= (const ShadowWindow&);
  60198. };
  60199. DropShadower::DropShadower (const float alpha_,
  60200. const int xOffset_,
  60201. const int yOffset_,
  60202. const float blurRadius_)
  60203. : owner (0),
  60204. numShadows (0),
  60205. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60206. xOffset (xOffset_),
  60207. yOffset (yOffset_),
  60208. alpha (alpha_),
  60209. blurRadius (blurRadius_),
  60210. inDestructor (false),
  60211. reentrant (false)
  60212. {
  60213. }
  60214. DropShadower::~DropShadower()
  60215. {
  60216. if (owner != 0)
  60217. owner->removeComponentListener (this);
  60218. inDestructor = true;
  60219. deleteShadowWindows();
  60220. }
  60221. void DropShadower::deleteShadowWindows()
  60222. {
  60223. if (numShadows > 0)
  60224. {
  60225. int i;
  60226. for (i = numShadows; --i >= 0;)
  60227. delete shadowWindows[i];
  60228. numShadows = 0;
  60229. }
  60230. }
  60231. void DropShadower::setOwner (Component* componentToFollow)
  60232. {
  60233. if (componentToFollow != owner)
  60234. {
  60235. if (owner != 0)
  60236. owner->removeComponentListener (this);
  60237. // (the component can't be null)
  60238. jassert (componentToFollow != 0);
  60239. owner = componentToFollow;
  60240. jassert (owner != 0);
  60241. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60242. owner->addComponentListener (this);
  60243. updateShadows();
  60244. }
  60245. }
  60246. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60247. {
  60248. updateShadows();
  60249. }
  60250. void DropShadower::componentBroughtToFront (Component&)
  60251. {
  60252. bringShadowWindowsToFront();
  60253. }
  60254. void DropShadower::componentChildrenChanged (Component&)
  60255. {
  60256. }
  60257. void DropShadower::componentParentHierarchyChanged (Component&)
  60258. {
  60259. deleteShadowWindows();
  60260. updateShadows();
  60261. }
  60262. void DropShadower::componentVisibilityChanged (Component&)
  60263. {
  60264. updateShadows();
  60265. }
  60266. void DropShadower::updateShadows()
  60267. {
  60268. if (reentrant || inDestructor || (owner == 0))
  60269. return;
  60270. reentrant = true;
  60271. ComponentPeer* const nw = owner->getPeer();
  60272. const bool isOwnerVisible = owner->isVisible()
  60273. && (nw == 0 || ! nw->isMinimised());
  60274. const bool createShadowWindows = numShadows == 0
  60275. && owner->getWidth() > 0
  60276. && owner->getHeight() > 0
  60277. && isOwnerVisible
  60278. && (Desktop::canUseSemiTransparentWindows()
  60279. || owner->getParentComponent() != 0);
  60280. if (createShadowWindows)
  60281. {
  60282. // keep a cached version of the image to save doing the gaussian too often
  60283. String imageId;
  60284. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60285. const int hash = imageId.hashCode();
  60286. Image bigIm (ImageCache::getFromHashCode (hash));
  60287. if (bigIm.isNull())
  60288. {
  60289. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60290. Graphics bigG (bigIm);
  60291. bigG.setColour (Colours::black.withAlpha (alpha));
  60292. bigG.fillRect (shadowEdge + xOffset,
  60293. shadowEdge + yOffset,
  60294. bigIm.getWidth() - (shadowEdge * 2),
  60295. bigIm.getHeight() - (shadowEdge * 2));
  60296. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60297. blurKernel.createGaussianBlur (blurRadius);
  60298. blurKernel.applyToImage (bigIm, bigIm,
  60299. Rectangle<int> (xOffset, yOffset,
  60300. bigIm.getWidth(), bigIm.getHeight()));
  60301. ImageCache::addImageToCache (bigIm, hash);
  60302. }
  60303. const int iw = bigIm.getWidth();
  60304. const int ih = bigIm.getHeight();
  60305. const int shadowEdge2 = shadowEdge * 2;
  60306. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60307. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60308. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60309. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60310. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60311. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60312. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60313. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60314. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60315. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60316. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60317. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60318. for (int i = 0; i < 4; ++i)
  60319. {
  60320. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60321. ++numShadows;
  60322. }
  60323. }
  60324. if (numShadows > 0)
  60325. {
  60326. for (int i = numShadows; --i >= 0;)
  60327. {
  60328. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60329. shadowWindows[i]->setVisible (isOwnerVisible);
  60330. }
  60331. const int x = owner->getX();
  60332. const int y = owner->getY() - shadowEdge;
  60333. const int w = owner->getWidth();
  60334. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60335. shadowWindows[0]->setBounds (x - shadowEdge,
  60336. y,
  60337. shadowEdge,
  60338. h);
  60339. shadowWindows[1]->setBounds (x + w,
  60340. y,
  60341. shadowEdge,
  60342. h);
  60343. shadowWindows[2]->setBounds (x,
  60344. y,
  60345. w,
  60346. shadowEdge);
  60347. shadowWindows[3]->setBounds (x,
  60348. owner->getBottom(),
  60349. w,
  60350. shadowEdge);
  60351. }
  60352. reentrant = false;
  60353. if (createShadowWindows)
  60354. bringShadowWindowsToFront();
  60355. }
  60356. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60357. const int sx, const int sy)
  60358. {
  60359. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60360. Graphics g (shadowImageSections[num]);
  60361. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60362. }
  60363. void DropShadower::bringShadowWindowsToFront()
  60364. {
  60365. if (! (inDestructor || reentrant))
  60366. {
  60367. updateShadows();
  60368. reentrant = true;
  60369. for (int i = numShadows; --i >= 0;)
  60370. shadowWindows[i]->toBehind (owner);
  60371. reentrant = false;
  60372. }
  60373. }
  60374. END_JUCE_NAMESPACE
  60375. /*** End of inlined file: juce_DropShadower.cpp ***/
  60376. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60377. BEGIN_JUCE_NAMESPACE
  60378. class MagnifyingPeer : public ComponentPeer
  60379. {
  60380. public:
  60381. MagnifyingPeer (Component* const component_,
  60382. MagnifierComponent* const magnifierComp_)
  60383. : ComponentPeer (component_, 0),
  60384. magnifierComp (magnifierComp_)
  60385. {
  60386. }
  60387. ~MagnifyingPeer()
  60388. {
  60389. }
  60390. void* getNativeHandle() const { return 0; }
  60391. void setVisible (bool) {}
  60392. void setTitle (const String&) {}
  60393. void setPosition (int, int) {}
  60394. void setSize (int, int) {}
  60395. void setBounds (int, int, int, int, bool) {}
  60396. void setMinimised (bool) {}
  60397. void setAlpha (float /*newAlpha*/) {}
  60398. bool isMinimised() const { return false; }
  60399. void setFullScreen (bool) {}
  60400. bool isFullScreen() const { return false; }
  60401. const BorderSize getFrameSize() const { return BorderSize (0); }
  60402. bool setAlwaysOnTop (bool) { return true; }
  60403. void toFront (bool) {}
  60404. void toBehind (ComponentPeer*) {}
  60405. void setIcon (const Image&) {}
  60406. bool isFocused() const
  60407. {
  60408. return magnifierComp->hasKeyboardFocus (true);
  60409. }
  60410. void grabFocus()
  60411. {
  60412. ComponentPeer* peer = magnifierComp->getPeer();
  60413. if (peer != 0)
  60414. peer->grabFocus();
  60415. }
  60416. void textInputRequired (const Point<int>& position)
  60417. {
  60418. ComponentPeer* peer = magnifierComp->getPeer();
  60419. if (peer != 0)
  60420. peer->textInputRequired (position);
  60421. }
  60422. const Rectangle<int> getBounds() const
  60423. {
  60424. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60425. component->getWidth(), component->getHeight());
  60426. }
  60427. const Point<int> getScreenPosition() const
  60428. {
  60429. return magnifierComp->getScreenPosition();
  60430. }
  60431. const Point<int> localToGlobal (const Point<int>& relativePosition)
  60432. {
  60433. const double zoom = magnifierComp->getScaleFactor();
  60434. return magnifierComp->localPointToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60435. roundToInt (relativePosition.getY() * zoom)));
  60436. }
  60437. const Point<int> globalToLocal (const Point<int>& screenPosition)
  60438. {
  60439. const Point<int> p (magnifierComp->getLocalPoint (0, screenPosition));
  60440. const double zoom = magnifierComp->getScaleFactor();
  60441. return Point<int> (roundToInt (p.getX() / zoom),
  60442. roundToInt (p.getY() / zoom));
  60443. }
  60444. bool contains (const Point<int>& position, bool) const
  60445. {
  60446. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60447. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60448. }
  60449. void repaint (const Rectangle<int>& area)
  60450. {
  60451. const double zoom = magnifierComp->getScaleFactor();
  60452. magnifierComp->repaint ((int) (area.getX() * zoom),
  60453. (int) (area.getY() * zoom),
  60454. roundToInt (area.getWidth() * zoom) + 1,
  60455. roundToInt (area.getHeight() * zoom) + 1);
  60456. }
  60457. void performAnyPendingRepaintsNow()
  60458. {
  60459. }
  60460. juce_UseDebuggingNewOperator
  60461. private:
  60462. MagnifierComponent* const magnifierComp;
  60463. MagnifyingPeer (const MagnifyingPeer&);
  60464. MagnifyingPeer& operator= (const MagnifyingPeer&);
  60465. };
  60466. class PeerHolderComp : public Component
  60467. {
  60468. public:
  60469. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60470. : magnifierComp (magnifierComp_)
  60471. {
  60472. setVisible (true);
  60473. }
  60474. ~PeerHolderComp()
  60475. {
  60476. }
  60477. ComponentPeer* createNewPeer (int, void*)
  60478. {
  60479. return new MagnifyingPeer (this, magnifierComp);
  60480. }
  60481. void childBoundsChanged (Component* c)
  60482. {
  60483. if (c != 0)
  60484. {
  60485. setSize (c->getWidth(), c->getHeight());
  60486. magnifierComp->childBoundsChanged (this);
  60487. }
  60488. }
  60489. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60490. {
  60491. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60492. Component* const p = magnifierComp->getParentComponent();
  60493. if (p != 0)
  60494. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60495. }
  60496. private:
  60497. MagnifierComponent* const magnifierComp;
  60498. PeerHolderComp (const PeerHolderComp&);
  60499. PeerHolderComp& operator= (const PeerHolderComp&);
  60500. };
  60501. MagnifierComponent::MagnifierComponent (Component* const content_,
  60502. const bool deleteContentCompWhenNoLongerNeeded)
  60503. : content (content_),
  60504. scaleFactor (0.0),
  60505. peer (0),
  60506. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60507. quality (Graphics::lowResamplingQuality),
  60508. mouseSource (0, true)
  60509. {
  60510. holderComp = new PeerHolderComp (this);
  60511. setScaleFactor (1.0);
  60512. }
  60513. MagnifierComponent::~MagnifierComponent()
  60514. {
  60515. delete holderComp;
  60516. if (deleteContent)
  60517. delete content;
  60518. }
  60519. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60520. {
  60521. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60522. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60523. if (scaleFactor != newScaleFactor)
  60524. {
  60525. scaleFactor = newScaleFactor;
  60526. if (scaleFactor == 1.0)
  60527. {
  60528. holderComp->removeFromDesktop();
  60529. peer = 0;
  60530. addChildComponent (content);
  60531. childBoundsChanged (content);
  60532. }
  60533. else
  60534. {
  60535. holderComp->addAndMakeVisible (content);
  60536. holderComp->childBoundsChanged (content);
  60537. childBoundsChanged (holderComp);
  60538. holderComp->addToDesktop (0);
  60539. peer = holderComp->getPeer();
  60540. }
  60541. repaint();
  60542. }
  60543. }
  60544. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60545. {
  60546. quality = newQuality;
  60547. }
  60548. void MagnifierComponent::paint (Graphics& g)
  60549. {
  60550. const int w = holderComp->getWidth();
  60551. const int h = holderComp->getHeight();
  60552. if (w == 0 || h == 0)
  60553. return;
  60554. const Rectangle<int> r (g.getClipBounds());
  60555. const int srcX = (int) (r.getX() / scaleFactor);
  60556. const int srcY = (int) (r.getY() / scaleFactor);
  60557. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60558. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60559. if (scaleFactor >= 1.0)
  60560. {
  60561. ++srcW;
  60562. ++srcH;
  60563. }
  60564. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60565. const Rectangle<int> area (srcX, srcY, srcW, srcH);
  60566. temp.clear (area);
  60567. {
  60568. Graphics g2 (temp);
  60569. g2.reduceClipRegion (area);
  60570. holderComp->paintEntireComponent (g2, false);
  60571. }
  60572. g.setImageResamplingQuality (quality);
  60573. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60574. }
  60575. void MagnifierComponent::childBoundsChanged (Component* c)
  60576. {
  60577. if (c != 0)
  60578. setSize (roundToInt (c->getWidth() * scaleFactor),
  60579. roundToInt (c->getHeight() * scaleFactor));
  60580. }
  60581. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60582. {
  60583. if (peer != 0)
  60584. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60585. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60586. }
  60587. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60588. {
  60589. passOnMouseEventToPeer (e);
  60590. }
  60591. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60592. {
  60593. passOnMouseEventToPeer (e);
  60594. }
  60595. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60596. {
  60597. passOnMouseEventToPeer (e);
  60598. }
  60599. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60600. {
  60601. passOnMouseEventToPeer (e);
  60602. }
  60603. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60604. {
  60605. passOnMouseEventToPeer (e);
  60606. }
  60607. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60608. {
  60609. passOnMouseEventToPeer (e);
  60610. }
  60611. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60612. {
  60613. if (peer != 0)
  60614. peer->handleMouseWheel (e.source.getIndex(),
  60615. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60616. ix * 256.0f, iy * 256.0f);
  60617. else
  60618. Component::mouseWheelMove (e, ix, iy);
  60619. }
  60620. int MagnifierComponent::scaleInt (const int n) const
  60621. {
  60622. return roundToInt (n / scaleFactor);
  60623. }
  60624. END_JUCE_NAMESPACE
  60625. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60626. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60627. BEGIN_JUCE_NAMESPACE
  60628. class MidiKeyboardUpDownButton : public Button
  60629. {
  60630. public:
  60631. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60632. : Button (String::empty),
  60633. owner (owner_),
  60634. delta (delta_)
  60635. {
  60636. setOpaque (true);
  60637. }
  60638. void clicked()
  60639. {
  60640. int note = owner.getLowestVisibleKey();
  60641. if (delta < 0)
  60642. note = (note - 1) / 12;
  60643. else
  60644. note = note / 12 + 1;
  60645. owner.setLowestVisibleKey (note * 12);
  60646. }
  60647. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60648. {
  60649. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60650. isMouseOverButton, isButtonDown,
  60651. delta > 0);
  60652. }
  60653. private:
  60654. MidiKeyboardComponent& owner;
  60655. const int delta;
  60656. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60657. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60658. };
  60659. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60660. const Orientation orientation_)
  60661. : state (state_),
  60662. xOffset (0),
  60663. blackNoteLength (1),
  60664. keyWidth (16.0f),
  60665. orientation (orientation_),
  60666. midiChannel (1),
  60667. midiInChannelMask (0xffff),
  60668. velocity (1.0f),
  60669. noteUnderMouse (-1),
  60670. mouseDownNote (-1),
  60671. rangeStart (0),
  60672. rangeEnd (127),
  60673. firstKey (12 * 4),
  60674. canScroll (true),
  60675. mouseDragging (false),
  60676. useMousePositionForVelocity (true),
  60677. keyMappingOctave (6),
  60678. octaveNumForMiddleC (3)
  60679. {
  60680. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60681. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60682. // initialise with a default set of querty key-mappings..
  60683. const char* const keymap = "awsedftgyhujkolp;";
  60684. for (int i = String (keymap).length(); --i >= 0;)
  60685. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60686. setOpaque (true);
  60687. setWantsKeyboardFocus (true);
  60688. state.addListener (this);
  60689. }
  60690. MidiKeyboardComponent::~MidiKeyboardComponent()
  60691. {
  60692. state.removeListener (this);
  60693. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60694. }
  60695. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60696. {
  60697. keyWidth = widthInPixels;
  60698. resized();
  60699. }
  60700. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60701. {
  60702. if (orientation != newOrientation)
  60703. {
  60704. orientation = newOrientation;
  60705. resized();
  60706. }
  60707. }
  60708. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60709. const int highestNote)
  60710. {
  60711. jassert (lowestNote >= 0 && lowestNote <= 127);
  60712. jassert (highestNote >= 0 && highestNote <= 127);
  60713. jassert (lowestNote <= highestNote);
  60714. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60715. {
  60716. rangeStart = jlimit (0, 127, lowestNote);
  60717. rangeEnd = jlimit (0, 127, highestNote);
  60718. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60719. resized();
  60720. }
  60721. }
  60722. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60723. {
  60724. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60725. if (noteNumber != firstKey)
  60726. {
  60727. firstKey = noteNumber;
  60728. sendChangeMessage();
  60729. resized();
  60730. }
  60731. }
  60732. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60733. {
  60734. if (canScroll != canScroll_)
  60735. {
  60736. canScroll = canScroll_;
  60737. resized();
  60738. }
  60739. }
  60740. void MidiKeyboardComponent::colourChanged()
  60741. {
  60742. repaint();
  60743. }
  60744. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60745. {
  60746. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60747. if (midiChannel != midiChannelNumber)
  60748. {
  60749. resetAnyKeysInUse();
  60750. midiChannel = jlimit (1, 16, midiChannelNumber);
  60751. }
  60752. }
  60753. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60754. {
  60755. midiInChannelMask = midiChannelMask;
  60756. triggerAsyncUpdate();
  60757. }
  60758. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60759. {
  60760. velocity = jlimit (0.0f, 1.0f, velocity_);
  60761. useMousePositionForVelocity = useMousePositionForVelocity_;
  60762. }
  60763. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60764. {
  60765. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60766. static const float blackNoteWidth = 0.7f;
  60767. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60768. 1.0f, 2 - blackNoteWidth * 0.4f,
  60769. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60770. 4.0f, 5 - blackNoteWidth * 0.5f,
  60771. 5.0f, 6 - blackNoteWidth * 0.3f,
  60772. 6.0f };
  60773. static const float widths[] = { 1.0f, blackNoteWidth,
  60774. 1.0f, blackNoteWidth,
  60775. 1.0f, 1.0f, blackNoteWidth,
  60776. 1.0f, blackNoteWidth,
  60777. 1.0f, blackNoteWidth,
  60778. 1.0f };
  60779. const int octave = midiNoteNumber / 12;
  60780. const int note = midiNoteNumber % 12;
  60781. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60782. w = roundToInt (widths [note] * keyWidth_);
  60783. }
  60784. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60785. {
  60786. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60787. int rx, rw;
  60788. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60789. x -= xOffset + rx;
  60790. }
  60791. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60792. {
  60793. int x, y;
  60794. getKeyPos (midiNoteNumber, x, y);
  60795. return x;
  60796. }
  60797. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60798. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60799. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60800. {
  60801. if (! reallyContains (pos.getX(), pos.getY(), false))
  60802. return -1;
  60803. Point<int> p (pos);
  60804. if (orientation != horizontalKeyboard)
  60805. {
  60806. p = Point<int> (p.getY(), p.getX());
  60807. if (orientation == verticalKeyboardFacingLeft)
  60808. p = Point<int> (p.getX(), getWidth() - p.getY());
  60809. else
  60810. p = Point<int> (getHeight() - p.getX(), p.getY());
  60811. }
  60812. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60813. }
  60814. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60815. {
  60816. if (pos.getY() < blackNoteLength)
  60817. {
  60818. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60819. {
  60820. for (int i = 0; i < 5; ++i)
  60821. {
  60822. const int note = octaveStart + blackNotes [i];
  60823. if (note >= rangeStart && note <= rangeEnd)
  60824. {
  60825. int kx, kw;
  60826. getKeyPos (note, kx, kw);
  60827. kx += xOffset;
  60828. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60829. {
  60830. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60831. return note;
  60832. }
  60833. }
  60834. }
  60835. }
  60836. }
  60837. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60838. {
  60839. for (int i = 0; i < 7; ++i)
  60840. {
  60841. const int note = octaveStart + whiteNotes [i];
  60842. if (note >= rangeStart && note <= rangeEnd)
  60843. {
  60844. int kx, kw;
  60845. getKeyPos (note, kx, kw);
  60846. kx += xOffset;
  60847. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60848. {
  60849. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60850. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60851. return note;
  60852. }
  60853. }
  60854. }
  60855. }
  60856. mousePositionVelocity = 0;
  60857. return -1;
  60858. }
  60859. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60860. {
  60861. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60862. {
  60863. int x, w;
  60864. getKeyPos (noteNum, x, w);
  60865. if (orientation == horizontalKeyboard)
  60866. repaint (x, 0, w, getHeight());
  60867. else if (orientation == verticalKeyboardFacingLeft)
  60868. repaint (0, x, getWidth(), w);
  60869. else if (orientation == verticalKeyboardFacingRight)
  60870. repaint (0, getHeight() - x - w, getWidth(), w);
  60871. }
  60872. }
  60873. void MidiKeyboardComponent::paint (Graphics& g)
  60874. {
  60875. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60876. const Colour lineColour (findColour (keySeparatorLineColourId));
  60877. const Colour textColour (findColour (textLabelColourId));
  60878. int x, w, octave;
  60879. for (octave = 0; octave < 128; octave += 12)
  60880. {
  60881. for (int white = 0; white < 7; ++white)
  60882. {
  60883. const int noteNum = octave + whiteNotes [white];
  60884. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60885. {
  60886. getKeyPos (noteNum, x, w);
  60887. if (orientation == horizontalKeyboard)
  60888. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60889. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60890. noteUnderMouse == noteNum,
  60891. lineColour, textColour);
  60892. else if (orientation == verticalKeyboardFacingLeft)
  60893. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60894. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60895. noteUnderMouse == noteNum,
  60896. lineColour, textColour);
  60897. else if (orientation == verticalKeyboardFacingRight)
  60898. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60899. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60900. noteUnderMouse == noteNum,
  60901. lineColour, textColour);
  60902. }
  60903. }
  60904. }
  60905. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60906. if (orientation == verticalKeyboardFacingLeft)
  60907. {
  60908. x1 = getWidth() - 1.0f;
  60909. x2 = getWidth() - 5.0f;
  60910. }
  60911. else if (orientation == verticalKeyboardFacingRight)
  60912. x2 = 5.0f;
  60913. else
  60914. y2 = 5.0f;
  60915. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60916. Colours::transparentBlack, x2, y2, false));
  60917. getKeyPos (rangeEnd, x, w);
  60918. x += w;
  60919. if (orientation == verticalKeyboardFacingLeft)
  60920. g.fillRect (getWidth() - 5, 0, 5, x);
  60921. else if (orientation == verticalKeyboardFacingRight)
  60922. g.fillRect (0, 0, 5, x);
  60923. else
  60924. g.fillRect (0, 0, x, 5);
  60925. g.setColour (lineColour);
  60926. if (orientation == verticalKeyboardFacingLeft)
  60927. g.fillRect (0, 0, 1, x);
  60928. else if (orientation == verticalKeyboardFacingRight)
  60929. g.fillRect (getWidth() - 1, 0, 1, x);
  60930. else
  60931. g.fillRect (0, getHeight() - 1, x, 1);
  60932. const Colour blackNoteColour (findColour (blackNoteColourId));
  60933. for (octave = 0; octave < 128; octave += 12)
  60934. {
  60935. for (int black = 0; black < 5; ++black)
  60936. {
  60937. const int noteNum = octave + blackNotes [black];
  60938. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60939. {
  60940. getKeyPos (noteNum, x, w);
  60941. if (orientation == horizontalKeyboard)
  60942. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60943. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60944. noteUnderMouse == noteNum,
  60945. blackNoteColour);
  60946. else if (orientation == verticalKeyboardFacingLeft)
  60947. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60948. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60949. noteUnderMouse == noteNum,
  60950. blackNoteColour);
  60951. else if (orientation == verticalKeyboardFacingRight)
  60952. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60953. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60954. noteUnderMouse == noteNum,
  60955. blackNoteColour);
  60956. }
  60957. }
  60958. }
  60959. }
  60960. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60961. Graphics& g, int x, int y, int w, int h,
  60962. bool isDown, bool isOver,
  60963. const Colour& lineColour,
  60964. const Colour& textColour)
  60965. {
  60966. Colour c (Colours::transparentWhite);
  60967. if (isDown)
  60968. c = findColour (keyDownOverlayColourId);
  60969. if (isOver)
  60970. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60971. g.setColour (c);
  60972. g.fillRect (x, y, w, h);
  60973. const String text (getWhiteNoteText (midiNoteNumber));
  60974. if (! text.isEmpty())
  60975. {
  60976. g.setColour (textColour);
  60977. Font f (jmin (12.0f, keyWidth * 0.9f));
  60978. f.setHorizontalScale (0.8f);
  60979. g.setFont (f);
  60980. Justification justification (Justification::centredBottom);
  60981. if (orientation == verticalKeyboardFacingLeft)
  60982. justification = Justification::centredLeft;
  60983. else if (orientation == verticalKeyboardFacingRight)
  60984. justification = Justification::centredRight;
  60985. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60986. }
  60987. g.setColour (lineColour);
  60988. if (orientation == horizontalKeyboard)
  60989. g.fillRect (x, y, 1, h);
  60990. else if (orientation == verticalKeyboardFacingLeft)
  60991. g.fillRect (x, y, w, 1);
  60992. else if (orientation == verticalKeyboardFacingRight)
  60993. g.fillRect (x, y + h - 1, w, 1);
  60994. if (midiNoteNumber == rangeEnd)
  60995. {
  60996. if (orientation == horizontalKeyboard)
  60997. g.fillRect (x + w, y, 1, h);
  60998. else if (orientation == verticalKeyboardFacingLeft)
  60999. g.fillRect (x, y + h, w, 1);
  61000. else if (orientation == verticalKeyboardFacingRight)
  61001. g.fillRect (x, y - 1, w, 1);
  61002. }
  61003. }
  61004. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61005. Graphics& g, int x, int y, int w, int h,
  61006. bool isDown, bool isOver,
  61007. const Colour& noteFillColour)
  61008. {
  61009. Colour c (noteFillColour);
  61010. if (isDown)
  61011. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61012. if (isOver)
  61013. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61014. g.setColour (c);
  61015. g.fillRect (x, y, w, h);
  61016. if (isDown)
  61017. {
  61018. g.setColour (noteFillColour);
  61019. g.drawRect (x, y, w, h);
  61020. }
  61021. else
  61022. {
  61023. const int xIndent = jmax (1, jmin (w, h) / 8);
  61024. g.setColour (c.brighter());
  61025. if (orientation == horizontalKeyboard)
  61026. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61027. else if (orientation == verticalKeyboardFacingLeft)
  61028. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61029. else if (orientation == verticalKeyboardFacingRight)
  61030. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61031. }
  61032. }
  61033. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61034. {
  61035. octaveNumForMiddleC = octaveNumForMiddleC_;
  61036. repaint();
  61037. }
  61038. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61039. {
  61040. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61041. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61042. return String::empty;
  61043. }
  61044. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61045. const bool isMouseOver_,
  61046. const bool isButtonDown,
  61047. const bool movesOctavesUp)
  61048. {
  61049. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61050. float angle;
  61051. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61052. angle = movesOctavesUp ? 0.0f : 0.5f;
  61053. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61054. angle = movesOctavesUp ? 0.25f : 0.75f;
  61055. else
  61056. angle = movesOctavesUp ? 0.75f : 0.25f;
  61057. Path path;
  61058. path.lineTo (0.0f, 1.0f);
  61059. path.lineTo (1.0f, 0.5f);
  61060. path.closeSubPath();
  61061. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61062. g.setColour (findColour (upDownButtonArrowColourId)
  61063. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61064. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61065. w - 2.0f,
  61066. h - 2.0f,
  61067. true));
  61068. }
  61069. void MidiKeyboardComponent::resized()
  61070. {
  61071. int w = getWidth();
  61072. int h = getHeight();
  61073. if (w > 0 && h > 0)
  61074. {
  61075. if (orientation != horizontalKeyboard)
  61076. swapVariables (w, h);
  61077. blackNoteLength = roundToInt (h * 0.7f);
  61078. int kx2, kw2;
  61079. getKeyPos (rangeEnd, kx2, kw2);
  61080. kx2 += kw2;
  61081. if (firstKey != rangeStart)
  61082. {
  61083. int kx1, kw1;
  61084. getKeyPos (rangeStart, kx1, kw1);
  61085. if (kx2 - kx1 <= w)
  61086. {
  61087. firstKey = rangeStart;
  61088. sendChangeMessage();
  61089. repaint();
  61090. }
  61091. }
  61092. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61093. scrollDown->setVisible (showScrollButtons);
  61094. scrollUp->setVisible (showScrollButtons);
  61095. xOffset = 0;
  61096. if (showScrollButtons)
  61097. {
  61098. const int scrollButtonW = jmin (12, w / 2);
  61099. if (orientation == horizontalKeyboard)
  61100. {
  61101. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61102. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61103. }
  61104. else if (orientation == verticalKeyboardFacingLeft)
  61105. {
  61106. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61107. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61108. }
  61109. else if (orientation == verticalKeyboardFacingRight)
  61110. {
  61111. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61112. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61113. }
  61114. int endOfLastKey, kw;
  61115. getKeyPos (rangeEnd, endOfLastKey, kw);
  61116. endOfLastKey += kw;
  61117. float mousePositionVelocity;
  61118. const int spaceAvailable = w - scrollButtonW * 2;
  61119. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61120. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61121. {
  61122. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61123. sendChangeMessage();
  61124. }
  61125. int newOffset = 0;
  61126. getKeyPos (firstKey, newOffset, kw);
  61127. xOffset = newOffset - scrollButtonW;
  61128. }
  61129. else
  61130. {
  61131. firstKey = rangeStart;
  61132. }
  61133. timerCallback();
  61134. repaint();
  61135. }
  61136. }
  61137. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61138. {
  61139. triggerAsyncUpdate();
  61140. }
  61141. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61142. {
  61143. triggerAsyncUpdate();
  61144. }
  61145. void MidiKeyboardComponent::handleAsyncUpdate()
  61146. {
  61147. for (int i = rangeStart; i <= rangeEnd; ++i)
  61148. {
  61149. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61150. {
  61151. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61152. repaintNote (i);
  61153. }
  61154. }
  61155. }
  61156. void MidiKeyboardComponent::resetAnyKeysInUse()
  61157. {
  61158. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61159. {
  61160. state.allNotesOff (midiChannel);
  61161. keysPressed.clear();
  61162. mouseDownNote = -1;
  61163. }
  61164. }
  61165. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61166. {
  61167. float mousePositionVelocity = 0.0f;
  61168. const int newNote = (mouseDragging || isMouseOver())
  61169. ? xyToNote (pos, mousePositionVelocity) : -1;
  61170. if (noteUnderMouse != newNote)
  61171. {
  61172. if (mouseDownNote >= 0)
  61173. {
  61174. state.noteOff (midiChannel, mouseDownNote);
  61175. mouseDownNote = -1;
  61176. }
  61177. if (mouseDragging && newNote >= 0)
  61178. {
  61179. if (! useMousePositionForVelocity)
  61180. mousePositionVelocity = 1.0f;
  61181. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61182. mouseDownNote = newNote;
  61183. }
  61184. repaintNote (noteUnderMouse);
  61185. noteUnderMouse = newNote;
  61186. repaintNote (noteUnderMouse);
  61187. }
  61188. else if (mouseDownNote >= 0 && ! mouseDragging)
  61189. {
  61190. state.noteOff (midiChannel, mouseDownNote);
  61191. mouseDownNote = -1;
  61192. }
  61193. }
  61194. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61195. {
  61196. updateNoteUnderMouse (e.getPosition());
  61197. stopTimer();
  61198. }
  61199. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61200. {
  61201. float mousePositionVelocity;
  61202. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61203. if (newNote >= 0)
  61204. mouseDraggedToKey (newNote, e);
  61205. updateNoteUnderMouse (e.getPosition());
  61206. }
  61207. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61208. {
  61209. return true;
  61210. }
  61211. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61212. {
  61213. }
  61214. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61215. {
  61216. float mousePositionVelocity;
  61217. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61218. mouseDragging = false;
  61219. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61220. {
  61221. repaintNote (noteUnderMouse);
  61222. noteUnderMouse = -1;
  61223. mouseDragging = true;
  61224. updateNoteUnderMouse (e.getPosition());
  61225. startTimer (500);
  61226. }
  61227. }
  61228. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61229. {
  61230. mouseDragging = false;
  61231. updateNoteUnderMouse (e.getPosition());
  61232. stopTimer();
  61233. }
  61234. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61235. {
  61236. updateNoteUnderMouse (e.getPosition());
  61237. }
  61238. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61239. {
  61240. updateNoteUnderMouse (e.getPosition());
  61241. }
  61242. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61243. {
  61244. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61245. }
  61246. void MidiKeyboardComponent::timerCallback()
  61247. {
  61248. updateNoteUnderMouse (getMouseXYRelative());
  61249. }
  61250. void MidiKeyboardComponent::clearKeyMappings()
  61251. {
  61252. resetAnyKeysInUse();
  61253. keyPressNotes.clear();
  61254. keyPresses.clear();
  61255. }
  61256. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61257. const int midiNoteOffsetFromC)
  61258. {
  61259. removeKeyPressForNote (midiNoteOffsetFromC);
  61260. keyPressNotes.add (midiNoteOffsetFromC);
  61261. keyPresses.add (key);
  61262. }
  61263. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61264. {
  61265. for (int i = keyPressNotes.size(); --i >= 0;)
  61266. {
  61267. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61268. {
  61269. keyPressNotes.remove (i);
  61270. keyPresses.remove (i);
  61271. }
  61272. }
  61273. }
  61274. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61275. {
  61276. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61277. keyMappingOctave = newOctaveNumber;
  61278. }
  61279. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61280. {
  61281. bool keyPressUsed = false;
  61282. for (int i = keyPresses.size(); --i >= 0;)
  61283. {
  61284. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61285. if (keyPresses.getReference(i).isCurrentlyDown())
  61286. {
  61287. if (! keysPressed [note])
  61288. {
  61289. keysPressed.setBit (note);
  61290. state.noteOn (midiChannel, note, velocity);
  61291. keyPressUsed = true;
  61292. }
  61293. }
  61294. else
  61295. {
  61296. if (keysPressed [note])
  61297. {
  61298. keysPressed.clearBit (note);
  61299. state.noteOff (midiChannel, note);
  61300. keyPressUsed = true;
  61301. }
  61302. }
  61303. }
  61304. return keyPressUsed;
  61305. }
  61306. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61307. {
  61308. resetAnyKeysInUse();
  61309. }
  61310. END_JUCE_NAMESPACE
  61311. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61312. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61313. #if JUCE_OPENGL
  61314. BEGIN_JUCE_NAMESPACE
  61315. extern void juce_glViewport (const int w, const int h);
  61316. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61317. const int alphaBits_,
  61318. const int depthBufferBits_,
  61319. const int stencilBufferBits_)
  61320. : redBits (bitsPerRGBComponent),
  61321. greenBits (bitsPerRGBComponent),
  61322. blueBits (bitsPerRGBComponent),
  61323. alphaBits (alphaBits_),
  61324. depthBufferBits (depthBufferBits_),
  61325. stencilBufferBits (stencilBufferBits_),
  61326. accumulationBufferRedBits (0),
  61327. accumulationBufferGreenBits (0),
  61328. accumulationBufferBlueBits (0),
  61329. accumulationBufferAlphaBits (0),
  61330. fullSceneAntiAliasingNumSamples (0)
  61331. {
  61332. }
  61333. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61334. : redBits (other.redBits),
  61335. greenBits (other.greenBits),
  61336. blueBits (other.blueBits),
  61337. alphaBits (other.alphaBits),
  61338. depthBufferBits (other.depthBufferBits),
  61339. stencilBufferBits (other.stencilBufferBits),
  61340. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61341. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61342. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61343. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61344. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61345. {
  61346. }
  61347. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61348. {
  61349. redBits = other.redBits;
  61350. greenBits = other.greenBits;
  61351. blueBits = other.blueBits;
  61352. alphaBits = other.alphaBits;
  61353. depthBufferBits = other.depthBufferBits;
  61354. stencilBufferBits = other.stencilBufferBits;
  61355. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61356. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61357. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61358. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61359. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61360. return *this;
  61361. }
  61362. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61363. {
  61364. return redBits == other.redBits
  61365. && greenBits == other.greenBits
  61366. && blueBits == other.blueBits
  61367. && alphaBits == other.alphaBits
  61368. && depthBufferBits == other.depthBufferBits
  61369. && stencilBufferBits == other.stencilBufferBits
  61370. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61371. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61372. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61373. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61374. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61375. }
  61376. static Array<OpenGLContext*> knownContexts;
  61377. OpenGLContext::OpenGLContext() throw()
  61378. {
  61379. knownContexts.add (this);
  61380. }
  61381. OpenGLContext::~OpenGLContext()
  61382. {
  61383. knownContexts.removeValue (this);
  61384. }
  61385. OpenGLContext* OpenGLContext::getCurrentContext()
  61386. {
  61387. for (int i = knownContexts.size(); --i >= 0;)
  61388. {
  61389. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61390. if (oglc->isActive())
  61391. return oglc;
  61392. }
  61393. return 0;
  61394. }
  61395. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61396. {
  61397. public:
  61398. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61399. : ComponentMovementWatcher (owner_),
  61400. owner (owner_),
  61401. wasShowing (false)
  61402. {
  61403. }
  61404. ~OpenGLComponentWatcher() {}
  61405. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61406. {
  61407. owner->updateContextPosition();
  61408. }
  61409. void componentPeerChanged()
  61410. {
  61411. const ScopedLock sl (owner->getContextLock());
  61412. owner->deleteContext();
  61413. }
  61414. void componentVisibilityChanged (Component&)
  61415. {
  61416. const bool isShowingNow = owner->isShowing();
  61417. if (wasShowing != isShowingNow)
  61418. {
  61419. wasShowing = isShowingNow;
  61420. if (! isShowingNow)
  61421. {
  61422. const ScopedLock sl (owner->getContextLock());
  61423. owner->deleteContext();
  61424. }
  61425. }
  61426. }
  61427. juce_UseDebuggingNewOperator
  61428. private:
  61429. OpenGLComponent* const owner;
  61430. bool wasShowing;
  61431. };
  61432. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61433. : type (type_),
  61434. contextToShareListsWith (0),
  61435. needToUpdateViewport (true)
  61436. {
  61437. setOpaque (true);
  61438. componentWatcher = new OpenGLComponentWatcher (this);
  61439. }
  61440. OpenGLComponent::~OpenGLComponent()
  61441. {
  61442. deleteContext();
  61443. componentWatcher = 0;
  61444. }
  61445. void OpenGLComponent::deleteContext()
  61446. {
  61447. const ScopedLock sl (contextLock);
  61448. context = 0;
  61449. }
  61450. void OpenGLComponent::updateContextPosition()
  61451. {
  61452. needToUpdateViewport = true;
  61453. if (getWidth() > 0 && getHeight() > 0)
  61454. {
  61455. Component* const topComp = getTopLevelComponent();
  61456. if (topComp->getPeer() != 0)
  61457. {
  61458. const ScopedLock sl (contextLock);
  61459. if (context != 0)
  61460. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61461. getScreenY() - topComp->getScreenY(),
  61462. getWidth(),
  61463. getHeight(),
  61464. topComp->getHeight());
  61465. }
  61466. }
  61467. }
  61468. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61469. {
  61470. OpenGLPixelFormat pf;
  61471. const ScopedLock sl (contextLock);
  61472. if (context != 0)
  61473. pf = context->getPixelFormat();
  61474. return pf;
  61475. }
  61476. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61477. {
  61478. if (! (preferredPixelFormat == formatToUse))
  61479. {
  61480. const ScopedLock sl (contextLock);
  61481. deleteContext();
  61482. preferredPixelFormat = formatToUse;
  61483. }
  61484. }
  61485. void OpenGLComponent::shareWith (OpenGLContext* c)
  61486. {
  61487. if (contextToShareListsWith != c)
  61488. {
  61489. const ScopedLock sl (contextLock);
  61490. deleteContext();
  61491. contextToShareListsWith = c;
  61492. }
  61493. }
  61494. bool OpenGLComponent::makeCurrentContextActive()
  61495. {
  61496. if (context == 0)
  61497. {
  61498. const ScopedLock sl (contextLock);
  61499. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61500. {
  61501. context = createContext();
  61502. if (context != 0)
  61503. {
  61504. updateContextPosition();
  61505. if (context->makeActive())
  61506. newOpenGLContextCreated();
  61507. }
  61508. }
  61509. }
  61510. return context != 0 && context->makeActive();
  61511. }
  61512. void OpenGLComponent::makeCurrentContextInactive()
  61513. {
  61514. if (context != 0)
  61515. context->makeInactive();
  61516. }
  61517. bool OpenGLComponent::isActiveContext() const throw()
  61518. {
  61519. return context != 0 && context->isActive();
  61520. }
  61521. void OpenGLComponent::swapBuffers()
  61522. {
  61523. if (context != 0)
  61524. context->swapBuffers();
  61525. }
  61526. void OpenGLComponent::paint (Graphics&)
  61527. {
  61528. if (renderAndSwapBuffers())
  61529. {
  61530. ComponentPeer* const peer = getPeer();
  61531. if (peer != 0)
  61532. {
  61533. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61534. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61535. }
  61536. }
  61537. }
  61538. bool OpenGLComponent::renderAndSwapBuffers()
  61539. {
  61540. const ScopedLock sl (contextLock);
  61541. if (! makeCurrentContextActive())
  61542. return false;
  61543. if (needToUpdateViewport)
  61544. {
  61545. needToUpdateViewport = false;
  61546. juce_glViewport (getWidth(), getHeight());
  61547. }
  61548. renderOpenGL();
  61549. swapBuffers();
  61550. return true;
  61551. }
  61552. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61553. {
  61554. Component::internalRepaint (x, y, w, h);
  61555. if (context != 0)
  61556. context->repaint();
  61557. }
  61558. END_JUCE_NAMESPACE
  61559. #endif
  61560. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61561. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61562. BEGIN_JUCE_NAMESPACE
  61563. PreferencesPanel::PreferencesPanel()
  61564. : buttonSize (70)
  61565. {
  61566. }
  61567. PreferencesPanel::~PreferencesPanel()
  61568. {
  61569. }
  61570. void PreferencesPanel::addSettingsPage (const String& title,
  61571. const Drawable* icon,
  61572. const Drawable* overIcon,
  61573. const Drawable* downIcon)
  61574. {
  61575. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61576. buttons.add (button);
  61577. button->setImages (icon, overIcon, downIcon);
  61578. button->setRadioGroupId (1);
  61579. button->addButtonListener (this);
  61580. button->setClickingTogglesState (true);
  61581. button->setWantsKeyboardFocus (false);
  61582. addAndMakeVisible (button);
  61583. resized();
  61584. if (currentPage == 0)
  61585. setCurrentPage (title);
  61586. }
  61587. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61588. {
  61589. DrawableImage icon, iconOver, iconDown;
  61590. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61591. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61592. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61593. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61594. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61595. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61596. }
  61597. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61598. {
  61599. setSize (dialogWidth, dialogHeight);
  61600. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61601. }
  61602. void PreferencesPanel::resized()
  61603. {
  61604. for (int i = 0; i < buttons.size(); ++i)
  61605. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61606. if (currentPage != 0)
  61607. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61608. }
  61609. void PreferencesPanel::paint (Graphics& g)
  61610. {
  61611. g.setColour (Colours::grey);
  61612. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61613. }
  61614. void PreferencesPanel::setCurrentPage (const String& pageName)
  61615. {
  61616. if (currentPageName != pageName)
  61617. {
  61618. currentPageName = pageName;
  61619. currentPage = 0;
  61620. currentPage = createComponentForPage (pageName);
  61621. if (currentPage != 0)
  61622. {
  61623. addAndMakeVisible (currentPage);
  61624. currentPage->toBack();
  61625. resized();
  61626. }
  61627. for (int i = 0; i < buttons.size(); ++i)
  61628. {
  61629. if (buttons.getUnchecked(i)->getName() == pageName)
  61630. {
  61631. buttons.getUnchecked(i)->setToggleState (true, false);
  61632. break;
  61633. }
  61634. }
  61635. }
  61636. }
  61637. void PreferencesPanel::buttonClicked (Button*)
  61638. {
  61639. for (int i = 0; i < buttons.size(); ++i)
  61640. {
  61641. if (buttons.getUnchecked(i)->getToggleState())
  61642. {
  61643. setCurrentPage (buttons.getUnchecked(i)->getName());
  61644. break;
  61645. }
  61646. }
  61647. }
  61648. END_JUCE_NAMESPACE
  61649. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61650. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61651. #if JUCE_WINDOWS || JUCE_LINUX
  61652. BEGIN_JUCE_NAMESPACE
  61653. SystemTrayIconComponent::SystemTrayIconComponent()
  61654. {
  61655. addToDesktop (0);
  61656. }
  61657. SystemTrayIconComponent::~SystemTrayIconComponent()
  61658. {
  61659. }
  61660. END_JUCE_NAMESPACE
  61661. #endif
  61662. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61663. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61664. BEGIN_JUCE_NAMESPACE
  61665. class AlertWindowTextEditor : public TextEditor
  61666. {
  61667. public:
  61668. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61669. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61670. {
  61671. setSelectAllWhenFocused (true);
  61672. }
  61673. ~AlertWindowTextEditor()
  61674. {
  61675. }
  61676. void returnPressed()
  61677. {
  61678. // pass these up the component hierarchy to be trigger the buttons
  61679. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61680. }
  61681. void escapePressed()
  61682. {
  61683. // pass these up the component hierarchy to be trigger the buttons
  61684. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61685. }
  61686. private:
  61687. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61688. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61689. static juce_wchar getDefaultPasswordChar() throw()
  61690. {
  61691. #if JUCE_LINUX
  61692. return 0x2022;
  61693. #else
  61694. return 0x25cf;
  61695. #endif
  61696. }
  61697. };
  61698. AlertWindow::AlertWindow (const String& title,
  61699. const String& message,
  61700. AlertIconType iconType,
  61701. Component* associatedComponent_)
  61702. : TopLevelWindow (title, true),
  61703. alertIconType (iconType),
  61704. associatedComponent (associatedComponent_)
  61705. {
  61706. if (message.isEmpty())
  61707. text = " "; // to force an update if the message is empty
  61708. setMessage (message);
  61709. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61710. {
  61711. Component* const c = Desktop::getInstance().getComponent (i);
  61712. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61713. {
  61714. setAlwaysOnTop (true);
  61715. break;
  61716. }
  61717. }
  61718. if (! JUCEApplication::isStandaloneApp())
  61719. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61720. lookAndFeelChanged();
  61721. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61722. }
  61723. AlertWindow::~AlertWindow()
  61724. {
  61725. removeAllChildren();
  61726. }
  61727. void AlertWindow::userTriedToCloseWindow()
  61728. {
  61729. exitModalState (0);
  61730. }
  61731. void AlertWindow::setMessage (const String& message)
  61732. {
  61733. const String newMessage (message.substring (0, 2048));
  61734. if (text != newMessage)
  61735. {
  61736. text = newMessage;
  61737. font.setHeight (15.0f);
  61738. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61739. textLayout.setText (getName() + "\n\n", titleFont);
  61740. textLayout.appendText (text, font);
  61741. updateLayout (true);
  61742. repaint();
  61743. }
  61744. }
  61745. void AlertWindow::buttonClicked (Button* button)
  61746. {
  61747. if (button->getParentComponent() != 0)
  61748. button->getParentComponent()->exitModalState (button->getCommandID());
  61749. }
  61750. void AlertWindow::addButton (const String& name,
  61751. const int returnValue,
  61752. const KeyPress& shortcutKey1,
  61753. const KeyPress& shortcutKey2)
  61754. {
  61755. TextButton* const b = new TextButton (name, String::empty);
  61756. buttons.add (b);
  61757. b->setWantsKeyboardFocus (true);
  61758. b->setMouseClickGrabsKeyboardFocus (false);
  61759. b->setCommandToTrigger (0, returnValue, false);
  61760. b->addShortcut (shortcutKey1);
  61761. b->addShortcut (shortcutKey2);
  61762. b->addButtonListener (this);
  61763. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61764. addAndMakeVisible (b, 0);
  61765. updateLayout (false);
  61766. }
  61767. int AlertWindow::getNumButtons() const
  61768. {
  61769. return buttons.size();
  61770. }
  61771. void AlertWindow::triggerButtonClick (const String& buttonName)
  61772. {
  61773. for (int i = buttons.size(); --i >= 0;)
  61774. {
  61775. TextButton* const b = buttons.getUnchecked(i);
  61776. if (buttonName == b->getName())
  61777. {
  61778. b->triggerClick();
  61779. break;
  61780. }
  61781. }
  61782. }
  61783. void AlertWindow::addTextEditor (const String& name,
  61784. const String& initialContents,
  61785. const String& onScreenLabel,
  61786. const bool isPasswordBox)
  61787. {
  61788. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61789. textBoxes.add (tc);
  61790. allComps.add (tc);
  61791. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61792. tc->setFont (font);
  61793. tc->setText (initialContents);
  61794. tc->setCaretPosition (initialContents.length());
  61795. addAndMakeVisible (tc);
  61796. textboxNames.add (onScreenLabel);
  61797. updateLayout (false);
  61798. }
  61799. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61800. {
  61801. for (int i = textBoxes.size(); --i >= 0;)
  61802. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61803. return textBoxes.getUnchecked(i);
  61804. return 0;
  61805. }
  61806. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61807. {
  61808. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61809. return t != 0 ? t->getText() : String::empty;
  61810. }
  61811. void AlertWindow::addComboBox (const String& name,
  61812. const StringArray& items,
  61813. const String& onScreenLabel)
  61814. {
  61815. ComboBox* const cb = new ComboBox (name);
  61816. comboBoxes.add (cb);
  61817. allComps.add (cb);
  61818. for (int i = 0; i < items.size(); ++i)
  61819. cb->addItem (items[i], i + 1);
  61820. addAndMakeVisible (cb);
  61821. cb->setSelectedItemIndex (0);
  61822. comboBoxNames.add (onScreenLabel);
  61823. updateLayout (false);
  61824. }
  61825. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61826. {
  61827. for (int i = comboBoxes.size(); --i >= 0;)
  61828. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61829. return comboBoxes.getUnchecked(i);
  61830. return 0;
  61831. }
  61832. class AlertTextComp : public TextEditor
  61833. {
  61834. public:
  61835. AlertTextComp (const String& message,
  61836. const Font& font)
  61837. {
  61838. setReadOnly (true);
  61839. setMultiLine (true, true);
  61840. setCaretVisible (false);
  61841. setScrollbarsShown (true);
  61842. lookAndFeelChanged();
  61843. setWantsKeyboardFocus (false);
  61844. setFont (font);
  61845. setText (message, false);
  61846. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61847. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61848. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61849. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61850. }
  61851. ~AlertTextComp()
  61852. {
  61853. }
  61854. int getPreferredWidth() const throw() { return bestWidth; }
  61855. void updateLayout (const int width)
  61856. {
  61857. TextLayout text;
  61858. text.appendText (getText(), getFont());
  61859. text.layout (width - 8, Justification::topLeft, true);
  61860. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61861. }
  61862. private:
  61863. int bestWidth;
  61864. AlertTextComp (const AlertTextComp&);
  61865. AlertTextComp& operator= (const AlertTextComp&);
  61866. };
  61867. void AlertWindow::addTextBlock (const String& textBlock)
  61868. {
  61869. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61870. textBlocks.add (c);
  61871. allComps.add (c);
  61872. addAndMakeVisible (c);
  61873. updateLayout (false);
  61874. }
  61875. void AlertWindow::addProgressBarComponent (double& progressValue)
  61876. {
  61877. ProgressBar* const pb = new ProgressBar (progressValue);
  61878. progressBars.add (pb);
  61879. allComps.add (pb);
  61880. addAndMakeVisible (pb);
  61881. updateLayout (false);
  61882. }
  61883. void AlertWindow::addCustomComponent (Component* const component)
  61884. {
  61885. customComps.add (component);
  61886. allComps.add (component);
  61887. addAndMakeVisible (component);
  61888. updateLayout (false);
  61889. }
  61890. int AlertWindow::getNumCustomComponents() const
  61891. {
  61892. return customComps.size();
  61893. }
  61894. Component* AlertWindow::getCustomComponent (const int index) const
  61895. {
  61896. return customComps [index];
  61897. }
  61898. Component* AlertWindow::removeCustomComponent (const int index)
  61899. {
  61900. Component* const c = getCustomComponent (index);
  61901. if (c != 0)
  61902. {
  61903. customComps.removeValue (c);
  61904. allComps.removeValue (c);
  61905. removeChildComponent (c);
  61906. updateLayout (false);
  61907. }
  61908. return c;
  61909. }
  61910. void AlertWindow::paint (Graphics& g)
  61911. {
  61912. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61913. g.setColour (findColour (textColourId));
  61914. g.setFont (getLookAndFeel().getAlertWindowFont());
  61915. int i;
  61916. for (i = textBoxes.size(); --i >= 0;)
  61917. {
  61918. const TextEditor* const te = textBoxes.getUnchecked(i);
  61919. g.drawFittedText (textboxNames[i],
  61920. te->getX(), te->getY() - 14,
  61921. te->getWidth(), 14,
  61922. Justification::centredLeft, 1);
  61923. }
  61924. for (i = comboBoxNames.size(); --i >= 0;)
  61925. {
  61926. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61927. g.drawFittedText (comboBoxNames[i],
  61928. cb->getX(), cb->getY() - 14,
  61929. cb->getWidth(), 14,
  61930. Justification::centredLeft, 1);
  61931. }
  61932. for (i = customComps.size(); --i >= 0;)
  61933. {
  61934. const Component* const c = customComps.getUnchecked(i);
  61935. g.drawFittedText (c->getName(),
  61936. c->getX(), c->getY() - 14,
  61937. c->getWidth(), 14,
  61938. Justification::centredLeft, 1);
  61939. }
  61940. }
  61941. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61942. {
  61943. const int titleH = 24;
  61944. const int iconWidth = 80;
  61945. const int wid = jmax (font.getStringWidth (text),
  61946. font.getStringWidth (getName()));
  61947. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61948. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61949. const int edgeGap = 10;
  61950. const int labelHeight = 18;
  61951. int iconSpace;
  61952. if (alertIconType == NoIcon)
  61953. {
  61954. textLayout.layout (w, Justification::horizontallyCentred, true);
  61955. iconSpace = 0;
  61956. }
  61957. else
  61958. {
  61959. textLayout.layout (w, Justification::left, true);
  61960. iconSpace = iconWidth;
  61961. }
  61962. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61963. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61964. const int textLayoutH = textLayout.getHeight();
  61965. const int textBottom = 16 + titleH + textLayoutH;
  61966. int h = textBottom;
  61967. int buttonW = 40;
  61968. int i;
  61969. for (i = 0; i < buttons.size(); ++i)
  61970. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61971. w = jmax (buttonW, w);
  61972. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61973. if (buttons.size() > 0)
  61974. h += 20 + buttons.getUnchecked(0)->getHeight();
  61975. for (i = customComps.size(); --i >= 0;)
  61976. {
  61977. Component* c = customComps.getUnchecked(i);
  61978. w = jmax (w, (c->getWidth() * 100) / 80);
  61979. h += 10 + c->getHeight();
  61980. if (c->getName().isNotEmpty())
  61981. h += labelHeight;
  61982. }
  61983. for (i = textBlocks.size(); --i >= 0;)
  61984. {
  61985. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61986. w = jmax (w, ac->getPreferredWidth());
  61987. }
  61988. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61989. for (i = textBlocks.size(); --i >= 0;)
  61990. {
  61991. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61992. ac->updateLayout ((int) (w * 0.8f));
  61993. h += ac->getHeight() + 10;
  61994. }
  61995. h = jmin (getParentHeight() - 50, h);
  61996. if (onlyIncreaseSize)
  61997. {
  61998. w = jmax (w, getWidth());
  61999. h = jmax (h, getHeight());
  62000. }
  62001. if (! isVisible())
  62002. {
  62003. centreAroundComponent (associatedComponent, w, h);
  62004. }
  62005. else
  62006. {
  62007. const int cx = getX() + getWidth() / 2;
  62008. const int cy = getY() + getHeight() / 2;
  62009. setBounds (cx - w / 2,
  62010. cy - h / 2,
  62011. w, h);
  62012. }
  62013. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62014. const int spacer = 16;
  62015. int totalWidth = -spacer;
  62016. for (i = buttons.size(); --i >= 0;)
  62017. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  62018. int x = (w - totalWidth) / 2;
  62019. int y = (int) (getHeight() * 0.95f);
  62020. for (i = 0; i < buttons.size(); ++i)
  62021. {
  62022. TextButton* const c = buttons.getUnchecked(i);
  62023. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62024. c->setTopLeftPosition (x, ny);
  62025. if (ny < y)
  62026. y = ny;
  62027. x += c->getWidth() + spacer;
  62028. c->toFront (false);
  62029. }
  62030. y = textBottom;
  62031. for (i = 0; i < allComps.size(); ++i)
  62032. {
  62033. Component* const c = allComps.getUnchecked(i);
  62034. h = 22;
  62035. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  62036. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62037. y += labelHeight;
  62038. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  62039. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62040. y += labelHeight;
  62041. if (customComps.contains (c))
  62042. {
  62043. if (c->getName().isNotEmpty())
  62044. y += labelHeight;
  62045. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62046. h = c->getHeight();
  62047. }
  62048. else if (textBlocks.contains (c))
  62049. {
  62050. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62051. h = c->getHeight();
  62052. }
  62053. else
  62054. {
  62055. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62056. }
  62057. y += h + 10;
  62058. }
  62059. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62060. }
  62061. bool AlertWindow::containsAnyExtraComponents() const
  62062. {
  62063. return allComps.size() > 0;
  62064. }
  62065. void AlertWindow::mouseDown (const MouseEvent&)
  62066. {
  62067. dragger.startDraggingComponent (this, &constrainer);
  62068. }
  62069. void AlertWindow::mouseDrag (const MouseEvent& e)
  62070. {
  62071. dragger.dragComponent (this, e);
  62072. }
  62073. bool AlertWindow::keyPressed (const KeyPress& key)
  62074. {
  62075. for (int i = buttons.size(); --i >= 0;)
  62076. {
  62077. TextButton* const b = buttons.getUnchecked(i);
  62078. if (b->isRegisteredForShortcut (key))
  62079. {
  62080. b->triggerClick();
  62081. return true;
  62082. }
  62083. }
  62084. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62085. {
  62086. exitModalState (0);
  62087. return true;
  62088. }
  62089. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62090. {
  62091. buttons.getUnchecked(0)->triggerClick();
  62092. return true;
  62093. }
  62094. return false;
  62095. }
  62096. void AlertWindow::lookAndFeelChanged()
  62097. {
  62098. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62099. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62100. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62101. }
  62102. int AlertWindow::getDesktopWindowStyleFlags() const
  62103. {
  62104. return getLookAndFeel().getAlertBoxWindowFlags();
  62105. }
  62106. class AlertWindowInfo
  62107. {
  62108. public:
  62109. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  62110. AlertWindow::AlertIconType iconType_, int numButtons_)
  62111. : title (title_), message (message_), iconType (iconType_),
  62112. numButtons (numButtons_), returnValue (0), associatedComponent (component)
  62113. {
  62114. }
  62115. String title, message, button1, button2, button3;
  62116. AlertWindow::AlertIconType iconType;
  62117. int numButtons, returnValue;
  62118. Component::SafePointer<Component> associatedComponent;
  62119. int showModal() const
  62120. {
  62121. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62122. return returnValue;
  62123. }
  62124. private:
  62125. void show()
  62126. {
  62127. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62128. : LookAndFeel::getDefaultLookAndFeel();
  62129. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62130. iconType, numButtons, associatedComponent));
  62131. jassert (alertBox != 0); // you have to return one of these!
  62132. returnValue = alertBox->runModalLoop();
  62133. }
  62134. static void* showCallback (void* userData)
  62135. {
  62136. static_cast <AlertWindowInfo*> (userData)->show();
  62137. return 0;
  62138. }
  62139. };
  62140. void AlertWindow::showMessageBox (AlertIconType iconType,
  62141. const String& title,
  62142. const String& message,
  62143. const String& buttonText,
  62144. Component* associatedComponent)
  62145. {
  62146. AlertWindowInfo info (title, message, associatedComponent, iconType, 1);
  62147. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62148. info.showModal();
  62149. }
  62150. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62151. const String& title,
  62152. const String& message,
  62153. const String& button1Text,
  62154. const String& button2Text,
  62155. Component* associatedComponent)
  62156. {
  62157. AlertWindowInfo info (title, message, associatedComponent, iconType, 2);
  62158. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62159. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62160. return info.showModal() != 0;
  62161. }
  62162. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62163. const String& title,
  62164. const String& message,
  62165. const String& button1Text,
  62166. const String& button2Text,
  62167. const String& button3Text,
  62168. Component* associatedComponent)
  62169. {
  62170. AlertWindowInfo info (title, message, associatedComponent, iconType, 3);
  62171. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62172. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62173. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62174. return info.showModal();
  62175. }
  62176. END_JUCE_NAMESPACE
  62177. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62178. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62179. BEGIN_JUCE_NAMESPACE
  62180. CallOutBox::CallOutBox (Component& contentComponent,
  62181. Component& componentToPointTo,
  62182. Component* const parentComponent)
  62183. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62184. {
  62185. addAndMakeVisible (&content);
  62186. if (parentComponent != 0)
  62187. {
  62188. parentComponent->addChildComponent (this);
  62189. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  62190. parentComponent->getLocalBounds());
  62191. setVisible (true);
  62192. }
  62193. else
  62194. {
  62195. if (! JUCEApplication::isStandaloneApp())
  62196. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62197. updatePosition (componentToPointTo.getScreenBounds(),
  62198. componentToPointTo.getParentMonitorArea());
  62199. addToDesktop (ComponentPeer::windowIsTemporary);
  62200. }
  62201. }
  62202. CallOutBox::~CallOutBox()
  62203. {
  62204. }
  62205. void CallOutBox::setArrowSize (const float newSize)
  62206. {
  62207. arrowSize = newSize;
  62208. borderSpace = jmax (20, (int) arrowSize);
  62209. refreshPath();
  62210. }
  62211. void CallOutBox::paint (Graphics& g)
  62212. {
  62213. if (background.isNull())
  62214. {
  62215. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62216. Graphics g (background);
  62217. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62218. }
  62219. g.setColour (Colours::black);
  62220. g.drawImageAt (background, 0, 0);
  62221. }
  62222. void CallOutBox::resized()
  62223. {
  62224. content.setTopLeftPosition (borderSpace, borderSpace);
  62225. refreshPath();
  62226. }
  62227. void CallOutBox::moved()
  62228. {
  62229. refreshPath();
  62230. }
  62231. void CallOutBox::childBoundsChanged (Component*)
  62232. {
  62233. updatePosition (targetArea, availableArea);
  62234. }
  62235. bool CallOutBox::hitTest (int x, int y)
  62236. {
  62237. return outline.contains ((float) x, (float) y);
  62238. }
  62239. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62240. void CallOutBox::inputAttemptWhenModal()
  62241. {
  62242. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62243. if (targetArea.contains (mousePos))
  62244. {
  62245. // if you click on the area that originally popped-up the callout, you expect it
  62246. // to get rid of the box, but deleting the box here allows the click to pass through and
  62247. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62248. postCommandMessage (callOutBoxDismissCommandId);
  62249. }
  62250. else
  62251. {
  62252. exitModalState (0);
  62253. setVisible (false);
  62254. }
  62255. }
  62256. void CallOutBox::handleCommandMessage (int commandId)
  62257. {
  62258. Component::handleCommandMessage (commandId);
  62259. if (commandId == callOutBoxDismissCommandId)
  62260. {
  62261. exitModalState (0);
  62262. setVisible (false);
  62263. }
  62264. }
  62265. bool CallOutBox::keyPressed (const KeyPress& key)
  62266. {
  62267. if (key.isKeyCode (KeyPress::escapeKey))
  62268. {
  62269. inputAttemptWhenModal();
  62270. return true;
  62271. }
  62272. return false;
  62273. }
  62274. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62275. {
  62276. targetArea = newAreaToPointTo;
  62277. availableArea = newAreaToFitIn;
  62278. Rectangle<int> bounds (0, 0,
  62279. content.getWidth() + borderSpace * 2,
  62280. content.getHeight() + borderSpace * 2);
  62281. const int hw = bounds.getWidth() / 2;
  62282. const int hh = bounds.getHeight() / 2;
  62283. const float hwReduced = (float) (hw - borderSpace * 3);
  62284. const float hhReduced = (float) (hh - borderSpace * 3);
  62285. const float arrowIndent = borderSpace - arrowSize;
  62286. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62287. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62288. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62289. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62290. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62291. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62292. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62293. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62294. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62295. float nearest = 1.0e9f;
  62296. for (int i = 0; i < 4; ++i)
  62297. {
  62298. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62299. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62300. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62301. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62302. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62303. distanceFromCentre *= 2.0f;
  62304. if (distanceFromCentre < nearest)
  62305. {
  62306. nearest = distanceFromCentre;
  62307. targetPoint = targets[i];
  62308. bounds.setPosition ((int) (centre.getX() - hw),
  62309. (int) (centre.getY() - hh));
  62310. }
  62311. }
  62312. setBounds (bounds);
  62313. }
  62314. void CallOutBox::refreshPath()
  62315. {
  62316. repaint();
  62317. background = Image::null;
  62318. outline.clear();
  62319. const float gap = 4.5f;
  62320. const float cornerSize = 9.0f;
  62321. const float cornerSize2 = 2.0f * cornerSize;
  62322. const float arrowBaseWidth = arrowSize * 0.7f;
  62323. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62324. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62325. outline.startNewSubPath (left + cornerSize, top);
  62326. if (targetY <= top)
  62327. {
  62328. outline.lineTo (targetX - arrowBaseWidth, top);
  62329. outline.lineTo (targetX, targetY);
  62330. outline.lineTo (targetX + arrowBaseWidth, top);
  62331. }
  62332. outline.lineTo (right - cornerSize, top);
  62333. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62334. if (targetX >= right)
  62335. {
  62336. outline.lineTo (right, targetY - arrowBaseWidth);
  62337. outline.lineTo (targetX, targetY);
  62338. outline.lineTo (right, targetY + arrowBaseWidth);
  62339. }
  62340. outline.lineTo (right, bottom - cornerSize);
  62341. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62342. if (targetY >= bottom)
  62343. {
  62344. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62345. outline.lineTo (targetX, targetY);
  62346. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62347. }
  62348. outline.lineTo (left + cornerSize, bottom);
  62349. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62350. if (targetX <= left)
  62351. {
  62352. outline.lineTo (left, targetY + arrowBaseWidth);
  62353. outline.lineTo (targetX, targetY);
  62354. outline.lineTo (left, targetY - arrowBaseWidth);
  62355. }
  62356. outline.lineTo (left, top + cornerSize);
  62357. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62358. outline.closeSubPath();
  62359. }
  62360. END_JUCE_NAMESPACE
  62361. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62362. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62363. BEGIN_JUCE_NAMESPACE
  62364. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62365. static Array <ComponentPeer*> heavyweightPeers;
  62366. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62367. : component (component_),
  62368. styleFlags (styleFlags_),
  62369. lastPaintTime (0),
  62370. constrainer (0),
  62371. lastDragAndDropCompUnderMouse (0),
  62372. fakeMouseMessageSent (false),
  62373. isWindowMinimised (false)
  62374. {
  62375. heavyweightPeers.add (this);
  62376. }
  62377. ComponentPeer::~ComponentPeer()
  62378. {
  62379. heavyweightPeers.removeValue (this);
  62380. Desktop::getInstance().triggerFocusCallback();
  62381. }
  62382. int ComponentPeer::getNumPeers() throw()
  62383. {
  62384. return heavyweightPeers.size();
  62385. }
  62386. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62387. {
  62388. return heavyweightPeers [index];
  62389. }
  62390. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62391. {
  62392. for (int i = heavyweightPeers.size(); --i >= 0;)
  62393. {
  62394. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62395. if (peer->getComponent() == component)
  62396. return peer;
  62397. }
  62398. return 0;
  62399. }
  62400. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62401. {
  62402. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62403. }
  62404. void ComponentPeer::updateCurrentModifiers() throw()
  62405. {
  62406. ModifierKeys::updateCurrentModifiers();
  62407. }
  62408. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62409. {
  62410. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62411. jassert (mouse != 0); // not enough sources!
  62412. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62413. }
  62414. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62415. {
  62416. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62417. jassert (mouse != 0); // not enough sources!
  62418. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62419. }
  62420. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62421. {
  62422. Graphics g (&contextToPaintTo);
  62423. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62424. g.saveState();
  62425. #endif
  62426. JUCE_TRY
  62427. {
  62428. component->paintEntireComponent (g, true);
  62429. }
  62430. JUCE_CATCH_EXCEPTION
  62431. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62432. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62433. // clearly when things are being repainted.
  62434. {
  62435. g.restoreState();
  62436. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62437. (uint8) Random::getSystemRandom().nextInt (255),
  62438. (uint8) Random::getSystemRandom().nextInt (255),
  62439. (uint8) 0x50));
  62440. }
  62441. #endif
  62442. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62443. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62444. mess up a lot of the calculations that the library needs to do.
  62445. */
  62446. jassert (roundToInt (10.1f) == 10);
  62447. }
  62448. bool ComponentPeer::handleKeyPress (const int keyCode,
  62449. const juce_wchar textCharacter)
  62450. {
  62451. updateCurrentModifiers();
  62452. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62453. ? Component::getCurrentlyFocusedComponent()
  62454. : component;
  62455. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62456. {
  62457. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62458. if (currentModalComp != 0)
  62459. target = currentModalComp;
  62460. }
  62461. const KeyPress keyInfo (keyCode,
  62462. ModifierKeys::getCurrentModifiers().getRawFlags()
  62463. & ModifierKeys::allKeyboardModifiers,
  62464. textCharacter);
  62465. bool keyWasUsed = false;
  62466. while (target != 0)
  62467. {
  62468. const Component::SafePointer<Component> deletionChecker (target);
  62469. if (target->keyListeners_ != 0)
  62470. {
  62471. for (int i = target->keyListeners_->size(); --i >= 0;)
  62472. {
  62473. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62474. if (keyWasUsed || deletionChecker == 0)
  62475. return keyWasUsed;
  62476. i = jmin (i, target->keyListeners_->size());
  62477. }
  62478. }
  62479. keyWasUsed = target->keyPressed (keyInfo);
  62480. if (keyWasUsed || deletionChecker == 0)
  62481. break;
  62482. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62483. {
  62484. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62485. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62486. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62487. break;
  62488. }
  62489. target = target->parentComponent_;
  62490. }
  62491. return keyWasUsed;
  62492. }
  62493. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62494. {
  62495. updateCurrentModifiers();
  62496. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62497. ? Component::getCurrentlyFocusedComponent()
  62498. : component;
  62499. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62500. {
  62501. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62502. if (currentModalComp != 0)
  62503. target = currentModalComp;
  62504. }
  62505. bool keyWasUsed = false;
  62506. while (target != 0)
  62507. {
  62508. const Component::SafePointer<Component> deletionChecker (target);
  62509. keyWasUsed = target->keyStateChanged (isKeyDown);
  62510. if (keyWasUsed || deletionChecker == 0)
  62511. break;
  62512. if (target->keyListeners_ != 0)
  62513. {
  62514. for (int i = target->keyListeners_->size(); --i >= 0;)
  62515. {
  62516. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62517. if (keyWasUsed || deletionChecker == 0)
  62518. return keyWasUsed;
  62519. i = jmin (i, target->keyListeners_->size());
  62520. }
  62521. }
  62522. target = target->parentComponent_;
  62523. }
  62524. return keyWasUsed;
  62525. }
  62526. void ComponentPeer::handleModifierKeysChange()
  62527. {
  62528. updateCurrentModifiers();
  62529. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62530. if (target == 0)
  62531. target = Component::getCurrentlyFocusedComponent();
  62532. if (target == 0)
  62533. target = component;
  62534. if (target != 0)
  62535. target->internalModifierKeysChanged();
  62536. }
  62537. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62538. {
  62539. Component* const c = Component::getCurrentlyFocusedComponent();
  62540. if (component->isParentOf (c))
  62541. {
  62542. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62543. if (ti != 0 && ti->isTextInputActive())
  62544. return ti;
  62545. }
  62546. return 0;
  62547. }
  62548. void ComponentPeer::handleBroughtToFront()
  62549. {
  62550. updateCurrentModifiers();
  62551. if (component != 0)
  62552. component->internalBroughtToFront();
  62553. }
  62554. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62555. {
  62556. constrainer = newConstrainer;
  62557. }
  62558. void ComponentPeer::handleMovedOrResized()
  62559. {
  62560. updateCurrentModifiers();
  62561. const bool nowMinimised = isMinimised();
  62562. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62563. {
  62564. const Component::SafePointer<Component> deletionChecker (component);
  62565. const Rectangle<int> newBounds (getBounds());
  62566. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62567. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62568. if (wasMoved || wasResized)
  62569. {
  62570. component->bounds_ = newBounds;
  62571. if (wasResized)
  62572. component->repaint();
  62573. component->sendMovedResizedMessages (wasMoved, wasResized);
  62574. if (deletionChecker == 0)
  62575. return;
  62576. }
  62577. }
  62578. if (isWindowMinimised != nowMinimised)
  62579. {
  62580. isWindowMinimised = nowMinimised;
  62581. component->minimisationStateChanged (nowMinimised);
  62582. component->sendVisibilityChangeMessage();
  62583. }
  62584. if (! isFullScreen())
  62585. lastNonFullscreenBounds = component->getBounds();
  62586. }
  62587. void ComponentPeer::handleFocusGain()
  62588. {
  62589. updateCurrentModifiers();
  62590. if (component->isParentOf (lastFocusedComponent))
  62591. {
  62592. Component::currentlyFocusedComponent = lastFocusedComponent;
  62593. Desktop::getInstance().triggerFocusCallback();
  62594. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62595. }
  62596. else
  62597. {
  62598. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62599. component->grabKeyboardFocus();
  62600. else
  62601. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62602. }
  62603. }
  62604. void ComponentPeer::handleFocusLoss()
  62605. {
  62606. updateCurrentModifiers();
  62607. if (component->hasKeyboardFocus (true))
  62608. {
  62609. lastFocusedComponent = Component::currentlyFocusedComponent;
  62610. if (lastFocusedComponent != 0)
  62611. {
  62612. Component::currentlyFocusedComponent = 0;
  62613. Desktop::getInstance().triggerFocusCallback();
  62614. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62615. }
  62616. }
  62617. }
  62618. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62619. {
  62620. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62621. ? static_cast <Component*> (lastFocusedComponent)
  62622. : component;
  62623. }
  62624. void ComponentPeer::handleScreenSizeChange()
  62625. {
  62626. updateCurrentModifiers();
  62627. component->parentSizeChanged();
  62628. handleMovedOrResized();
  62629. }
  62630. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62631. {
  62632. lastNonFullscreenBounds = newBounds;
  62633. }
  62634. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62635. {
  62636. return lastNonFullscreenBounds;
  62637. }
  62638. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62639. {
  62640. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62641. }
  62642. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62643. {
  62644. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62645. }
  62646. namespace ComponentPeerHelpers
  62647. {
  62648. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62649. const StringArray& files,
  62650. FileDragAndDropTarget* const lastOne)
  62651. {
  62652. while (c != 0)
  62653. {
  62654. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62655. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62656. return t;
  62657. c = c->getParentComponent();
  62658. }
  62659. return 0;
  62660. }
  62661. }
  62662. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62663. {
  62664. updateCurrentModifiers();
  62665. FileDragAndDropTarget* lastTarget
  62666. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62667. FileDragAndDropTarget* newTarget = 0;
  62668. Component* const compUnderMouse = component->getComponentAt (position);
  62669. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62670. {
  62671. lastDragAndDropCompUnderMouse = compUnderMouse;
  62672. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62673. if (newTarget != lastTarget)
  62674. {
  62675. if (lastTarget != 0)
  62676. lastTarget->fileDragExit (files);
  62677. dragAndDropTargetComponent = 0;
  62678. if (newTarget != 0)
  62679. {
  62680. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62681. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62682. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62683. }
  62684. }
  62685. }
  62686. else
  62687. {
  62688. newTarget = lastTarget;
  62689. }
  62690. if (newTarget != 0)
  62691. {
  62692. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62693. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62694. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62695. }
  62696. }
  62697. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62698. {
  62699. handleFileDragMove (files, Point<int> (-1, -1));
  62700. jassert (dragAndDropTargetComponent == 0);
  62701. lastDragAndDropCompUnderMouse = 0;
  62702. }
  62703. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62704. {
  62705. handleFileDragMove (files, position);
  62706. if (dragAndDropTargetComponent != 0)
  62707. {
  62708. FileDragAndDropTarget* const target
  62709. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62710. dragAndDropTargetComponent = 0;
  62711. lastDragAndDropCompUnderMouse = 0;
  62712. if (target != 0)
  62713. {
  62714. Component* const targetComp = dynamic_cast <Component*> (target);
  62715. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62716. {
  62717. targetComp->internalModalInputAttempt();
  62718. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62719. return;
  62720. }
  62721. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62722. target->filesDropped (files, pos.getX(), pos.getY());
  62723. }
  62724. }
  62725. }
  62726. void ComponentPeer::handleUserClosingWindow()
  62727. {
  62728. updateCurrentModifiers();
  62729. component->userTriedToCloseWindow();
  62730. }
  62731. void ComponentPeer::clearMaskedRegion()
  62732. {
  62733. maskedRegion.clear();
  62734. }
  62735. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62736. {
  62737. maskedRegion.add (x, y, w, h);
  62738. }
  62739. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62740. {
  62741. StringArray s;
  62742. s.add ("Software Renderer");
  62743. return s;
  62744. }
  62745. int ComponentPeer::getCurrentRenderingEngine() throw()
  62746. {
  62747. return 0;
  62748. }
  62749. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62750. {
  62751. }
  62752. END_JUCE_NAMESPACE
  62753. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62754. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62755. BEGIN_JUCE_NAMESPACE
  62756. DialogWindow::DialogWindow (const String& name,
  62757. const Colour& backgroundColour_,
  62758. const bool escapeKeyTriggersCloseButton_,
  62759. const bool addToDesktop_)
  62760. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62761. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62762. {
  62763. }
  62764. DialogWindow::~DialogWindow()
  62765. {
  62766. }
  62767. void DialogWindow::resized()
  62768. {
  62769. DocumentWindow::resized();
  62770. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62771. if (escapeKeyTriggersCloseButton
  62772. && getCloseButton() != 0
  62773. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62774. {
  62775. getCloseButton()->addShortcut (esc);
  62776. }
  62777. }
  62778. class TempDialogWindow : public DialogWindow
  62779. {
  62780. public:
  62781. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62782. : DialogWindow (title, colour, escapeCloses, true)
  62783. {
  62784. if (! JUCEApplication::isStandaloneApp())
  62785. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62786. }
  62787. void closeButtonPressed()
  62788. {
  62789. setVisible (false);
  62790. }
  62791. private:
  62792. TempDialogWindow (const TempDialogWindow&);
  62793. TempDialogWindow& operator= (const TempDialogWindow&);
  62794. };
  62795. int DialogWindow::showModalDialog (const String& dialogTitle,
  62796. Component* contentComponent,
  62797. Component* componentToCentreAround,
  62798. const Colour& colour,
  62799. const bool escapeKeyTriggersCloseButton,
  62800. const bool shouldBeResizable,
  62801. const bool useBottomRightCornerResizer)
  62802. {
  62803. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62804. dw.setContentComponent (contentComponent, true, true);
  62805. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62806. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62807. const int result = dw.runModalLoop();
  62808. dw.setContentComponent (0, false);
  62809. return result;
  62810. }
  62811. END_JUCE_NAMESPACE
  62812. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62813. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62814. BEGIN_JUCE_NAMESPACE
  62815. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62816. {
  62817. public:
  62818. ButtonListenerProxy (DocumentWindow& owner_)
  62819. : owner (owner_)
  62820. {
  62821. }
  62822. void buttonClicked (Button* button)
  62823. {
  62824. if (button == owner.getMinimiseButton())
  62825. owner.minimiseButtonPressed();
  62826. else if (button == owner.getMaximiseButton())
  62827. owner.maximiseButtonPressed();
  62828. else if (button == owner.getCloseButton())
  62829. owner.closeButtonPressed();
  62830. }
  62831. juce_UseDebuggingNewOperator
  62832. private:
  62833. DocumentWindow& owner;
  62834. ButtonListenerProxy (const ButtonListenerProxy&);
  62835. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  62836. };
  62837. DocumentWindow::DocumentWindow (const String& title,
  62838. const Colour& backgroundColour,
  62839. const int requiredButtons_,
  62840. const bool addToDesktop_)
  62841. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62842. titleBarHeight (26),
  62843. menuBarHeight (24),
  62844. requiredButtons (requiredButtons_),
  62845. #if JUCE_MAC
  62846. positionTitleBarButtonsOnLeft (true),
  62847. #else
  62848. positionTitleBarButtonsOnLeft (false),
  62849. #endif
  62850. drawTitleTextCentred (true),
  62851. menuBarModel (0)
  62852. {
  62853. setResizeLimits (128, 128, 32768, 32768);
  62854. lookAndFeelChanged();
  62855. }
  62856. DocumentWindow::~DocumentWindow()
  62857. {
  62858. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62859. titleBarButtons[i] = 0;
  62860. menuBar = 0;
  62861. }
  62862. void DocumentWindow::repaintTitleBar()
  62863. {
  62864. repaint (getTitleBarArea());
  62865. }
  62866. void DocumentWindow::setName (const String& newName)
  62867. {
  62868. if (newName != getName())
  62869. {
  62870. Component::setName (newName);
  62871. repaintTitleBar();
  62872. }
  62873. }
  62874. void DocumentWindow::setIcon (const Image& imageToUse)
  62875. {
  62876. titleBarIcon = imageToUse;
  62877. repaintTitleBar();
  62878. }
  62879. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62880. {
  62881. titleBarHeight = newHeight;
  62882. resized();
  62883. repaintTitleBar();
  62884. }
  62885. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62886. const bool positionTitleBarButtonsOnLeft_)
  62887. {
  62888. requiredButtons = requiredButtons_;
  62889. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62890. lookAndFeelChanged();
  62891. }
  62892. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62893. {
  62894. drawTitleTextCentred = textShouldBeCentred;
  62895. repaintTitleBar();
  62896. }
  62897. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62898. const int menuBarHeight_)
  62899. {
  62900. if (menuBarModel != menuBarModel_)
  62901. {
  62902. menuBar = 0;
  62903. menuBarModel = menuBarModel_;
  62904. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62905. : getLookAndFeel().getDefaultMenuBarHeight();
  62906. if (menuBarModel != 0)
  62907. {
  62908. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62909. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62910. menuBar->setEnabled (isActiveWindow());
  62911. }
  62912. resized();
  62913. }
  62914. }
  62915. void DocumentWindow::closeButtonPressed()
  62916. {
  62917. /* If you've got a close button, you have to override this method to get
  62918. rid of your window!
  62919. If the window is just a pop-up, you should override this method and make
  62920. it delete the window in whatever way is appropriate for your app. E.g. you
  62921. might just want to call "delete this".
  62922. If your app is centred around this window such that the whole app should quit when
  62923. the window is closed, then you will probably want to use this method as an opportunity
  62924. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62925. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62926. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62927. or closing it via the taskbar icon on Windows).
  62928. */
  62929. jassertfalse;
  62930. }
  62931. void DocumentWindow::minimiseButtonPressed()
  62932. {
  62933. setMinimised (true);
  62934. }
  62935. void DocumentWindow::maximiseButtonPressed()
  62936. {
  62937. setFullScreen (! isFullScreen());
  62938. }
  62939. void DocumentWindow::paint (Graphics& g)
  62940. {
  62941. ResizableWindow::paint (g);
  62942. if (resizableBorder == 0)
  62943. {
  62944. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62945. const BorderSize border (getBorderThickness());
  62946. g.fillRect (0, 0, getWidth(), border.getTop());
  62947. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62948. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62949. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62950. }
  62951. const Rectangle<int> titleBarArea (getTitleBarArea());
  62952. g.reduceClipRegion (titleBarArea);
  62953. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62954. int titleSpaceX1 = 6;
  62955. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62956. for (int i = 0; i < 3; ++i)
  62957. {
  62958. if (titleBarButtons[i] != 0)
  62959. {
  62960. if (positionTitleBarButtonsOnLeft)
  62961. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62962. else
  62963. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62964. }
  62965. }
  62966. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62967. titleBarArea.getWidth(),
  62968. titleBarArea.getHeight(),
  62969. titleSpaceX1,
  62970. jmax (1, titleSpaceX2 - titleSpaceX1),
  62971. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62972. ! drawTitleTextCentred);
  62973. }
  62974. void DocumentWindow::resized()
  62975. {
  62976. ResizableWindow::resized();
  62977. if (titleBarButtons[1] != 0)
  62978. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62979. const Rectangle<int> titleBarArea (getTitleBarArea());
  62980. getLookAndFeel()
  62981. .positionDocumentWindowButtons (*this,
  62982. titleBarArea.getX(), titleBarArea.getY(),
  62983. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62984. titleBarButtons[0],
  62985. titleBarButtons[1],
  62986. titleBarButtons[2],
  62987. positionTitleBarButtonsOnLeft);
  62988. if (menuBar != 0)
  62989. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62990. titleBarArea.getWidth(), menuBarHeight);
  62991. }
  62992. const BorderSize DocumentWindow::getBorderThickness()
  62993. {
  62994. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62995. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62996. }
  62997. const BorderSize DocumentWindow::getContentComponentBorder()
  62998. {
  62999. BorderSize border (getBorderThickness());
  63000. border.setTop (border.getTop()
  63001. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63002. + (menuBar != 0 ? menuBarHeight : 0));
  63003. return border;
  63004. }
  63005. int DocumentWindow::getTitleBarHeight() const
  63006. {
  63007. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63008. }
  63009. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63010. {
  63011. const BorderSize border (getBorderThickness());
  63012. return Rectangle<int> (border.getLeft(), border.getTop(),
  63013. getWidth() - border.getLeftAndRight(),
  63014. getTitleBarHeight());
  63015. }
  63016. Button* DocumentWindow::getCloseButton() const throw()
  63017. {
  63018. return titleBarButtons[2];
  63019. }
  63020. Button* DocumentWindow::getMinimiseButton() const throw()
  63021. {
  63022. return titleBarButtons[0];
  63023. }
  63024. Button* DocumentWindow::getMaximiseButton() const throw()
  63025. {
  63026. return titleBarButtons[1];
  63027. }
  63028. int DocumentWindow::getDesktopWindowStyleFlags() const
  63029. {
  63030. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63031. if ((requiredButtons & minimiseButton) != 0)
  63032. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63033. if ((requiredButtons & maximiseButton) != 0)
  63034. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63035. if ((requiredButtons & closeButton) != 0)
  63036. styleFlags |= ComponentPeer::windowHasCloseButton;
  63037. return styleFlags;
  63038. }
  63039. void DocumentWindow::lookAndFeelChanged()
  63040. {
  63041. int i;
  63042. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63043. titleBarButtons[i] = 0;
  63044. if (! isUsingNativeTitleBar())
  63045. {
  63046. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63047. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63048. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63049. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63050. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63051. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63052. for (i = 0; i < 3; ++i)
  63053. {
  63054. if (titleBarButtons[i] != 0)
  63055. {
  63056. if (buttonListener == 0)
  63057. buttonListener = new ButtonListenerProxy (*this);
  63058. titleBarButtons[i]->addButtonListener (buttonListener);
  63059. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63060. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63061. Component::addAndMakeVisible (titleBarButtons[i]);
  63062. }
  63063. }
  63064. if (getCloseButton() != 0)
  63065. {
  63066. #if JUCE_MAC
  63067. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63068. #else
  63069. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63070. #endif
  63071. }
  63072. }
  63073. activeWindowStatusChanged();
  63074. ResizableWindow::lookAndFeelChanged();
  63075. }
  63076. void DocumentWindow::parentHierarchyChanged()
  63077. {
  63078. lookAndFeelChanged();
  63079. }
  63080. void DocumentWindow::activeWindowStatusChanged()
  63081. {
  63082. ResizableWindow::activeWindowStatusChanged();
  63083. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63084. if (titleBarButtons[i] != 0)
  63085. titleBarButtons[i]->setEnabled (isActiveWindow());
  63086. if (menuBar != 0)
  63087. menuBar->setEnabled (isActiveWindow());
  63088. }
  63089. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63090. {
  63091. if (getTitleBarArea().contains (e.x, e.y)
  63092. && getMaximiseButton() != 0)
  63093. {
  63094. getMaximiseButton()->triggerClick();
  63095. }
  63096. }
  63097. void DocumentWindow::userTriedToCloseWindow()
  63098. {
  63099. closeButtonPressed();
  63100. }
  63101. END_JUCE_NAMESPACE
  63102. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63103. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63104. BEGIN_JUCE_NAMESPACE
  63105. ResizableWindow::ResizableWindow (const String& name,
  63106. const bool addToDesktop_)
  63107. : TopLevelWindow (name, addToDesktop_),
  63108. resizeToFitContent (false),
  63109. fullscreen (false),
  63110. lastNonFullScreenPos (50, 50, 256, 256),
  63111. constrainer (0)
  63112. #if JUCE_DEBUG
  63113. , hasBeenResized (false)
  63114. #endif
  63115. {
  63116. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63117. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63118. if (addToDesktop_)
  63119. Component::addToDesktop (getDesktopWindowStyleFlags());
  63120. }
  63121. ResizableWindow::ResizableWindow (const String& name,
  63122. const Colour& backgroundColour_,
  63123. const bool addToDesktop_)
  63124. : TopLevelWindow (name, addToDesktop_),
  63125. resizeToFitContent (false),
  63126. fullscreen (false),
  63127. lastNonFullScreenPos (50, 50, 256, 256),
  63128. constrainer (0)
  63129. #if JUCE_DEBUG
  63130. , hasBeenResized (false)
  63131. #endif
  63132. {
  63133. setBackgroundColour (backgroundColour_);
  63134. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63135. if (addToDesktop_)
  63136. Component::addToDesktop (getDesktopWindowStyleFlags());
  63137. }
  63138. ResizableWindow::~ResizableWindow()
  63139. {
  63140. resizableCorner = 0;
  63141. resizableBorder = 0;
  63142. contentComponent.deleteAndZero();
  63143. // have you been adding your own components directly to this window..? tut tut tut.
  63144. // Read the instructions for using a ResizableWindow!
  63145. jassert (getNumChildComponents() == 0);
  63146. }
  63147. int ResizableWindow::getDesktopWindowStyleFlags() const
  63148. {
  63149. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63150. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63151. styleFlags |= ComponentPeer::windowIsResizable;
  63152. return styleFlags;
  63153. }
  63154. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63155. const bool deleteOldOne,
  63156. const bool resizeToFit)
  63157. {
  63158. resizeToFitContent = resizeToFit;
  63159. if (newContentComponent != static_cast <Component*> (contentComponent))
  63160. {
  63161. if (deleteOldOne)
  63162. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63163. // external deletion of the content comp)
  63164. else
  63165. removeChildComponent (contentComponent);
  63166. contentComponent = newContentComponent;
  63167. Component::addAndMakeVisible (contentComponent);
  63168. }
  63169. if (resizeToFit)
  63170. childBoundsChanged (contentComponent);
  63171. resized(); // must always be called to position the new content comp
  63172. }
  63173. void ResizableWindow::setContentComponentSize (int width, int height)
  63174. {
  63175. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63176. const BorderSize border (getContentComponentBorder());
  63177. setSize (width + border.getLeftAndRight(),
  63178. height + border.getTopAndBottom());
  63179. }
  63180. const BorderSize ResizableWindow::getBorderThickness()
  63181. {
  63182. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63183. }
  63184. const BorderSize ResizableWindow::getContentComponentBorder()
  63185. {
  63186. return getBorderThickness();
  63187. }
  63188. void ResizableWindow::moved()
  63189. {
  63190. updateLastPos();
  63191. }
  63192. void ResizableWindow::visibilityChanged()
  63193. {
  63194. TopLevelWindow::visibilityChanged();
  63195. updateLastPos();
  63196. }
  63197. void ResizableWindow::resized()
  63198. {
  63199. if (resizableBorder != 0)
  63200. {
  63201. #if JUCE_WINDOWS || JUCE_LINUX
  63202. // hide the resizable border if the OS already provides one..
  63203. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63204. #else
  63205. resizableBorder->setVisible (! isFullScreen());
  63206. #endif
  63207. resizableBorder->setBorderThickness (getBorderThickness());
  63208. resizableBorder->setSize (getWidth(), getHeight());
  63209. resizableBorder->toBack();
  63210. }
  63211. if (resizableCorner != 0)
  63212. {
  63213. #if JUCE_MAC
  63214. // hide the resizable border if the OS already provides one..
  63215. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63216. #else
  63217. resizableCorner->setVisible (! isFullScreen());
  63218. #endif
  63219. const int resizerSize = 18;
  63220. resizableCorner->setBounds (getWidth() - resizerSize,
  63221. getHeight() - resizerSize,
  63222. resizerSize, resizerSize);
  63223. }
  63224. if (contentComponent != 0)
  63225. contentComponent->setBoundsInset (getContentComponentBorder());
  63226. updateLastPos();
  63227. #if JUCE_DEBUG
  63228. hasBeenResized = true;
  63229. #endif
  63230. }
  63231. void ResizableWindow::childBoundsChanged (Component* child)
  63232. {
  63233. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63234. {
  63235. // not going to look very good if this component has a zero size..
  63236. jassert (child->getWidth() > 0);
  63237. jassert (child->getHeight() > 0);
  63238. const BorderSize borders (getContentComponentBorder());
  63239. setSize (child->getWidth() + borders.getLeftAndRight(),
  63240. child->getHeight() + borders.getTopAndBottom());
  63241. }
  63242. }
  63243. void ResizableWindow::activeWindowStatusChanged()
  63244. {
  63245. const BorderSize border (getContentComponentBorder());
  63246. Rectangle<int> area (getLocalBounds());
  63247. repaint (area.removeFromTop (border.getTop()));
  63248. repaint (area.removeFromLeft (border.getLeft()));
  63249. repaint (area.removeFromRight (border.getRight()));
  63250. repaint (area.removeFromBottom (border.getBottom()));
  63251. }
  63252. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63253. const bool useBottomRightCornerResizer)
  63254. {
  63255. if (shouldBeResizable)
  63256. {
  63257. if (useBottomRightCornerResizer)
  63258. {
  63259. resizableBorder = 0;
  63260. if (resizableCorner == 0)
  63261. {
  63262. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63263. resizableCorner->setAlwaysOnTop (true);
  63264. }
  63265. }
  63266. else
  63267. {
  63268. resizableCorner = 0;
  63269. if (resizableBorder == 0)
  63270. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63271. }
  63272. }
  63273. else
  63274. {
  63275. resizableCorner = 0;
  63276. resizableBorder = 0;
  63277. }
  63278. if (isUsingNativeTitleBar())
  63279. recreateDesktopWindow();
  63280. childBoundsChanged (contentComponent);
  63281. resized();
  63282. }
  63283. bool ResizableWindow::isResizable() const throw()
  63284. {
  63285. return resizableCorner != 0
  63286. || resizableBorder != 0;
  63287. }
  63288. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63289. const int newMinimumHeight,
  63290. const int newMaximumWidth,
  63291. const int newMaximumHeight) throw()
  63292. {
  63293. // if you've set up a custom constrainer then these settings won't have any effect..
  63294. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63295. if (constrainer == 0)
  63296. setConstrainer (&defaultConstrainer);
  63297. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63298. newMaximumWidth, newMaximumHeight);
  63299. setBoundsConstrained (getBounds());
  63300. }
  63301. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63302. {
  63303. if (constrainer != newConstrainer)
  63304. {
  63305. constrainer = newConstrainer;
  63306. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63307. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63308. resizableCorner = 0;
  63309. resizableBorder = 0;
  63310. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63311. ComponentPeer* const peer = getPeer();
  63312. if (peer != 0)
  63313. peer->setConstrainer (newConstrainer);
  63314. }
  63315. }
  63316. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63317. {
  63318. if (constrainer != 0)
  63319. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63320. else
  63321. setBounds (bounds);
  63322. }
  63323. void ResizableWindow::paint (Graphics& g)
  63324. {
  63325. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63326. getBorderThickness(), *this);
  63327. if (! isFullScreen())
  63328. {
  63329. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63330. getBorderThickness(), *this);
  63331. }
  63332. #if JUCE_DEBUG
  63333. /* If this fails, then you've probably written a subclass with a resized()
  63334. callback but forgotten to make it call its parent class's resized() method.
  63335. It's important when you override methods like resized(), moved(),
  63336. etc., that you make sure the base class methods also get called.
  63337. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63338. because your content should all be inside the content component - and it's the
  63339. content component's resized() method that you should be using to do your
  63340. layout.
  63341. */
  63342. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63343. #endif
  63344. }
  63345. void ResizableWindow::lookAndFeelChanged()
  63346. {
  63347. resized();
  63348. if (isOnDesktop())
  63349. {
  63350. Component::addToDesktop (getDesktopWindowStyleFlags());
  63351. ComponentPeer* const peer = getPeer();
  63352. if (peer != 0)
  63353. peer->setConstrainer (constrainer);
  63354. }
  63355. }
  63356. const Colour ResizableWindow::getBackgroundColour() const throw()
  63357. {
  63358. return findColour (backgroundColourId, false);
  63359. }
  63360. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63361. {
  63362. Colour backgroundColour (newColour);
  63363. if (! Desktop::canUseSemiTransparentWindows())
  63364. backgroundColour = newColour.withAlpha (1.0f);
  63365. setColour (backgroundColourId, backgroundColour);
  63366. setOpaque (backgroundColour.isOpaque());
  63367. repaint();
  63368. }
  63369. bool ResizableWindow::isFullScreen() const
  63370. {
  63371. if (isOnDesktop())
  63372. {
  63373. ComponentPeer* const peer = getPeer();
  63374. return peer != 0 && peer->isFullScreen();
  63375. }
  63376. return fullscreen;
  63377. }
  63378. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63379. {
  63380. if (shouldBeFullScreen != isFullScreen())
  63381. {
  63382. updateLastPos();
  63383. fullscreen = shouldBeFullScreen;
  63384. if (isOnDesktop())
  63385. {
  63386. ComponentPeer* const peer = getPeer();
  63387. if (peer != 0)
  63388. {
  63389. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63390. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63391. peer->setFullScreen (shouldBeFullScreen);
  63392. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63393. setBounds (lastPos);
  63394. }
  63395. else
  63396. {
  63397. jassertfalse;
  63398. }
  63399. }
  63400. else
  63401. {
  63402. if (shouldBeFullScreen)
  63403. setBounds (0, 0, getParentWidth(), getParentHeight());
  63404. else
  63405. setBounds (lastNonFullScreenPos);
  63406. }
  63407. resized();
  63408. }
  63409. }
  63410. bool ResizableWindow::isMinimised() const
  63411. {
  63412. ComponentPeer* const peer = getPeer();
  63413. return (peer != 0) && peer->isMinimised();
  63414. }
  63415. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63416. {
  63417. if (shouldMinimise != isMinimised())
  63418. {
  63419. ComponentPeer* const peer = getPeer();
  63420. if (peer != 0)
  63421. {
  63422. updateLastPos();
  63423. peer->setMinimised (shouldMinimise);
  63424. }
  63425. else
  63426. {
  63427. jassertfalse;
  63428. }
  63429. }
  63430. }
  63431. void ResizableWindow::updateLastPos()
  63432. {
  63433. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63434. {
  63435. lastNonFullScreenPos = getBounds();
  63436. }
  63437. }
  63438. void ResizableWindow::parentSizeChanged()
  63439. {
  63440. if (isFullScreen() && getParentComponent() != 0)
  63441. {
  63442. setBounds (0, 0, getParentWidth(), getParentHeight());
  63443. }
  63444. }
  63445. const String ResizableWindow::getWindowStateAsString()
  63446. {
  63447. updateLastPos();
  63448. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63449. }
  63450. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63451. {
  63452. StringArray tokens;
  63453. tokens.addTokens (s, false);
  63454. tokens.removeEmptyStrings();
  63455. tokens.trim();
  63456. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63457. const int firstCoord = fs ? 1 : 0;
  63458. if (tokens.size() != firstCoord + 4)
  63459. return false;
  63460. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63461. tokens[firstCoord + 1].getIntValue(),
  63462. tokens[firstCoord + 2].getIntValue(),
  63463. tokens[firstCoord + 3].getIntValue());
  63464. if (newPos.isEmpty())
  63465. return false;
  63466. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63467. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63468. if (peer != 0)
  63469. peer->getFrameSize().addTo (newPos);
  63470. if (! screen.contains (newPos))
  63471. {
  63472. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63473. jmin (newPos.getHeight(), screen.getHeight()));
  63474. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63475. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63476. }
  63477. if (peer != 0)
  63478. {
  63479. peer->getFrameSize().subtractFrom (newPos);
  63480. peer->setNonFullScreenBounds (newPos);
  63481. }
  63482. lastNonFullScreenPos = newPos;
  63483. setFullScreen (fs);
  63484. if (! fs)
  63485. setBoundsConstrained (newPos);
  63486. return true;
  63487. }
  63488. void ResizableWindow::mouseDown (const MouseEvent&)
  63489. {
  63490. if (! isFullScreen())
  63491. dragger.startDraggingComponent (this, constrainer);
  63492. }
  63493. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63494. {
  63495. if (! isFullScreen())
  63496. dragger.dragComponent (this, e);
  63497. }
  63498. #if JUCE_DEBUG
  63499. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63500. {
  63501. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63502. manages its child components automatically, and if you add your own it'll cause
  63503. trouble. Instead, use setContentComponent() to give it a component which
  63504. will be automatically resized and kept in the right place - then you can add
  63505. subcomponents to the content comp. See the notes for the ResizableWindow class
  63506. for more info.
  63507. If you really know what you're doing and want to avoid this assertion, just call
  63508. Component::addChildComponent directly.
  63509. */
  63510. jassertfalse;
  63511. Component::addChildComponent (child, zOrder);
  63512. }
  63513. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63514. {
  63515. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63516. manages its child components automatically, and if you add your own it'll cause
  63517. trouble. Instead, use setContentComponent() to give it a component which
  63518. will be automatically resized and kept in the right place - then you can add
  63519. subcomponents to the content comp. See the notes for the ResizableWindow class
  63520. for more info.
  63521. If you really know what you're doing and want to avoid this assertion, just call
  63522. Component::addAndMakeVisible directly.
  63523. */
  63524. jassertfalse;
  63525. Component::addAndMakeVisible (child, zOrder);
  63526. }
  63527. #endif
  63528. END_JUCE_NAMESPACE
  63529. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63530. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63531. BEGIN_JUCE_NAMESPACE
  63532. SplashScreen::SplashScreen()
  63533. {
  63534. setOpaque (true);
  63535. }
  63536. SplashScreen::~SplashScreen()
  63537. {
  63538. }
  63539. void SplashScreen::show (const String& title,
  63540. const Image& backgroundImage_,
  63541. const int minimumTimeToDisplayFor,
  63542. const bool useDropShadow,
  63543. const bool removeOnMouseClick)
  63544. {
  63545. backgroundImage = backgroundImage_;
  63546. jassert (backgroundImage_.isValid());
  63547. if (backgroundImage_.isValid())
  63548. {
  63549. setOpaque (! backgroundImage_.hasAlphaChannel());
  63550. show (title,
  63551. backgroundImage_.getWidth(),
  63552. backgroundImage_.getHeight(),
  63553. minimumTimeToDisplayFor,
  63554. useDropShadow,
  63555. removeOnMouseClick);
  63556. }
  63557. }
  63558. void SplashScreen::show (const String& title,
  63559. const int width,
  63560. const int height,
  63561. const int minimumTimeToDisplayFor,
  63562. const bool useDropShadow,
  63563. const bool removeOnMouseClick)
  63564. {
  63565. setName (title);
  63566. setAlwaysOnTop (true);
  63567. setVisible (true);
  63568. centreWithSize (width, height);
  63569. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63570. toFront (false);
  63571. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63572. repaint();
  63573. originalClickCounter = removeOnMouseClick
  63574. ? Desktop::getMouseButtonClickCounter()
  63575. : std::numeric_limits<int>::max();
  63576. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63577. startTimer (50);
  63578. }
  63579. void SplashScreen::paint (Graphics& g)
  63580. {
  63581. g.setOpacity (1.0f);
  63582. g.drawImage (backgroundImage,
  63583. 0, 0, getWidth(), getHeight(),
  63584. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63585. }
  63586. void SplashScreen::timerCallback()
  63587. {
  63588. if (Time::getCurrentTime() > earliestTimeToDelete
  63589. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63590. {
  63591. delete this;
  63592. }
  63593. }
  63594. END_JUCE_NAMESPACE
  63595. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63596. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63597. BEGIN_JUCE_NAMESPACE
  63598. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63599. const bool hasProgressBar,
  63600. const bool hasCancelButton,
  63601. const int timeOutMsWhenCancelling_,
  63602. const String& cancelButtonText)
  63603. : Thread ("Juce Progress Window"),
  63604. progress (0.0),
  63605. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63606. {
  63607. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63608. .createAlertWindow (title, String::empty, cancelButtonText,
  63609. String::empty, String::empty,
  63610. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63611. if (hasProgressBar)
  63612. alertWindow->addProgressBarComponent (progress);
  63613. }
  63614. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63615. {
  63616. stopThread (timeOutMsWhenCancelling);
  63617. }
  63618. bool ThreadWithProgressWindow::runThread (const int priority)
  63619. {
  63620. startThread (priority);
  63621. startTimer (100);
  63622. {
  63623. const ScopedLock sl (messageLock);
  63624. alertWindow->setMessage (message);
  63625. }
  63626. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63627. stopThread (timeOutMsWhenCancelling);
  63628. alertWindow->setVisible (false);
  63629. return finishedNaturally;
  63630. }
  63631. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63632. {
  63633. progress = newProgress;
  63634. }
  63635. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63636. {
  63637. const ScopedLock sl (messageLock);
  63638. message = newStatusMessage;
  63639. }
  63640. void ThreadWithProgressWindow::timerCallback()
  63641. {
  63642. if (! isThreadRunning())
  63643. {
  63644. // thread has finished normally..
  63645. alertWindow->exitModalState (1);
  63646. alertWindow->setVisible (false);
  63647. }
  63648. else
  63649. {
  63650. const ScopedLock sl (messageLock);
  63651. alertWindow->setMessage (message);
  63652. }
  63653. }
  63654. END_JUCE_NAMESPACE
  63655. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63656. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63657. BEGIN_JUCE_NAMESPACE
  63658. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63659. const int millisecondsBeforeTipAppears_)
  63660. : Component ("tooltip"),
  63661. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63662. mouseClicks (0),
  63663. lastHideTime (0),
  63664. lastComponentUnderMouse (0),
  63665. changedCompsSinceShown (true)
  63666. {
  63667. if (Desktop::getInstance().getMainMouseSource().canHover())
  63668. startTimer (123);
  63669. setAlwaysOnTop (true);
  63670. setOpaque (true);
  63671. if (parentComponent != 0)
  63672. parentComponent->addChildComponent (this);
  63673. }
  63674. TooltipWindow::~TooltipWindow()
  63675. {
  63676. hide();
  63677. }
  63678. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63679. {
  63680. millisecondsBeforeTipAppears = newTimeMs;
  63681. }
  63682. void TooltipWindow::paint (Graphics& g)
  63683. {
  63684. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63685. }
  63686. void TooltipWindow::mouseEnter (const MouseEvent&)
  63687. {
  63688. hide();
  63689. }
  63690. void TooltipWindow::showFor (const String& tip)
  63691. {
  63692. jassert (tip.isNotEmpty());
  63693. if (tipShowing != tip)
  63694. repaint();
  63695. tipShowing = tip;
  63696. Point<int> mousePos (Desktop::getMousePosition());
  63697. if (getParentComponent() != 0)
  63698. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63699. int x, y, w, h;
  63700. getLookAndFeel().getTooltipSize (tip, w, h);
  63701. if (mousePos.getX() > getParentWidth() / 2)
  63702. x = mousePos.getX() - (w + 12);
  63703. else
  63704. x = mousePos.getX() + 24;
  63705. if (mousePos.getY() > getParentHeight() / 2)
  63706. y = mousePos.getY() - (h + 6);
  63707. else
  63708. y = mousePos.getY() + 6;
  63709. setBounds (x, y, w, h);
  63710. setVisible (true);
  63711. if (getParentComponent() == 0)
  63712. {
  63713. addToDesktop (ComponentPeer::windowHasDropShadow
  63714. | ComponentPeer::windowIsTemporary
  63715. | ComponentPeer::windowIgnoresKeyPresses);
  63716. }
  63717. toFront (false);
  63718. }
  63719. const String TooltipWindow::getTipFor (Component* const c)
  63720. {
  63721. if (c != 0
  63722. && Process::isForegroundProcess()
  63723. && ! Component::isMouseButtonDownAnywhere())
  63724. {
  63725. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63726. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63727. return ttc->getTooltip();
  63728. }
  63729. return String::empty;
  63730. }
  63731. void TooltipWindow::hide()
  63732. {
  63733. tipShowing = String::empty;
  63734. removeFromDesktop();
  63735. setVisible (false);
  63736. }
  63737. void TooltipWindow::timerCallback()
  63738. {
  63739. const unsigned int now = Time::getApproximateMillisecondCounter();
  63740. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63741. const String newTip (getTipFor (newComp));
  63742. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63743. lastComponentUnderMouse = newComp;
  63744. lastTipUnderMouse = newTip;
  63745. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63746. const bool mouseWasClicked = clickCount > mouseClicks;
  63747. mouseClicks = clickCount;
  63748. const Point<int> mousePos (Desktop::getMousePosition());
  63749. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63750. lastMousePos = mousePos;
  63751. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63752. lastCompChangeTime = now;
  63753. if (isVisible() || now < lastHideTime + 500)
  63754. {
  63755. // if a tip is currently visible (or has just disappeared), update to a new one
  63756. // immediately if needed..
  63757. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63758. {
  63759. if (isVisible())
  63760. {
  63761. lastHideTime = now;
  63762. hide();
  63763. }
  63764. }
  63765. else if (tipChanged)
  63766. {
  63767. showFor (newTip);
  63768. }
  63769. }
  63770. else
  63771. {
  63772. // if there isn't currently a tip, but one is needed, only let it
  63773. // appear after a timeout..
  63774. if (newTip.isNotEmpty()
  63775. && newTip != tipShowing
  63776. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63777. {
  63778. showFor (newTip);
  63779. }
  63780. }
  63781. }
  63782. END_JUCE_NAMESPACE
  63783. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63784. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63785. BEGIN_JUCE_NAMESPACE
  63786. /** Keeps track of the active top level window.
  63787. */
  63788. class TopLevelWindowManager : public Timer,
  63789. public DeletedAtShutdown
  63790. {
  63791. public:
  63792. TopLevelWindowManager()
  63793. : currentActive (0)
  63794. {
  63795. }
  63796. ~TopLevelWindowManager()
  63797. {
  63798. clearSingletonInstance();
  63799. }
  63800. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63801. void timerCallback()
  63802. {
  63803. startTimer (jmin (1731, getTimerInterval() * 2));
  63804. TopLevelWindow* active = 0;
  63805. if (Process::isForegroundProcess())
  63806. {
  63807. active = currentActive;
  63808. Component* const c = Component::getCurrentlyFocusedComponent();
  63809. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63810. if (tlw == 0 && c != 0)
  63811. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63812. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63813. if (tlw != 0)
  63814. active = tlw;
  63815. }
  63816. if (active != currentActive)
  63817. {
  63818. currentActive = active;
  63819. for (int i = windows.size(); --i >= 0;)
  63820. {
  63821. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63822. tlw->setWindowActive (isWindowActive (tlw));
  63823. i = jmin (i, windows.size() - 1);
  63824. }
  63825. Desktop::getInstance().triggerFocusCallback();
  63826. }
  63827. }
  63828. bool addWindow (TopLevelWindow* const w)
  63829. {
  63830. windows.add (w);
  63831. startTimer (10);
  63832. return isWindowActive (w);
  63833. }
  63834. void removeWindow (TopLevelWindow* const w)
  63835. {
  63836. startTimer (10);
  63837. if (currentActive == w)
  63838. currentActive = 0;
  63839. windows.removeValue (w);
  63840. if (windows.size() == 0)
  63841. deleteInstance();
  63842. }
  63843. Array <TopLevelWindow*> windows;
  63844. private:
  63845. TopLevelWindow* currentActive;
  63846. bool isWindowActive (TopLevelWindow* const tlw) const
  63847. {
  63848. return (tlw == currentActive
  63849. || tlw->isParentOf (currentActive)
  63850. || tlw->hasKeyboardFocus (true))
  63851. && tlw->isShowing();
  63852. }
  63853. TopLevelWindowManager (const TopLevelWindowManager&);
  63854. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  63855. };
  63856. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63857. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63858. {
  63859. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63860. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63861. }
  63862. TopLevelWindow::TopLevelWindow (const String& name,
  63863. const bool addToDesktop_)
  63864. : Component (name),
  63865. useDropShadow (true),
  63866. useNativeTitleBar (false),
  63867. windowIsActive_ (false)
  63868. {
  63869. setOpaque (true);
  63870. if (addToDesktop_)
  63871. Component::addToDesktop (getDesktopWindowStyleFlags());
  63872. else
  63873. setDropShadowEnabled (true);
  63874. setWantsKeyboardFocus (true);
  63875. setBroughtToFrontOnMouseClick (true);
  63876. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63877. }
  63878. TopLevelWindow::~TopLevelWindow()
  63879. {
  63880. shadower = 0;
  63881. TopLevelWindowManager::getInstance()->removeWindow (this);
  63882. }
  63883. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63884. {
  63885. if (hasKeyboardFocus (true))
  63886. TopLevelWindowManager::getInstance()->timerCallback();
  63887. else
  63888. TopLevelWindowManager::getInstance()->startTimer (10);
  63889. }
  63890. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63891. {
  63892. if (windowIsActive_ != isNowActive)
  63893. {
  63894. windowIsActive_ = isNowActive;
  63895. activeWindowStatusChanged();
  63896. }
  63897. }
  63898. void TopLevelWindow::activeWindowStatusChanged()
  63899. {
  63900. }
  63901. void TopLevelWindow::parentHierarchyChanged()
  63902. {
  63903. setDropShadowEnabled (useDropShadow);
  63904. }
  63905. void TopLevelWindow::visibilityChanged()
  63906. {
  63907. if (isShowing())
  63908. toFront (true);
  63909. }
  63910. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63911. {
  63912. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63913. if (useDropShadow)
  63914. styleFlags |= ComponentPeer::windowHasDropShadow;
  63915. if (useNativeTitleBar)
  63916. styleFlags |= ComponentPeer::windowHasTitleBar;
  63917. return styleFlags;
  63918. }
  63919. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63920. {
  63921. useDropShadow = useShadow;
  63922. if (isOnDesktop())
  63923. {
  63924. shadower = 0;
  63925. Component::addToDesktop (getDesktopWindowStyleFlags());
  63926. }
  63927. else
  63928. {
  63929. if (useShadow && isOpaque())
  63930. {
  63931. if (shadower == 0)
  63932. {
  63933. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63934. if (shadower != 0)
  63935. shadower->setOwner (this);
  63936. }
  63937. }
  63938. else
  63939. {
  63940. shadower = 0;
  63941. }
  63942. }
  63943. }
  63944. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63945. {
  63946. if (useNativeTitleBar != useNativeTitleBar_)
  63947. {
  63948. useNativeTitleBar = useNativeTitleBar_;
  63949. recreateDesktopWindow();
  63950. sendLookAndFeelChange();
  63951. }
  63952. }
  63953. void TopLevelWindow::recreateDesktopWindow()
  63954. {
  63955. if (isOnDesktop())
  63956. {
  63957. Component::addToDesktop (getDesktopWindowStyleFlags());
  63958. toFront (true);
  63959. }
  63960. }
  63961. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63962. {
  63963. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63964. because this class needs to make sure its layout corresponds with settings like whether
  63965. it's got a native title bar or not.
  63966. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63967. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63968. method, then add or remove whatever flags are necessary from this value before returning it.
  63969. */
  63970. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63971. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63972. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63973. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63974. sendLookAndFeelChange();
  63975. }
  63976. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63977. {
  63978. if (c == 0)
  63979. c = TopLevelWindow::getActiveTopLevelWindow();
  63980. if (c == 0)
  63981. {
  63982. centreWithSize (width, height);
  63983. }
  63984. else
  63985. {
  63986. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63987. Rectangle<int> parentArea (c->getParentMonitorArea());
  63988. if (getParentComponent() != 0)
  63989. {
  63990. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63991. parentArea = getParentComponent()->getLocalBounds();
  63992. }
  63993. parentArea.reduce (12, 12);
  63994. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63995. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63996. width, height);
  63997. }
  63998. }
  63999. int TopLevelWindow::getNumTopLevelWindows() throw()
  64000. {
  64001. return TopLevelWindowManager::getInstance()->windows.size();
  64002. }
  64003. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64004. {
  64005. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64006. }
  64007. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64008. {
  64009. TopLevelWindow* best = 0;
  64010. int bestNumTWLParents = -1;
  64011. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64012. {
  64013. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64014. if (tlw->isActiveWindow())
  64015. {
  64016. int numTWLParents = 0;
  64017. const Component* c = tlw->getParentComponent();
  64018. while (c != 0)
  64019. {
  64020. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64021. ++numTWLParents;
  64022. c = c->getParentComponent();
  64023. }
  64024. if (bestNumTWLParents < numTWLParents)
  64025. {
  64026. best = tlw;
  64027. bestNumTWLParents = numTWLParents;
  64028. }
  64029. }
  64030. }
  64031. return best;
  64032. }
  64033. END_JUCE_NAMESPACE
  64034. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64035. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64036. BEGIN_JUCE_NAMESPACE
  64037. namespace RelativeCoordinateHelpers
  64038. {
  64039. void skipComma (const juce_wchar* const s, int& i)
  64040. {
  64041. while (CharacterFunctions::isWhitespace (s[i]))
  64042. ++i;
  64043. if (s[i] == ',')
  64044. ++i;
  64045. }
  64046. }
  64047. const String RelativeCoordinate::Strings::parent ("parent");
  64048. const String RelativeCoordinate::Strings::left ("left");
  64049. const String RelativeCoordinate::Strings::right ("right");
  64050. const String RelativeCoordinate::Strings::top ("top");
  64051. const String RelativeCoordinate::Strings::bottom ("bottom");
  64052. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64053. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64054. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64055. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64056. RelativeCoordinate::RelativeCoordinate()
  64057. {
  64058. }
  64059. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64060. : term (term_)
  64061. {
  64062. }
  64063. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64064. : term (other.term)
  64065. {
  64066. }
  64067. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64068. {
  64069. term = other.term;
  64070. return *this;
  64071. }
  64072. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64073. : term (absoluteDistanceFromOrigin)
  64074. {
  64075. }
  64076. RelativeCoordinate::RelativeCoordinate (const String& s)
  64077. {
  64078. try
  64079. {
  64080. term = Expression (s);
  64081. }
  64082. catch (...)
  64083. {}
  64084. }
  64085. RelativeCoordinate::~RelativeCoordinate()
  64086. {
  64087. }
  64088. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64089. {
  64090. return term.toString() == other.term.toString();
  64091. }
  64092. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64093. {
  64094. return ! operator== (other);
  64095. }
  64096. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64097. {
  64098. try
  64099. {
  64100. if (context != 0)
  64101. return term.evaluate (*context);
  64102. else
  64103. return term.evaluate();
  64104. }
  64105. catch (...)
  64106. {}
  64107. return 0.0;
  64108. }
  64109. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64110. {
  64111. try
  64112. {
  64113. if (context != 0)
  64114. term.evaluate (*context);
  64115. else
  64116. term.evaluate();
  64117. }
  64118. catch (...)
  64119. {
  64120. return true;
  64121. }
  64122. return false;
  64123. }
  64124. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64125. {
  64126. try
  64127. {
  64128. if (context != 0)
  64129. {
  64130. term = term.adjustedToGiveNewResult (newPos, *context);
  64131. }
  64132. else
  64133. {
  64134. Expression::EvaluationContext defaultContext;
  64135. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64136. }
  64137. }
  64138. catch (...)
  64139. {}
  64140. }
  64141. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64142. {
  64143. try
  64144. {
  64145. return term.referencesSymbol (coordName, context);
  64146. }
  64147. catch (...)
  64148. {}
  64149. return false;
  64150. }
  64151. bool RelativeCoordinate::isDynamic() const
  64152. {
  64153. return term.usesAnySymbols();
  64154. }
  64155. const String RelativeCoordinate::toString() const
  64156. {
  64157. return term.toString();
  64158. }
  64159. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64160. {
  64161. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64162. if (term.referencesSymbol (oldName, 0))
  64163. term = term.withRenamedSymbol (oldName, newName);
  64164. }
  64165. RelativePoint::RelativePoint()
  64166. {
  64167. }
  64168. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64169. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64170. {
  64171. }
  64172. RelativePoint::RelativePoint (const float x_, const float y_)
  64173. : x (x_), y (y_)
  64174. {
  64175. }
  64176. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64177. : x (x_), y (y_)
  64178. {
  64179. }
  64180. RelativePoint::RelativePoint (const String& s)
  64181. {
  64182. int i = 0;
  64183. x = RelativeCoordinate (Expression::parse (s, i));
  64184. RelativeCoordinateHelpers::skipComma (s, i);
  64185. y = RelativeCoordinate (Expression::parse (s, i));
  64186. }
  64187. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64188. {
  64189. return x == other.x && y == other.y;
  64190. }
  64191. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64192. {
  64193. return ! operator== (other);
  64194. }
  64195. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64196. {
  64197. return Point<float> ((float) x.resolve (context),
  64198. (float) y.resolve (context));
  64199. }
  64200. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64201. {
  64202. x.moveToAbsolute (newPos.getX(), context);
  64203. y.moveToAbsolute (newPos.getY(), context);
  64204. }
  64205. const String RelativePoint::toString() const
  64206. {
  64207. return x.toString() + ", " + y.toString();
  64208. }
  64209. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64210. {
  64211. x.renameSymbolIfUsed (oldName, newName);
  64212. y.renameSymbolIfUsed (oldName, newName);
  64213. }
  64214. bool RelativePoint::isDynamic() const
  64215. {
  64216. return x.isDynamic() || y.isDynamic();
  64217. }
  64218. RelativeRectangle::RelativeRectangle()
  64219. {
  64220. }
  64221. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64222. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64223. : left (left_), right (right_), top (top_), bottom (bottom_)
  64224. {
  64225. }
  64226. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64227. : left (rect.getX()),
  64228. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64229. top (rect.getY()),
  64230. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64231. {
  64232. }
  64233. RelativeRectangle::RelativeRectangle (const String& s)
  64234. {
  64235. int i = 0;
  64236. left = RelativeCoordinate (Expression::parse (s, i));
  64237. RelativeCoordinateHelpers::skipComma (s, i);
  64238. top = RelativeCoordinate (Expression::parse (s, i));
  64239. RelativeCoordinateHelpers::skipComma (s, i);
  64240. right = RelativeCoordinate (Expression::parse (s, i));
  64241. RelativeCoordinateHelpers::skipComma (s, i);
  64242. bottom = RelativeCoordinate (Expression::parse (s, i));
  64243. }
  64244. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64245. {
  64246. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64247. }
  64248. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64249. {
  64250. return ! operator== (other);
  64251. }
  64252. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64253. {
  64254. const double l = left.resolve (context);
  64255. const double r = right.resolve (context);
  64256. const double t = top.resolve (context);
  64257. const double b = bottom.resolve (context);
  64258. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64259. }
  64260. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64261. {
  64262. left.moveToAbsolute (newPos.getX(), context);
  64263. right.moveToAbsolute (newPos.getRight(), context);
  64264. top.moveToAbsolute (newPos.getY(), context);
  64265. bottom.moveToAbsolute (newPos.getBottom(), context);
  64266. }
  64267. const String RelativeRectangle::toString() const
  64268. {
  64269. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64270. }
  64271. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64272. {
  64273. left.renameSymbolIfUsed (oldName, newName);
  64274. right.renameSymbolIfUsed (oldName, newName);
  64275. top.renameSymbolIfUsed (oldName, newName);
  64276. bottom.renameSymbolIfUsed (oldName, newName);
  64277. }
  64278. RelativePointPath::RelativePointPath()
  64279. : usesNonZeroWinding (true),
  64280. containsDynamicPoints (false)
  64281. {
  64282. }
  64283. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64284. : usesNonZeroWinding (true),
  64285. containsDynamicPoints (false)
  64286. {
  64287. ValueTree state (DrawablePath::valueTreeType);
  64288. other.writeTo (state, 0);
  64289. parse (state);
  64290. }
  64291. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64292. : usesNonZeroWinding (true),
  64293. containsDynamicPoints (false)
  64294. {
  64295. parse (drawable);
  64296. }
  64297. RelativePointPath::RelativePointPath (const Path& path)
  64298. {
  64299. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64300. Path::Iterator i (path);
  64301. while (i.next())
  64302. {
  64303. switch (i.elementType)
  64304. {
  64305. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64306. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64307. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64308. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64309. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64310. default: jassertfalse; break;
  64311. }
  64312. }
  64313. }
  64314. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64315. {
  64316. DrawablePath::ValueTreeWrapper wrapper (state);
  64317. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64318. ValueTree pathTree (wrapper.getPathState());
  64319. pathTree.removeAllChildren (undoManager);
  64320. for (int i = 0; i < elements.size(); ++i)
  64321. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64322. }
  64323. void RelativePointPath::parse (const ValueTree& state)
  64324. {
  64325. DrawablePath::ValueTreeWrapper wrapper (state);
  64326. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64327. RelativePoint points[3];
  64328. const ValueTree pathTree (wrapper.getPathState());
  64329. const int num = pathTree.getNumChildren();
  64330. for (int i = 0; i < num; ++i)
  64331. {
  64332. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64333. const int numCps = e.getNumControlPoints();
  64334. for (int j = 0; j < numCps; ++j)
  64335. {
  64336. points[j] = e.getControlPoint (j);
  64337. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64338. }
  64339. const Identifier type (e.getType());
  64340. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64341. elements.add (new StartSubPath (points[0]));
  64342. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64343. elements.add (new CloseSubPath());
  64344. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64345. elements.add (new LineTo (points[0]));
  64346. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64347. elements.add (new QuadraticTo (points[0], points[1]));
  64348. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64349. elements.add (new CubicTo (points[0], points[1], points[2]));
  64350. else
  64351. jassertfalse;
  64352. }
  64353. }
  64354. RelativePointPath::~RelativePointPath()
  64355. {
  64356. }
  64357. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64358. {
  64359. elements.swapWithArray (other.elements);
  64360. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64361. }
  64362. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64363. {
  64364. for (int i = 0; i < elements.size(); ++i)
  64365. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64366. }
  64367. bool RelativePointPath::containsAnyDynamicPoints() const
  64368. {
  64369. return containsDynamicPoints;
  64370. }
  64371. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64372. {
  64373. }
  64374. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64375. : ElementBase (startSubPathElement), startPos (pos)
  64376. {
  64377. }
  64378. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64379. {
  64380. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64381. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64382. return v;
  64383. }
  64384. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64385. {
  64386. path.startNewSubPath (startPos.resolve (coordFinder));
  64387. }
  64388. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64389. {
  64390. numPoints = 1;
  64391. return &startPos;
  64392. }
  64393. RelativePointPath::CloseSubPath::CloseSubPath()
  64394. : ElementBase (closeSubPathElement)
  64395. {
  64396. }
  64397. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64398. {
  64399. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64400. }
  64401. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64402. {
  64403. path.closeSubPath();
  64404. }
  64405. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64406. {
  64407. numPoints = 0;
  64408. return 0;
  64409. }
  64410. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64411. : ElementBase (lineToElement), endPoint (endPoint_)
  64412. {
  64413. }
  64414. const ValueTree RelativePointPath::LineTo::createTree() const
  64415. {
  64416. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64417. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64418. return v;
  64419. }
  64420. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64421. {
  64422. path.lineTo (endPoint.resolve (coordFinder));
  64423. }
  64424. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64425. {
  64426. numPoints = 1;
  64427. return &endPoint;
  64428. }
  64429. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64430. : ElementBase (quadraticToElement)
  64431. {
  64432. controlPoints[0] = controlPoint;
  64433. controlPoints[1] = endPoint;
  64434. }
  64435. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64436. {
  64437. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64438. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64439. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64440. return v;
  64441. }
  64442. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64443. {
  64444. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64445. controlPoints[1].resolve (coordFinder));
  64446. }
  64447. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64448. {
  64449. numPoints = 2;
  64450. return controlPoints;
  64451. }
  64452. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64453. : ElementBase (cubicToElement)
  64454. {
  64455. controlPoints[0] = controlPoint1;
  64456. controlPoints[1] = controlPoint2;
  64457. controlPoints[2] = endPoint;
  64458. }
  64459. const ValueTree RelativePointPath::CubicTo::createTree() const
  64460. {
  64461. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64462. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64463. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64464. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64465. return v;
  64466. }
  64467. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64468. {
  64469. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64470. controlPoints[1].resolve (coordFinder),
  64471. controlPoints[2].resolve (coordFinder));
  64472. }
  64473. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64474. {
  64475. numPoints = 3;
  64476. return controlPoints;
  64477. }
  64478. RelativeParallelogram::RelativeParallelogram()
  64479. {
  64480. }
  64481. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64482. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64483. {
  64484. }
  64485. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64486. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64487. {
  64488. }
  64489. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64490. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64491. {
  64492. }
  64493. RelativeParallelogram::~RelativeParallelogram()
  64494. {
  64495. }
  64496. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64497. {
  64498. points[0] = topLeft.resolve (coordFinder);
  64499. points[1] = topRight.resolve (coordFinder);
  64500. points[2] = bottomLeft.resolve (coordFinder);
  64501. }
  64502. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64503. {
  64504. resolveThreePoints (points, coordFinder);
  64505. points[3] = points[1] + (points[2] - points[0]);
  64506. }
  64507. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64508. {
  64509. Point<float> points[4];
  64510. resolveFourCorners (points, coordFinder);
  64511. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64512. }
  64513. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64514. {
  64515. Point<float> points[4];
  64516. resolveFourCorners (points, coordFinder);
  64517. path.startNewSubPath (points[0]);
  64518. path.lineTo (points[1]);
  64519. path.lineTo (points[3]);
  64520. path.lineTo (points[2]);
  64521. path.closeSubPath();
  64522. }
  64523. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64524. {
  64525. Point<float> corners[3];
  64526. resolveThreePoints (corners, coordFinder);
  64527. const Line<float> top (corners[0], corners[1]);
  64528. const Line<float> left (corners[0], corners[2]);
  64529. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64530. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64531. topRight.moveToAbsolute (newTopRight, coordFinder);
  64532. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64533. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64534. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64535. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64536. }
  64537. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64538. {
  64539. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64540. }
  64541. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64542. {
  64543. return ! operator== (other);
  64544. }
  64545. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64546. {
  64547. const Point<float> tr (corners[1] - corners[0]);
  64548. const Point<float> bl (corners[2] - corners[0]);
  64549. target -= corners[0];
  64550. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64551. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64552. }
  64553. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64554. {
  64555. return corners[0]
  64556. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64557. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64558. }
  64559. END_JUCE_NAMESPACE
  64560. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64561. #endif
  64562. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64563. /*** Start of inlined file: juce_Colour.cpp ***/
  64564. BEGIN_JUCE_NAMESPACE
  64565. namespace ColourHelpers
  64566. {
  64567. uint8 floatAlphaToInt (const float alpha) throw()
  64568. {
  64569. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64570. }
  64571. void convertHSBtoRGB (float h, float s, float v,
  64572. uint8& r, uint8& g, uint8& b) throw()
  64573. {
  64574. v = jlimit (0.0f, 1.0f, v);
  64575. v *= 255.0f;
  64576. const uint8 intV = (uint8) roundToInt (v);
  64577. if (s <= 0)
  64578. {
  64579. r = intV;
  64580. g = intV;
  64581. b = intV;
  64582. }
  64583. else
  64584. {
  64585. s = jmin (1.0f, s);
  64586. h = jlimit (0.0f, 1.0f, h);
  64587. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64588. const float f = h - std::floor (h);
  64589. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64590. const float y = v * (1.0f - s * f);
  64591. const float z = v * (1.0f - (s * (1.0f - f)));
  64592. if (h < 1.0f)
  64593. {
  64594. r = intV;
  64595. g = (uint8) roundToInt (z);
  64596. b = x;
  64597. }
  64598. else if (h < 2.0f)
  64599. {
  64600. r = (uint8) roundToInt (y);
  64601. g = intV;
  64602. b = x;
  64603. }
  64604. else if (h < 3.0f)
  64605. {
  64606. r = x;
  64607. g = intV;
  64608. b = (uint8) roundToInt (z);
  64609. }
  64610. else if (h < 4.0f)
  64611. {
  64612. r = x;
  64613. g = (uint8) roundToInt (y);
  64614. b = intV;
  64615. }
  64616. else if (h < 5.0f)
  64617. {
  64618. r = (uint8) roundToInt (z);
  64619. g = x;
  64620. b = intV;
  64621. }
  64622. else if (h < 6.0f)
  64623. {
  64624. r = intV;
  64625. g = x;
  64626. b = (uint8) roundToInt (y);
  64627. }
  64628. else
  64629. {
  64630. r = 0;
  64631. g = 0;
  64632. b = 0;
  64633. }
  64634. }
  64635. }
  64636. }
  64637. Colour::Colour() throw()
  64638. : argb (0)
  64639. {
  64640. }
  64641. Colour::Colour (const Colour& other) throw()
  64642. : argb (other.argb)
  64643. {
  64644. }
  64645. Colour& Colour::operator= (const Colour& other) throw()
  64646. {
  64647. argb = other.argb;
  64648. return *this;
  64649. }
  64650. bool Colour::operator== (const Colour& other) const throw()
  64651. {
  64652. return argb.getARGB() == other.argb.getARGB();
  64653. }
  64654. bool Colour::operator!= (const Colour& other) const throw()
  64655. {
  64656. return argb.getARGB() != other.argb.getARGB();
  64657. }
  64658. Colour::Colour (const uint32 argb_) throw()
  64659. : argb (argb_)
  64660. {
  64661. }
  64662. Colour::Colour (const uint8 red,
  64663. const uint8 green,
  64664. const uint8 blue) throw()
  64665. {
  64666. argb.setARGB (0xff, red, green, blue);
  64667. }
  64668. const Colour Colour::fromRGB (const uint8 red,
  64669. const uint8 green,
  64670. const uint8 blue) throw()
  64671. {
  64672. return Colour (red, green, blue);
  64673. }
  64674. Colour::Colour (const uint8 red,
  64675. const uint8 green,
  64676. const uint8 blue,
  64677. const uint8 alpha) throw()
  64678. {
  64679. argb.setARGB (alpha, red, green, blue);
  64680. }
  64681. const Colour Colour::fromRGBA (const uint8 red,
  64682. const uint8 green,
  64683. const uint8 blue,
  64684. const uint8 alpha) throw()
  64685. {
  64686. return Colour (red, green, blue, alpha);
  64687. }
  64688. Colour::Colour (const uint8 red,
  64689. const uint8 green,
  64690. const uint8 blue,
  64691. const float alpha) throw()
  64692. {
  64693. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64694. }
  64695. const Colour Colour::fromRGBAFloat (const uint8 red,
  64696. const uint8 green,
  64697. const uint8 blue,
  64698. const float alpha) throw()
  64699. {
  64700. return Colour (red, green, blue, alpha);
  64701. }
  64702. Colour::Colour (const float hue,
  64703. const float saturation,
  64704. const float brightness,
  64705. const float alpha) throw()
  64706. {
  64707. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64708. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64709. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64710. }
  64711. const Colour Colour::fromHSV (const float hue,
  64712. const float saturation,
  64713. const float brightness,
  64714. const float alpha) throw()
  64715. {
  64716. return Colour (hue, saturation, brightness, alpha);
  64717. }
  64718. Colour::Colour (const float hue,
  64719. const float saturation,
  64720. const float brightness,
  64721. const uint8 alpha) throw()
  64722. {
  64723. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64724. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64725. argb.setARGB (alpha, r, g, b);
  64726. }
  64727. Colour::~Colour() throw()
  64728. {
  64729. }
  64730. const PixelARGB Colour::getPixelARGB() const throw()
  64731. {
  64732. PixelARGB p (argb);
  64733. p.premultiply();
  64734. return p;
  64735. }
  64736. uint32 Colour::getARGB() const throw()
  64737. {
  64738. return argb.getARGB();
  64739. }
  64740. bool Colour::isTransparent() const throw()
  64741. {
  64742. return getAlpha() == 0;
  64743. }
  64744. bool Colour::isOpaque() const throw()
  64745. {
  64746. return getAlpha() == 0xff;
  64747. }
  64748. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64749. {
  64750. PixelARGB newCol (argb);
  64751. newCol.setAlpha (newAlpha);
  64752. return Colour (newCol.getARGB());
  64753. }
  64754. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64755. {
  64756. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64757. PixelARGB newCol (argb);
  64758. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64759. return Colour (newCol.getARGB());
  64760. }
  64761. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64762. {
  64763. jassert (alphaMultiplier >= 0);
  64764. PixelARGB newCol (argb);
  64765. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64766. return Colour (newCol.getARGB());
  64767. }
  64768. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64769. {
  64770. const int destAlpha = getAlpha();
  64771. if (destAlpha > 0)
  64772. {
  64773. const int invA = 0xff - (int) src.getAlpha();
  64774. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64775. if (resA > 0)
  64776. {
  64777. const int da = (invA * destAlpha) / resA;
  64778. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64779. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64780. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64781. (uint8) resA);
  64782. }
  64783. return *this;
  64784. }
  64785. else
  64786. {
  64787. return src;
  64788. }
  64789. }
  64790. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64791. {
  64792. if (proportionOfOther <= 0)
  64793. return *this;
  64794. if (proportionOfOther >= 1.0f)
  64795. return other;
  64796. PixelARGB c1 (getPixelARGB());
  64797. const PixelARGB c2 (other.getPixelARGB());
  64798. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64799. c1.unpremultiply();
  64800. return Colour (c1.getARGB());
  64801. }
  64802. float Colour::getFloatRed() const throw()
  64803. {
  64804. return getRed() / 255.0f;
  64805. }
  64806. float Colour::getFloatGreen() const throw()
  64807. {
  64808. return getGreen() / 255.0f;
  64809. }
  64810. float Colour::getFloatBlue() const throw()
  64811. {
  64812. return getBlue() / 255.0f;
  64813. }
  64814. float Colour::getFloatAlpha() const throw()
  64815. {
  64816. return getAlpha() / 255.0f;
  64817. }
  64818. void Colour::getHSB (float& h, float& s, float& v) const throw()
  64819. {
  64820. const int r = getRed();
  64821. const int g = getGreen();
  64822. const int b = getBlue();
  64823. const int hi = jmax (r, g, b);
  64824. const int lo = jmin (r, g, b);
  64825. if (hi != 0)
  64826. {
  64827. s = (hi - lo) / (float) hi;
  64828. if (s != 0)
  64829. {
  64830. const float invDiff = 1.0f / (hi - lo);
  64831. const float red = (hi - r) * invDiff;
  64832. const float green = (hi - g) * invDiff;
  64833. const float blue = (hi - b) * invDiff;
  64834. if (r == hi)
  64835. h = blue - green;
  64836. else if (g == hi)
  64837. h = 2.0f + red - blue;
  64838. else
  64839. h = 4.0f + green - red;
  64840. h *= 1.0f / 6.0f;
  64841. if (h < 0)
  64842. ++h;
  64843. }
  64844. else
  64845. {
  64846. h = 0;
  64847. }
  64848. }
  64849. else
  64850. {
  64851. s = 0;
  64852. h = 0;
  64853. }
  64854. v = hi / 255.0f;
  64855. }
  64856. float Colour::getHue() const throw()
  64857. {
  64858. float h, s, b;
  64859. getHSB (h, s, b);
  64860. return h;
  64861. }
  64862. const Colour Colour::withHue (const float hue) const throw()
  64863. {
  64864. float h, s, b;
  64865. getHSB (h, s, b);
  64866. return Colour (hue, s, b, getAlpha());
  64867. }
  64868. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  64869. {
  64870. float h, s, b;
  64871. getHSB (h, s, b);
  64872. h += amountToRotate;
  64873. h -= std::floor (h);
  64874. return Colour (h, s, b, getAlpha());
  64875. }
  64876. float Colour::getSaturation() const throw()
  64877. {
  64878. float h, s, b;
  64879. getHSB (h, s, b);
  64880. return s;
  64881. }
  64882. const Colour Colour::withSaturation (const float saturation) const throw()
  64883. {
  64884. float h, s, b;
  64885. getHSB (h, s, b);
  64886. return Colour (h, saturation, b, getAlpha());
  64887. }
  64888. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  64889. {
  64890. float h, s, b;
  64891. getHSB (h, s, b);
  64892. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  64893. }
  64894. float Colour::getBrightness() const throw()
  64895. {
  64896. float h, s, b;
  64897. getHSB (h, s, b);
  64898. return b;
  64899. }
  64900. const Colour Colour::withBrightness (const float brightness) const throw()
  64901. {
  64902. float h, s, b;
  64903. getHSB (h, s, b);
  64904. return Colour (h, s, brightness, getAlpha());
  64905. }
  64906. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  64907. {
  64908. float h, s, b;
  64909. getHSB (h, s, b);
  64910. b *= amount;
  64911. if (b > 1.0f)
  64912. b = 1.0f;
  64913. return Colour (h, s, b, getAlpha());
  64914. }
  64915. const Colour Colour::brighter (float amount) const throw()
  64916. {
  64917. amount = 1.0f / (1.0f + amount);
  64918. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  64919. (uint8) (255 - (amount * (255 - getGreen()))),
  64920. (uint8) (255 - (amount * (255 - getBlue()))),
  64921. getAlpha());
  64922. }
  64923. const Colour Colour::darker (float amount) const throw()
  64924. {
  64925. amount = 1.0f / (1.0f + amount);
  64926. return Colour ((uint8) (amount * getRed()),
  64927. (uint8) (amount * getGreen()),
  64928. (uint8) (amount * getBlue()),
  64929. getAlpha());
  64930. }
  64931. const Colour Colour::greyLevel (const float brightness) throw()
  64932. {
  64933. const uint8 level
  64934. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  64935. return Colour (level, level, level);
  64936. }
  64937. const Colour Colour::contrasting (const float amount) const throw()
  64938. {
  64939. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  64940. ? Colours::black
  64941. : Colours::white).withAlpha (amount));
  64942. }
  64943. const Colour Colour::contrasting (const Colour& colour1,
  64944. const Colour& colour2) throw()
  64945. {
  64946. const float b1 = colour1.getBrightness();
  64947. const float b2 = colour2.getBrightness();
  64948. float best = 0.0f;
  64949. float bestDist = 0.0f;
  64950. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  64951. {
  64952. const float d1 = std::abs (i - b1);
  64953. const float d2 = std::abs (i - b2);
  64954. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  64955. if (dist > bestDist)
  64956. {
  64957. best = i;
  64958. bestDist = dist;
  64959. }
  64960. }
  64961. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  64962. .withBrightness (best);
  64963. }
  64964. const String Colour::toString() const
  64965. {
  64966. return String::toHexString ((int) argb.getARGB());
  64967. }
  64968. const Colour Colour::fromString (const String& encodedColourString)
  64969. {
  64970. return Colour ((uint32) encodedColourString.getHexValue32());
  64971. }
  64972. const String Colour::toDisplayString (const bool includeAlphaValue) const
  64973. {
  64974. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  64975. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  64976. .toUpperCase();
  64977. }
  64978. END_JUCE_NAMESPACE
  64979. /*** End of inlined file: juce_Colour.cpp ***/
  64980. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  64981. BEGIN_JUCE_NAMESPACE
  64982. ColourGradient::ColourGradient() throw()
  64983. {
  64984. #if JUCE_DEBUG
  64985. point1.setX (987654.0f);
  64986. #endif
  64987. }
  64988. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  64989. const Colour& colour2, const float x2_, const float y2_,
  64990. const bool isRadial_)
  64991. : point1 (x1_, y1_),
  64992. point2 (x2_, y2_),
  64993. isRadial (isRadial_)
  64994. {
  64995. colours.add (ColourPoint (0.0, colour1));
  64996. colours.add (ColourPoint (1.0, colour2));
  64997. }
  64998. ColourGradient::~ColourGradient()
  64999. {
  65000. }
  65001. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65002. {
  65003. return point1 == other.point1 && point2 == other.point2
  65004. && isRadial == other.isRadial
  65005. && colours == other.colours;
  65006. }
  65007. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65008. {
  65009. return ! operator== (other);
  65010. }
  65011. void ColourGradient::clearColours()
  65012. {
  65013. colours.clear();
  65014. }
  65015. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65016. {
  65017. // must be within the two end-points
  65018. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65019. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65020. int i;
  65021. for (i = 0; i < colours.size(); ++i)
  65022. if (colours.getReference(i).position > pos)
  65023. break;
  65024. colours.insert (i, ColourPoint (pos, colour));
  65025. return i;
  65026. }
  65027. void ColourGradient::removeColour (int index)
  65028. {
  65029. jassert (index > 0 && index < colours.size() - 1);
  65030. colours.remove (index);
  65031. }
  65032. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65033. {
  65034. for (int i = 0; i < colours.size(); ++i)
  65035. {
  65036. Colour& c = colours.getReference(i).colour;
  65037. c = c.withMultipliedAlpha (multiplier);
  65038. }
  65039. }
  65040. int ColourGradient::getNumColours() const throw()
  65041. {
  65042. return colours.size();
  65043. }
  65044. double ColourGradient::getColourPosition (const int index) const throw()
  65045. {
  65046. if (((unsigned int) index) < (unsigned int) colours.size())
  65047. return colours.getReference (index).position;
  65048. return 0;
  65049. }
  65050. const Colour ColourGradient::getColour (const int index) const throw()
  65051. {
  65052. if (((unsigned int) index) < (unsigned int) colours.size())
  65053. return colours.getReference (index).colour;
  65054. return Colour();
  65055. }
  65056. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65057. {
  65058. if (((unsigned int) index) < (unsigned int) colours.size())
  65059. colours.getReference (index).colour = newColour;
  65060. }
  65061. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65062. {
  65063. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65064. if (position <= 0 || colours.size() <= 1)
  65065. return colours.getReference(0).colour;
  65066. int i = colours.size() - 1;
  65067. while (position < colours.getReference(i).position)
  65068. --i;
  65069. const ColourPoint& p1 = colours.getReference (i);
  65070. if (i >= colours.size() - 1)
  65071. return p1.colour;
  65072. const ColourPoint& p2 = colours.getReference (i + 1);
  65073. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65074. }
  65075. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65076. {
  65077. #if JUCE_DEBUG
  65078. // trying to use the object without setting its co-ordinates? Have a careful read of
  65079. // the comments for the constructors.
  65080. jassert (point1.getX() != 987654.0f);
  65081. #endif
  65082. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65083. 3 * (int) point1.transformedBy (transform)
  65084. .getDistanceFrom (point2.transformedBy (transform)));
  65085. lookupTable.malloc (numEntries);
  65086. if (colours.size() >= 2)
  65087. {
  65088. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65089. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65090. int index = 0;
  65091. for (int j = 1; j < colours.size(); ++j)
  65092. {
  65093. const ColourPoint& p = colours.getReference (j);
  65094. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65095. const PixelARGB pix2 (p.colour.getPixelARGB());
  65096. for (int i = 0; i < numToDo; ++i)
  65097. {
  65098. jassert (index >= 0 && index < numEntries);
  65099. lookupTable[index] = pix1;
  65100. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65101. ++index;
  65102. }
  65103. pix1 = pix2;
  65104. }
  65105. while (index < numEntries)
  65106. lookupTable [index++] = pix1;
  65107. }
  65108. else
  65109. {
  65110. jassertfalse; // no colours specified!
  65111. }
  65112. return numEntries;
  65113. }
  65114. bool ColourGradient::isOpaque() const throw()
  65115. {
  65116. for (int i = 0; i < colours.size(); ++i)
  65117. if (! colours.getReference(i).colour.isOpaque())
  65118. return false;
  65119. return true;
  65120. }
  65121. bool ColourGradient::isInvisible() const throw()
  65122. {
  65123. for (int i = 0; i < colours.size(); ++i)
  65124. if (! colours.getReference(i).colour.isTransparent())
  65125. return false;
  65126. return true;
  65127. }
  65128. END_JUCE_NAMESPACE
  65129. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65130. /*** Start of inlined file: juce_Colours.cpp ***/
  65131. BEGIN_JUCE_NAMESPACE
  65132. const Colour Colours::transparentBlack (0);
  65133. const Colour Colours::transparentWhite (0x00ffffff);
  65134. const Colour Colours::aliceblue (0xfff0f8ff);
  65135. const Colour Colours::antiquewhite (0xfffaebd7);
  65136. const Colour Colours::aqua (0xff00ffff);
  65137. const Colour Colours::aquamarine (0xff7fffd4);
  65138. const Colour Colours::azure (0xfff0ffff);
  65139. const Colour Colours::beige (0xfff5f5dc);
  65140. const Colour Colours::bisque (0xffffe4c4);
  65141. const Colour Colours::black (0xff000000);
  65142. const Colour Colours::blanchedalmond (0xffffebcd);
  65143. const Colour Colours::blue (0xff0000ff);
  65144. const Colour Colours::blueviolet (0xff8a2be2);
  65145. const Colour Colours::brown (0xffa52a2a);
  65146. const Colour Colours::burlywood (0xffdeb887);
  65147. const Colour Colours::cadetblue (0xff5f9ea0);
  65148. const Colour Colours::chartreuse (0xff7fff00);
  65149. const Colour Colours::chocolate (0xffd2691e);
  65150. const Colour Colours::coral (0xffff7f50);
  65151. const Colour Colours::cornflowerblue (0xff6495ed);
  65152. const Colour Colours::cornsilk (0xfffff8dc);
  65153. const Colour Colours::crimson (0xffdc143c);
  65154. const Colour Colours::cyan (0xff00ffff);
  65155. const Colour Colours::darkblue (0xff00008b);
  65156. const Colour Colours::darkcyan (0xff008b8b);
  65157. const Colour Colours::darkgoldenrod (0xffb8860b);
  65158. const Colour Colours::darkgrey (0xff555555);
  65159. const Colour Colours::darkgreen (0xff006400);
  65160. const Colour Colours::darkkhaki (0xffbdb76b);
  65161. const Colour Colours::darkmagenta (0xff8b008b);
  65162. const Colour Colours::darkolivegreen (0xff556b2f);
  65163. const Colour Colours::darkorange (0xffff8c00);
  65164. const Colour Colours::darkorchid (0xff9932cc);
  65165. const Colour Colours::darkred (0xff8b0000);
  65166. const Colour Colours::darksalmon (0xffe9967a);
  65167. const Colour Colours::darkseagreen (0xff8fbc8f);
  65168. const Colour Colours::darkslateblue (0xff483d8b);
  65169. const Colour Colours::darkslategrey (0xff2f4f4f);
  65170. const Colour Colours::darkturquoise (0xff00ced1);
  65171. const Colour Colours::darkviolet (0xff9400d3);
  65172. const Colour Colours::deeppink (0xffff1493);
  65173. const Colour Colours::deepskyblue (0xff00bfff);
  65174. const Colour Colours::dimgrey (0xff696969);
  65175. const Colour Colours::dodgerblue (0xff1e90ff);
  65176. const Colour Colours::firebrick (0xffb22222);
  65177. const Colour Colours::floralwhite (0xfffffaf0);
  65178. const Colour Colours::forestgreen (0xff228b22);
  65179. const Colour Colours::fuchsia (0xffff00ff);
  65180. const Colour Colours::gainsboro (0xffdcdcdc);
  65181. const Colour Colours::gold (0xffffd700);
  65182. const Colour Colours::goldenrod (0xffdaa520);
  65183. const Colour Colours::grey (0xff808080);
  65184. const Colour Colours::green (0xff008000);
  65185. const Colour Colours::greenyellow (0xffadff2f);
  65186. const Colour Colours::honeydew (0xfff0fff0);
  65187. const Colour Colours::hotpink (0xffff69b4);
  65188. const Colour Colours::indianred (0xffcd5c5c);
  65189. const Colour Colours::indigo (0xff4b0082);
  65190. const Colour Colours::ivory (0xfffffff0);
  65191. const Colour Colours::khaki (0xfff0e68c);
  65192. const Colour Colours::lavender (0xffe6e6fa);
  65193. const Colour Colours::lavenderblush (0xfffff0f5);
  65194. const Colour Colours::lemonchiffon (0xfffffacd);
  65195. const Colour Colours::lightblue (0xffadd8e6);
  65196. const Colour Colours::lightcoral (0xfff08080);
  65197. const Colour Colours::lightcyan (0xffe0ffff);
  65198. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65199. const Colour Colours::lightgreen (0xff90ee90);
  65200. const Colour Colours::lightgrey (0xffd3d3d3);
  65201. const Colour Colours::lightpink (0xffffb6c1);
  65202. const Colour Colours::lightsalmon (0xffffa07a);
  65203. const Colour Colours::lightseagreen (0xff20b2aa);
  65204. const Colour Colours::lightskyblue (0xff87cefa);
  65205. const Colour Colours::lightslategrey (0xff778899);
  65206. const Colour Colours::lightsteelblue (0xffb0c4de);
  65207. const Colour Colours::lightyellow (0xffffffe0);
  65208. const Colour Colours::lime (0xff00ff00);
  65209. const Colour Colours::limegreen (0xff32cd32);
  65210. const Colour Colours::linen (0xfffaf0e6);
  65211. const Colour Colours::magenta (0xffff00ff);
  65212. const Colour Colours::maroon (0xff800000);
  65213. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65214. const Colour Colours::mediumblue (0xff0000cd);
  65215. const Colour Colours::mediumorchid (0xffba55d3);
  65216. const Colour Colours::mediumpurple (0xff9370db);
  65217. const Colour Colours::mediumseagreen (0xff3cb371);
  65218. const Colour Colours::mediumslateblue (0xff7b68ee);
  65219. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65220. const Colour Colours::mediumturquoise (0xff48d1cc);
  65221. const Colour Colours::mediumvioletred (0xffc71585);
  65222. const Colour Colours::midnightblue (0xff191970);
  65223. const Colour Colours::mintcream (0xfff5fffa);
  65224. const Colour Colours::mistyrose (0xffffe4e1);
  65225. const Colour Colours::navajowhite (0xffffdead);
  65226. const Colour Colours::navy (0xff000080);
  65227. const Colour Colours::oldlace (0xfffdf5e6);
  65228. const Colour Colours::olive (0xff808000);
  65229. const Colour Colours::olivedrab (0xff6b8e23);
  65230. const Colour Colours::orange (0xffffa500);
  65231. const Colour Colours::orangered (0xffff4500);
  65232. const Colour Colours::orchid (0xffda70d6);
  65233. const Colour Colours::palegoldenrod (0xffeee8aa);
  65234. const Colour Colours::palegreen (0xff98fb98);
  65235. const Colour Colours::paleturquoise (0xffafeeee);
  65236. const Colour Colours::palevioletred (0xffdb7093);
  65237. const Colour Colours::papayawhip (0xffffefd5);
  65238. const Colour Colours::peachpuff (0xffffdab9);
  65239. const Colour Colours::peru (0xffcd853f);
  65240. const Colour Colours::pink (0xffffc0cb);
  65241. const Colour Colours::plum (0xffdda0dd);
  65242. const Colour Colours::powderblue (0xffb0e0e6);
  65243. const Colour Colours::purple (0xff800080);
  65244. const Colour Colours::red (0xffff0000);
  65245. const Colour Colours::rosybrown (0xffbc8f8f);
  65246. const Colour Colours::royalblue (0xff4169e1);
  65247. const Colour Colours::saddlebrown (0xff8b4513);
  65248. const Colour Colours::salmon (0xfffa8072);
  65249. const Colour Colours::sandybrown (0xfff4a460);
  65250. const Colour Colours::seagreen (0xff2e8b57);
  65251. const Colour Colours::seashell (0xfffff5ee);
  65252. const Colour Colours::sienna (0xffa0522d);
  65253. const Colour Colours::silver (0xffc0c0c0);
  65254. const Colour Colours::skyblue (0xff87ceeb);
  65255. const Colour Colours::slateblue (0xff6a5acd);
  65256. const Colour Colours::slategrey (0xff708090);
  65257. const Colour Colours::snow (0xfffffafa);
  65258. const Colour Colours::springgreen (0xff00ff7f);
  65259. const Colour Colours::steelblue (0xff4682b4);
  65260. const Colour Colours::tan (0xffd2b48c);
  65261. const Colour Colours::teal (0xff008080);
  65262. const Colour Colours::thistle (0xffd8bfd8);
  65263. const Colour Colours::tomato (0xffff6347);
  65264. const Colour Colours::turquoise (0xff40e0d0);
  65265. const Colour Colours::violet (0xffee82ee);
  65266. const Colour Colours::wheat (0xfff5deb3);
  65267. const Colour Colours::white (0xffffffff);
  65268. const Colour Colours::whitesmoke (0xfff5f5f5);
  65269. const Colour Colours::yellow (0xffffff00);
  65270. const Colour Colours::yellowgreen (0xff9acd32);
  65271. const Colour Colours::findColourForName (const String& colourName,
  65272. const Colour& defaultColour)
  65273. {
  65274. static const int presets[] =
  65275. {
  65276. // (first value is the string's hashcode, second is ARGB)
  65277. 0x05978fff, 0xff000000, /* black */
  65278. 0x06bdcc29, 0xffffffff, /* white */
  65279. 0x002e305a, 0xff0000ff, /* blue */
  65280. 0x00308adf, 0xff808080, /* grey */
  65281. 0x05e0cf03, 0xff008000, /* green */
  65282. 0x0001b891, 0xffff0000, /* red */
  65283. 0xd43c6474, 0xffffff00, /* yellow */
  65284. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65285. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65286. 0x002dcebc, 0xff00ffff, /* aqua */
  65287. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65288. 0x0590228f, 0xfff0ffff, /* azure */
  65289. 0x05947fe4, 0xfff5f5dc, /* beige */
  65290. 0xad388e35, 0xffffe4c4, /* bisque */
  65291. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65292. 0x39129959, 0xff8a2be2, /* blueviolet */
  65293. 0x059a8136, 0xffa52a2a, /* brown */
  65294. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65295. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65296. 0x6b748956, 0xff7fff00, /* chartreuse */
  65297. 0x2903623c, 0xffd2691e, /* chocolate */
  65298. 0x05a74431, 0xffff7f50, /* coral */
  65299. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65300. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65301. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65302. 0x002ed323, 0xff00ffff, /* cyan */
  65303. 0x67cc74d0, 0xff00008b, /* darkblue */
  65304. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65305. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65306. 0x67cecf55, 0xff555555, /* darkgrey */
  65307. 0x920b194d, 0xff006400, /* darkgreen */
  65308. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65309. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65310. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65311. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65312. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65313. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65314. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65315. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65316. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65317. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65318. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65319. 0xc8769375, 0xff9400d3, /* darkviolet */
  65320. 0x25832862, 0xffff1493, /* deeppink */
  65321. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65322. 0x634c8b67, 0xff696969, /* dimgrey */
  65323. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65324. 0xef19e3cb, 0xffb22222, /* firebrick */
  65325. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65326. 0xd086fd06, 0xff228b22, /* forestgreen */
  65327. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65328. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65329. 0x00308060, 0xffffd700, /* gold */
  65330. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65331. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65332. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65333. 0x41892743, 0xffff69b4, /* hotpink */
  65334. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65335. 0xb969fed2, 0xff4b0082, /* indigo */
  65336. 0x05fef6a9, 0xfffffff0, /* ivory */
  65337. 0x06149302, 0xfff0e68c, /* khaki */
  65338. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65339. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65340. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65341. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65342. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65343. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65344. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65345. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65346. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65347. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65348. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65349. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65350. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65351. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65352. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65353. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65354. 0x0032afd5, 0xff00ff00, /* lime */
  65355. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65356. 0x06234efa, 0xfffaf0e6, /* linen */
  65357. 0x316858a9, 0xffff00ff, /* magenta */
  65358. 0xbf8ca470, 0xff800000, /* maroon */
  65359. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65360. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65361. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65362. 0x07556b71, 0xff9370db, /* mediumpurple */
  65363. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65364. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65365. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65366. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65367. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65368. 0x168eb32a, 0xff191970, /* midnightblue */
  65369. 0x4306b960, 0xfff5fffa, /* mintcream */
  65370. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65371. 0xe97218a6, 0xffffdead, /* navajowhite */
  65372. 0x00337bb6, 0xff000080, /* navy */
  65373. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65374. 0x064ee1db, 0xff808000, /* olive */
  65375. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65376. 0xc3de262e, 0xffffa500, /* orange */
  65377. 0x58bebba3, 0xffff4500, /* orangered */
  65378. 0xc3def8a3, 0xffda70d6, /* orchid */
  65379. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65380. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65381. 0x74022737, 0xffafeeee, /* paleturquoise */
  65382. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65383. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65384. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65385. 0x003472f8, 0xffcd853f, /* peru */
  65386. 0x00348176, 0xffffc0cb, /* pink */
  65387. 0x00348d94, 0xffdda0dd, /* plum */
  65388. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65389. 0xc5c507bc, 0xff800080, /* purple */
  65390. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65391. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65392. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65393. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65394. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65395. 0x34636c14, 0xff2e8b57, /* seagreen */
  65396. 0x3507fb41, 0xfffff5ee, /* seashell */
  65397. 0xca348772, 0xffa0522d, /* sienna */
  65398. 0xca37d30d, 0xffc0c0c0, /* silver */
  65399. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65400. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65401. 0x44ab37f8, 0xff708090, /* slategrey */
  65402. 0x0035f183, 0xfffffafa, /* snow */
  65403. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65404. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65405. 0x0001bfa1, 0xffd2b48c, /* tan */
  65406. 0x0036425c, 0xff008080, /* teal */
  65407. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65408. 0xcc41600a, 0xffff6347, /* tomato */
  65409. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65410. 0xcf57947f, 0xffee82ee, /* violet */
  65411. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65412. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65413. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65414. };
  65415. const int hash = colourName.trim().toLowerCase().hashCode();
  65416. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65417. if (presets [i] == hash)
  65418. return Colour (presets [i + 1]);
  65419. return defaultColour;
  65420. }
  65421. END_JUCE_NAMESPACE
  65422. /*** End of inlined file: juce_Colours.cpp ***/
  65423. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65424. BEGIN_JUCE_NAMESPACE
  65425. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65426. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65427. const Path& path, const AffineTransform& transform)
  65428. : bounds (bounds_),
  65429. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65430. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65431. needToCheckEmptinesss (true)
  65432. {
  65433. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65434. int* t = table;
  65435. for (int i = bounds.getHeight(); --i >= 0;)
  65436. {
  65437. *t = 0;
  65438. t += lineStrideElements;
  65439. }
  65440. const int topLimit = bounds.getY() << 8;
  65441. const int heightLimit = bounds.getHeight() << 8;
  65442. const int leftLimit = bounds.getX() << 8;
  65443. const int rightLimit = bounds.getRight() << 8;
  65444. PathFlatteningIterator iter (path, transform);
  65445. while (iter.next())
  65446. {
  65447. int y1 = roundToInt (iter.y1 * 256.0f);
  65448. int y2 = roundToInt (iter.y2 * 256.0f);
  65449. if (y1 != y2)
  65450. {
  65451. y1 -= topLimit;
  65452. y2 -= topLimit;
  65453. const int startY = y1;
  65454. int direction = -1;
  65455. if (y1 > y2)
  65456. {
  65457. swapVariables (y1, y2);
  65458. direction = 1;
  65459. }
  65460. if (y1 < 0)
  65461. y1 = 0;
  65462. if (y2 > heightLimit)
  65463. y2 = heightLimit;
  65464. if (y1 < y2)
  65465. {
  65466. const double startX = 256.0f * iter.x1;
  65467. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65468. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65469. do
  65470. {
  65471. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65472. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65473. if (x < leftLimit)
  65474. x = leftLimit;
  65475. else if (x >= rightLimit)
  65476. x = rightLimit - 1;
  65477. addEdgePoint (x, y1 >> 8, direction * step);
  65478. y1 += step;
  65479. }
  65480. while (y1 < y2);
  65481. }
  65482. }
  65483. }
  65484. sanitiseLevels (path.isUsingNonZeroWinding());
  65485. }
  65486. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65487. : bounds (rectangleToAdd),
  65488. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65489. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65490. needToCheckEmptinesss (true)
  65491. {
  65492. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65493. table[0] = 0;
  65494. const int x1 = rectangleToAdd.getX() << 8;
  65495. const int x2 = rectangleToAdd.getRight() << 8;
  65496. int* t = table;
  65497. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65498. {
  65499. t[0] = 2;
  65500. t[1] = x1;
  65501. t[2] = 255;
  65502. t[3] = x2;
  65503. t[4] = 0;
  65504. t += lineStrideElements;
  65505. }
  65506. }
  65507. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65508. : bounds (rectanglesToAdd.getBounds()),
  65509. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65510. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65511. needToCheckEmptinesss (true)
  65512. {
  65513. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65514. int* t = table;
  65515. for (int i = bounds.getHeight(); --i >= 0;)
  65516. {
  65517. *t = 0;
  65518. t += lineStrideElements;
  65519. }
  65520. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65521. {
  65522. const Rectangle<int>* const r = iter.getRectangle();
  65523. const int x1 = r->getX() << 8;
  65524. const int x2 = r->getRight() << 8;
  65525. int y = r->getY() - bounds.getY();
  65526. for (int j = r->getHeight(); --j >= 0;)
  65527. {
  65528. addEdgePoint (x1, y, 255);
  65529. addEdgePoint (x2, y, -255);
  65530. ++y;
  65531. }
  65532. }
  65533. sanitiseLevels (true);
  65534. }
  65535. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65536. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65537. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65538. 2 + (int) rectangleToAdd.getWidth(),
  65539. 2 + (int) rectangleToAdd.getHeight())),
  65540. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65541. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65542. needToCheckEmptinesss (true)
  65543. {
  65544. jassert (! rectangleToAdd.isEmpty());
  65545. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65546. table[0] = 0;
  65547. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65548. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65549. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65550. jassert (y1 < 256);
  65551. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65552. if (x2 <= x1 || y2 <= y1)
  65553. {
  65554. bounds.setHeight (0);
  65555. return;
  65556. }
  65557. int lineY = 0;
  65558. int* t = table;
  65559. if ((y1 >> 8) == (y2 >> 8))
  65560. {
  65561. t[0] = 2;
  65562. t[1] = x1;
  65563. t[2] = y2 - y1;
  65564. t[3] = x2;
  65565. t[4] = 0;
  65566. ++lineY;
  65567. t += lineStrideElements;
  65568. }
  65569. else
  65570. {
  65571. t[0] = 2;
  65572. t[1] = x1;
  65573. t[2] = 255 - (y1 & 255);
  65574. t[3] = x2;
  65575. t[4] = 0;
  65576. ++lineY;
  65577. t += lineStrideElements;
  65578. while (lineY < (y2 >> 8))
  65579. {
  65580. t[0] = 2;
  65581. t[1] = x1;
  65582. t[2] = 255;
  65583. t[3] = x2;
  65584. t[4] = 0;
  65585. ++lineY;
  65586. t += lineStrideElements;
  65587. }
  65588. jassert (lineY < bounds.getHeight());
  65589. t[0] = 2;
  65590. t[1] = x1;
  65591. t[2] = y2 & 255;
  65592. t[3] = x2;
  65593. t[4] = 0;
  65594. ++lineY;
  65595. t += lineStrideElements;
  65596. }
  65597. while (lineY < bounds.getHeight())
  65598. {
  65599. t[0] = 0;
  65600. t += lineStrideElements;
  65601. ++lineY;
  65602. }
  65603. }
  65604. EdgeTable::EdgeTable (const EdgeTable& other)
  65605. {
  65606. operator= (other);
  65607. }
  65608. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65609. {
  65610. bounds = other.bounds;
  65611. maxEdgesPerLine = other.maxEdgesPerLine;
  65612. lineStrideElements = other.lineStrideElements;
  65613. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65614. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65615. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65616. return *this;
  65617. }
  65618. EdgeTable::~EdgeTable()
  65619. {
  65620. }
  65621. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65622. {
  65623. while (--numLines >= 0)
  65624. {
  65625. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65626. src += srcLineStride;
  65627. dest += destLineStride;
  65628. }
  65629. }
  65630. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65631. {
  65632. // Convert the table from relative windings to absolute levels..
  65633. int* lineStart = table;
  65634. for (int i = bounds.getHeight(); --i >= 0;)
  65635. {
  65636. int* line = lineStart;
  65637. lineStart += lineStrideElements;
  65638. int num = *line;
  65639. if (num == 0)
  65640. continue;
  65641. int level = 0;
  65642. if (useNonZeroWinding)
  65643. {
  65644. while (--num > 0)
  65645. {
  65646. line += 2;
  65647. level += *line;
  65648. int corrected = abs (level);
  65649. if (corrected >> 8)
  65650. corrected = 255;
  65651. *line = corrected;
  65652. }
  65653. }
  65654. else
  65655. {
  65656. while (--num > 0)
  65657. {
  65658. line += 2;
  65659. level += *line;
  65660. int corrected = abs (level);
  65661. if (corrected >> 8)
  65662. {
  65663. corrected &= 511;
  65664. if (corrected >> 8)
  65665. corrected = 511 - corrected;
  65666. }
  65667. *line = corrected;
  65668. }
  65669. }
  65670. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65671. }
  65672. }
  65673. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  65674. {
  65675. if (newNumEdgesPerLine != maxEdgesPerLine)
  65676. {
  65677. maxEdgesPerLine = newNumEdgesPerLine;
  65678. jassert (bounds.getHeight() > 0);
  65679. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65680. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65681. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65682. table.swapWith (newTable);
  65683. lineStrideElements = newLineStrideElements;
  65684. }
  65685. }
  65686. void EdgeTable::optimiseTable() throw()
  65687. {
  65688. int maxLineElements = 0;
  65689. for (int i = bounds.getHeight(); --i >= 0;)
  65690. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65691. remapTableForNumEdges (maxLineElements);
  65692. }
  65693. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  65694. {
  65695. jassert (y >= 0 && y < bounds.getHeight());
  65696. int* line = table + lineStrideElements * y;
  65697. const int numPoints = line[0];
  65698. int n = numPoints << 1;
  65699. if (n > 0)
  65700. {
  65701. while (n > 0)
  65702. {
  65703. const int cx = line [n - 1];
  65704. if (cx <= x)
  65705. {
  65706. if (cx == x)
  65707. {
  65708. line [n] += winding;
  65709. return;
  65710. }
  65711. break;
  65712. }
  65713. n -= 2;
  65714. }
  65715. if (numPoints >= maxEdgesPerLine)
  65716. {
  65717. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65718. jassert (numPoints < maxEdgesPerLine);
  65719. line = table + lineStrideElements * y;
  65720. }
  65721. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65722. }
  65723. line [n + 1] = x;
  65724. line [n + 2] = winding;
  65725. line[0]++;
  65726. }
  65727. void EdgeTable::translate (float dx, const int dy) throw()
  65728. {
  65729. bounds.translate ((int) std::floor (dx), dy);
  65730. int* lineStart = table;
  65731. const int intDx = (int) (dx * 256.0f);
  65732. for (int i = bounds.getHeight(); --i >= 0;)
  65733. {
  65734. int* line = lineStart;
  65735. lineStart += lineStrideElements;
  65736. int num = *line++;
  65737. while (--num >= 0)
  65738. {
  65739. *line += intDx;
  65740. line += 2;
  65741. }
  65742. }
  65743. }
  65744. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  65745. {
  65746. jassert (y >= 0 && y < bounds.getHeight());
  65747. int* dest = table + lineStrideElements * y;
  65748. if (dest[0] == 0)
  65749. return;
  65750. int otherNumPoints = *otherLine;
  65751. if (otherNumPoints == 0)
  65752. {
  65753. *dest = 0;
  65754. return;
  65755. }
  65756. const int right = bounds.getRight() << 8;
  65757. // optimise for the common case where our line lies entirely within a
  65758. // single pair of points, as happens when clipping to a simple rect.
  65759. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65760. {
  65761. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65762. return;
  65763. }
  65764. ++otherLine;
  65765. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65766. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65767. memcpy (temp, dest, lineSizeBytes);
  65768. const int* src1 = temp;
  65769. int srcNum1 = *src1++;
  65770. int x1 = *src1++;
  65771. const int* src2 = otherLine;
  65772. int srcNum2 = otherNumPoints;
  65773. int x2 = *src2++;
  65774. int destIndex = 0, destTotal = 0;
  65775. int level1 = 0, level2 = 0;
  65776. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65777. while (srcNum1 > 0 && srcNum2 > 0)
  65778. {
  65779. int nextX;
  65780. if (x1 < x2)
  65781. {
  65782. nextX = x1;
  65783. level1 = *src1++;
  65784. x1 = *src1++;
  65785. --srcNum1;
  65786. }
  65787. else if (x1 == x2)
  65788. {
  65789. nextX = x1;
  65790. level1 = *src1++;
  65791. level2 = *src2++;
  65792. x1 = *src1++;
  65793. x2 = *src2++;
  65794. --srcNum1;
  65795. --srcNum2;
  65796. }
  65797. else
  65798. {
  65799. nextX = x2;
  65800. level2 = *src2++;
  65801. x2 = *src2++;
  65802. --srcNum2;
  65803. }
  65804. if (nextX > lastX)
  65805. {
  65806. if (nextX >= right)
  65807. break;
  65808. lastX = nextX;
  65809. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  65810. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  65811. if (nextLevel != lastLevel)
  65812. {
  65813. if (destTotal >= maxEdgesPerLine)
  65814. {
  65815. dest[0] = destTotal;
  65816. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65817. dest = table + lineStrideElements * y;
  65818. }
  65819. ++destTotal;
  65820. lastLevel = nextLevel;
  65821. dest[++destIndex] = nextX;
  65822. dest[++destIndex] = nextLevel;
  65823. }
  65824. }
  65825. }
  65826. if (lastLevel > 0)
  65827. {
  65828. if (destTotal >= maxEdgesPerLine)
  65829. {
  65830. dest[0] = destTotal;
  65831. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65832. dest = table + lineStrideElements * y;
  65833. }
  65834. ++destTotal;
  65835. dest[++destIndex] = right;
  65836. dest[++destIndex] = 0;
  65837. }
  65838. dest[0] = destTotal;
  65839. #if JUCE_DEBUG
  65840. int last = std::numeric_limits<int>::min();
  65841. for (int i = 0; i < dest[0]; ++i)
  65842. {
  65843. jassert (dest[i * 2 + 1] > last);
  65844. last = dest[i * 2 + 1];
  65845. }
  65846. jassert (dest [dest[0] * 2] == 0);
  65847. #endif
  65848. }
  65849. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  65850. {
  65851. int* lastItem = dest + (dest[0] * 2 - 1);
  65852. if (x2 < lastItem[0])
  65853. {
  65854. if (x2 <= dest[1])
  65855. {
  65856. dest[0] = 0;
  65857. return;
  65858. }
  65859. while (x2 < lastItem[-2])
  65860. {
  65861. --(dest[0]);
  65862. lastItem -= 2;
  65863. }
  65864. lastItem[0] = x2;
  65865. lastItem[1] = 0;
  65866. }
  65867. if (x1 > dest[1])
  65868. {
  65869. while (lastItem[0] > x1)
  65870. lastItem -= 2;
  65871. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  65872. if (itemsRemoved > 0)
  65873. {
  65874. dest[0] -= itemsRemoved;
  65875. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  65876. }
  65877. dest[1] = x1;
  65878. }
  65879. }
  65880. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  65881. {
  65882. const Rectangle<int> clipped (r.getIntersection (bounds));
  65883. if (clipped.isEmpty())
  65884. {
  65885. needToCheckEmptinesss = false;
  65886. bounds.setHeight (0);
  65887. }
  65888. else
  65889. {
  65890. const int top = clipped.getY() - bounds.getY();
  65891. const int bottom = clipped.getBottom() - bounds.getY();
  65892. if (bottom < bounds.getHeight())
  65893. bounds.setHeight (bottom);
  65894. if (clipped.getRight() < bounds.getRight())
  65895. bounds.setRight (clipped.getRight());
  65896. for (int i = top; --i >= 0;)
  65897. table [lineStrideElements * i] = 0;
  65898. if (clipped.getX() > bounds.getX())
  65899. {
  65900. const int x1 = clipped.getX() << 8;
  65901. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  65902. int* line = table + lineStrideElements * top;
  65903. for (int i = bottom - top; --i >= 0;)
  65904. {
  65905. if (line[0] != 0)
  65906. clipEdgeTableLineToRange (line, x1, x2);
  65907. line += lineStrideElements;
  65908. }
  65909. }
  65910. needToCheckEmptinesss = true;
  65911. }
  65912. }
  65913. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  65914. {
  65915. const Rectangle<int> clipped (r.getIntersection (bounds));
  65916. if (! clipped.isEmpty())
  65917. {
  65918. const int top = clipped.getY() - bounds.getY();
  65919. const int bottom = clipped.getBottom() - bounds.getY();
  65920. //XXX optimise here by shortening the table if it fills top or bottom
  65921. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  65922. clipped.getX() << 8, 0,
  65923. clipped.getRight() << 8, 255,
  65924. std::numeric_limits<int>::max(), 0 };
  65925. for (int i = top; i < bottom; ++i)
  65926. intersectWithEdgeTableLine (i, rectLine);
  65927. needToCheckEmptinesss = true;
  65928. }
  65929. }
  65930. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  65931. {
  65932. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  65933. if (clipped.isEmpty())
  65934. {
  65935. needToCheckEmptinesss = false;
  65936. bounds.setHeight (0);
  65937. }
  65938. else
  65939. {
  65940. const int top = clipped.getY() - bounds.getY();
  65941. const int bottom = clipped.getBottom() - bounds.getY();
  65942. if (bottom < bounds.getHeight())
  65943. bounds.setHeight (bottom);
  65944. if (clipped.getRight() < bounds.getRight())
  65945. bounds.setRight (clipped.getRight());
  65946. int i = 0;
  65947. for (i = top; --i >= 0;)
  65948. table [lineStrideElements * i] = 0;
  65949. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  65950. for (i = top; i < bottom; ++i)
  65951. {
  65952. intersectWithEdgeTableLine (i, otherLine);
  65953. otherLine += other.lineStrideElements;
  65954. }
  65955. needToCheckEmptinesss = true;
  65956. }
  65957. }
  65958. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  65959. {
  65960. y -= bounds.getY();
  65961. if (y < 0 || y >= bounds.getHeight())
  65962. return;
  65963. needToCheckEmptinesss = true;
  65964. if (numPixels <= 0)
  65965. {
  65966. table [lineStrideElements * y] = 0;
  65967. return;
  65968. }
  65969. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  65970. int destIndex = 0, lastLevel = 0;
  65971. while (--numPixels >= 0)
  65972. {
  65973. const int alpha = *mask;
  65974. mask += maskStride;
  65975. if (alpha != lastLevel)
  65976. {
  65977. tempLine[++destIndex] = (x << 8);
  65978. tempLine[++destIndex] = alpha;
  65979. lastLevel = alpha;
  65980. }
  65981. ++x;
  65982. }
  65983. if (lastLevel > 0)
  65984. {
  65985. tempLine[++destIndex] = (x << 8);
  65986. tempLine[++destIndex] = 0;
  65987. }
  65988. tempLine[0] = destIndex >> 1;
  65989. intersectWithEdgeTableLine (y, tempLine);
  65990. }
  65991. bool EdgeTable::isEmpty() throw()
  65992. {
  65993. if (needToCheckEmptinesss)
  65994. {
  65995. needToCheckEmptinesss = false;
  65996. int* t = table;
  65997. for (int i = bounds.getHeight(); --i >= 0;)
  65998. {
  65999. if (t[0] > 1)
  66000. return false;
  66001. t += lineStrideElements;
  66002. }
  66003. bounds.setHeight (0);
  66004. }
  66005. return bounds.getHeight() == 0;
  66006. }
  66007. END_JUCE_NAMESPACE
  66008. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66009. /*** Start of inlined file: juce_FillType.cpp ***/
  66010. BEGIN_JUCE_NAMESPACE
  66011. FillType::FillType() throw()
  66012. : colour (0xff000000), image (0)
  66013. {
  66014. }
  66015. FillType::FillType (const Colour& colour_) throw()
  66016. : colour (colour_), image (0)
  66017. {
  66018. }
  66019. FillType::FillType (const ColourGradient& gradient_)
  66020. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66021. {
  66022. }
  66023. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66024. : colour (0xff000000), image (image_), transform (transform_)
  66025. {
  66026. }
  66027. FillType::FillType (const FillType& other)
  66028. : colour (other.colour),
  66029. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66030. image (other.image), transform (other.transform)
  66031. {
  66032. }
  66033. FillType& FillType::operator= (const FillType& other)
  66034. {
  66035. if (this != &other)
  66036. {
  66037. colour = other.colour;
  66038. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66039. image = other.image;
  66040. transform = other.transform;
  66041. }
  66042. return *this;
  66043. }
  66044. FillType::~FillType() throw()
  66045. {
  66046. }
  66047. bool FillType::operator== (const FillType& other) const
  66048. {
  66049. return colour == other.colour && image == other.image
  66050. && transform == other.transform
  66051. && (gradient == other.gradient
  66052. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66053. }
  66054. bool FillType::operator!= (const FillType& other) const
  66055. {
  66056. return ! operator== (other);
  66057. }
  66058. void FillType::setColour (const Colour& newColour) throw()
  66059. {
  66060. gradient = 0;
  66061. image = Image::null;
  66062. colour = newColour;
  66063. }
  66064. void FillType::setGradient (const ColourGradient& newGradient)
  66065. {
  66066. if (gradient != 0)
  66067. {
  66068. *gradient = newGradient;
  66069. }
  66070. else
  66071. {
  66072. image = Image::null;
  66073. gradient = new ColourGradient (newGradient);
  66074. colour = Colours::black;
  66075. }
  66076. }
  66077. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66078. {
  66079. gradient = 0;
  66080. image = image_;
  66081. transform = transform_;
  66082. colour = Colours::black;
  66083. }
  66084. void FillType::setOpacity (const float newOpacity) throw()
  66085. {
  66086. colour = colour.withAlpha (newOpacity);
  66087. }
  66088. bool FillType::isInvisible() const throw()
  66089. {
  66090. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66091. }
  66092. END_JUCE_NAMESPACE
  66093. /*** End of inlined file: juce_FillType.cpp ***/
  66094. /*** Start of inlined file: juce_Graphics.cpp ***/
  66095. BEGIN_JUCE_NAMESPACE
  66096. namespace
  66097. {
  66098. template <typename Type>
  66099. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66100. {
  66101. const int maxVal = 0x3fffffff;
  66102. return (int) x >= -maxVal && (int) x <= maxVal
  66103. && (int) y >= -maxVal && (int) y <= maxVal
  66104. && (int) w >= -maxVal && (int) w <= maxVal
  66105. && (int) h >= -maxVal && (int) h <= maxVal;
  66106. }
  66107. }
  66108. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66109. {
  66110. }
  66111. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66112. {
  66113. }
  66114. Graphics::Graphics (const Image& imageToDrawOnto)
  66115. : context (imageToDrawOnto.createLowLevelContext()),
  66116. contextToDelete (context),
  66117. saveStatePending (false)
  66118. {
  66119. }
  66120. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66121. : context (internalContext),
  66122. saveStatePending (false)
  66123. {
  66124. }
  66125. Graphics::~Graphics()
  66126. {
  66127. }
  66128. void Graphics::resetToDefaultState()
  66129. {
  66130. saveStateIfPending();
  66131. context->setFill (FillType());
  66132. context->setFont (Font());
  66133. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66134. }
  66135. bool Graphics::isVectorDevice() const
  66136. {
  66137. return context->isVectorDevice();
  66138. }
  66139. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66140. {
  66141. saveStateIfPending();
  66142. return context->clipToRectangle (area);
  66143. }
  66144. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66145. {
  66146. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66147. }
  66148. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66149. {
  66150. saveStateIfPending();
  66151. return context->clipToRectangleList (clipRegion);
  66152. }
  66153. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66154. {
  66155. saveStateIfPending();
  66156. context->clipToPath (path, transform);
  66157. return ! context->isClipEmpty();
  66158. }
  66159. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66160. {
  66161. saveStateIfPending();
  66162. context->clipToImageAlpha (image, transform);
  66163. return ! context->isClipEmpty();
  66164. }
  66165. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66166. {
  66167. saveStateIfPending();
  66168. context->excludeClipRectangle (rectangleToExclude);
  66169. }
  66170. bool Graphics::isClipEmpty() const
  66171. {
  66172. return context->isClipEmpty();
  66173. }
  66174. const Rectangle<int> Graphics::getClipBounds() const
  66175. {
  66176. return context->getClipBounds();
  66177. }
  66178. void Graphics::saveState()
  66179. {
  66180. saveStateIfPending();
  66181. saveStatePending = true;
  66182. }
  66183. void Graphics::restoreState()
  66184. {
  66185. if (saveStatePending)
  66186. saveStatePending = false;
  66187. else
  66188. context->restoreState();
  66189. }
  66190. void Graphics::saveStateIfPending()
  66191. {
  66192. if (saveStatePending)
  66193. {
  66194. saveStatePending = false;
  66195. context->saveState();
  66196. }
  66197. }
  66198. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66199. {
  66200. saveStateIfPending();
  66201. context->setOrigin (newOriginX, newOriginY);
  66202. }
  66203. void Graphics::addTransform (const AffineTransform& transform)
  66204. {
  66205. context->addTransform (transform);
  66206. }
  66207. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66208. {
  66209. return context->clipRegionIntersects (area);
  66210. }
  66211. void Graphics::setColour (const Colour& newColour)
  66212. {
  66213. saveStateIfPending();
  66214. context->setFill (newColour);
  66215. }
  66216. void Graphics::setOpacity (const float newOpacity)
  66217. {
  66218. saveStateIfPending();
  66219. context->setOpacity (newOpacity);
  66220. }
  66221. void Graphics::setGradientFill (const ColourGradient& gradient)
  66222. {
  66223. setFillType (gradient);
  66224. }
  66225. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66226. {
  66227. saveStateIfPending();
  66228. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66229. context->setOpacity (opacity);
  66230. }
  66231. void Graphics::setFillType (const FillType& newFill)
  66232. {
  66233. saveStateIfPending();
  66234. context->setFill (newFill);
  66235. }
  66236. void Graphics::setFont (const Font& newFont)
  66237. {
  66238. saveStateIfPending();
  66239. context->setFont (newFont);
  66240. }
  66241. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66242. {
  66243. saveStateIfPending();
  66244. Font f (context->getFont());
  66245. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66246. context->setFont (f);
  66247. }
  66248. const Font Graphics::getCurrentFont() const
  66249. {
  66250. return context->getFont();
  66251. }
  66252. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66253. {
  66254. if (text.isNotEmpty()
  66255. && startX < context->getClipBounds().getRight())
  66256. {
  66257. GlyphArrangement arr;
  66258. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66259. arr.draw (*this);
  66260. }
  66261. }
  66262. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66263. {
  66264. if (text.isNotEmpty())
  66265. {
  66266. GlyphArrangement arr;
  66267. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66268. arr.draw (*this, transform);
  66269. }
  66270. }
  66271. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66272. {
  66273. if (text.isNotEmpty()
  66274. && startX < context->getClipBounds().getRight())
  66275. {
  66276. GlyphArrangement arr;
  66277. arr.addJustifiedText (context->getFont(), text,
  66278. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66279. Justification::left);
  66280. arr.draw (*this);
  66281. }
  66282. }
  66283. void Graphics::drawText (const String& text,
  66284. const int x, const int y, const int width, const int height,
  66285. const Justification& justificationType,
  66286. const bool useEllipsesIfTooBig) const
  66287. {
  66288. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66289. {
  66290. GlyphArrangement arr;
  66291. arr.addCurtailedLineOfText (context->getFont(), text,
  66292. 0.0f, 0.0f, (float) width,
  66293. useEllipsesIfTooBig);
  66294. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66295. (float) x, (float) y, (float) width, (float) height,
  66296. justificationType);
  66297. arr.draw (*this);
  66298. }
  66299. }
  66300. void Graphics::drawFittedText (const String& text,
  66301. const int x, const int y, const int width, const int height,
  66302. const Justification& justification,
  66303. const int maximumNumberOfLines,
  66304. const float minimumHorizontalScale) const
  66305. {
  66306. if (text.isNotEmpty()
  66307. && width > 0 && height > 0
  66308. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66309. {
  66310. GlyphArrangement arr;
  66311. arr.addFittedText (context->getFont(), text,
  66312. (float) x, (float) y, (float) width, (float) height,
  66313. justification,
  66314. maximumNumberOfLines,
  66315. minimumHorizontalScale);
  66316. arr.draw (*this);
  66317. }
  66318. }
  66319. void Graphics::fillRect (int x, int y, int width, int height) const
  66320. {
  66321. // passing in a silly number can cause maths problems in rendering!
  66322. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66323. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66324. }
  66325. void Graphics::fillRect (const Rectangle<int>& r) const
  66326. {
  66327. context->fillRect (r, false);
  66328. }
  66329. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66330. {
  66331. // passing in a silly number can cause maths problems in rendering!
  66332. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66333. Path p;
  66334. p.addRectangle (x, y, width, height);
  66335. fillPath (p);
  66336. }
  66337. void Graphics::setPixel (int x, int y) const
  66338. {
  66339. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66340. }
  66341. void Graphics::fillAll() const
  66342. {
  66343. fillRect (context->getClipBounds());
  66344. }
  66345. void Graphics::fillAll (const Colour& colourToUse) const
  66346. {
  66347. if (! colourToUse.isTransparent())
  66348. {
  66349. const Rectangle<int> clip (context->getClipBounds());
  66350. context->saveState();
  66351. context->setFill (colourToUse);
  66352. context->fillRect (clip, false);
  66353. context->restoreState();
  66354. }
  66355. }
  66356. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66357. {
  66358. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66359. context->fillPath (path, transform);
  66360. }
  66361. void Graphics::strokePath (const Path& path,
  66362. const PathStrokeType& strokeType,
  66363. const AffineTransform& transform) const
  66364. {
  66365. Path stroke;
  66366. strokeType.createStrokedPath (stroke, path, transform);
  66367. fillPath (stroke);
  66368. }
  66369. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66370. const int lineThickness) const
  66371. {
  66372. // passing in a silly number can cause maths problems in rendering!
  66373. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66374. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66375. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66376. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66377. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66378. }
  66379. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66380. {
  66381. // passing in a silly number can cause maths problems in rendering!
  66382. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66383. Path p;
  66384. p.addRectangle (x, y, width, lineThickness);
  66385. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66386. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66387. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66388. fillPath (p);
  66389. }
  66390. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66391. {
  66392. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66393. }
  66394. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66395. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66396. const bool useGradient, const bool sharpEdgeOnOutside) const
  66397. {
  66398. // passing in a silly number can cause maths problems in rendering!
  66399. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66400. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66401. {
  66402. context->saveState();
  66403. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66404. const float ramp = oldOpacity / bevelThickness;
  66405. for (int i = bevelThickness; --i >= 0;)
  66406. {
  66407. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66408. : oldOpacity;
  66409. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66410. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66411. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66412. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66413. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66414. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66415. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66416. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66417. }
  66418. context->restoreState();
  66419. }
  66420. }
  66421. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66422. {
  66423. // passing in a silly number can cause maths problems in rendering!
  66424. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66425. Path p;
  66426. p.addEllipse (x, y, width, height);
  66427. fillPath (p);
  66428. }
  66429. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66430. const float lineThickness) const
  66431. {
  66432. // passing in a silly number can cause maths problems in rendering!
  66433. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66434. Path p;
  66435. p.addEllipse (x, y, width, height);
  66436. strokePath (p, PathStrokeType (lineThickness));
  66437. }
  66438. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66439. {
  66440. // passing in a silly number can cause maths problems in rendering!
  66441. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66442. Path p;
  66443. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66444. fillPath (p);
  66445. }
  66446. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66447. {
  66448. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66449. }
  66450. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66451. const float cornerSize, const float lineThickness) const
  66452. {
  66453. // passing in a silly number can cause maths problems in rendering!
  66454. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66455. Path p;
  66456. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66457. strokePath (p, PathStrokeType (lineThickness));
  66458. }
  66459. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66460. {
  66461. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66462. }
  66463. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66464. {
  66465. Path p;
  66466. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66467. fillPath (p);
  66468. }
  66469. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66470. const int checkWidth, const int checkHeight,
  66471. const Colour& colour1, const Colour& colour2) const
  66472. {
  66473. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66474. if (checkWidth > 0 && checkHeight > 0)
  66475. {
  66476. context->saveState();
  66477. if (colour1 == colour2)
  66478. {
  66479. context->setFill (colour1);
  66480. context->fillRect (area, false);
  66481. }
  66482. else
  66483. {
  66484. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66485. if (! clipped.isEmpty())
  66486. {
  66487. context->clipToRectangle (clipped);
  66488. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66489. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66490. const int startX = area.getX() + checkNumX * checkWidth;
  66491. const int startY = area.getY() + checkNumY * checkHeight;
  66492. const int right = clipped.getRight();
  66493. const int bottom = clipped.getBottom();
  66494. for (int i = 0; i < 2; ++i)
  66495. {
  66496. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66497. int cy = i;
  66498. for (int y = startY; y < bottom; y += checkHeight)
  66499. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66500. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66501. }
  66502. }
  66503. }
  66504. context->restoreState();
  66505. }
  66506. }
  66507. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66508. {
  66509. context->drawVerticalLine (x, top, bottom);
  66510. }
  66511. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66512. {
  66513. context->drawHorizontalLine (y, left, right);
  66514. }
  66515. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66516. {
  66517. context->drawLine (Line<float> (x1, y1, x2, y2));
  66518. }
  66519. void Graphics::drawLine (const float startX, const float startY,
  66520. const float endX, const float endY,
  66521. const float lineThickness) const
  66522. {
  66523. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66524. }
  66525. void Graphics::drawLine (const Line<float>& line) const
  66526. {
  66527. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66528. }
  66529. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66530. {
  66531. Path p;
  66532. p.addLineSegment (line, lineThickness);
  66533. fillPath (p);
  66534. }
  66535. void Graphics::drawDashedLine (const float startX, const float startY,
  66536. const float endX, const float endY,
  66537. const float* const dashLengths,
  66538. const int numDashLengths,
  66539. const float lineThickness) const
  66540. {
  66541. const double dx = endX - startX;
  66542. const double dy = endY - startY;
  66543. const double totalLen = juce_hypot (dx, dy);
  66544. if (totalLen >= 0.5)
  66545. {
  66546. const double onePixAlpha = 1.0 / totalLen;
  66547. double alpha = 0.0;
  66548. float x = startX;
  66549. float y = startY;
  66550. int n = 0;
  66551. while (alpha < 1.0f)
  66552. {
  66553. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66554. n = n % numDashLengths;
  66555. const float oldX = x;
  66556. const float oldY = y;
  66557. x = (float) (startX + dx * alpha);
  66558. y = (float) (startY + dy * alpha);
  66559. if ((n & 1) != 0)
  66560. {
  66561. if (lineThickness != 1.0f)
  66562. drawLine (oldX, oldY, x, y, lineThickness);
  66563. else
  66564. drawLine (oldX, oldY, x, y);
  66565. }
  66566. }
  66567. }
  66568. }
  66569. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66570. {
  66571. saveStateIfPending();
  66572. context->setInterpolationQuality (newQuality);
  66573. }
  66574. void Graphics::drawImageAt (const Image& imageToDraw,
  66575. const int topLeftX, const int topLeftY,
  66576. const bool fillAlphaChannelWithCurrentBrush) const
  66577. {
  66578. const int imageW = imageToDraw.getWidth();
  66579. const int imageH = imageToDraw.getHeight();
  66580. drawImage (imageToDraw,
  66581. topLeftX, topLeftY, imageW, imageH,
  66582. 0, 0, imageW, imageH,
  66583. fillAlphaChannelWithCurrentBrush);
  66584. }
  66585. void Graphics::drawImageWithin (const Image& imageToDraw,
  66586. const int destX, const int destY,
  66587. const int destW, const int destH,
  66588. const RectanglePlacement& placementWithinTarget,
  66589. const bool fillAlphaChannelWithCurrentBrush) const
  66590. {
  66591. // passing in a silly number can cause maths problems in rendering!
  66592. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66593. if (imageToDraw.isValid())
  66594. {
  66595. const int imageW = imageToDraw.getWidth();
  66596. const int imageH = imageToDraw.getHeight();
  66597. if (imageW > 0 && imageH > 0)
  66598. {
  66599. double newX = 0.0, newY = 0.0;
  66600. double newW = imageW;
  66601. double newH = imageH;
  66602. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66603. destX, destY, destW, destH);
  66604. if (newW > 0 && newH > 0)
  66605. {
  66606. drawImage (imageToDraw,
  66607. roundToInt (newX), roundToInt (newY),
  66608. roundToInt (newW), roundToInt (newH),
  66609. 0, 0, imageW, imageH,
  66610. fillAlphaChannelWithCurrentBrush);
  66611. }
  66612. }
  66613. }
  66614. }
  66615. void Graphics::drawImage (const Image& imageToDraw,
  66616. int dx, int dy, int dw, int dh,
  66617. int sx, int sy, int sw, int sh,
  66618. const bool fillAlphaChannelWithCurrentBrush) const
  66619. {
  66620. // passing in a silly number can cause maths problems in rendering!
  66621. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66622. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66623. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66624. {
  66625. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66626. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66627. .translated ((float) dx, (float) dy),
  66628. fillAlphaChannelWithCurrentBrush);
  66629. }
  66630. }
  66631. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66632. const AffineTransform& transform,
  66633. const bool fillAlphaChannelWithCurrentBrush) const
  66634. {
  66635. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66636. {
  66637. if (fillAlphaChannelWithCurrentBrush)
  66638. {
  66639. context->saveState();
  66640. context->clipToImageAlpha (imageToDraw, transform);
  66641. fillAll();
  66642. context->restoreState();
  66643. }
  66644. else
  66645. {
  66646. context->drawImage (imageToDraw, transform, false);
  66647. }
  66648. }
  66649. }
  66650. END_JUCE_NAMESPACE
  66651. /*** End of inlined file: juce_Graphics.cpp ***/
  66652. /*** Start of inlined file: juce_Justification.cpp ***/
  66653. BEGIN_JUCE_NAMESPACE
  66654. Justification::Justification (const Justification& other) throw()
  66655. : flags (other.flags)
  66656. {
  66657. }
  66658. Justification& Justification::operator= (const Justification& other) throw()
  66659. {
  66660. flags = other.flags;
  66661. return *this;
  66662. }
  66663. int Justification::getOnlyVerticalFlags() const throw()
  66664. {
  66665. return flags & (top | bottom | verticallyCentred);
  66666. }
  66667. int Justification::getOnlyHorizontalFlags() const throw()
  66668. {
  66669. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66670. }
  66671. void Justification::applyToRectangle (int& x, int& y,
  66672. const int w, const int h,
  66673. const int spaceX, const int spaceY,
  66674. const int spaceW, const int spaceH) const throw()
  66675. {
  66676. if ((flags & horizontallyCentred) != 0)
  66677. x = spaceX + ((spaceW - w) >> 1);
  66678. else if ((flags & right) != 0)
  66679. x = spaceX + spaceW - w;
  66680. else
  66681. x = spaceX;
  66682. if ((flags & verticallyCentred) != 0)
  66683. y = spaceY + ((spaceH - h) >> 1);
  66684. else if ((flags & bottom) != 0)
  66685. y = spaceY + spaceH - h;
  66686. else
  66687. y = spaceY;
  66688. }
  66689. END_JUCE_NAMESPACE
  66690. /*** End of inlined file: juce_Justification.cpp ***/
  66691. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66692. BEGIN_JUCE_NAMESPACE
  66693. // this will throw an assertion if you try to draw something that's not
  66694. // possible in postscript
  66695. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66696. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66697. #define notPossibleInPostscriptAssert jassertfalse
  66698. #else
  66699. #define notPossibleInPostscriptAssert
  66700. #endif
  66701. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66702. const String& documentTitle,
  66703. const int totalWidth_,
  66704. const int totalHeight_)
  66705. : out (resultingPostScript),
  66706. totalWidth (totalWidth_),
  66707. totalHeight (totalHeight_),
  66708. needToClip (true)
  66709. {
  66710. stateStack.add (new SavedState());
  66711. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66712. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66713. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66714. "\n%%BoundingBox: 0 0 600 824"
  66715. "\n%%Pages: 0"
  66716. "\n%%Creator: Raw Material Software JUCE"
  66717. "\n%%Title: " << documentTitle <<
  66718. "\n%%CreationDate: none"
  66719. "\n%%LanguageLevel: 2"
  66720. "\n%%EndComments"
  66721. "\n%%BeginProlog"
  66722. "\n%%BeginResource: JRes"
  66723. "\n/bd {bind def} bind def"
  66724. "\n/c {setrgbcolor} bd"
  66725. "\n/m {moveto} bd"
  66726. "\n/l {lineto} bd"
  66727. "\n/rl {rlineto} bd"
  66728. "\n/ct {curveto} bd"
  66729. "\n/cp {closepath} bd"
  66730. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66731. "\n/doclip {initclip newpath} bd"
  66732. "\n/endclip {clip newpath} bd"
  66733. "\n%%EndResource"
  66734. "\n%%EndProlog"
  66735. "\n%%BeginSetup"
  66736. "\n%%EndSetup"
  66737. "\n%%Page: 1 1"
  66738. "\n%%BeginPageSetup"
  66739. "\n%%EndPageSetup\n\n"
  66740. << "40 800 translate\n"
  66741. << scale << ' ' << scale << " scale\n\n";
  66742. }
  66743. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66744. {
  66745. }
  66746. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66747. {
  66748. return true;
  66749. }
  66750. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66751. {
  66752. if (x != 0 || y != 0)
  66753. {
  66754. stateStack.getLast()->xOffset += x;
  66755. stateStack.getLast()->yOffset += y;
  66756. needToClip = true;
  66757. }
  66758. }
  66759. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  66760. {
  66761. //xxx
  66762. jassertfalse;
  66763. }
  66764. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66765. {
  66766. needToClip = true;
  66767. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66768. }
  66769. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66770. {
  66771. needToClip = true;
  66772. return stateStack.getLast()->clip.clipTo (clipRegion);
  66773. }
  66774. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66775. {
  66776. needToClip = true;
  66777. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66778. }
  66779. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66780. {
  66781. writeClip();
  66782. Path p (path);
  66783. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66784. writePath (p);
  66785. out << "clip\n";
  66786. }
  66787. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66788. {
  66789. needToClip = true;
  66790. jassertfalse; // xxx
  66791. }
  66792. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66793. {
  66794. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66795. }
  66796. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66797. {
  66798. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66799. -stateStack.getLast()->yOffset);
  66800. }
  66801. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66802. {
  66803. return stateStack.getLast()->clip.isEmpty();
  66804. }
  66805. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66806. : xOffset (0),
  66807. yOffset (0)
  66808. {
  66809. }
  66810. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  66811. {
  66812. }
  66813. void LowLevelGraphicsPostScriptRenderer::saveState()
  66814. {
  66815. stateStack.add (new SavedState (*stateStack.getLast()));
  66816. }
  66817. void LowLevelGraphicsPostScriptRenderer::restoreState()
  66818. {
  66819. jassert (stateStack.size() > 0);
  66820. if (stateStack.size() > 0)
  66821. stateStack.removeLast();
  66822. }
  66823. void LowLevelGraphicsPostScriptRenderer::writeClip()
  66824. {
  66825. if (needToClip)
  66826. {
  66827. needToClip = false;
  66828. out << "doclip ";
  66829. int itemsOnLine = 0;
  66830. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  66831. {
  66832. if (++itemsOnLine == 6)
  66833. {
  66834. itemsOnLine = 0;
  66835. out << '\n';
  66836. }
  66837. const Rectangle<int>& r = *i.getRectangle();
  66838. out << r.getX() << ' ' << -r.getY() << ' '
  66839. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  66840. }
  66841. out << "endclip\n";
  66842. }
  66843. }
  66844. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  66845. {
  66846. Colour c (Colours::white.overlaidWith (colour));
  66847. if (lastColour != c)
  66848. {
  66849. lastColour = c;
  66850. out << String (c.getFloatRed(), 3) << ' '
  66851. << String (c.getFloatGreen(), 3) << ' '
  66852. << String (c.getFloatBlue(), 3) << " c\n";
  66853. }
  66854. }
  66855. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  66856. {
  66857. out << String (x, 2) << ' '
  66858. << String (-y, 2) << ' ';
  66859. }
  66860. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  66861. {
  66862. out << "newpath ";
  66863. float lastX = 0.0f;
  66864. float lastY = 0.0f;
  66865. int itemsOnLine = 0;
  66866. Path::Iterator i (path);
  66867. while (i.next())
  66868. {
  66869. if (++itemsOnLine == 4)
  66870. {
  66871. itemsOnLine = 0;
  66872. out << '\n';
  66873. }
  66874. switch (i.elementType)
  66875. {
  66876. case Path::Iterator::startNewSubPath:
  66877. writeXY (i.x1, i.y1);
  66878. lastX = i.x1;
  66879. lastY = i.y1;
  66880. out << "m ";
  66881. break;
  66882. case Path::Iterator::lineTo:
  66883. writeXY (i.x1, i.y1);
  66884. lastX = i.x1;
  66885. lastY = i.y1;
  66886. out << "l ";
  66887. break;
  66888. case Path::Iterator::quadraticTo:
  66889. {
  66890. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  66891. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  66892. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  66893. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  66894. writeXY (cp1x, cp1y);
  66895. writeXY (cp2x, cp2y);
  66896. writeXY (i.x2, i.y2);
  66897. out << "ct ";
  66898. lastX = i.x2;
  66899. lastY = i.y2;
  66900. }
  66901. break;
  66902. case Path::Iterator::cubicTo:
  66903. writeXY (i.x1, i.y1);
  66904. writeXY (i.x2, i.y2);
  66905. writeXY (i.x3, i.y3);
  66906. out << "ct ";
  66907. lastX = i.x3;
  66908. lastY = i.y3;
  66909. break;
  66910. case Path::Iterator::closePath:
  66911. out << "cp ";
  66912. break;
  66913. default:
  66914. jassertfalse;
  66915. break;
  66916. }
  66917. }
  66918. out << '\n';
  66919. }
  66920. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  66921. {
  66922. out << "[ "
  66923. << trans.mat00 << ' '
  66924. << trans.mat10 << ' '
  66925. << trans.mat01 << ' '
  66926. << trans.mat11 << ' '
  66927. << trans.mat02 << ' '
  66928. << trans.mat12 << " ] concat ";
  66929. }
  66930. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  66931. {
  66932. stateStack.getLast()->fillType = fillType;
  66933. }
  66934. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  66935. {
  66936. }
  66937. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  66938. {
  66939. }
  66940. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  66941. {
  66942. if (stateStack.getLast()->fillType.isColour())
  66943. {
  66944. writeClip();
  66945. writeColour (stateStack.getLast()->fillType.colour);
  66946. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66947. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  66948. }
  66949. else
  66950. {
  66951. Path p;
  66952. p.addRectangle (r);
  66953. fillPath (p, AffineTransform::identity);
  66954. }
  66955. }
  66956. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  66957. {
  66958. if (stateStack.getLast()->fillType.isColour())
  66959. {
  66960. writeClip();
  66961. Path p (path);
  66962. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  66963. (float) stateStack.getLast()->yOffset));
  66964. writePath (p);
  66965. writeColour (stateStack.getLast()->fillType.colour);
  66966. out << "fill\n";
  66967. }
  66968. else if (stateStack.getLast()->fillType.isGradient())
  66969. {
  66970. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  66971. // postscript can't do semi-transparent ones.
  66972. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  66973. writeClip();
  66974. out << "gsave ";
  66975. {
  66976. Path p (path);
  66977. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66978. writePath (p);
  66979. out << "clip\n";
  66980. }
  66981. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  66982. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  66983. // time-being, this just fills it with the average colour..
  66984. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  66985. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  66986. out << "grestore\n";
  66987. }
  66988. }
  66989. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  66990. const int sx, const int sy,
  66991. const int maxW, const int maxH) const
  66992. {
  66993. out << "{<\n";
  66994. const int w = jmin (maxW, im.getWidth());
  66995. const int h = jmin (maxH, im.getHeight());
  66996. int charsOnLine = 0;
  66997. const Image::BitmapData srcData (im, 0, 0, w, h);
  66998. Colour pixel;
  66999. for (int y = h; --y >= 0;)
  67000. {
  67001. for (int x = 0; x < w; ++x)
  67002. {
  67003. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67004. if (x >= sx && y >= sy)
  67005. {
  67006. if (im.isARGB())
  67007. {
  67008. PixelARGB p (*(const PixelARGB*) pixelData);
  67009. p.unpremultiply();
  67010. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67011. }
  67012. else if (im.isRGB())
  67013. {
  67014. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67015. }
  67016. else
  67017. {
  67018. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67019. }
  67020. }
  67021. else
  67022. {
  67023. pixel = Colours::transparentWhite;
  67024. }
  67025. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67026. out << String::toHexString (pixelValues, 3, 0);
  67027. charsOnLine += 3;
  67028. if (charsOnLine > 100)
  67029. {
  67030. out << '\n';
  67031. charsOnLine = 0;
  67032. }
  67033. }
  67034. }
  67035. out << "\n>}\n";
  67036. }
  67037. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67038. {
  67039. const int w = sourceImage.getWidth();
  67040. const int h = sourceImage.getHeight();
  67041. writeClip();
  67042. out << "gsave ";
  67043. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67044. .scaled (1.0f, -1.0f));
  67045. RectangleList imageClip;
  67046. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67047. out << "newpath ";
  67048. int itemsOnLine = 0;
  67049. for (RectangleList::Iterator i (imageClip); i.next();)
  67050. {
  67051. if (++itemsOnLine == 6)
  67052. {
  67053. out << '\n';
  67054. itemsOnLine = 0;
  67055. }
  67056. const Rectangle<int>& r = *i.getRectangle();
  67057. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67058. }
  67059. out << " clip newpath\n";
  67060. out << w << ' ' << h << " scale\n";
  67061. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67062. writeImage (sourceImage, 0, 0, w, h);
  67063. out << "false 3 colorimage grestore\n";
  67064. needToClip = true;
  67065. }
  67066. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67067. {
  67068. Path p;
  67069. p.addLineSegment (line, 1.0f);
  67070. fillPath (p, AffineTransform::identity);
  67071. }
  67072. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67073. {
  67074. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67075. }
  67076. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67077. {
  67078. drawLine (Line<float> (left, (float) y, right, (float) y));
  67079. }
  67080. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67081. {
  67082. stateStack.getLast()->font = newFont;
  67083. }
  67084. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67085. {
  67086. return stateStack.getLast()->font;
  67087. }
  67088. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67089. {
  67090. Path p;
  67091. Font& font = stateStack.getLast()->font;
  67092. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67093. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67094. }
  67095. END_JUCE_NAMESPACE
  67096. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67097. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67098. BEGIN_JUCE_NAMESPACE
  67099. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67100. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67101. #endif
  67102. #if JUCE_MSVC
  67103. #pragma warning (push)
  67104. #pragma warning (disable: 4127) // "expression is constant" warning
  67105. #if JUCE_DEBUG
  67106. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67107. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67108. #endif
  67109. #endif
  67110. namespace SoftwareRendererClasses
  67111. {
  67112. template <class PixelType, bool replaceExisting = false>
  67113. class SolidColourEdgeTableRenderer
  67114. {
  67115. public:
  67116. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67117. : data (data_),
  67118. sourceColour (colour)
  67119. {
  67120. if (sizeof (PixelType) == 3)
  67121. {
  67122. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67123. && sourceColour.getGreen() == sourceColour.getBlue();
  67124. filler[0].set (sourceColour);
  67125. filler[1].set (sourceColour);
  67126. filler[2].set (sourceColour);
  67127. filler[3].set (sourceColour);
  67128. }
  67129. }
  67130. forcedinline void setEdgeTableYPos (const int y) throw()
  67131. {
  67132. linePixels = (PixelType*) data.getLinePointer (y);
  67133. }
  67134. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67135. {
  67136. if (replaceExisting)
  67137. linePixels[x].set (sourceColour);
  67138. else
  67139. linePixels[x].blend (sourceColour, alphaLevel);
  67140. }
  67141. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67142. {
  67143. if (replaceExisting)
  67144. linePixels[x].set (sourceColour);
  67145. else
  67146. linePixels[x].blend (sourceColour);
  67147. }
  67148. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67149. {
  67150. PixelARGB p (sourceColour);
  67151. p.multiplyAlpha (alphaLevel);
  67152. PixelType* dest = linePixels + x;
  67153. if (replaceExisting || p.getAlpha() >= 0xff)
  67154. replaceLine (dest, p, width);
  67155. else
  67156. blendLine (dest, p, width);
  67157. }
  67158. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67159. {
  67160. PixelType* dest = linePixels + x;
  67161. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67162. replaceLine (dest, sourceColour, width);
  67163. else
  67164. blendLine (dest, sourceColour, width);
  67165. }
  67166. private:
  67167. const Image::BitmapData& data;
  67168. PixelType* linePixels;
  67169. PixelARGB sourceColour;
  67170. PixelRGB filler [4];
  67171. bool areRGBComponentsEqual;
  67172. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67173. {
  67174. do
  67175. {
  67176. dest->blend (colour);
  67177. ++dest;
  67178. } while (--width > 0);
  67179. }
  67180. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67181. {
  67182. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67183. {
  67184. memset (dest, colour.getRed(), width * 3);
  67185. }
  67186. else
  67187. {
  67188. if (width >> 5)
  67189. {
  67190. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67191. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67192. {
  67193. dest->set (colour);
  67194. ++dest;
  67195. --width;
  67196. }
  67197. while (width > 4)
  67198. {
  67199. int* d = reinterpret_cast<int*> (dest);
  67200. *d++ = intFiller[0];
  67201. *d++ = intFiller[1];
  67202. *d++ = intFiller[2];
  67203. dest = reinterpret_cast<PixelRGB*> (d);
  67204. width -= 4;
  67205. }
  67206. }
  67207. while (--width >= 0)
  67208. {
  67209. dest->set (colour);
  67210. ++dest;
  67211. }
  67212. }
  67213. }
  67214. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67215. {
  67216. memset (dest, colour.getAlpha(), width);
  67217. }
  67218. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67219. {
  67220. do
  67221. {
  67222. dest->set (colour);
  67223. ++dest;
  67224. } while (--width > 0);
  67225. }
  67226. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67227. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67228. };
  67229. class LinearGradientPixelGenerator
  67230. {
  67231. public:
  67232. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67233. : lookupTable (lookupTable_), numEntries (numEntries_)
  67234. {
  67235. jassert (numEntries_ >= 0);
  67236. Point<float> p1 (gradient.point1);
  67237. Point<float> p2 (gradient.point2);
  67238. if (! transform.isIdentity())
  67239. {
  67240. const Line<float> l (p2, p1);
  67241. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67242. p1.applyTransform (transform);
  67243. p2.applyTransform (transform);
  67244. p3.applyTransform (transform);
  67245. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67246. }
  67247. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67248. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67249. if (vertical)
  67250. {
  67251. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67252. start = roundToInt (p1.getY() * scale);
  67253. }
  67254. else if (horizontal)
  67255. {
  67256. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67257. start = roundToInt (p1.getX() * scale);
  67258. }
  67259. else
  67260. {
  67261. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67262. yTerm = p1.getY() - p1.getX() / grad;
  67263. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67264. grad *= scale;
  67265. }
  67266. }
  67267. forcedinline void setY (const int y) throw()
  67268. {
  67269. if (vertical)
  67270. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67271. else if (! horizontal)
  67272. start = roundToInt ((y - yTerm) * grad);
  67273. }
  67274. inline const PixelARGB getPixel (const int x) const throw()
  67275. {
  67276. return vertical ? linePix
  67277. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67278. }
  67279. private:
  67280. const PixelARGB* const lookupTable;
  67281. const int numEntries;
  67282. PixelARGB linePix;
  67283. int start, scale;
  67284. double grad, yTerm;
  67285. bool vertical, horizontal;
  67286. enum { numScaleBits = 12 };
  67287. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67288. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67289. };
  67290. class RadialGradientPixelGenerator
  67291. {
  67292. public:
  67293. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67294. const PixelARGB* const lookupTable_, const int numEntries_)
  67295. : lookupTable (lookupTable_),
  67296. numEntries (numEntries_),
  67297. gx1 (gradient.point1.getX()),
  67298. gy1 (gradient.point1.getY())
  67299. {
  67300. jassert (numEntries_ >= 0);
  67301. const Point<float> diff (gradient.point1 - gradient.point2);
  67302. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67303. invScale = numEntries / std::sqrt (maxDist);
  67304. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67305. }
  67306. forcedinline void setY (const int y) throw()
  67307. {
  67308. dy = y - gy1;
  67309. dy *= dy;
  67310. }
  67311. inline const PixelARGB getPixel (const int px) const throw()
  67312. {
  67313. double x = px - gx1;
  67314. x *= x;
  67315. x += dy;
  67316. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67317. }
  67318. protected:
  67319. const PixelARGB* const lookupTable;
  67320. const int numEntries;
  67321. const double gx1, gy1;
  67322. double maxDist, invScale, dy;
  67323. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67324. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67325. };
  67326. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67327. {
  67328. public:
  67329. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67330. const PixelARGB* const lookupTable_, const int numEntries_)
  67331. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67332. inverseTransform (transform.inverted())
  67333. {
  67334. tM10 = inverseTransform.mat10;
  67335. tM00 = inverseTransform.mat00;
  67336. }
  67337. forcedinline void setY (const int y) throw()
  67338. {
  67339. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67340. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67341. }
  67342. inline const PixelARGB getPixel (const int px) const throw()
  67343. {
  67344. double x = px;
  67345. const double y = tM10 * x + lineYM11;
  67346. x = tM00 * x + lineYM01;
  67347. x *= x;
  67348. x += y * y;
  67349. if (x >= maxDist)
  67350. return lookupTable [numEntries];
  67351. else
  67352. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67353. }
  67354. private:
  67355. double tM10, tM00, lineYM01, lineYM11;
  67356. const AffineTransform inverseTransform;
  67357. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67358. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67359. };
  67360. template <class PixelType, class GradientType>
  67361. class GradientEdgeTableRenderer : public GradientType
  67362. {
  67363. public:
  67364. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67365. const PixelARGB* const lookupTable_, const int numEntries_)
  67366. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67367. destData (destData_)
  67368. {
  67369. }
  67370. forcedinline void setEdgeTableYPos (const int y) throw()
  67371. {
  67372. linePixels = (PixelType*) destData.getLinePointer (y);
  67373. GradientType::setY (y);
  67374. }
  67375. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67376. {
  67377. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67378. }
  67379. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67380. {
  67381. linePixels[x].blend (GradientType::getPixel (x));
  67382. }
  67383. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67384. {
  67385. PixelType* dest = linePixels + x;
  67386. if (alphaLevel < 0xff)
  67387. {
  67388. do
  67389. {
  67390. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67391. } while (--width > 0);
  67392. }
  67393. else
  67394. {
  67395. do
  67396. {
  67397. (dest++)->blend (GradientType::getPixel (x++));
  67398. } while (--width > 0);
  67399. }
  67400. }
  67401. void handleEdgeTableLineFull (int x, int width) const throw()
  67402. {
  67403. PixelType* dest = linePixels + x;
  67404. do
  67405. {
  67406. (dest++)->blend (GradientType::getPixel (x++));
  67407. } while (--width > 0);
  67408. }
  67409. private:
  67410. const Image::BitmapData& destData;
  67411. PixelType* linePixels;
  67412. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67413. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67414. };
  67415. namespace RenderingHelpers
  67416. {
  67417. forcedinline int safeModulo (int n, const int divisor) throw()
  67418. {
  67419. jassert (divisor > 0);
  67420. n %= divisor;
  67421. return (n < 0) ? (n + divisor) : n;
  67422. }
  67423. }
  67424. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67425. class ImageFillEdgeTableRenderer
  67426. {
  67427. public:
  67428. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67429. const Image::BitmapData& srcData_,
  67430. const int extraAlpha_,
  67431. const int x, const int y)
  67432. : destData (destData_),
  67433. srcData (srcData_),
  67434. extraAlpha (extraAlpha_ + 1),
  67435. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67436. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67437. {
  67438. }
  67439. forcedinline void setEdgeTableYPos (int y) throw()
  67440. {
  67441. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67442. y -= yOffset;
  67443. if (repeatPattern)
  67444. {
  67445. jassert (y >= 0);
  67446. y %= srcData.height;
  67447. }
  67448. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67449. }
  67450. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67451. {
  67452. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67453. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67454. }
  67455. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67456. {
  67457. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67458. }
  67459. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67460. {
  67461. DestPixelType* dest = linePixels + x;
  67462. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67463. x -= xOffset;
  67464. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67465. if (alphaLevel < 0xfe)
  67466. {
  67467. do
  67468. {
  67469. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67470. } while (--width > 0);
  67471. }
  67472. else
  67473. {
  67474. if (repeatPattern)
  67475. {
  67476. do
  67477. {
  67478. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67479. } while (--width > 0);
  67480. }
  67481. else
  67482. {
  67483. copyRow (dest, sourceLineStart + x, width);
  67484. }
  67485. }
  67486. }
  67487. void handleEdgeTableLineFull (int x, int width) const throw()
  67488. {
  67489. DestPixelType* dest = linePixels + x;
  67490. x -= xOffset;
  67491. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67492. if (extraAlpha < 0xfe)
  67493. {
  67494. do
  67495. {
  67496. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67497. } while (--width > 0);
  67498. }
  67499. else
  67500. {
  67501. if (repeatPattern)
  67502. {
  67503. do
  67504. {
  67505. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67506. } while (--width > 0);
  67507. }
  67508. else
  67509. {
  67510. copyRow (dest, sourceLineStart + x, width);
  67511. }
  67512. }
  67513. }
  67514. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67515. {
  67516. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67517. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67518. uint8* mask = (uint8*) (s + x - xOffset);
  67519. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67520. mask += PixelARGB::indexA;
  67521. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67522. }
  67523. private:
  67524. const Image::BitmapData& destData;
  67525. const Image::BitmapData& srcData;
  67526. const int extraAlpha, xOffset, yOffset;
  67527. DestPixelType* linePixels;
  67528. SrcPixelType* sourceLineStart;
  67529. template <class PixelType1, class PixelType2>
  67530. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67531. {
  67532. do
  67533. {
  67534. dest++ ->blend (*src++);
  67535. } while (--width > 0);
  67536. }
  67537. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67538. {
  67539. memcpy (dest, src, width * sizeof (PixelRGB));
  67540. }
  67541. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67542. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67543. };
  67544. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67545. class TransformedImageFillEdgeTableRenderer
  67546. {
  67547. public:
  67548. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67549. const Image::BitmapData& srcData_,
  67550. const AffineTransform& transform,
  67551. const int extraAlpha_,
  67552. const bool betterQuality_)
  67553. : interpolator (transform,
  67554. betterQuality_ ? 0.5f : 0.0f,
  67555. betterQuality_ ? -128 : 0),
  67556. destData (destData_),
  67557. srcData (srcData_),
  67558. extraAlpha (extraAlpha_ + 1),
  67559. betterQuality (betterQuality_),
  67560. maxX (srcData_.width - 1),
  67561. maxY (srcData_.height - 1),
  67562. scratchSize (2048)
  67563. {
  67564. scratchBuffer.malloc (scratchSize);
  67565. }
  67566. forcedinline void setEdgeTableYPos (const int newY) throw()
  67567. {
  67568. y = newY;
  67569. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67570. }
  67571. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  67572. {
  67573. SrcPixelType p;
  67574. generate (&p, x, 1);
  67575. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  67576. }
  67577. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67578. {
  67579. SrcPixelType p;
  67580. generate (&p, x, 1);
  67581. linePixels[x].blend (p, extraAlpha);
  67582. }
  67583. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67584. {
  67585. if (width > scratchSize)
  67586. {
  67587. scratchSize = width;
  67588. scratchBuffer.malloc (scratchSize);
  67589. }
  67590. SrcPixelType* span = scratchBuffer;
  67591. generate (span, x, width);
  67592. DestPixelType* dest = linePixels + x;
  67593. alphaLevel *= extraAlpha;
  67594. alphaLevel >>= 8;
  67595. if (alphaLevel < 0xfe)
  67596. {
  67597. do
  67598. {
  67599. dest++ ->blend (*span++, alphaLevel);
  67600. } while (--width > 0);
  67601. }
  67602. else
  67603. {
  67604. do
  67605. {
  67606. dest++ ->blend (*span++);
  67607. } while (--width > 0);
  67608. }
  67609. }
  67610. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67611. {
  67612. handleEdgeTableLine (x, width, 255);
  67613. }
  67614. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67615. {
  67616. if (width > scratchSize)
  67617. {
  67618. scratchSize = width;
  67619. scratchBuffer.malloc (scratchSize);
  67620. }
  67621. y = y_;
  67622. generate (static_cast <SrcPixelType*> (scratchBuffer), x, width);
  67623. et.clipLineToMask (x, y_,
  67624. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67625. sizeof (SrcPixelType), width);
  67626. }
  67627. private:
  67628. template <class PixelType>
  67629. void generate (PixelType* dest, const int x, int numPixels) throw()
  67630. {
  67631. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  67632. do
  67633. {
  67634. int hiResX, hiResY;
  67635. this->interpolator.next (hiResX, hiResY);
  67636. int loResX = hiResX >> 8;
  67637. int loResY = hiResY >> 8;
  67638. if (repeatPattern)
  67639. {
  67640. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  67641. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  67642. }
  67643. if (betterQuality)
  67644. {
  67645. if (((unsigned int) loResX) < (unsigned int) maxX)
  67646. {
  67647. if (((unsigned int) loResY) < (unsigned int) maxY)
  67648. {
  67649. // In the centre of the image..
  67650. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  67651. hiResX & 255, hiResY & 255);
  67652. ++dest;
  67653. continue;
  67654. }
  67655. else
  67656. {
  67657. // At a top or bottom edge..
  67658. if (! repeatPattern)
  67659. {
  67660. if (loResY < 0)
  67661. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255, hiResY & 255);
  67662. else
  67663. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255, 255 - (hiResY & 255));
  67664. ++dest;
  67665. continue;
  67666. }
  67667. }
  67668. }
  67669. else
  67670. {
  67671. if (((unsigned int) loResY) < (unsigned int) maxY)
  67672. {
  67673. // At a left or right hand edge..
  67674. if (! repeatPattern)
  67675. {
  67676. if (loResX < 0)
  67677. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255, hiResX & 255);
  67678. else
  67679. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255, 255 - (hiResX & 255));
  67680. ++dest;
  67681. continue;
  67682. }
  67683. }
  67684. }
  67685. }
  67686. if (! repeatPattern)
  67687. {
  67688. if (loResX < 0) loResX = 0;
  67689. if (loResY < 0) loResY = 0;
  67690. if (loResX > maxX) loResX = maxX;
  67691. if (loResY > maxY) loResY = maxY;
  67692. }
  67693. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  67694. ++dest;
  67695. } while (--numPixels > 0);
  67696. }
  67697. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67698. {
  67699. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67700. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67701. c[0] += weight * src[0];
  67702. c[1] += weight * src[1];
  67703. c[2] += weight * src[2];
  67704. c[3] += weight * src[3];
  67705. weight = subPixelX * (256 - subPixelY);
  67706. c[0] += weight * src[4];
  67707. c[1] += weight * src[5];
  67708. c[2] += weight * src[6];
  67709. c[3] += weight * src[7];
  67710. src += this->srcData.lineStride;
  67711. weight = (256 - subPixelX) * subPixelY;
  67712. c[0] += weight * src[0];
  67713. c[1] += weight * src[1];
  67714. c[2] += weight * src[2];
  67715. c[3] += weight * src[3];
  67716. weight = subPixelX * subPixelY;
  67717. c[0] += weight * src[4];
  67718. c[1] += weight * src[5];
  67719. c[2] += weight * src[6];
  67720. c[3] += weight * src[7];
  67721. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67722. (uint8) (c[PixelARGB::indexR] >> 16),
  67723. (uint8) (c[PixelARGB::indexG] >> 16),
  67724. (uint8) (c[PixelARGB::indexB] >> 16));
  67725. }
  67726. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67727. {
  67728. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67729. uint32 weight = (256 - subPixelX) * alpha;
  67730. c[0] += weight * src[0];
  67731. c[1] += weight * src[1];
  67732. c[2] += weight * src[2];
  67733. c[3] += weight * src[3];
  67734. weight = subPixelX * alpha;
  67735. c[0] += weight * src[4];
  67736. c[1] += weight * src[5];
  67737. c[2] += weight * src[6];
  67738. c[3] += weight * src[7];
  67739. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67740. (uint8) (c[PixelARGB::indexR] >> 16),
  67741. (uint8) (c[PixelARGB::indexG] >> 16),
  67742. (uint8) (c[PixelARGB::indexB] >> 16));
  67743. }
  67744. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67745. {
  67746. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67747. uint32 weight = (256 - subPixelY) * alpha;
  67748. c[0] += weight * src[0];
  67749. c[1] += weight * src[1];
  67750. c[2] += weight * src[2];
  67751. c[3] += weight * src[3];
  67752. src += this->srcData.lineStride;
  67753. weight = subPixelY * alpha;
  67754. c[0] += weight * src[0];
  67755. c[1] += weight * src[1];
  67756. c[2] += weight * src[2];
  67757. c[3] += weight * src[3];
  67758. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67759. (uint8) (c[PixelARGB::indexR] >> 16),
  67760. (uint8) (c[PixelARGB::indexG] >> 16),
  67761. (uint8) (c[PixelARGB::indexB] >> 16));
  67762. }
  67763. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67764. {
  67765. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67766. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67767. c[0] += weight * src[0];
  67768. c[1] += weight * src[1];
  67769. c[2] += weight * src[2];
  67770. weight = subPixelX * (256 - subPixelY);
  67771. c[0] += weight * src[3];
  67772. c[1] += weight * src[4];
  67773. c[2] += weight * src[5];
  67774. src += this->srcData.lineStride;
  67775. weight = (256 - subPixelX) * subPixelY;
  67776. c[0] += weight * src[0];
  67777. c[1] += weight * src[1];
  67778. c[2] += weight * src[2];
  67779. weight = subPixelX * subPixelY;
  67780. c[0] += weight * src[3];
  67781. c[1] += weight * src[4];
  67782. c[2] += weight * src[5];
  67783. dest->setARGB ((uint8) 255,
  67784. (uint8) (c[PixelRGB::indexR] >> 16),
  67785. (uint8) (c[PixelRGB::indexG] >> 16),
  67786. (uint8) (c[PixelRGB::indexB] >> 16));
  67787. }
  67788. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX, const int /*alpha*/) throw()
  67789. {
  67790. uint32 c[3] = { 128, 128, 128 };
  67791. uint32 weight = (256 - subPixelX);
  67792. c[0] += weight * src[0];
  67793. c[1] += weight * src[1];
  67794. c[2] += weight * src[2];
  67795. c[0] += subPixelX * src[3];
  67796. c[1] += subPixelX * src[4];
  67797. c[2] += subPixelX * src[5];
  67798. dest->setARGB ((uint8) 255,
  67799. (uint8) (c[PixelRGB::indexR] >> 8),
  67800. (uint8) (c[PixelRGB::indexG] >> 8),
  67801. (uint8) (c[PixelRGB::indexB] >> 8));
  67802. }
  67803. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY, const int /*alpha*/) throw()
  67804. {
  67805. uint32 c[3] = { 128, 128, 128 };
  67806. uint32 weight = (256 - subPixelY);
  67807. c[0] += weight * src[0];
  67808. c[1] += weight * src[1];
  67809. c[2] += weight * src[2];
  67810. src += this->srcData.lineStride;
  67811. c[0] += subPixelY * src[0];
  67812. c[1] += subPixelY * src[1];
  67813. c[2] += subPixelY * src[2];
  67814. dest->setARGB ((uint8) 255,
  67815. (uint8) (c[PixelRGB::indexR] >> 8),
  67816. (uint8) (c[PixelRGB::indexG] >> 8),
  67817. (uint8) (c[PixelRGB::indexB] >> 8));
  67818. }
  67819. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67820. {
  67821. uint32 c = 256 * 128;
  67822. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  67823. c += src[1] * (subPixelX * (256 - subPixelY));
  67824. src += this->srcData.lineStride;
  67825. c += src[0] * ((256 - subPixelX) * subPixelY);
  67826. c += src[1] * (subPixelX * subPixelY);
  67827. *((uint8*) dest) = (uint8) (c >> 16);
  67828. }
  67829. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67830. {
  67831. uint32 c = 256 * 128;
  67832. c += src[0] * (256 - subPixelX) * alpha;
  67833. c += src[1] * subPixelX * alpha;
  67834. *((uint8*) dest) = (uint8) (c >> 16);
  67835. }
  67836. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67837. {
  67838. uint32 c = 256 * 128;
  67839. c += src[0] * (256 - subPixelY) * alpha;
  67840. src += this->srcData.lineStride;
  67841. c += src[0] * subPixelY * alpha;
  67842. *((uint8*) dest) = (uint8) (c >> 16);
  67843. }
  67844. class TransformedImageSpanInterpolator
  67845. {
  67846. public:
  67847. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  67848. : inverseTransform (transform.inverted()),
  67849. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  67850. {}
  67851. void setStartOfLine (float x, float y, const int numPixels) throw()
  67852. {
  67853. jassert (numPixels > 0);
  67854. x += pixelOffset;
  67855. y += pixelOffset;
  67856. float x1 = x, y1 = y;
  67857. x += numPixels;
  67858. inverseTransform.transformPoints (x1, y1, x, y);
  67859. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  67860. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  67861. }
  67862. void next (int& x, int& y) throw()
  67863. {
  67864. x = xBresenham.n;
  67865. xBresenham.stepToNext();
  67866. y = yBresenham.n;
  67867. yBresenham.stepToNext();
  67868. }
  67869. private:
  67870. class BresenhamInterpolator
  67871. {
  67872. public:
  67873. BresenhamInterpolator() throw() {}
  67874. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  67875. {
  67876. numSteps = numSteps_;
  67877. step = (n2 - n1) / numSteps;
  67878. remainder = modulo = (n2 - n1) % numSteps;
  67879. n = n1 + pixelOffsetInt;
  67880. if (modulo <= 0)
  67881. {
  67882. modulo += numSteps;
  67883. remainder += numSteps;
  67884. --step;
  67885. }
  67886. modulo -= numSteps;
  67887. }
  67888. forcedinline void stepToNext() throw()
  67889. {
  67890. modulo += remainder;
  67891. n += step;
  67892. if (modulo > 0)
  67893. {
  67894. modulo -= numSteps;
  67895. ++n;
  67896. }
  67897. }
  67898. int n;
  67899. private:
  67900. int numSteps, step, modulo, remainder;
  67901. };
  67902. const AffineTransform inverseTransform;
  67903. BresenhamInterpolator xBresenham, yBresenham;
  67904. const float pixelOffset;
  67905. const int pixelOffsetInt;
  67906. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  67907. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  67908. };
  67909. TransformedImageSpanInterpolator interpolator;
  67910. const Image::BitmapData& destData;
  67911. const Image::BitmapData& srcData;
  67912. const int extraAlpha;
  67913. const bool betterQuality;
  67914. const int maxX, maxY;
  67915. int y;
  67916. DestPixelType* linePixels;
  67917. HeapBlock <SrcPixelType> scratchBuffer;
  67918. int scratchSize;
  67919. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  67920. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  67921. };
  67922. class ClipRegionBase : public ReferenceCountedObject
  67923. {
  67924. public:
  67925. ClipRegionBase() {}
  67926. virtual ~ClipRegionBase() {}
  67927. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  67928. virtual const Ptr clone() const = 0;
  67929. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  67930. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  67931. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  67932. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  67933. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  67934. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  67935. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  67936. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  67937. virtual const Rectangle<int> getClipBounds() const = 0;
  67938. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  67939. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  67940. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  67941. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  67942. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  67943. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  67944. protected:
  67945. template <class Iterator>
  67946. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  67947. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  67948. {
  67949. switch (destData.pixelFormat)
  67950. {
  67951. case Image::ARGB:
  67952. switch (srcData.pixelFormat)
  67953. {
  67954. case Image::ARGB:
  67955. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67956. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67957. break;
  67958. case Image::RGB:
  67959. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67960. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67961. break;
  67962. default:
  67963. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67964. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67965. break;
  67966. }
  67967. break;
  67968. case Image::RGB:
  67969. switch (srcData.pixelFormat)
  67970. {
  67971. case Image::ARGB:
  67972. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67973. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67974. break;
  67975. case Image::RGB:
  67976. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67977. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67978. break;
  67979. default:
  67980. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67981. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67982. break;
  67983. }
  67984. break;
  67985. default:
  67986. switch (srcData.pixelFormat)
  67987. {
  67988. case Image::ARGB:
  67989. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67990. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67991. break;
  67992. case Image::RGB:
  67993. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67994. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67995. break;
  67996. default:
  67997. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67998. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  67999. break;
  68000. }
  68001. break;
  68002. }
  68003. }
  68004. template <class Iterator>
  68005. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68006. {
  68007. switch (destData.pixelFormat)
  68008. {
  68009. case Image::ARGB:
  68010. switch (srcData.pixelFormat)
  68011. {
  68012. case Image::ARGB:
  68013. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68014. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68015. break;
  68016. case Image::RGB:
  68017. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68018. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68019. break;
  68020. default:
  68021. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68022. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68023. break;
  68024. }
  68025. break;
  68026. case Image::RGB:
  68027. switch (srcData.pixelFormat)
  68028. {
  68029. case Image::ARGB:
  68030. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68031. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68032. break;
  68033. case Image::RGB:
  68034. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68035. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68036. break;
  68037. default:
  68038. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68039. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68040. break;
  68041. }
  68042. break;
  68043. default:
  68044. switch (srcData.pixelFormat)
  68045. {
  68046. case Image::ARGB:
  68047. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68048. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68049. break;
  68050. case Image::RGB:
  68051. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68052. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68053. break;
  68054. default:
  68055. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68056. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68057. break;
  68058. }
  68059. break;
  68060. }
  68061. }
  68062. template <class Iterator, class DestPixelType>
  68063. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68064. {
  68065. jassert (destData.pixelStride == sizeof (DestPixelType));
  68066. if (replaceContents)
  68067. {
  68068. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68069. iter.iterate (r);
  68070. }
  68071. else
  68072. {
  68073. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68074. iter.iterate (r);
  68075. }
  68076. }
  68077. template <class Iterator, class DestPixelType>
  68078. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68079. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68080. {
  68081. jassert (destData.pixelStride == sizeof (DestPixelType));
  68082. if (g.isRadial)
  68083. {
  68084. if (isIdentity)
  68085. {
  68086. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68087. iter.iterate (renderer);
  68088. }
  68089. else
  68090. {
  68091. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68092. iter.iterate (renderer);
  68093. }
  68094. }
  68095. else
  68096. {
  68097. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68098. iter.iterate (renderer);
  68099. }
  68100. }
  68101. };
  68102. class ClipRegion_EdgeTable : public ClipRegionBase
  68103. {
  68104. public:
  68105. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68106. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68107. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68108. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68109. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68110. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68111. ~ClipRegion_EdgeTable() {}
  68112. const Ptr clone() const
  68113. {
  68114. return new ClipRegion_EdgeTable (*this);
  68115. }
  68116. const Ptr applyClipTo (const Ptr& target) const
  68117. {
  68118. return target->clipToEdgeTable (edgeTable);
  68119. }
  68120. const Ptr clipToRectangle (const Rectangle<int>& r)
  68121. {
  68122. edgeTable.clipToRectangle (r);
  68123. return edgeTable.isEmpty() ? 0 : this;
  68124. }
  68125. const Ptr clipToRectangleList (const RectangleList& r)
  68126. {
  68127. RectangleList inverse (edgeTable.getMaximumBounds());
  68128. if (inverse.subtract (r))
  68129. for (RectangleList::Iterator iter (inverse); iter.next();)
  68130. edgeTable.excludeRectangle (*iter.getRectangle());
  68131. return edgeTable.isEmpty() ? 0 : this;
  68132. }
  68133. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68134. {
  68135. edgeTable.excludeRectangle (r);
  68136. return edgeTable.isEmpty() ? 0 : this;
  68137. }
  68138. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68139. {
  68140. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68141. edgeTable.clipToEdgeTable (et);
  68142. return edgeTable.isEmpty() ? 0 : this;
  68143. }
  68144. const Ptr clipToEdgeTable (const EdgeTable& et)
  68145. {
  68146. edgeTable.clipToEdgeTable (et);
  68147. return edgeTable.isEmpty() ? 0 : this;
  68148. }
  68149. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68150. {
  68151. const Image::BitmapData srcData (image, false);
  68152. if (transform.isOnlyTranslation())
  68153. {
  68154. // If our translation doesn't involve any distortion, just use a simple blit..
  68155. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68156. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68157. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68158. {
  68159. const int imageX = ((tx + 128) >> 8);
  68160. const int imageY = ((ty + 128) >> 8);
  68161. if (image.getFormat() == Image::ARGB)
  68162. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68163. else
  68164. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68165. return edgeTable.isEmpty() ? 0 : this;
  68166. }
  68167. }
  68168. if (transform.isSingularity())
  68169. return 0;
  68170. {
  68171. Path p;
  68172. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68173. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68174. edgeTable.clipToEdgeTable (et2);
  68175. }
  68176. if (! edgeTable.isEmpty())
  68177. {
  68178. if (image.getFormat() == Image::ARGB)
  68179. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68180. else
  68181. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68182. }
  68183. return edgeTable.isEmpty() ? 0 : this;
  68184. }
  68185. bool clipRegionIntersects (const Rectangle<int>& r) const
  68186. {
  68187. return edgeTable.getMaximumBounds().intersects (r);
  68188. }
  68189. const Rectangle<int> getClipBounds() const
  68190. {
  68191. return edgeTable.getMaximumBounds();
  68192. }
  68193. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68194. {
  68195. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68196. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68197. if (! clipped.isEmpty())
  68198. {
  68199. ClipRegion_EdgeTable et (clipped);
  68200. et.edgeTable.clipToEdgeTable (edgeTable);
  68201. et.fillAllWithColour (destData, colour, replaceContents);
  68202. }
  68203. }
  68204. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68205. {
  68206. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68207. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68208. if (! clipped.isEmpty())
  68209. {
  68210. ClipRegion_EdgeTable et (clipped);
  68211. et.edgeTable.clipToEdgeTable (edgeTable);
  68212. et.fillAllWithColour (destData, colour, false);
  68213. }
  68214. }
  68215. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68216. {
  68217. switch (destData.pixelFormat)
  68218. {
  68219. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68220. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68221. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68222. }
  68223. }
  68224. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68225. {
  68226. HeapBlock <PixelARGB> lookupTable;
  68227. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68228. jassert (numLookupEntries > 0);
  68229. switch (destData.pixelFormat)
  68230. {
  68231. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68232. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68233. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68234. }
  68235. }
  68236. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68237. {
  68238. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68239. }
  68240. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68241. {
  68242. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68243. }
  68244. EdgeTable edgeTable;
  68245. private:
  68246. template <class SrcPixelType>
  68247. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68248. {
  68249. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68250. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68251. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68252. edgeTable.getMaximumBounds().getWidth());
  68253. }
  68254. template <class SrcPixelType>
  68255. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68256. {
  68257. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68258. edgeTable.clipToRectangle (r);
  68259. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68260. for (int y = 0; y < r.getHeight(); ++y)
  68261. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68262. }
  68263. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68264. };
  68265. class ClipRegion_RectangleList : public ClipRegionBase
  68266. {
  68267. public:
  68268. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68269. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68270. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68271. ~ClipRegion_RectangleList() {}
  68272. const Ptr clone() const
  68273. {
  68274. return new ClipRegion_RectangleList (*this);
  68275. }
  68276. const Ptr applyClipTo (const Ptr& target) const
  68277. {
  68278. return target->clipToRectangleList (clip);
  68279. }
  68280. const Ptr clipToRectangle (const Rectangle<int>& r)
  68281. {
  68282. clip.clipTo (r);
  68283. return clip.isEmpty() ? 0 : this;
  68284. }
  68285. const Ptr clipToRectangleList (const RectangleList& r)
  68286. {
  68287. clip.clipTo (r);
  68288. return clip.isEmpty() ? 0 : this;
  68289. }
  68290. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68291. {
  68292. clip.subtract (r);
  68293. return clip.isEmpty() ? 0 : this;
  68294. }
  68295. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68296. {
  68297. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68298. }
  68299. const Ptr clipToEdgeTable (const EdgeTable& et)
  68300. {
  68301. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68302. }
  68303. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68304. {
  68305. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68306. }
  68307. bool clipRegionIntersects (const Rectangle<int>& r) const
  68308. {
  68309. return clip.intersects (r);
  68310. }
  68311. const Rectangle<int> getClipBounds() const
  68312. {
  68313. return clip.getBounds();
  68314. }
  68315. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68316. {
  68317. SubRectangleIterator iter (clip, area);
  68318. switch (destData.pixelFormat)
  68319. {
  68320. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68321. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68322. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68323. }
  68324. }
  68325. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68326. {
  68327. SubRectangleIteratorFloat iter (clip, area);
  68328. switch (destData.pixelFormat)
  68329. {
  68330. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68331. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68332. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68333. }
  68334. }
  68335. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68336. {
  68337. switch (destData.pixelFormat)
  68338. {
  68339. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68340. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68341. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68342. }
  68343. }
  68344. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68345. {
  68346. HeapBlock <PixelARGB> lookupTable;
  68347. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68348. jassert (numLookupEntries > 0);
  68349. switch (destData.pixelFormat)
  68350. {
  68351. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68352. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68353. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68354. }
  68355. }
  68356. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68357. {
  68358. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68359. }
  68360. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68361. {
  68362. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68363. }
  68364. RectangleList clip;
  68365. template <class Renderer>
  68366. void iterate (Renderer& r) const throw()
  68367. {
  68368. RectangleList::Iterator iter (clip);
  68369. while (iter.next())
  68370. {
  68371. const Rectangle<int> rect (*iter.getRectangle());
  68372. const int x = rect.getX();
  68373. const int w = rect.getWidth();
  68374. jassert (w > 0);
  68375. const int bottom = rect.getBottom();
  68376. for (int y = rect.getY(); y < bottom; ++y)
  68377. {
  68378. r.setEdgeTableYPos (y);
  68379. r.handleEdgeTableLineFull (x, w);
  68380. }
  68381. }
  68382. }
  68383. private:
  68384. class SubRectangleIterator
  68385. {
  68386. public:
  68387. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68388. : clip (clip_), area (area_)
  68389. {
  68390. }
  68391. template <class Renderer>
  68392. void iterate (Renderer& r) const throw()
  68393. {
  68394. RectangleList::Iterator iter (clip);
  68395. while (iter.next())
  68396. {
  68397. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68398. if (! rect.isEmpty())
  68399. {
  68400. const int x = rect.getX();
  68401. const int w = rect.getWidth();
  68402. const int bottom = rect.getBottom();
  68403. for (int y = rect.getY(); y < bottom; ++y)
  68404. {
  68405. r.setEdgeTableYPos (y);
  68406. r.handleEdgeTableLineFull (x, w);
  68407. }
  68408. }
  68409. }
  68410. }
  68411. private:
  68412. const RectangleList& clip;
  68413. const Rectangle<int> area;
  68414. SubRectangleIterator (const SubRectangleIterator&);
  68415. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68416. };
  68417. class SubRectangleIteratorFloat
  68418. {
  68419. public:
  68420. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68421. : clip (clip_), area (area_)
  68422. {
  68423. }
  68424. template <class Renderer>
  68425. void iterate (Renderer& r) const throw()
  68426. {
  68427. int left = roundToInt (area.getX() * 256.0f);
  68428. int top = roundToInt (area.getY() * 256.0f);
  68429. int right = roundToInt (area.getRight() * 256.0f);
  68430. int bottom = roundToInt (area.getBottom() * 256.0f);
  68431. int totalTop, totalLeft, totalBottom, totalRight;
  68432. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68433. if ((top >> 8) == (bottom >> 8))
  68434. {
  68435. topAlpha = bottom - top;
  68436. bottomAlpha = 0;
  68437. totalTop = top >> 8;
  68438. totalBottom = bottom = top = totalTop + 1;
  68439. }
  68440. else
  68441. {
  68442. if ((top & 255) == 0)
  68443. {
  68444. topAlpha = 0;
  68445. top = totalTop = (top >> 8);
  68446. }
  68447. else
  68448. {
  68449. topAlpha = 255 - (top & 255);
  68450. totalTop = (top >> 8);
  68451. top = totalTop + 1;
  68452. }
  68453. bottomAlpha = bottom & 255;
  68454. bottom >>= 8;
  68455. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68456. }
  68457. if ((left >> 8) == (right >> 8))
  68458. {
  68459. leftAlpha = right - left;
  68460. rightAlpha = 0;
  68461. totalLeft = (left >> 8);
  68462. totalRight = right = left = totalLeft + 1;
  68463. }
  68464. else
  68465. {
  68466. if ((left & 255) == 0)
  68467. {
  68468. leftAlpha = 0;
  68469. left = totalLeft = (left >> 8);
  68470. }
  68471. else
  68472. {
  68473. leftAlpha = 255 - (left & 255);
  68474. totalLeft = (left >> 8);
  68475. left = totalLeft + 1;
  68476. }
  68477. rightAlpha = right & 255;
  68478. right >>= 8;
  68479. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68480. }
  68481. RectangleList::Iterator iter (clip);
  68482. while (iter.next())
  68483. {
  68484. const int clipLeft = iter.getRectangle()->getX();
  68485. const int clipRight = iter.getRectangle()->getRight();
  68486. const int clipTop = iter.getRectangle()->getY();
  68487. const int clipBottom = iter.getRectangle()->getBottom();
  68488. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68489. {
  68490. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68491. {
  68492. if (topAlpha != 0 && totalTop >= clipTop)
  68493. {
  68494. r.setEdgeTableYPos (totalTop);
  68495. r.handleEdgeTablePixel (left, topAlpha);
  68496. }
  68497. const int endY = jmin (bottom, clipBottom);
  68498. for (int y = jmax (clipTop, top); y < endY; ++y)
  68499. {
  68500. r.setEdgeTableYPos (y);
  68501. r.handleEdgeTablePixelFull (left);
  68502. }
  68503. if (bottomAlpha != 0 && bottom < clipBottom)
  68504. {
  68505. r.setEdgeTableYPos (bottom);
  68506. r.handleEdgeTablePixel (left, bottomAlpha);
  68507. }
  68508. }
  68509. else
  68510. {
  68511. const int clippedLeft = jmax (left, clipLeft);
  68512. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68513. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68514. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68515. if (topAlpha != 0 && totalTop >= clipTop)
  68516. {
  68517. r.setEdgeTableYPos (totalTop);
  68518. if (doLeftAlpha)
  68519. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68520. if (clippedWidth > 0)
  68521. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68522. if (doRightAlpha)
  68523. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68524. }
  68525. const int endY = jmin (bottom, clipBottom);
  68526. for (int y = jmax (clipTop, top); y < endY; ++y)
  68527. {
  68528. r.setEdgeTableYPos (y);
  68529. if (doLeftAlpha)
  68530. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68531. if (clippedWidth > 0)
  68532. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68533. if (doRightAlpha)
  68534. r.handleEdgeTablePixel (right, rightAlpha);
  68535. }
  68536. if (bottomAlpha != 0 && bottom < clipBottom)
  68537. {
  68538. r.setEdgeTableYPos (bottom);
  68539. if (doLeftAlpha)
  68540. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68541. if (clippedWidth > 0)
  68542. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68543. if (doRightAlpha)
  68544. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68545. }
  68546. }
  68547. }
  68548. }
  68549. }
  68550. private:
  68551. const RectangleList& clip;
  68552. const Rectangle<float>& area;
  68553. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68554. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68555. };
  68556. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68557. };
  68558. }
  68559. class LowLevelGraphicsSoftwareRenderer::SavedState
  68560. {
  68561. public:
  68562. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68563. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68564. xOffset (xOffset_), yOffset (yOffset_), isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68565. {
  68566. }
  68567. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68568. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68569. xOffset (xOffset_), yOffset (yOffset_), isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68570. {
  68571. }
  68572. SavedState (const SavedState& other)
  68573. : clip (other.clip), complexTransform (other.complexTransform), xOffset (other.xOffset), yOffset (other.yOffset),
  68574. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68575. {
  68576. }
  68577. void setOrigin (const int x, const int y) throw()
  68578. {
  68579. if (isOnlyTranslated)
  68580. {
  68581. xOffset += x;
  68582. yOffset += y;
  68583. }
  68584. else
  68585. {
  68586. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  68587. }
  68588. }
  68589. void addTransform (const AffineTransform& t)
  68590. {
  68591. if ((! isOnlyTranslated)
  68592. || (! t.isOnlyTranslation())
  68593. || (int) (t.getTranslationX() * 256.0f) != 0
  68594. || (int) (t.getTranslationY() * 256.0f) != 0)
  68595. {
  68596. complexTransform = getTransformWith (t);
  68597. isOnlyTranslated = false;
  68598. }
  68599. else
  68600. {
  68601. xOffset += (int) t.getTranslationX();
  68602. yOffset += (int) t.getTranslationY();
  68603. }
  68604. }
  68605. bool clipToRectangle (const Rectangle<int>& r)
  68606. {
  68607. if (clip != 0)
  68608. {
  68609. if (isOnlyTranslated)
  68610. {
  68611. cloneClipIfMultiplyReferenced();
  68612. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68613. }
  68614. else
  68615. {
  68616. Path p;
  68617. p.addRectangle (r);
  68618. clipToPath (p, AffineTransform::identity);
  68619. }
  68620. }
  68621. return clip != 0;
  68622. }
  68623. bool clipToRectangleList (const RectangleList& r)
  68624. {
  68625. if (clip != 0)
  68626. {
  68627. if (isOnlyTranslated)
  68628. {
  68629. cloneClipIfMultiplyReferenced();
  68630. RectangleList offsetList (r);
  68631. offsetList.offsetAll (xOffset, yOffset);
  68632. clip = clip->clipToRectangleList (offsetList);
  68633. }
  68634. else
  68635. {
  68636. clipToPath (r.toPath(), AffineTransform::identity);
  68637. }
  68638. }
  68639. return clip != 0;
  68640. }
  68641. bool excludeClipRectangle (const Rectangle<int>& r)
  68642. {
  68643. if (clip != 0)
  68644. {
  68645. if (isOnlyTranslated)
  68646. {
  68647. cloneClipIfMultiplyReferenced();
  68648. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68649. }
  68650. else
  68651. {
  68652. RectangleList all (getClipBounds());
  68653. all.subtract (r);
  68654. return clipToRectangleList (all);
  68655. }
  68656. }
  68657. return clip != 0;
  68658. }
  68659. void clipToPath (const Path& p, const AffineTransform& transform)
  68660. {
  68661. if (clip != 0)
  68662. {
  68663. cloneClipIfMultiplyReferenced();
  68664. clip = clip->clipToPath (p, getTransformWith (transform));
  68665. }
  68666. }
  68667. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68668. {
  68669. if (clip != 0)
  68670. {
  68671. if (image.hasAlphaChannel())
  68672. {
  68673. cloneClipIfMultiplyReferenced();
  68674. clip = clip->clipToImageAlpha (image, getTransformWith (t),
  68675. interpolationQuality != Graphics::lowResamplingQuality);
  68676. }
  68677. else
  68678. {
  68679. Path p;
  68680. p.addRectangle (image.getBounds());
  68681. clipToPath (p, t);
  68682. }
  68683. }
  68684. }
  68685. bool clipRegionIntersects (const Rectangle<int>& r) const
  68686. {
  68687. if (clip != 0)
  68688. {
  68689. if (isOnlyTranslated)
  68690. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68691. else
  68692. return getClipBounds().intersects (r);
  68693. }
  68694. return false;
  68695. }
  68696. const Rectangle<int> getClipBounds() const
  68697. {
  68698. if (clip != 0)
  68699. {
  68700. if (isOnlyTranslated)
  68701. return clip->getClipBounds().translated (-xOffset, -yOffset);
  68702. else
  68703. return clip->getClipBounds().toFloat().transformed (getTransform().inverted()).getSmallestIntegerContainer();
  68704. }
  68705. return Rectangle<int>();
  68706. }
  68707. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68708. {
  68709. if (clip != 0)
  68710. {
  68711. if (isOnlyTranslated)
  68712. {
  68713. if (fillType.isColour())
  68714. {
  68715. Image::BitmapData destData (image, true);
  68716. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68717. }
  68718. else
  68719. {
  68720. const Rectangle<int> totalClip (clip->getClipBounds());
  68721. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68722. if (! clipped.isEmpty())
  68723. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68724. }
  68725. }
  68726. else
  68727. {
  68728. Path p;
  68729. p.addRectangle (r);
  68730. fillPath (image, p, AffineTransform::identity);
  68731. }
  68732. }
  68733. }
  68734. void fillRect (Image& image, const Rectangle<float>& r)
  68735. {
  68736. if (clip != 0)
  68737. {
  68738. if (isOnlyTranslated)
  68739. {
  68740. if (fillType.isColour())
  68741. {
  68742. Image::BitmapData destData (image, true);
  68743. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68744. }
  68745. else
  68746. {
  68747. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68748. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68749. if (! clipped.isEmpty())
  68750. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68751. }
  68752. }
  68753. else
  68754. {
  68755. Path p;
  68756. p.addRectangle (r);
  68757. fillPath (image, p, AffineTransform::identity);
  68758. }
  68759. }
  68760. }
  68761. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  68762. {
  68763. if (clip != 0)
  68764. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  68765. }
  68766. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  68767. {
  68768. jassert (isOnlyTranslated);
  68769. if (clip != 0)
  68770. {
  68771. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68772. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68773. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68774. fillShape (image, shapeToFill, false);
  68775. }
  68776. }
  68777. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68778. {
  68779. jassert (clip != 0);
  68780. shapeToFill = clip->applyClipTo (shapeToFill);
  68781. if (shapeToFill != 0)
  68782. {
  68783. Image::BitmapData destData (image, true);
  68784. if (fillType.isGradient())
  68785. {
  68786. jassert (! replaceContents); // that option is just for solid colours
  68787. ColourGradient g2 (*(fillType.gradient));
  68788. g2.multiplyOpacity (fillType.getOpacity());
  68789. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  68790. const bool isIdentity = transform.isOnlyTranslation();
  68791. if (isIdentity)
  68792. {
  68793. // If our translation doesn't involve any distortion, we can speed it up..
  68794. g2.point1.applyTransform (transform);
  68795. g2.point2.applyTransform (transform);
  68796. transform = AffineTransform::identity;
  68797. }
  68798. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68799. }
  68800. else if (fillType.isTiledImage())
  68801. {
  68802. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  68803. }
  68804. else
  68805. {
  68806. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68807. }
  68808. }
  68809. }
  68810. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68811. {
  68812. const AffineTransform transform (getTransformWith (t));
  68813. const Image::BitmapData destData (destImage, true);
  68814. const Image::BitmapData srcData (sourceImage, false);
  68815. const int alpha = fillType.colour.getAlpha();
  68816. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68817. if (transform.isOnlyTranslation())
  68818. {
  68819. // If our translation doesn't involve any distortion, just use a simple blit..
  68820. int tx = (int) (transform.getTranslationX() * 256.0f);
  68821. int ty = (int) (transform.getTranslationY() * 256.0f);
  68822. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68823. {
  68824. tx = ((tx + 128) >> 8);
  68825. ty = ((ty + 128) >> 8);
  68826. if (tiledFillClipRegion != 0)
  68827. {
  68828. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68829. }
  68830. else
  68831. {
  68832. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  68833. c = clip->applyClipTo (c);
  68834. if (c != 0)
  68835. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68836. }
  68837. return;
  68838. }
  68839. }
  68840. if (transform.isSingularity())
  68841. return;
  68842. if (tiledFillClipRegion != 0)
  68843. {
  68844. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68845. }
  68846. else
  68847. {
  68848. Path p;
  68849. p.addRectangle (sourceImage.getBounds());
  68850. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68851. c = c->clipToPath (p, transform);
  68852. if (c != 0)
  68853. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68854. }
  68855. }
  68856. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68857. private:
  68858. AffineTransform complexTransform;
  68859. int xOffset, yOffset;
  68860. public:
  68861. bool isOnlyTranslated;
  68862. Font font;
  68863. FillType fillType;
  68864. Graphics::ResamplingQuality interpolationQuality;
  68865. private:
  68866. void cloneClipIfMultiplyReferenced()
  68867. {
  68868. if (clip->getReferenceCount() > 1)
  68869. clip = clip->clone();
  68870. }
  68871. const AffineTransform getTransform() const
  68872. {
  68873. if (isOnlyTranslated)
  68874. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  68875. return complexTransform;
  68876. }
  68877. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  68878. {
  68879. if (isOnlyTranslated)
  68880. return userTransform.translated ((float) xOffset, (float) yOffset);
  68881. return userTransform.followedBy (complexTransform);
  68882. }
  68883. SavedState& operator= (const SavedState&);
  68884. };
  68885. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  68886. : image (image_)
  68887. {
  68888. currentState = new SavedState (image_.getBounds(), 0, 0);
  68889. }
  68890. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  68891. const RectangleList& initialClip)
  68892. : image (image_)
  68893. {
  68894. currentState = new SavedState (initialClip, xOffset, yOffset);
  68895. }
  68896. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  68897. {
  68898. }
  68899. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  68900. {
  68901. return false;
  68902. }
  68903. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  68904. {
  68905. currentState->setOrigin (x, y);
  68906. }
  68907. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  68908. {
  68909. currentState->addTransform (transform);
  68910. }
  68911. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  68912. {
  68913. return currentState->clipToRectangle (r);
  68914. }
  68915. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  68916. {
  68917. return currentState->clipToRectangleList (clipRegion);
  68918. }
  68919. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  68920. {
  68921. currentState->excludeClipRectangle (r);
  68922. }
  68923. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  68924. {
  68925. currentState->clipToPath (path, transform);
  68926. }
  68927. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  68928. {
  68929. currentState->clipToImageAlpha (sourceImage, transform);
  68930. }
  68931. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  68932. {
  68933. return currentState->clipRegionIntersects (r);
  68934. }
  68935. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  68936. {
  68937. return currentState->getClipBounds();
  68938. }
  68939. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  68940. {
  68941. return currentState->clip == 0;
  68942. }
  68943. void LowLevelGraphicsSoftwareRenderer::saveState()
  68944. {
  68945. stateStack.add (new SavedState (*currentState));
  68946. }
  68947. void LowLevelGraphicsSoftwareRenderer::restoreState()
  68948. {
  68949. SavedState* const top = stateStack.getLast();
  68950. if (top != 0)
  68951. {
  68952. currentState = top;
  68953. stateStack.removeLast (1, false);
  68954. }
  68955. else
  68956. {
  68957. jassertfalse; // trying to pop with an empty stack!
  68958. }
  68959. }
  68960. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  68961. {
  68962. currentState->fillType = fillType;
  68963. }
  68964. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  68965. {
  68966. currentState->fillType.setOpacity (newOpacity);
  68967. }
  68968. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  68969. {
  68970. currentState->interpolationQuality = quality;
  68971. }
  68972. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  68973. {
  68974. currentState->fillRect (image, r, replaceExistingContents);
  68975. }
  68976. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  68977. {
  68978. currentState->fillPath (image, path, transform);
  68979. }
  68980. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  68981. {
  68982. currentState->renderImage (image, sourceImage, transform,
  68983. fillEntireClipAsTiles ? currentState->clip : 0);
  68984. }
  68985. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  68986. {
  68987. Path p;
  68988. p.addLineSegment (line, 1.0f);
  68989. fillPath (p, AffineTransform::identity);
  68990. }
  68991. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  68992. {
  68993. if (bottom > top)
  68994. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  68995. }
  68996. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  68997. {
  68998. if (right > left)
  68999. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69000. }
  69001. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69002. {
  69003. public:
  69004. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69005. ~CachedGlyph() {}
  69006. void draw (SavedState& state, Image& image, const float x, const float y) const
  69007. {
  69008. if (edgeTable != 0)
  69009. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69010. }
  69011. void generate (const Font& newFont, const int glyphNumber)
  69012. {
  69013. font = newFont;
  69014. glyph = glyphNumber;
  69015. edgeTable = 0;
  69016. Path glyphPath;
  69017. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69018. if (! glyphPath.isEmpty())
  69019. {
  69020. const float fontHeight = font.getHeight();
  69021. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69022. #if JUCE_MAC || JUCE_IOS
  69023. .translated (0.0f, -0.5f)
  69024. #endif
  69025. );
  69026. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69027. glyphPath, transform);
  69028. }
  69029. }
  69030. int glyph, lastAccessCount;
  69031. Font font;
  69032. juce_UseDebuggingNewOperator
  69033. private:
  69034. ScopedPointer <EdgeTable> edgeTable;
  69035. CachedGlyph (const CachedGlyph&);
  69036. CachedGlyph& operator= (const CachedGlyph&);
  69037. };
  69038. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69039. {
  69040. public:
  69041. GlyphCache()
  69042. : accessCounter (0), hits (0), misses (0)
  69043. {
  69044. for (int i = 120; --i >= 0;)
  69045. glyphs.add (new CachedGlyph());
  69046. }
  69047. ~GlyphCache()
  69048. {
  69049. clearSingletonInstance();
  69050. }
  69051. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69052. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69053. {
  69054. ++accessCounter;
  69055. int oldestCounter = std::numeric_limits<int>::max();
  69056. CachedGlyph* oldest = 0;
  69057. for (int i = glyphs.size(); --i >= 0;)
  69058. {
  69059. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69060. if (glyph->glyph == glyphNumber && glyph->font == font)
  69061. {
  69062. ++hits;
  69063. glyph->lastAccessCount = accessCounter;
  69064. glyph->draw (state, image, x, y);
  69065. return;
  69066. }
  69067. if (glyph->lastAccessCount <= oldestCounter)
  69068. {
  69069. oldestCounter = glyph->lastAccessCount;
  69070. oldest = glyph;
  69071. }
  69072. }
  69073. if (hits + ++misses > (glyphs.size() << 4))
  69074. {
  69075. if (misses * 2 > hits)
  69076. {
  69077. for (int i = 32; --i >= 0;)
  69078. glyphs.add (new CachedGlyph());
  69079. }
  69080. hits = misses = 0;
  69081. oldest = glyphs.getLast();
  69082. }
  69083. jassert (oldest != 0);
  69084. oldest->lastAccessCount = accessCounter;
  69085. oldest->generate (font, glyphNumber);
  69086. oldest->draw (state, image, x, y);
  69087. }
  69088. juce_UseDebuggingNewOperator
  69089. private:
  69090. friend class OwnedArray <CachedGlyph>;
  69091. OwnedArray <CachedGlyph> glyphs;
  69092. int accessCounter, hits, misses;
  69093. GlyphCache (const GlyphCache&);
  69094. GlyphCache& operator= (const GlyphCache&);
  69095. };
  69096. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69097. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69098. {
  69099. currentState->font = newFont;
  69100. }
  69101. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69102. {
  69103. return currentState->font;
  69104. }
  69105. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69106. {
  69107. Font& f = currentState->font;
  69108. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69109. {
  69110. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69111. transform.getTranslationX(),
  69112. transform.getTranslationY());
  69113. }
  69114. else
  69115. {
  69116. Path p;
  69117. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69118. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69119. }
  69120. }
  69121. #if JUCE_MSVC
  69122. #pragma warning (pop)
  69123. #if JUCE_DEBUG
  69124. #pragma optimize ("", on) // resets optimisations to the project defaults
  69125. #endif
  69126. #endif
  69127. END_JUCE_NAMESPACE
  69128. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69129. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69130. BEGIN_JUCE_NAMESPACE
  69131. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69132. : flags (other.flags)
  69133. {
  69134. }
  69135. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69136. {
  69137. flags = other.flags;
  69138. return *this;
  69139. }
  69140. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69141. const double dx, const double dy, const double dw, const double dh) const throw()
  69142. {
  69143. if (w == 0 || h == 0)
  69144. return;
  69145. if ((flags & stretchToFit) != 0)
  69146. {
  69147. x = dx;
  69148. y = dy;
  69149. w = dw;
  69150. h = dh;
  69151. }
  69152. else
  69153. {
  69154. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69155. : jmin (dw / w, dh / h);
  69156. if ((flags & onlyReduceInSize) != 0)
  69157. scale = jmin (scale, 1.0);
  69158. if ((flags & onlyIncreaseInSize) != 0)
  69159. scale = jmax (scale, 1.0);
  69160. w *= scale;
  69161. h *= scale;
  69162. if ((flags & xLeft) != 0)
  69163. x = dx;
  69164. else if ((flags & xRight) != 0)
  69165. x = dx + dw - w;
  69166. else
  69167. x = dx + (dw - w) * 0.5;
  69168. if ((flags & yTop) != 0)
  69169. y = dy;
  69170. else if ((flags & yBottom) != 0)
  69171. y = dy + dh - h;
  69172. else
  69173. y = dy + (dh - h) * 0.5;
  69174. }
  69175. }
  69176. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69177. {
  69178. if (source.isEmpty())
  69179. return AffineTransform::identity;
  69180. float newX = destination.getX();
  69181. float newY = destination.getY();
  69182. float scaleX = destination.getWidth() / source.getWidth();
  69183. float scaleY = destination.getHeight() / source.getHeight();
  69184. if ((flags & stretchToFit) == 0)
  69185. {
  69186. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69187. : jmin (scaleX, scaleY);
  69188. if ((flags & onlyReduceInSize) != 0)
  69189. scaleX = jmin (scaleX, 1.0f);
  69190. if ((flags & onlyIncreaseInSize) != 0)
  69191. scaleX = jmax (scaleX, 1.0f);
  69192. scaleY = scaleX;
  69193. if ((flags & xRight) != 0)
  69194. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69195. else if ((flags & xLeft) == 0)
  69196. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69197. if ((flags & yBottom) != 0)
  69198. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69199. else if ((flags & yTop) == 0)
  69200. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69201. }
  69202. return AffineTransform::translation (-source.getX(), -source.getY())
  69203. .scaled (scaleX, scaleY)
  69204. .translated (newX, newY);
  69205. }
  69206. END_JUCE_NAMESPACE
  69207. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69208. /*** Start of inlined file: juce_Drawable.cpp ***/
  69209. BEGIN_JUCE_NAMESPACE
  69210. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69211. const AffineTransform& transform_,
  69212. const float opacity_) throw()
  69213. : g (g_),
  69214. transform (transform_),
  69215. opacity (opacity_)
  69216. {
  69217. }
  69218. Drawable::Drawable()
  69219. : parent (0)
  69220. {
  69221. }
  69222. Drawable::~Drawable()
  69223. {
  69224. }
  69225. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69226. {
  69227. render (RenderingContext (g, transform, opacity));
  69228. }
  69229. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69230. {
  69231. draw (g, opacity, AffineTransform::translation (x, y));
  69232. }
  69233. void Drawable::drawWithin (Graphics& g,
  69234. const Rectangle<float>& destArea,
  69235. const RectanglePlacement& placement,
  69236. const float opacity) const
  69237. {
  69238. if (! destArea.isEmpty())
  69239. draw (g, opacity, placement.getTransformToFit (getBounds(), destArea));
  69240. }
  69241. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69242. {
  69243. Drawable* result = 0;
  69244. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69245. if (image.isValid())
  69246. {
  69247. DrawableImage* const di = new DrawableImage();
  69248. di->setImage (image);
  69249. result = di;
  69250. }
  69251. else
  69252. {
  69253. const String asString (String::createStringFromData (data, (int) numBytes));
  69254. XmlDocument doc (asString);
  69255. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69256. if (outer != 0 && outer->hasTagName ("svg"))
  69257. {
  69258. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69259. if (svg != 0)
  69260. result = Drawable::createFromSVG (*svg);
  69261. }
  69262. }
  69263. return result;
  69264. }
  69265. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69266. {
  69267. MemoryOutputStream mo;
  69268. mo.writeFromInputStream (dataSource, -1);
  69269. return createFromImageData (mo.getData(), mo.getDataSize());
  69270. }
  69271. Drawable* Drawable::createFromImageFile (const File& file)
  69272. {
  69273. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69274. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69275. }
  69276. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69277. {
  69278. return createChildFromValueTree (0, tree, imageProvider);
  69279. }
  69280. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69281. {
  69282. const Identifier type (tree.getType());
  69283. Drawable* d = 0;
  69284. if (type == DrawablePath::valueTreeType)
  69285. d = new DrawablePath();
  69286. else if (type == DrawableComposite::valueTreeType)
  69287. d = new DrawableComposite();
  69288. else if (type == DrawableRectangle::valueTreeType)
  69289. d = new DrawableRectangle();
  69290. else if (type == DrawableImage::valueTreeType)
  69291. d = new DrawableImage();
  69292. else if (type == DrawableText::valueTreeType)
  69293. d = new DrawableText();
  69294. if (d != 0)
  69295. {
  69296. d->parent = parent;
  69297. d->refreshFromValueTree (tree, imageProvider);
  69298. }
  69299. return d;
  69300. }
  69301. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69302. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69303. : state (state_)
  69304. {
  69305. }
  69306. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69307. {
  69308. }
  69309. const String Drawable::ValueTreeWrapperBase::getID() const
  69310. {
  69311. return state [idProperty];
  69312. }
  69313. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69314. {
  69315. if (newID.isEmpty())
  69316. state.removeProperty (idProperty, undoManager);
  69317. else
  69318. state.setProperty (idProperty, newID, undoManager);
  69319. }
  69320. END_JUCE_NAMESPACE
  69321. /*** End of inlined file: juce_Drawable.cpp ***/
  69322. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69323. BEGIN_JUCE_NAMESPACE
  69324. DrawableShape::DrawableShape()
  69325. : strokeType (0.0f),
  69326. mainFill (Colours::black),
  69327. strokeFill (Colours::black),
  69328. pathNeedsUpdating (true),
  69329. strokeNeedsUpdating (true)
  69330. {
  69331. }
  69332. DrawableShape::DrawableShape (const DrawableShape& other)
  69333. : strokeType (other.strokeType),
  69334. mainFill (other.mainFill),
  69335. strokeFill (other.strokeFill),
  69336. pathNeedsUpdating (true),
  69337. strokeNeedsUpdating (true)
  69338. {
  69339. }
  69340. DrawableShape::~DrawableShape()
  69341. {
  69342. }
  69343. void DrawableShape::setFill (const FillType& newFill)
  69344. {
  69345. mainFill = newFill;
  69346. }
  69347. void DrawableShape::setStrokeFill (const FillType& newFill)
  69348. {
  69349. strokeFill = newFill;
  69350. }
  69351. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69352. {
  69353. strokeType = newStrokeType;
  69354. strokeNeedsUpdating = true;
  69355. }
  69356. void DrawableShape::setStrokeThickness (const float newThickness)
  69357. {
  69358. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69359. }
  69360. bool DrawableShape::isStrokeVisible() const throw()
  69361. {
  69362. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69363. }
  69364. void DrawableShape::setBrush (const Drawable::RenderingContext& context, const FillType& type)
  69365. {
  69366. FillType f (type);
  69367. if (f.isGradient())
  69368. f.gradient->multiplyOpacity (context.opacity);
  69369. else
  69370. f.setOpacity (f.getOpacity() * context.opacity);
  69371. f.transform = f.transform.followedBy (context.transform);
  69372. context.g.setFillType (f);
  69373. }
  69374. bool DrawableShape::refreshFillTypes (const FillAndStrokeState& newState,
  69375. Expression::EvaluationContext* /*nameFinder*/,
  69376. ImageProvider* imageProvider)
  69377. {
  69378. bool hasChanged = false;
  69379. {
  69380. const FillType f (newState.getMainFill (parent, imageProvider));
  69381. if (mainFill != f)
  69382. {
  69383. hasChanged = true;
  69384. mainFill = f;
  69385. }
  69386. }
  69387. {
  69388. const FillType f (newState.getStrokeFill (parent, imageProvider));
  69389. if (strokeFill != f)
  69390. {
  69391. hasChanged = true;
  69392. strokeFill = f;
  69393. }
  69394. }
  69395. return hasChanged;
  69396. }
  69397. void DrawableShape::writeTo (FillAndStrokeState& state, ImageProvider* imageProvider, UndoManager* undoManager) const
  69398. {
  69399. state.setMainFill (mainFill, 0, 0, 0, imageProvider, undoManager);
  69400. state.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, undoManager);
  69401. state.setStrokeType (strokeType, undoManager);
  69402. }
  69403. void DrawableShape::render (const Drawable::RenderingContext& context) const
  69404. {
  69405. setBrush (context, mainFill);
  69406. context.g.fillPath (getCachedPath(), context.transform);
  69407. if (isStrokeVisible())
  69408. {
  69409. setBrush (context, strokeFill);
  69410. context.g.fillPath (getCachedStrokePath(), context.transform);
  69411. }
  69412. }
  69413. void DrawableShape::pathChanged()
  69414. {
  69415. pathNeedsUpdating = true;
  69416. }
  69417. void DrawableShape::strokeChanged()
  69418. {
  69419. strokeNeedsUpdating = true;
  69420. }
  69421. void DrawableShape::invalidatePoints()
  69422. {
  69423. pathNeedsUpdating = true;
  69424. strokeNeedsUpdating = true;
  69425. }
  69426. const Path& DrawableShape::getCachedPath() const
  69427. {
  69428. if (pathNeedsUpdating)
  69429. {
  69430. pathNeedsUpdating = false;
  69431. if (rebuildPath (cachedPath))
  69432. strokeNeedsUpdating = true;
  69433. }
  69434. return cachedPath;
  69435. }
  69436. const Path& DrawableShape::getCachedStrokePath() const
  69437. {
  69438. if (strokeNeedsUpdating)
  69439. {
  69440. cachedStroke.clear();
  69441. strokeType.createStrokedPath (cachedStroke, getCachedPath(), AffineTransform::identity, 4.0f);
  69442. strokeNeedsUpdating = false; // (must be called after getCachedPath)
  69443. }
  69444. return cachedStroke;
  69445. }
  69446. const Rectangle<float> DrawableShape::getBounds() const
  69447. {
  69448. if (isStrokeVisible())
  69449. return getCachedStrokePath().getBounds();
  69450. else
  69451. return getCachedPath().getBounds();
  69452. }
  69453. bool DrawableShape::hitTest (float x, float y) const
  69454. {
  69455. return getCachedPath().contains (x, y)
  69456. || (isStrokeVisible() && getCachedStrokePath().contains (x, y));
  69457. }
  69458. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69459. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69460. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69461. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69462. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69463. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69464. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69465. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69466. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69467. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69468. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69469. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69470. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69471. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69472. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69473. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69474. : Drawable::ValueTreeWrapperBase (state_)
  69475. {
  69476. }
  69477. const FillType DrawableShape::FillAndStrokeState::getMainFill (Expression::EvaluationContext* nameFinder,
  69478. ImageProvider* imageProvider) const
  69479. {
  69480. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  69481. }
  69482. ValueTree DrawableShape::FillAndStrokeState::getMainFillState()
  69483. {
  69484. ValueTree v (state.getChildWithName (fill));
  69485. if (v.isValid())
  69486. return v;
  69487. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  69488. return getMainFillState();
  69489. }
  69490. void DrawableShape::FillAndStrokeState::setMainFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69491. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69492. {
  69493. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69494. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69495. }
  69496. const FillType DrawableShape::FillAndStrokeState::getStrokeFill (Expression::EvaluationContext* nameFinder,
  69497. ImageProvider* imageProvider) const
  69498. {
  69499. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  69500. }
  69501. ValueTree DrawableShape::FillAndStrokeState::getStrokeFillState()
  69502. {
  69503. ValueTree v (state.getChildWithName (stroke));
  69504. if (v.isValid())
  69505. return v;
  69506. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  69507. return getStrokeFillState();
  69508. }
  69509. void DrawableShape::FillAndStrokeState::setStrokeFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69510. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69511. {
  69512. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69513. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69514. }
  69515. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69516. {
  69517. const String jointStyleString (state [jointStyle].toString());
  69518. const String capStyleString (state [capStyle].toString());
  69519. return PathStrokeType (state [strokeWidth],
  69520. jointStyleString == "curved" ? PathStrokeType::curved
  69521. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69522. : PathStrokeType::mitered),
  69523. capStyleString == "square" ? PathStrokeType::square
  69524. : (capStyleString == "round" ? PathStrokeType::rounded
  69525. : PathStrokeType::butt));
  69526. }
  69527. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69528. {
  69529. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69530. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69531. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69532. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69533. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69534. }
  69535. const FillType DrawableShape::FillAndStrokeState::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69536. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69537. {
  69538. const String newType (v[type].toString());
  69539. if (newType == "solid")
  69540. {
  69541. const String colourString (v [colour].toString());
  69542. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69543. : (uint32) colourString.getHexValue32()));
  69544. }
  69545. else if (newType == "gradient")
  69546. {
  69547. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69548. ColourGradient g;
  69549. if (gp1 != 0) *gp1 = p1;
  69550. if (gp2 != 0) *gp2 = p2;
  69551. if (gp3 != 0) *gp3 = p3;
  69552. g.point1 = p1.resolve (nameFinder);
  69553. g.point2 = p2.resolve (nameFinder);
  69554. g.isRadial = v[radial];
  69555. StringArray colourSteps;
  69556. colourSteps.addTokens (v[colours].toString(), false);
  69557. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69558. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69559. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69560. FillType fillType (g);
  69561. if (g.isRadial)
  69562. {
  69563. const Point<float> point3 (p3.resolve (nameFinder));
  69564. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69565. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69566. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69567. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69568. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69569. }
  69570. return fillType;
  69571. }
  69572. else if (newType == "image")
  69573. {
  69574. Image im;
  69575. if (imageProvider != 0)
  69576. im = imageProvider->getImageForIdentifier (v[imageId]);
  69577. FillType f (im, AffineTransform::identity);
  69578. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69579. return f;
  69580. }
  69581. jassert (! v.isValid());
  69582. return FillType();
  69583. }
  69584. namespace DrawableShapeHelpers
  69585. {
  69586. const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69587. {
  69588. const ColourGradient& g = *fillType.gradient;
  69589. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69590. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69591. return point3Source.transformedBy (fillType.transform);
  69592. }
  69593. }
  69594. void DrawableShape::FillAndStrokeState::writeFillType (ValueTree& v, const FillType& fillType,
  69595. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69596. ImageProvider* imageProvider, UndoManager* const undoManager)
  69597. {
  69598. if (fillType.isColour())
  69599. {
  69600. v.setProperty (type, "solid", undoManager);
  69601. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69602. }
  69603. else if (fillType.isGradient())
  69604. {
  69605. v.setProperty (type, "gradient", undoManager);
  69606. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69607. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69608. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : DrawableShapeHelpers::calcThirdGradientPoint (fillType).toString(), undoManager);
  69609. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69610. String s;
  69611. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69612. s << ' ' << fillType.gradient->getColourPosition (i)
  69613. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69614. v.setProperty (colours, s.trimStart(), undoManager);
  69615. }
  69616. else if (fillType.isTiledImage())
  69617. {
  69618. v.setProperty (type, "image", undoManager);
  69619. if (imageProvider != 0)
  69620. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69621. if (fillType.getOpacity() < 1.0f)
  69622. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69623. else
  69624. v.removeProperty (imageOpacity, undoManager);
  69625. }
  69626. else
  69627. {
  69628. jassertfalse;
  69629. }
  69630. }
  69631. END_JUCE_NAMESPACE
  69632. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69633. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69634. BEGIN_JUCE_NAMESPACE
  69635. DrawableComposite::DrawableComposite()
  69636. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69637. {
  69638. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69639. RelativeCoordinate (100.0),
  69640. RelativeCoordinate (0.0),
  69641. RelativeCoordinate (100.0)));
  69642. }
  69643. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69644. {
  69645. bounds = other.bounds;
  69646. for (int i = 0; i < other.drawables.size(); ++i)
  69647. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69648. markersX.addCopiesOf (other.markersX);
  69649. markersY.addCopiesOf (other.markersY);
  69650. }
  69651. DrawableComposite::~DrawableComposite()
  69652. {
  69653. }
  69654. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69655. {
  69656. if (drawable != 0)
  69657. {
  69658. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69659. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69660. drawables.insert (index, drawable);
  69661. drawable->parent = this;
  69662. }
  69663. }
  69664. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69665. {
  69666. insertDrawable (drawable.createCopy(), index);
  69667. }
  69668. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69669. {
  69670. drawables.remove (index, deleteDrawable);
  69671. }
  69672. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69673. {
  69674. for (int i = drawables.size(); --i >= 0;)
  69675. if (drawables.getUnchecked(i)->getName() == name)
  69676. return drawables.getUnchecked(i);
  69677. return 0;
  69678. }
  69679. void DrawableComposite::bringToFront (const int index)
  69680. {
  69681. if (index >= 0 && index < drawables.size() - 1)
  69682. drawables.move (index, -1);
  69683. }
  69684. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69685. {
  69686. bounds = newBoundingBox;
  69687. }
  69688. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69689. : name (other.name), position (other.position)
  69690. {
  69691. }
  69692. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69693. : name (name_), position (position_)
  69694. {
  69695. }
  69696. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69697. {
  69698. return name != other.name || position != other.position;
  69699. }
  69700. const char* const DrawableComposite::contentLeftMarkerName = "left";
  69701. const char* const DrawableComposite::contentRightMarkerName = "right";
  69702. const char* const DrawableComposite::contentTopMarkerName = "top";
  69703. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  69704. const RelativeRectangle DrawableComposite::getContentArea() const
  69705. {
  69706. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69707. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69708. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69709. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69710. }
  69711. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69712. {
  69713. setMarker (contentLeftMarkerName, true, newArea.left);
  69714. setMarker (contentRightMarkerName, true, newArea.right);
  69715. setMarker (contentTopMarkerName, false, newArea.top);
  69716. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69717. }
  69718. void DrawableComposite::resetBoundingBoxToContentArea()
  69719. {
  69720. const RelativeRectangle content (getContentArea());
  69721. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69722. RelativePoint (content.right, content.top),
  69723. RelativePoint (content.left, content.bottom)));
  69724. }
  69725. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69726. {
  69727. const Rectangle<float> bounds (getUntransformedBounds (false));
  69728. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69729. RelativeCoordinate (bounds.getRight()),
  69730. RelativeCoordinate (bounds.getY()),
  69731. RelativeCoordinate (bounds.getBottom())));
  69732. resetBoundingBoxToContentArea();
  69733. }
  69734. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69735. {
  69736. return (xAxis ? markersX : markersY).size();
  69737. }
  69738. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69739. {
  69740. return (xAxis ? markersX : markersY) [index];
  69741. }
  69742. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69743. {
  69744. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69745. for (int i = 0; i < markers.size(); ++i)
  69746. {
  69747. Marker* const m = markers.getUnchecked(i);
  69748. if (m->name == name)
  69749. {
  69750. if (m->position != position)
  69751. {
  69752. m->position = position;
  69753. invalidatePoints();
  69754. }
  69755. return;
  69756. }
  69757. }
  69758. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69759. invalidatePoints();
  69760. }
  69761. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69762. {
  69763. jassert (index >= 2);
  69764. if (index >= 2)
  69765. (xAxis ? markersX : markersY).remove (index);
  69766. }
  69767. const AffineTransform DrawableComposite::calculateTransform() const
  69768. {
  69769. Point<float> resolved[3];
  69770. bounds.resolveThreePoints (resolved, parent);
  69771. const Rectangle<float> content (getContentArea().resolve (parent));
  69772. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69773. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69774. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69775. }
  69776. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69777. {
  69778. if (drawables.size() > 0 && context.opacity > 0)
  69779. {
  69780. if (context.opacity >= 1.0f || drawables.size() == 1)
  69781. {
  69782. Drawable::RenderingContext contextCopy (context);
  69783. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69784. for (int i = 0; i < drawables.size(); ++i)
  69785. drawables.getUnchecked(i)->render (contextCopy);
  69786. }
  69787. else
  69788. {
  69789. // To correctly render a whole composite layer with an overall transparency,
  69790. // we need to render everything opaquely into a temp buffer, then blend that
  69791. // with the target opacity...
  69792. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69793. if (! clipBounds.isEmpty())
  69794. {
  69795. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69796. {
  69797. Graphics tempG (tempImage);
  69798. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69799. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69800. render (tempContext);
  69801. }
  69802. context.g.setOpacity (context.opacity);
  69803. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69804. }
  69805. }
  69806. }
  69807. }
  69808. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69809. {
  69810. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69811. int i;
  69812. for (i = 0; i < markersX.size(); ++i)
  69813. {
  69814. Marker* const m = markersX.getUnchecked(i);
  69815. if (m->name == symbol)
  69816. return m->position.getExpression();
  69817. }
  69818. for (i = 0; i < markersY.size(); ++i)
  69819. {
  69820. Marker* const m = markersY.getUnchecked(i);
  69821. if (m->name == symbol)
  69822. return m->position.getExpression();
  69823. }
  69824. throw Expression::EvaluationError (symbol, member);
  69825. }
  69826. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69827. {
  69828. Rectangle<float> bounds;
  69829. int i;
  69830. for (i = 0; i < drawables.size(); ++i)
  69831. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69832. if (includeMarkers)
  69833. {
  69834. if (markersX.size() > 0)
  69835. {
  69836. float minX = std::numeric_limits<float>::max();
  69837. float maxX = std::numeric_limits<float>::min();
  69838. for (i = markersX.size(); --i >= 0;)
  69839. {
  69840. const Marker* m = markersX.getUnchecked(i);
  69841. const float pos = (float) m->position.resolve (this);
  69842. minX = jmin (minX, pos);
  69843. maxX = jmax (maxX, pos);
  69844. }
  69845. if (minX <= maxX)
  69846. {
  69847. if (bounds.getHeight() > 0)
  69848. {
  69849. minX = jmin (minX, bounds.getX());
  69850. maxX = jmax (maxX, bounds.getRight());
  69851. }
  69852. bounds.setLeft (minX);
  69853. bounds.setWidth (maxX - minX);
  69854. }
  69855. }
  69856. if (markersY.size() > 0)
  69857. {
  69858. float minY = std::numeric_limits<float>::max();
  69859. float maxY = std::numeric_limits<float>::min();
  69860. for (i = markersY.size(); --i >= 0;)
  69861. {
  69862. const Marker* m = markersY.getUnchecked(i);
  69863. const float pos = (float) m->position.resolve (this);
  69864. minY = jmin (minY, pos);
  69865. maxY = jmax (maxY, pos);
  69866. }
  69867. if (minY <= maxY)
  69868. {
  69869. if (bounds.getHeight() > 0)
  69870. {
  69871. minY = jmin (minY, bounds.getY());
  69872. maxY = jmax (maxY, bounds.getBottom());
  69873. }
  69874. bounds.setTop (minY);
  69875. bounds.setHeight (maxY - minY);
  69876. }
  69877. }
  69878. }
  69879. return bounds;
  69880. }
  69881. const Rectangle<float> DrawableComposite::getBounds() const
  69882. {
  69883. return getUntransformedBounds (true).transformed (calculateTransform());
  69884. }
  69885. bool DrawableComposite::hitTest (float x, float y) const
  69886. {
  69887. calculateTransform().inverted().transformPoint (x, y);
  69888. for (int i = 0; i < drawables.size(); ++i)
  69889. if (drawables.getUnchecked(i)->hitTest (x, y))
  69890. return true;
  69891. return false;
  69892. }
  69893. Drawable* DrawableComposite::createCopy() const
  69894. {
  69895. return new DrawableComposite (*this);
  69896. }
  69897. void DrawableComposite::invalidatePoints()
  69898. {
  69899. for (int i = 0; i < drawables.size(); ++i)
  69900. drawables.getUnchecked(i)->invalidatePoints();
  69901. }
  69902. const Identifier DrawableComposite::valueTreeType ("Group");
  69903. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69904. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69905. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69906. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69907. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69908. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69909. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69910. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69911. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69912. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69913. : ValueTreeWrapperBase (state_)
  69914. {
  69915. jassert (state.hasType (valueTreeType));
  69916. }
  69917. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69918. {
  69919. return state.getChildWithName (childGroupTag);
  69920. }
  69921. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69922. {
  69923. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69924. }
  69925. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69926. {
  69927. return getChildList().getNumChildren();
  69928. }
  69929. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69930. {
  69931. return getChildList().getChild (index);
  69932. }
  69933. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69934. {
  69935. if (getID() == objectId)
  69936. return state;
  69937. if (! recursive)
  69938. {
  69939. return getChildList().getChildWithProperty (idProperty, objectId);
  69940. }
  69941. else
  69942. {
  69943. const ValueTree childList (getChildList());
  69944. for (int i = getNumDrawables(); --i >= 0;)
  69945. {
  69946. const ValueTree& child = childList.getChild (i);
  69947. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69948. return child;
  69949. if (child.hasType (DrawableComposite::valueTreeType))
  69950. {
  69951. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69952. if (v.isValid())
  69953. return v;
  69954. }
  69955. }
  69956. return ValueTree::invalid;
  69957. }
  69958. }
  69959. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69960. {
  69961. return getChildList().indexOf (item);
  69962. }
  69963. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69964. {
  69965. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69966. }
  69967. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69968. {
  69969. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69970. }
  69971. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69972. {
  69973. getChildList().removeChild (child, undoManager);
  69974. }
  69975. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69976. {
  69977. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69978. state.getProperty (topRight, "100, 0"),
  69979. state.getProperty (bottomLeft, "0, 100"));
  69980. }
  69981. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69982. {
  69983. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69984. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69985. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69986. }
  69987. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69988. {
  69989. const RelativeRectangle content (getContentArea());
  69990. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69991. RelativePoint (content.right, content.top),
  69992. RelativePoint (content.left, content.bottom)), undoManager);
  69993. }
  69994. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  69995. {
  69996. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  69997. getMarker (true, getMarkerState (true, 1)).position,
  69998. getMarker (false, getMarkerState (false, 0)).position,
  69999. getMarker (false, getMarkerState (false, 1)).position);
  70000. }
  70001. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70002. {
  70003. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  70004. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  70005. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  70006. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70007. }
  70008. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70009. {
  70010. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70011. }
  70012. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70013. {
  70014. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70015. }
  70016. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  70017. {
  70018. return getMarkerList (xAxis).getNumChildren();
  70019. }
  70020. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  70021. {
  70022. return getMarkerList (xAxis).getChild (index);
  70023. }
  70024. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  70025. {
  70026. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  70027. }
  70028. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  70029. {
  70030. return state.isAChildOf (getMarkerList (xAxis));
  70031. }
  70032. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  70033. {
  70034. (void) xAxis;
  70035. jassert (containsMarker (xAxis, state));
  70036. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  70037. }
  70038. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  70039. {
  70040. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  70041. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  70042. if (marker.isValid())
  70043. {
  70044. marker.setProperty (posProperty, m.position.toString(), undoManager);
  70045. }
  70046. else
  70047. {
  70048. marker = ValueTree (markerTag);
  70049. marker.setProperty (nameProperty, m.name, 0);
  70050. marker.setProperty (posProperty, m.position.toString(), 0);
  70051. markerList.addChild (marker, -1, undoManager);
  70052. }
  70053. }
  70054. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70055. {
  70056. if (state [nameProperty].toString() != contentLeftMarkerName
  70057. && state [nameProperty].toString() != contentRightMarkerName
  70058. && state [nameProperty].toString() != contentTopMarkerName
  70059. && state [nameProperty].toString() != contentBottomMarkerName)
  70060. getMarkerList (xAxis).removeChild (state, undoManager);
  70061. }
  70062. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70063. {
  70064. const ValueTreeWrapper wrapper (tree);
  70065. setName (wrapper.getID());
  70066. Rectangle<float> damage;
  70067. bool redrawAll = false;
  70068. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70069. if (bounds != newBounds)
  70070. {
  70071. redrawAll = true;
  70072. damage = getBounds();
  70073. bounds = newBounds;
  70074. }
  70075. const int numMarkersX = wrapper.getNumMarkers (true);
  70076. const int numMarkersY = wrapper.getNumMarkers (false);
  70077. // Remove deleted markers...
  70078. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70079. {
  70080. if (! redrawAll)
  70081. {
  70082. redrawAll = true;
  70083. damage = getBounds();
  70084. }
  70085. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70086. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70087. }
  70088. // Update markers and add new ones..
  70089. int i;
  70090. for (i = 0; i < numMarkersX; ++i)
  70091. {
  70092. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70093. Marker* m = markersX[i];
  70094. if (m == 0 || newMarker != *m)
  70095. {
  70096. if (! redrawAll)
  70097. {
  70098. redrawAll = true;
  70099. damage = getBounds();
  70100. }
  70101. if (m == 0)
  70102. markersX.add (new Marker (newMarker));
  70103. else
  70104. *m = newMarker;
  70105. }
  70106. }
  70107. for (i = 0; i < numMarkersY; ++i)
  70108. {
  70109. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70110. Marker* m = markersY[i];
  70111. if (m == 0 || newMarker != *m)
  70112. {
  70113. if (! redrawAll)
  70114. {
  70115. redrawAll = true;
  70116. damage = getBounds();
  70117. }
  70118. if (m == 0)
  70119. markersY.add (new Marker (newMarker));
  70120. else
  70121. *m = newMarker;
  70122. }
  70123. }
  70124. // Remove deleted drawables..
  70125. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  70126. {
  70127. Drawable* const d = drawables.getUnchecked(i);
  70128. if (! redrawAll)
  70129. damage = damage.getUnion (d->getBounds());
  70130. d->parent = 0;
  70131. drawables.remove (i);
  70132. }
  70133. // Update drawables and add new ones..
  70134. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70135. {
  70136. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70137. Drawable* d = drawables[i];
  70138. if (d != 0)
  70139. {
  70140. if (newDrawable.hasType (d->getValueTreeType()))
  70141. {
  70142. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  70143. if (! redrawAll)
  70144. damage = damage.getUnion (area);
  70145. }
  70146. else
  70147. {
  70148. if (! redrawAll)
  70149. damage = damage.getUnion (d->getBounds());
  70150. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70151. drawables.set (i, d);
  70152. if (! redrawAll)
  70153. damage = damage.getUnion (d->getBounds());
  70154. }
  70155. }
  70156. else
  70157. {
  70158. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70159. drawables.set (i, d);
  70160. if (! redrawAll)
  70161. damage = damage.getUnion (d->getBounds());
  70162. }
  70163. }
  70164. invalidatePoints();
  70165. if (redrawAll)
  70166. damage = damage.getUnion (getBounds());
  70167. else if (! damage.isEmpty())
  70168. damage = damage.transformed (calculateTransform());
  70169. return damage;
  70170. }
  70171. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70172. {
  70173. ValueTree tree (valueTreeType);
  70174. ValueTreeWrapper v (tree);
  70175. v.setID (getName(), 0);
  70176. v.setBoundingBox (bounds, 0);
  70177. int i;
  70178. for (i = 0; i < drawables.size(); ++i)
  70179. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70180. for (i = 0; i < markersX.size(); ++i)
  70181. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70182. for (i = 0; i < markersY.size(); ++i)
  70183. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70184. return tree;
  70185. }
  70186. END_JUCE_NAMESPACE
  70187. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70188. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70189. BEGIN_JUCE_NAMESPACE
  70190. DrawableImage::DrawableImage()
  70191. : image (0),
  70192. opacity (1.0f),
  70193. overlayColour (0x00000000)
  70194. {
  70195. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70196. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70197. }
  70198. DrawableImage::DrawableImage (const DrawableImage& other)
  70199. : image (other.image),
  70200. opacity (other.opacity),
  70201. overlayColour (other.overlayColour),
  70202. bounds (other.bounds)
  70203. {
  70204. }
  70205. DrawableImage::~DrawableImage()
  70206. {
  70207. }
  70208. void DrawableImage::setImage (const Image& imageToUse)
  70209. {
  70210. image = imageToUse;
  70211. if (image.isValid())
  70212. {
  70213. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70214. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70215. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70216. }
  70217. }
  70218. void DrawableImage::setOpacity (const float newOpacity)
  70219. {
  70220. opacity = newOpacity;
  70221. }
  70222. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70223. {
  70224. overlayColour = newOverlayColour;
  70225. }
  70226. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70227. {
  70228. bounds = newBounds;
  70229. }
  70230. const AffineTransform DrawableImage::calculateTransform() const
  70231. {
  70232. if (image.isNull())
  70233. return AffineTransform::identity;
  70234. Point<float> resolved[3];
  70235. bounds.resolveThreePoints (resolved, parent);
  70236. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70237. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70238. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70239. tr.getX(), tr.getY(),
  70240. bl.getX(), bl.getY());
  70241. }
  70242. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70243. {
  70244. if (image.isValid())
  70245. {
  70246. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70247. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70248. {
  70249. context.g.setOpacity (context.opacity * opacity);
  70250. context.g.drawImageTransformed (image, t, false);
  70251. }
  70252. if (! overlayColour.isTransparent())
  70253. {
  70254. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70255. context.g.drawImageTransformed (image, t, true);
  70256. }
  70257. }
  70258. }
  70259. const Rectangle<float> DrawableImage::getBounds() const
  70260. {
  70261. if (image.isNull())
  70262. return Rectangle<float>();
  70263. return bounds.getBounds (parent);
  70264. }
  70265. bool DrawableImage::hitTest (float x, float y) const
  70266. {
  70267. if (image.isNull())
  70268. return false;
  70269. calculateTransform().inverted().transformPoint (x, y);
  70270. const int ix = roundToInt (x);
  70271. const int iy = roundToInt (y);
  70272. return ix >= 0
  70273. && iy >= 0
  70274. && ix < image.getWidth()
  70275. && iy < image.getHeight()
  70276. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70277. }
  70278. Drawable* DrawableImage::createCopy() const
  70279. {
  70280. return new DrawableImage (*this);
  70281. }
  70282. void DrawableImage::invalidatePoints()
  70283. {
  70284. }
  70285. const Identifier DrawableImage::valueTreeType ("Image");
  70286. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70287. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70288. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70289. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70290. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70291. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70292. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70293. : ValueTreeWrapperBase (state_)
  70294. {
  70295. jassert (state.hasType (valueTreeType));
  70296. }
  70297. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70298. {
  70299. return state [image];
  70300. }
  70301. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70302. {
  70303. return state.getPropertyAsValue (image, undoManager);
  70304. }
  70305. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70306. {
  70307. state.setProperty (image, newIdentifier, undoManager);
  70308. }
  70309. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70310. {
  70311. return (float) state.getProperty (opacity, 1.0);
  70312. }
  70313. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70314. {
  70315. if (! state.hasProperty (opacity))
  70316. state.setProperty (opacity, 1.0, undoManager);
  70317. return state.getPropertyAsValue (opacity, undoManager);
  70318. }
  70319. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70320. {
  70321. state.setProperty (opacity, newOpacity, undoManager);
  70322. }
  70323. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70324. {
  70325. return Colour (state [overlay].toString().getHexValue32());
  70326. }
  70327. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70328. {
  70329. if (newColour.isTransparent())
  70330. state.removeProperty (overlay, undoManager);
  70331. else
  70332. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70333. }
  70334. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70335. {
  70336. return state.getPropertyAsValue (overlay, undoManager);
  70337. }
  70338. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70339. {
  70340. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70341. state.getProperty (topRight, "100, 0"),
  70342. state.getProperty (bottomLeft, "0, 100"));
  70343. }
  70344. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70345. {
  70346. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70347. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70348. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70349. }
  70350. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70351. {
  70352. const ValueTreeWrapper controller (tree);
  70353. setName (controller.getID());
  70354. const float newOpacity = controller.getOpacity();
  70355. const Colour newOverlayColour (controller.getOverlayColour());
  70356. Image newImage;
  70357. const var imageIdentifier (controller.getImageIdentifier());
  70358. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70359. if (imageProvider != 0)
  70360. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70361. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70362. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70363. {
  70364. const Rectangle<float> damage (getBounds());
  70365. opacity = newOpacity;
  70366. overlayColour = newOverlayColour;
  70367. bounds = newBounds;
  70368. image = newImage;
  70369. return damage.getUnion (getBounds());
  70370. }
  70371. return Rectangle<float>();
  70372. }
  70373. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70374. {
  70375. ValueTree tree (valueTreeType);
  70376. ValueTreeWrapper v (tree);
  70377. v.setID (getName(), 0);
  70378. v.setOpacity (opacity, 0);
  70379. v.setOverlayColour (overlayColour, 0);
  70380. v.setBoundingBox (bounds, 0);
  70381. if (image.isValid())
  70382. {
  70383. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70384. if (imageProvider != 0)
  70385. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70386. }
  70387. return tree;
  70388. }
  70389. END_JUCE_NAMESPACE
  70390. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70391. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70392. BEGIN_JUCE_NAMESPACE
  70393. DrawablePath::DrawablePath()
  70394. {
  70395. }
  70396. DrawablePath::DrawablePath (const DrawablePath& other)
  70397. : DrawableShape (other)
  70398. {
  70399. if (other.relativePath != 0)
  70400. relativePath = new RelativePointPath (*other.relativePath);
  70401. else
  70402. cachedPath = other.cachedPath;
  70403. }
  70404. DrawablePath::~DrawablePath()
  70405. {
  70406. }
  70407. Drawable* DrawablePath::createCopy() const
  70408. {
  70409. return new DrawablePath (*this);
  70410. }
  70411. void DrawablePath::setPath (const Path& newPath)
  70412. {
  70413. cachedPath = newPath;
  70414. strokeChanged();
  70415. }
  70416. const Path& DrawablePath::getPath() const
  70417. {
  70418. return getCachedPath();
  70419. }
  70420. const Path& DrawablePath::getStrokePath() const
  70421. {
  70422. return getCachedStrokePath();
  70423. }
  70424. bool DrawablePath::rebuildPath (Path& path) const
  70425. {
  70426. if (relativePath != 0)
  70427. {
  70428. path.clear();
  70429. relativePath->createPath (path, parent);
  70430. return true;
  70431. }
  70432. return false;
  70433. }
  70434. const Identifier DrawablePath::valueTreeType ("Path");
  70435. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70436. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70437. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70438. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70439. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70440. : FillAndStrokeState (state_)
  70441. {
  70442. jassert (state.hasType (valueTreeType));
  70443. }
  70444. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70445. {
  70446. return state.getOrCreateChildWithName (path, 0);
  70447. }
  70448. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70449. {
  70450. return state [nonZeroWinding];
  70451. }
  70452. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70453. {
  70454. state.setProperty (nonZeroWinding, b, undoManager);
  70455. }
  70456. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70457. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70458. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70459. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70460. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70461. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70462. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70463. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70464. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70465. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70466. : state (state_)
  70467. {
  70468. }
  70469. DrawablePath::ValueTreeWrapper::Element::~Element()
  70470. {
  70471. }
  70472. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70473. {
  70474. return ValueTreeWrapper (state.getParent().getParent());
  70475. }
  70476. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70477. {
  70478. return Element (state.getSibling (-1));
  70479. }
  70480. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70481. {
  70482. const Identifier i (state.getType());
  70483. if (i == startSubPathElement || i == lineToElement) return 1;
  70484. if (i == quadraticToElement) return 2;
  70485. if (i == cubicToElement) return 3;
  70486. return 0;
  70487. }
  70488. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70489. {
  70490. jassert (index >= 0 && index < getNumControlPoints());
  70491. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70492. }
  70493. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70494. {
  70495. jassert (index >= 0 && index < getNumControlPoints());
  70496. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70497. }
  70498. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70499. {
  70500. jassert (index >= 0 && index < getNumControlPoints());
  70501. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70502. }
  70503. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70504. {
  70505. const Identifier i (state.getType());
  70506. if (i == startSubPathElement)
  70507. return getControlPoint (0);
  70508. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70509. return getPreviousElement().getEndPoint();
  70510. }
  70511. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70512. {
  70513. const Identifier i (state.getType());
  70514. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70515. if (i == quadraticToElement) return getControlPoint (1);
  70516. if (i == cubicToElement) return getControlPoint (2);
  70517. jassert (i == closeSubPathElement);
  70518. return RelativePoint();
  70519. }
  70520. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70521. {
  70522. const Identifier i (state.getType());
  70523. if (i == lineToElement || i == closeSubPathElement)
  70524. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70525. if (i == cubicToElement)
  70526. {
  70527. Path p;
  70528. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70529. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70530. return p.getLength();
  70531. }
  70532. if (i == quadraticToElement)
  70533. {
  70534. Path p;
  70535. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70536. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70537. return p.getLength();
  70538. }
  70539. jassert (i == startSubPathElement);
  70540. return 0;
  70541. }
  70542. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70543. {
  70544. return state [mode].toString();
  70545. }
  70546. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70547. {
  70548. if (state.hasType (cubicToElement))
  70549. state.setProperty (mode, newMode, undoManager);
  70550. }
  70551. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70552. {
  70553. const Identifier i (state.getType());
  70554. if (i == quadraticToElement || i == cubicToElement)
  70555. {
  70556. ValueTree newState (lineToElement);
  70557. Element e (newState);
  70558. e.setControlPoint (0, getEndPoint(), undoManager);
  70559. state = newState;
  70560. }
  70561. }
  70562. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70563. {
  70564. const Identifier i (state.getType());
  70565. if (i == lineToElement || i == quadraticToElement)
  70566. {
  70567. ValueTree newState (cubicToElement);
  70568. Element e (newState);
  70569. const RelativePoint start (getStartPoint());
  70570. const RelativePoint end (getEndPoint());
  70571. const Point<float> startResolved (start.resolve (nameFinder));
  70572. const Point<float> endResolved (end.resolve (nameFinder));
  70573. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70574. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70575. e.setControlPoint (2, end, undoManager);
  70576. state = newState;
  70577. }
  70578. }
  70579. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70580. {
  70581. const Identifier i (state.getType());
  70582. if (i != startSubPathElement)
  70583. {
  70584. ValueTree newState (startSubPathElement);
  70585. Element e (newState);
  70586. e.setControlPoint (0, getEndPoint(), undoManager);
  70587. state = newState;
  70588. }
  70589. }
  70590. namespace DrawablePathHelpers
  70591. {
  70592. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70593. {
  70594. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70595. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70596. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70597. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70598. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70599. return newCp1 + (newCp2 - newCp1) * proportion;
  70600. }
  70601. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70602. {
  70603. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70604. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70605. return mid1 + (mid2 - mid1) * proportion;
  70606. }
  70607. }
  70608. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70609. {
  70610. using namespace DrawablePathHelpers;
  70611. const Identifier i (state.getType());
  70612. float bestProp = 0;
  70613. if (i == cubicToElement)
  70614. {
  70615. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70616. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70617. float bestDistance = std::numeric_limits<float>::max();
  70618. for (int i = 110; --i >= 0;)
  70619. {
  70620. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70621. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70622. const float distance = centre.getDistanceFrom (targetPoint);
  70623. if (distance < bestDistance)
  70624. {
  70625. bestProp = prop;
  70626. bestDistance = distance;
  70627. }
  70628. }
  70629. }
  70630. else if (i == quadraticToElement)
  70631. {
  70632. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70633. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70634. float bestDistance = std::numeric_limits<float>::max();
  70635. for (int i = 110; --i >= 0;)
  70636. {
  70637. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70638. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70639. const float distance = centre.getDistanceFrom (targetPoint);
  70640. if (distance < bestDistance)
  70641. {
  70642. bestProp = prop;
  70643. bestDistance = distance;
  70644. }
  70645. }
  70646. }
  70647. else if (i == lineToElement)
  70648. {
  70649. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70650. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70651. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70652. }
  70653. return bestProp;
  70654. }
  70655. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70656. {
  70657. ValueTree newTree;
  70658. const Identifier i (state.getType());
  70659. if (i == cubicToElement)
  70660. {
  70661. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70662. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70663. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70664. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70665. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70666. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70667. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70668. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70669. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70670. setControlPoint (0, mid1, undoManager);
  70671. setControlPoint (1, newCp1, undoManager);
  70672. setControlPoint (2, newCentre, undoManager);
  70673. setModeOfEndPoint (roundedMode, undoManager);
  70674. Element newElement (newTree = ValueTree (cubicToElement));
  70675. newElement.setControlPoint (0, newCp2, 0);
  70676. newElement.setControlPoint (1, mid3, 0);
  70677. newElement.setControlPoint (2, rp4, 0);
  70678. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70679. }
  70680. else if (i == quadraticToElement)
  70681. {
  70682. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70683. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70684. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70685. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70686. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70687. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70688. setControlPoint (0, mid1, undoManager);
  70689. setControlPoint (1, newCentre, undoManager);
  70690. setModeOfEndPoint (roundedMode, undoManager);
  70691. Element newElement (newTree = ValueTree (quadraticToElement));
  70692. newElement.setControlPoint (0, mid2, 0);
  70693. newElement.setControlPoint (1, rp3, 0);
  70694. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70695. }
  70696. else if (i == lineToElement)
  70697. {
  70698. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70699. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70700. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70701. setControlPoint (0, newPoint, undoManager);
  70702. Element newElement (newTree = ValueTree (lineToElement));
  70703. newElement.setControlPoint (0, rp2, 0);
  70704. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70705. }
  70706. else if (i == closeSubPathElement)
  70707. {
  70708. }
  70709. return newTree;
  70710. }
  70711. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70712. {
  70713. state.getParent().removeChild (state, undoManager);
  70714. }
  70715. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70716. {
  70717. Rectangle<float> damageRect;
  70718. ValueTreeWrapper v (tree);
  70719. setName (v.getID());
  70720. bool needsRedraw = refreshFillTypes (v, parent, imageProvider);
  70721. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70722. Path newPath;
  70723. newRelativePath->createPath (newPath, parent);
  70724. if (! newRelativePath->containsAnyDynamicPoints())
  70725. newRelativePath = 0;
  70726. const PathStrokeType newStroke (v.getStrokeType());
  70727. if (strokeType != newStroke || cachedPath != newPath)
  70728. {
  70729. damageRect = getBounds();
  70730. cachedPath.swapWithPath (newPath);
  70731. strokeChanged();
  70732. strokeType = newStroke;
  70733. needsRedraw = true;
  70734. }
  70735. relativePath = newRelativePath;
  70736. if (needsRedraw)
  70737. damageRect = damageRect.getUnion (getBounds());
  70738. return damageRect;
  70739. }
  70740. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70741. {
  70742. ValueTree tree (valueTreeType);
  70743. ValueTreeWrapper v (tree);
  70744. v.setID (getName(), 0);
  70745. writeTo (v, imageProvider, 0);
  70746. if (relativePath != 0)
  70747. {
  70748. relativePath->writeTo (tree, 0);
  70749. }
  70750. else
  70751. {
  70752. RelativePointPath rp (getCachedPath());
  70753. rp.writeTo (tree, 0);
  70754. }
  70755. return tree;
  70756. }
  70757. END_JUCE_NAMESPACE
  70758. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70759. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70760. BEGIN_JUCE_NAMESPACE
  70761. DrawableRectangle::DrawableRectangle()
  70762. {
  70763. }
  70764. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70765. : DrawableShape (other)
  70766. {
  70767. }
  70768. DrawableRectangle::~DrawableRectangle()
  70769. {
  70770. }
  70771. Drawable* DrawableRectangle::createCopy() const
  70772. {
  70773. return new DrawableRectangle (*this);
  70774. }
  70775. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70776. {
  70777. bounds = newBounds;
  70778. pathChanged();
  70779. strokeChanged();
  70780. }
  70781. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70782. {
  70783. cornerSize = newSize;
  70784. pathChanged();
  70785. strokeChanged();
  70786. }
  70787. bool DrawableRectangle::rebuildPath (Path& path) const
  70788. {
  70789. Point<float> points[3];
  70790. bounds.resolveThreePoints (points, parent);
  70791. const float w = Line<float> (points[0], points[1]).getLength();
  70792. const float h = Line<float> (points[0], points[2]).getLength();
  70793. const float cornerSizeX = (float) cornerSize.x.resolve (parent);
  70794. const float cornerSizeY = (float) cornerSize.y.resolve (parent);
  70795. path.clear();
  70796. if (cornerSizeX > 0 && cornerSizeY > 0)
  70797. path.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70798. else
  70799. path.addRectangle (0, 0, w, h);
  70800. path.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70801. w, 0, points[1].getX(), points[1].getY(),
  70802. 0, h, points[2].getX(), points[2].getY()));
  70803. return true;
  70804. }
  70805. const AffineTransform DrawableRectangle::calculateTransform() const
  70806. {
  70807. Point<float> resolved[3];
  70808. bounds.resolveThreePoints (resolved, parent);
  70809. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70810. resolved[1].getX(), resolved[1].getY(),
  70811. resolved[2].getX(), resolved[2].getY());
  70812. }
  70813. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70814. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70815. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70816. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70817. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70818. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70819. : FillAndStrokeState (state_)
  70820. {
  70821. jassert (state.hasType (valueTreeType));
  70822. }
  70823. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70824. {
  70825. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70826. state.getProperty (topRight, "100, 0"),
  70827. state.getProperty (bottomLeft, "0, 100"));
  70828. }
  70829. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70830. {
  70831. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70832. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70833. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70834. }
  70835. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70836. {
  70837. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70838. }
  70839. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70840. {
  70841. return RelativePoint (state [cornerSize]);
  70842. }
  70843. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70844. {
  70845. return state.getPropertyAsValue (cornerSize, undoManager);
  70846. }
  70847. const Rectangle<float> DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70848. {
  70849. Rectangle<float> damageRect;
  70850. ValueTreeWrapper v (tree);
  70851. setName (v.getID());
  70852. bool needsRedraw = refreshFillTypes (v, parent, imageProvider);
  70853. RelativeParallelogram newBounds (v.getRectangle());
  70854. const PathStrokeType newStroke (v.getStrokeType());
  70855. const RelativePoint newCornerSize (v.getCornerSize());
  70856. if (strokeType != newStroke || newBounds != bounds || newCornerSize != cornerSize)
  70857. {
  70858. damageRect = getBounds();
  70859. bounds = newBounds;
  70860. strokeType = newStroke;
  70861. cornerSize = newCornerSize;
  70862. pathChanged();
  70863. strokeChanged();
  70864. needsRedraw = true;
  70865. }
  70866. if (needsRedraw)
  70867. damageRect = damageRect.getUnion (getBounds());
  70868. return damageRect;
  70869. }
  70870. const ValueTree DrawableRectangle::createValueTree (ImageProvider* imageProvider) const
  70871. {
  70872. ValueTree tree (valueTreeType);
  70873. ValueTreeWrapper v (tree);
  70874. v.setID (getName(), 0);
  70875. writeTo (v, imageProvider, 0);
  70876. v.setRectangle (bounds, 0);
  70877. v.setCornerSize (cornerSize, 0);
  70878. return tree;
  70879. }
  70880. END_JUCE_NAMESPACE
  70881. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  70882. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70883. BEGIN_JUCE_NAMESPACE
  70884. DrawableText::DrawableText()
  70885. : colour (Colours::black),
  70886. justification (Justification::centredLeft)
  70887. {
  70888. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70889. RelativePoint (50.0f, 0.0f),
  70890. RelativePoint (0.0f, 20.0f)));
  70891. setFont (Font (15.0f), true);
  70892. }
  70893. DrawableText::DrawableText (const DrawableText& other)
  70894. : bounds (other.bounds),
  70895. fontSizeControlPoint (other.fontSizeControlPoint),
  70896. font (other.font),
  70897. text (other.text),
  70898. colour (other.colour),
  70899. justification (other.justification)
  70900. {
  70901. }
  70902. DrawableText::~DrawableText()
  70903. {
  70904. }
  70905. void DrawableText::setText (const String& newText)
  70906. {
  70907. text = newText;
  70908. }
  70909. void DrawableText::setColour (const Colour& newColour)
  70910. {
  70911. colour = newColour;
  70912. }
  70913. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70914. {
  70915. font = newFont;
  70916. if (applySizeAndScale)
  70917. {
  70918. Point<float> corners[3];
  70919. bounds.resolveThreePoints (corners, parent);
  70920. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70921. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70922. }
  70923. }
  70924. void DrawableText::setJustification (const Justification& newJustification)
  70925. {
  70926. justification = newJustification;
  70927. }
  70928. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70929. {
  70930. bounds = newBounds;
  70931. }
  70932. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70933. {
  70934. fontSizeControlPoint = newPoint;
  70935. }
  70936. void DrawableText::render (const Drawable::RenderingContext& context) const
  70937. {
  70938. Point<float> points[3];
  70939. bounds.resolveThreePoints (points, parent);
  70940. const float w = Line<float> (points[0], points[1]).getLength();
  70941. const float h = Line<float> (points[0], points[2]).getLength();
  70942. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  70943. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  70944. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  70945. Font f (font);
  70946. f.setHeight (fontHeight);
  70947. f.setHorizontalScale (fontWidth / fontHeight);
  70948. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  70949. GlyphArrangement ga;
  70950. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70951. ga.draw (context.g,
  70952. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70953. w, 0, points[1].getX(), points[1].getY(),
  70954. 0, h, points[2].getX(), points[2].getY())
  70955. .followedBy (context.transform));
  70956. }
  70957. const Rectangle<float> DrawableText::getBounds() const
  70958. {
  70959. return bounds.getBounds (parent);
  70960. }
  70961. bool DrawableText::hitTest (float x, float y) const
  70962. {
  70963. Path p;
  70964. bounds.getPath (p, parent);
  70965. return p.contains (x, y);
  70966. }
  70967. Drawable* DrawableText::createCopy() const
  70968. {
  70969. return new DrawableText (*this);
  70970. }
  70971. void DrawableText::invalidatePoints()
  70972. {
  70973. }
  70974. const Identifier DrawableText::valueTreeType ("Text");
  70975. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70976. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70977. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70978. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70979. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70980. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70981. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70982. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70983. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70984. : ValueTreeWrapperBase (state_)
  70985. {
  70986. jassert (state.hasType (valueTreeType));
  70987. }
  70988. const String DrawableText::ValueTreeWrapper::getText() const
  70989. {
  70990. return state [text].toString();
  70991. }
  70992. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  70993. {
  70994. state.setProperty (text, newText, undoManager);
  70995. }
  70996. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  70997. {
  70998. return state.getPropertyAsValue (text, undoManager);
  70999. }
  71000. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71001. {
  71002. return Colour::fromString (state [colour].toString());
  71003. }
  71004. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71005. {
  71006. state.setProperty (colour, newColour.toString(), undoManager);
  71007. }
  71008. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71009. {
  71010. return Justification ((int) state [justification]);
  71011. }
  71012. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71013. {
  71014. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71015. }
  71016. const Font DrawableText::ValueTreeWrapper::getFont() const
  71017. {
  71018. return Font::fromString (state [font]);
  71019. }
  71020. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71021. {
  71022. state.setProperty (font, newFont.toString(), undoManager);
  71023. }
  71024. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71025. {
  71026. return state.getPropertyAsValue (font, undoManager);
  71027. }
  71028. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71029. {
  71030. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71031. }
  71032. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71033. {
  71034. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71035. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71036. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71037. }
  71038. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71039. {
  71040. return state [fontSizeAnchor].toString();
  71041. }
  71042. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71043. {
  71044. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71045. }
  71046. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  71047. {
  71048. ValueTreeWrapper v (tree);
  71049. setName (v.getID());
  71050. const RelativeParallelogram newBounds (v.getBoundingBox());
  71051. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71052. const Colour newColour (v.getColour());
  71053. const Justification newJustification (v.getJustification());
  71054. const String newText (v.getText());
  71055. const Font newFont (v.getFont());
  71056. if (text != newText || font != newFont || justification != newJustification
  71057. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71058. {
  71059. const Rectangle<float> damage (getBounds());
  71060. setBoundingBox (newBounds);
  71061. setFontSizeControlPoint (newFontPoint);
  71062. setColour (newColour);
  71063. setFont (newFont, false);
  71064. setJustification (newJustification);
  71065. setText (newText);
  71066. return damage.getUnion (getBounds());
  71067. }
  71068. return Rectangle<float>();
  71069. }
  71070. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  71071. {
  71072. ValueTree tree (valueTreeType);
  71073. ValueTreeWrapper v (tree);
  71074. v.setID (getName(), 0);
  71075. v.setText (text, 0);
  71076. v.setFont (font, 0);
  71077. v.setJustification (justification, 0);
  71078. v.setColour (colour, 0);
  71079. v.setBoundingBox (bounds, 0);
  71080. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71081. return tree;
  71082. }
  71083. END_JUCE_NAMESPACE
  71084. /*** End of inlined file: juce_DrawableText.cpp ***/
  71085. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71086. BEGIN_JUCE_NAMESPACE
  71087. class SVGState
  71088. {
  71089. public:
  71090. SVGState (const XmlElement* const topLevel)
  71091. : topLevelXml (topLevel),
  71092. elementX (0), elementY (0),
  71093. width (512), height (512),
  71094. viewBoxW (0), viewBoxH (0)
  71095. {
  71096. }
  71097. ~SVGState()
  71098. {
  71099. }
  71100. Drawable* parseSVGElement (const XmlElement& xml)
  71101. {
  71102. if (! xml.hasTagName ("svg"))
  71103. return 0;
  71104. DrawableComposite* const drawable = new DrawableComposite();
  71105. drawable->setName (xml.getStringAttribute ("id"));
  71106. SVGState newState (*this);
  71107. if (xml.hasAttribute ("transform"))
  71108. newState.addTransform (xml);
  71109. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71110. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71111. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71112. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71113. if (xml.hasAttribute ("viewBox"))
  71114. {
  71115. const String viewParams (xml.getStringAttribute ("viewBox"));
  71116. int i = 0;
  71117. float vx, vy, vw, vh;
  71118. if (parseCoords (viewParams, vx, vy, i, true)
  71119. && parseCoords (viewParams, vw, vh, i, true)
  71120. && vw > 0
  71121. && vh > 0)
  71122. {
  71123. newState.viewBoxW = vw;
  71124. newState.viewBoxH = vh;
  71125. int placementFlags = 0;
  71126. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71127. if (aspect.containsIgnoreCase ("none"))
  71128. {
  71129. placementFlags = RectanglePlacement::stretchToFit;
  71130. }
  71131. else
  71132. {
  71133. if (aspect.containsIgnoreCase ("slice"))
  71134. placementFlags |= RectanglePlacement::fillDestination;
  71135. if (aspect.containsIgnoreCase ("xMin"))
  71136. placementFlags |= RectanglePlacement::xLeft;
  71137. else if (aspect.containsIgnoreCase ("xMax"))
  71138. placementFlags |= RectanglePlacement::xRight;
  71139. else
  71140. placementFlags |= RectanglePlacement::xMid;
  71141. if (aspect.containsIgnoreCase ("yMin"))
  71142. placementFlags |= RectanglePlacement::yTop;
  71143. else if (aspect.containsIgnoreCase ("yMax"))
  71144. placementFlags |= RectanglePlacement::yBottom;
  71145. else
  71146. placementFlags |= RectanglePlacement::yMid;
  71147. }
  71148. const RectanglePlacement placement (placementFlags);
  71149. newState.transform
  71150. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71151. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71152. .followedBy (newState.transform);
  71153. }
  71154. }
  71155. else
  71156. {
  71157. if (viewBoxW == 0)
  71158. newState.viewBoxW = newState.width;
  71159. if (viewBoxH == 0)
  71160. newState.viewBoxH = newState.height;
  71161. }
  71162. newState.parseSubElements (xml, drawable);
  71163. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71164. return drawable;
  71165. }
  71166. private:
  71167. const XmlElement* const topLevelXml;
  71168. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71169. AffineTransform transform;
  71170. String cssStyleText;
  71171. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71172. {
  71173. forEachXmlChildElement (xml, e)
  71174. {
  71175. Drawable* d = 0;
  71176. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71177. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71178. else if (e->hasTagName ("path")) d = parsePath (*e);
  71179. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71180. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71181. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71182. else if (e->hasTagName ("line")) d = parseLine (*e);
  71183. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71184. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71185. else if (e->hasTagName ("text")) d = parseText (*e);
  71186. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71187. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71188. parentDrawable->insertDrawable (d);
  71189. }
  71190. }
  71191. DrawableComposite* parseSwitch (const XmlElement& xml)
  71192. {
  71193. const XmlElement* const group = xml.getChildByName ("g");
  71194. if (group != 0)
  71195. return parseGroupElement (*group);
  71196. return 0;
  71197. }
  71198. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71199. {
  71200. DrawableComposite* const drawable = new DrawableComposite();
  71201. drawable->setName (xml.getStringAttribute ("id"));
  71202. if (xml.hasAttribute ("transform"))
  71203. {
  71204. SVGState newState (*this);
  71205. newState.addTransform (xml);
  71206. newState.parseSubElements (xml, drawable);
  71207. }
  71208. else
  71209. {
  71210. parseSubElements (xml, drawable);
  71211. }
  71212. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71213. return drawable;
  71214. }
  71215. Drawable* parsePath (const XmlElement& xml) const
  71216. {
  71217. const String d (xml.getStringAttribute ("d").trimStart());
  71218. Path path;
  71219. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71220. path.setUsingNonZeroWinding (false);
  71221. int index = 0;
  71222. float lastX = 0, lastY = 0;
  71223. float lastX2 = 0, lastY2 = 0;
  71224. juce_wchar lastCommandChar = 0;
  71225. bool isRelative = true;
  71226. bool carryOn = true;
  71227. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71228. while (d[index] != 0)
  71229. {
  71230. float x, y, x2, y2, x3, y3;
  71231. if (validCommandChars.containsChar (d[index]))
  71232. {
  71233. lastCommandChar = d [index++];
  71234. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71235. }
  71236. switch (lastCommandChar)
  71237. {
  71238. case 'M':
  71239. case 'm':
  71240. case 'L':
  71241. case 'l':
  71242. if (parseCoords (d, x, y, index, false))
  71243. {
  71244. if (isRelative)
  71245. {
  71246. x += lastX;
  71247. y += lastY;
  71248. }
  71249. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71250. {
  71251. path.startNewSubPath (x, y);
  71252. lastCommandChar = 'l';
  71253. }
  71254. else
  71255. path.lineTo (x, y);
  71256. lastX2 = lastX;
  71257. lastY2 = lastY;
  71258. lastX = x;
  71259. lastY = y;
  71260. }
  71261. else
  71262. {
  71263. ++index;
  71264. }
  71265. break;
  71266. case 'H':
  71267. case 'h':
  71268. if (parseCoord (d, x, index, false, true))
  71269. {
  71270. if (isRelative)
  71271. x += lastX;
  71272. path.lineTo (x, lastY);
  71273. lastX2 = lastX;
  71274. lastX = x;
  71275. }
  71276. else
  71277. {
  71278. ++index;
  71279. }
  71280. break;
  71281. case 'V':
  71282. case 'v':
  71283. if (parseCoord (d, y, index, false, false))
  71284. {
  71285. if (isRelative)
  71286. y += lastY;
  71287. path.lineTo (lastX, y);
  71288. lastY2 = lastY;
  71289. lastY = y;
  71290. }
  71291. else
  71292. {
  71293. ++index;
  71294. }
  71295. break;
  71296. case 'C':
  71297. case 'c':
  71298. if (parseCoords (d, x, y, index, false)
  71299. && parseCoords (d, x2, y2, index, false)
  71300. && parseCoords (d, x3, y3, index, false))
  71301. {
  71302. if (isRelative)
  71303. {
  71304. x += lastX;
  71305. y += lastY;
  71306. x2 += lastX;
  71307. y2 += lastY;
  71308. x3 += lastX;
  71309. y3 += lastY;
  71310. }
  71311. path.cubicTo (x, y, x2, y2, x3, y3);
  71312. lastX2 = x2;
  71313. lastY2 = y2;
  71314. lastX = x3;
  71315. lastY = y3;
  71316. }
  71317. else
  71318. {
  71319. ++index;
  71320. }
  71321. break;
  71322. case 'S':
  71323. case 's':
  71324. if (parseCoords (d, x, y, index, false)
  71325. && parseCoords (d, x3, y3, index, false))
  71326. {
  71327. if (isRelative)
  71328. {
  71329. x += lastX;
  71330. y += lastY;
  71331. x3 += lastX;
  71332. y3 += lastY;
  71333. }
  71334. x2 = lastX + (lastX - lastX2);
  71335. y2 = lastY + (lastY - lastY2);
  71336. path.cubicTo (x2, y2, x, y, x3, y3);
  71337. lastX2 = x;
  71338. lastY2 = y;
  71339. lastX = x3;
  71340. lastY = y3;
  71341. }
  71342. else
  71343. {
  71344. ++index;
  71345. }
  71346. break;
  71347. case 'Q':
  71348. case 'q':
  71349. if (parseCoords (d, x, y, index, false)
  71350. && parseCoords (d, x2, y2, index, false))
  71351. {
  71352. if (isRelative)
  71353. {
  71354. x += lastX;
  71355. y += lastY;
  71356. x2 += lastX;
  71357. y2 += lastY;
  71358. }
  71359. path.quadraticTo (x, y, x2, y2);
  71360. lastX2 = x;
  71361. lastY2 = y;
  71362. lastX = x2;
  71363. lastY = y2;
  71364. }
  71365. else
  71366. {
  71367. ++index;
  71368. }
  71369. break;
  71370. case 'T':
  71371. case 't':
  71372. if (parseCoords (d, x, y, index, false))
  71373. {
  71374. if (isRelative)
  71375. {
  71376. x += lastX;
  71377. y += lastY;
  71378. }
  71379. x2 = lastX + (lastX - lastX2);
  71380. y2 = lastY + (lastY - lastY2);
  71381. path.quadraticTo (x2, y2, x, y);
  71382. lastX2 = x2;
  71383. lastY2 = y2;
  71384. lastX = x;
  71385. lastY = y;
  71386. }
  71387. else
  71388. {
  71389. ++index;
  71390. }
  71391. break;
  71392. case 'A':
  71393. case 'a':
  71394. if (parseCoords (d, x, y, index, false))
  71395. {
  71396. String num;
  71397. if (parseNextNumber (d, num, index, false))
  71398. {
  71399. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71400. if (parseNextNumber (d, num, index, false))
  71401. {
  71402. const bool largeArc = num.getIntValue() != 0;
  71403. if (parseNextNumber (d, num, index, false))
  71404. {
  71405. const bool sweep = num.getIntValue() != 0;
  71406. if (parseCoords (d, x2, y2, index, false))
  71407. {
  71408. if (isRelative)
  71409. {
  71410. x2 += lastX;
  71411. y2 += lastY;
  71412. }
  71413. if (lastX != x2 || lastY != y2)
  71414. {
  71415. double centreX, centreY, startAngle, deltaAngle;
  71416. double rx = x, ry = y;
  71417. endpointToCentreParameters (lastX, lastY, x2, y2,
  71418. angle, largeArc, sweep,
  71419. rx, ry, centreX, centreY,
  71420. startAngle, deltaAngle);
  71421. path.addCentredArc ((float) centreX, (float) centreY,
  71422. (float) rx, (float) ry,
  71423. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71424. false);
  71425. path.lineTo (x2, y2);
  71426. }
  71427. lastX2 = lastX;
  71428. lastY2 = lastY;
  71429. lastX = x2;
  71430. lastY = y2;
  71431. }
  71432. }
  71433. }
  71434. }
  71435. }
  71436. else
  71437. {
  71438. ++index;
  71439. }
  71440. break;
  71441. case 'Z':
  71442. case 'z':
  71443. path.closeSubPath();
  71444. while (CharacterFunctions::isWhitespace (d [index]))
  71445. ++index;
  71446. break;
  71447. default:
  71448. carryOn = false;
  71449. break;
  71450. }
  71451. if (! carryOn)
  71452. break;
  71453. }
  71454. return parseShape (xml, path);
  71455. }
  71456. Drawable* parseRect (const XmlElement& xml) const
  71457. {
  71458. Path rect;
  71459. const bool hasRX = xml.hasAttribute ("rx");
  71460. const bool hasRY = xml.hasAttribute ("ry");
  71461. if (hasRX || hasRY)
  71462. {
  71463. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71464. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71465. if (! hasRX)
  71466. rx = ry;
  71467. else if (! hasRY)
  71468. ry = rx;
  71469. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71470. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71471. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71472. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71473. rx, ry);
  71474. }
  71475. else
  71476. {
  71477. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71478. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71479. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71480. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71481. }
  71482. return parseShape (xml, rect);
  71483. }
  71484. Drawable* parseCircle (const XmlElement& xml) const
  71485. {
  71486. Path circle;
  71487. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71488. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71489. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71490. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71491. return parseShape (xml, circle);
  71492. }
  71493. Drawable* parseEllipse (const XmlElement& xml) const
  71494. {
  71495. Path ellipse;
  71496. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71497. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71498. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71499. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71500. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71501. return parseShape (xml, ellipse);
  71502. }
  71503. Drawable* parseLine (const XmlElement& xml) const
  71504. {
  71505. Path line;
  71506. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71507. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71508. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71509. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71510. line.startNewSubPath (x1, y1);
  71511. line.lineTo (x2, y2);
  71512. return parseShape (xml, line);
  71513. }
  71514. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71515. {
  71516. const String points (xml.getStringAttribute ("points"));
  71517. Path path;
  71518. int index = 0;
  71519. float x, y;
  71520. if (parseCoords (points, x, y, index, true))
  71521. {
  71522. float firstX = x;
  71523. float firstY = y;
  71524. float lastX = 0, lastY = 0;
  71525. path.startNewSubPath (x, y);
  71526. while (parseCoords (points, x, y, index, true))
  71527. {
  71528. lastX = x;
  71529. lastY = y;
  71530. path.lineTo (x, y);
  71531. }
  71532. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71533. path.closeSubPath();
  71534. }
  71535. return parseShape (xml, path);
  71536. }
  71537. Drawable* parseShape (const XmlElement& xml, Path& path,
  71538. const bool shouldParseTransform = true) const
  71539. {
  71540. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71541. {
  71542. SVGState newState (*this);
  71543. newState.addTransform (xml);
  71544. return newState.parseShape (xml, path, false);
  71545. }
  71546. DrawablePath* dp = new DrawablePath();
  71547. dp->setName (xml.getStringAttribute ("id"));
  71548. dp->setFill (Colours::transparentBlack);
  71549. path.applyTransform (transform);
  71550. dp->setPath (path);
  71551. Path::Iterator iter (path);
  71552. bool containsClosedSubPath = false;
  71553. while (iter.next())
  71554. {
  71555. if (iter.elementType == Path::Iterator::closePath)
  71556. {
  71557. containsClosedSubPath = true;
  71558. break;
  71559. }
  71560. }
  71561. dp->setFill (getPathFillType (path,
  71562. getStyleAttribute (&xml, "fill"),
  71563. getStyleAttribute (&xml, "fill-opacity"),
  71564. getStyleAttribute (&xml, "opacity"),
  71565. containsClosedSubPath ? Colours::black
  71566. : Colours::transparentBlack));
  71567. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71568. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71569. {
  71570. dp->setStrokeFill (getPathFillType (path, strokeType,
  71571. getStyleAttribute (&xml, "stroke-opacity"),
  71572. getStyleAttribute (&xml, "opacity"),
  71573. Colours::transparentBlack));
  71574. dp->setStrokeType (getStrokeFor (&xml));
  71575. }
  71576. return dp;
  71577. }
  71578. const XmlElement* findLinkedElement (const XmlElement* e) const
  71579. {
  71580. const String id (e->getStringAttribute ("xlink:href"));
  71581. if (! id.startsWithChar ('#'))
  71582. return 0;
  71583. return findElementForId (topLevelXml, id.substring (1));
  71584. }
  71585. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71586. {
  71587. if (fillXml == 0)
  71588. return;
  71589. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71590. {
  71591. int index = 0;
  71592. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71593. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71594. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71595. double offset = e->getDoubleAttribute ("offset");
  71596. if (e->getStringAttribute ("offset").containsChar ('%'))
  71597. offset *= 0.01;
  71598. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71599. }
  71600. }
  71601. const FillType getPathFillType (const Path& path,
  71602. const String& fill,
  71603. const String& fillOpacity,
  71604. const String& overallOpacity,
  71605. const Colour& defaultColour) const
  71606. {
  71607. float opacity = 1.0f;
  71608. if (overallOpacity.isNotEmpty())
  71609. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71610. if (fillOpacity.isNotEmpty())
  71611. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71612. if (fill.startsWithIgnoreCase ("url"))
  71613. {
  71614. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71615. .upToLastOccurrenceOf (")", false, false).trim());
  71616. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71617. if (fillXml != 0
  71618. && (fillXml->hasTagName ("linearGradient")
  71619. || fillXml->hasTagName ("radialGradient")))
  71620. {
  71621. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71622. ColourGradient gradient;
  71623. addGradientStopsIn (gradient, inheritedFrom);
  71624. addGradientStopsIn (gradient, fillXml);
  71625. if (gradient.getNumColours() > 0)
  71626. {
  71627. gradient.addColour (0.0, gradient.getColour (0));
  71628. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71629. }
  71630. else
  71631. {
  71632. gradient.addColour (0.0, Colours::black);
  71633. gradient.addColour (1.0, Colours::black);
  71634. }
  71635. if (overallOpacity.isNotEmpty())
  71636. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71637. jassert (gradient.getNumColours() > 0);
  71638. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71639. float gradientWidth = viewBoxW;
  71640. float gradientHeight = viewBoxH;
  71641. float dx = 0.0f;
  71642. float dy = 0.0f;
  71643. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71644. if (! userSpace)
  71645. {
  71646. const Rectangle<float> bounds (path.getBounds());
  71647. dx = bounds.getX();
  71648. dy = bounds.getY();
  71649. gradientWidth = bounds.getWidth();
  71650. gradientHeight = bounds.getHeight();
  71651. }
  71652. if (gradient.isRadial)
  71653. {
  71654. if (userSpace)
  71655. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71656. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71657. else
  71658. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71659. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71660. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71661. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71662. //xxx (the fx, fy focal point isn't handled properly here..)
  71663. }
  71664. else
  71665. {
  71666. if (userSpace)
  71667. {
  71668. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71669. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71670. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71671. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71672. }
  71673. else
  71674. {
  71675. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71676. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71677. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71678. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71679. }
  71680. if (gradient.point1 == gradient.point2)
  71681. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71682. }
  71683. FillType type (gradient);
  71684. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71685. .followedBy (transform);
  71686. return type;
  71687. }
  71688. }
  71689. if (fill.equalsIgnoreCase ("none"))
  71690. return Colours::transparentBlack;
  71691. int i = 0;
  71692. const Colour colour (parseColour (fill, i, defaultColour));
  71693. return colour.withMultipliedAlpha (opacity);
  71694. }
  71695. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71696. {
  71697. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71698. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71699. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71700. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71701. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71702. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71703. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71704. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71705. if (join.equalsIgnoreCase ("round"))
  71706. joinStyle = PathStrokeType::curved;
  71707. else if (join.equalsIgnoreCase ("bevel"))
  71708. joinStyle = PathStrokeType::beveled;
  71709. if (cap.equalsIgnoreCase ("round"))
  71710. capStyle = PathStrokeType::rounded;
  71711. else if (cap.equalsIgnoreCase ("square"))
  71712. capStyle = PathStrokeType::square;
  71713. float ox = 0.0f, oy = 0.0f;
  71714. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71715. transform.transformPoints (ox, oy, x, y);
  71716. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71717. joinStyle, capStyle);
  71718. }
  71719. Drawable* parseText (const XmlElement& xml)
  71720. {
  71721. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71722. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71723. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71724. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71725. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71726. //xxx not done text yet!
  71727. forEachXmlChildElement (xml, e)
  71728. {
  71729. if (e->isTextElement())
  71730. {
  71731. const String text (e->getText());
  71732. Path path;
  71733. Drawable* s = parseShape (*e, path);
  71734. delete s; // xxx not finished!
  71735. }
  71736. else if (e->hasTagName ("tspan"))
  71737. {
  71738. Drawable* s = parseText (*e);
  71739. delete s; // xxx not finished!
  71740. }
  71741. }
  71742. return 0;
  71743. }
  71744. void addTransform (const XmlElement& xml)
  71745. {
  71746. transform = parseTransform (xml.getStringAttribute ("transform"))
  71747. .followedBy (transform);
  71748. }
  71749. bool parseCoord (const String& s, float& value, int& index,
  71750. const bool allowUnits, const bool isX) const
  71751. {
  71752. String number;
  71753. if (! parseNextNumber (s, number, index, allowUnits))
  71754. {
  71755. value = 0;
  71756. return false;
  71757. }
  71758. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71759. return true;
  71760. }
  71761. bool parseCoords (const String& s, float& x, float& y,
  71762. int& index, const bool allowUnits) const
  71763. {
  71764. return parseCoord (s, x, index, allowUnits, true)
  71765. && parseCoord (s, y, index, allowUnits, false);
  71766. }
  71767. float getCoordLength (const String& s, const float sizeForProportions) const
  71768. {
  71769. float n = s.getFloatValue();
  71770. const int len = s.length();
  71771. if (len > 2)
  71772. {
  71773. const float dpi = 96.0f;
  71774. const juce_wchar n1 = s [len - 2];
  71775. const juce_wchar n2 = s [len - 1];
  71776. if (n1 == 'i' && n2 == 'n')
  71777. n *= dpi;
  71778. else if (n1 == 'm' && n2 == 'm')
  71779. n *= dpi / 25.4f;
  71780. else if (n1 == 'c' && n2 == 'm')
  71781. n *= dpi / 2.54f;
  71782. else if (n1 == 'p' && n2 == 'c')
  71783. n *= 15.0f;
  71784. else if (n2 == '%')
  71785. n *= 0.01f * sizeForProportions;
  71786. }
  71787. return n;
  71788. }
  71789. void getCoordList (Array <float>& coords, const String& list,
  71790. const bool allowUnits, const bool isX) const
  71791. {
  71792. int index = 0;
  71793. float value;
  71794. while (parseCoord (list, value, index, allowUnits, isX))
  71795. coords.add (value);
  71796. }
  71797. void parseCSSStyle (const XmlElement& xml)
  71798. {
  71799. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71800. }
  71801. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71802. const String& defaultValue = String::empty) const
  71803. {
  71804. if (xml->hasAttribute (attributeName))
  71805. return xml->getStringAttribute (attributeName, defaultValue);
  71806. const String styleAtt (xml->getStringAttribute ("style"));
  71807. if (styleAtt.isNotEmpty())
  71808. {
  71809. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71810. if (value.isNotEmpty())
  71811. return value;
  71812. }
  71813. else if (xml->hasAttribute ("class"))
  71814. {
  71815. const String className ("." + xml->getStringAttribute ("class"));
  71816. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71817. if (index < 0)
  71818. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71819. if (index >= 0)
  71820. {
  71821. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71822. if (openBracket > index)
  71823. {
  71824. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71825. if (closeBracket > openBracket)
  71826. {
  71827. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71828. if (value.isNotEmpty())
  71829. return value;
  71830. }
  71831. }
  71832. }
  71833. }
  71834. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71835. if (xml != 0)
  71836. return getStyleAttribute (xml, attributeName, defaultValue);
  71837. return defaultValue;
  71838. }
  71839. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71840. {
  71841. if (xml->hasAttribute (attributeName))
  71842. return xml->getStringAttribute (attributeName);
  71843. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71844. if (xml != 0)
  71845. return getInheritedAttribute (xml, attributeName);
  71846. return String::empty;
  71847. }
  71848. static bool isIdentifierChar (const juce_wchar c)
  71849. {
  71850. return CharacterFunctions::isLetter (c) || c == '-';
  71851. }
  71852. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71853. {
  71854. int i = 0;
  71855. for (;;)
  71856. {
  71857. i = list.indexOf (i, attributeName);
  71858. if (i < 0)
  71859. break;
  71860. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71861. && ! isIdentifierChar (list [i + attributeName.length()]))
  71862. {
  71863. i = list.indexOfChar (i, ':');
  71864. if (i < 0)
  71865. break;
  71866. int end = list.indexOfChar (i, ';');
  71867. if (end < 0)
  71868. end = 0x7ffff;
  71869. return list.substring (i + 1, end).trim();
  71870. }
  71871. ++i;
  71872. }
  71873. return defaultValue;
  71874. }
  71875. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71876. {
  71877. const juce_wchar* const s = source;
  71878. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71879. ++index;
  71880. int start = index;
  71881. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71882. ++index;
  71883. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71884. ++index;
  71885. if ((s[index] == 'e' || s[index] == 'E')
  71886. && (CharacterFunctions::isDigit (s[index + 1])
  71887. || s[index + 1] == '-'
  71888. || s[index + 1] == '+'))
  71889. {
  71890. index += 2;
  71891. while (CharacterFunctions::isDigit (s[index]))
  71892. ++index;
  71893. }
  71894. if (allowUnits)
  71895. {
  71896. while (CharacterFunctions::isLetter (s[index]))
  71897. ++index;
  71898. }
  71899. if (index == start)
  71900. return false;
  71901. value = String (s + start, index - start);
  71902. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71903. ++index;
  71904. return true;
  71905. }
  71906. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71907. {
  71908. if (s [index] == '#')
  71909. {
  71910. uint32 hex [6];
  71911. zeromem (hex, sizeof (hex));
  71912. int numChars = 0;
  71913. for (int i = 6; --i >= 0;)
  71914. {
  71915. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71916. if (hexValue >= 0)
  71917. hex [numChars++] = hexValue;
  71918. else
  71919. break;
  71920. }
  71921. if (numChars <= 3)
  71922. return Colour ((uint8) (hex [0] * 0x11),
  71923. (uint8) (hex [1] * 0x11),
  71924. (uint8) (hex [2] * 0x11));
  71925. else
  71926. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71927. (uint8) ((hex [2] << 4) + hex [3]),
  71928. (uint8) ((hex [4] << 4) + hex [5]));
  71929. }
  71930. else if (s [index] == 'r'
  71931. && s [index + 1] == 'g'
  71932. && s [index + 2] == 'b')
  71933. {
  71934. const int openBracket = s.indexOfChar (index, '(');
  71935. const int closeBracket = s.indexOfChar (openBracket, ')');
  71936. if (openBracket >= 3 && closeBracket > openBracket)
  71937. {
  71938. index = closeBracket;
  71939. StringArray tokens;
  71940. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71941. tokens.trim();
  71942. tokens.removeEmptyStrings();
  71943. if (tokens[0].containsChar ('%'))
  71944. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71945. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71946. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71947. else
  71948. return Colour ((uint8) tokens[0].getIntValue(),
  71949. (uint8) tokens[1].getIntValue(),
  71950. (uint8) tokens[2].getIntValue());
  71951. }
  71952. }
  71953. return Colours::findColourForName (s, defaultColour);
  71954. }
  71955. static const AffineTransform parseTransform (String t)
  71956. {
  71957. AffineTransform result;
  71958. while (t.isNotEmpty())
  71959. {
  71960. StringArray tokens;
  71961. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71962. .upToFirstOccurrenceOf (")", false, false),
  71963. ", ", String::empty);
  71964. tokens.removeEmptyStrings (true);
  71965. float numbers [6];
  71966. for (int i = 0; i < 6; ++i)
  71967. numbers[i] = tokens[i].getFloatValue();
  71968. AffineTransform trans;
  71969. if (t.startsWithIgnoreCase ("matrix"))
  71970. {
  71971. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71972. numbers[1], numbers[3], numbers[5]);
  71973. }
  71974. else if (t.startsWithIgnoreCase ("translate"))
  71975. {
  71976. jassert (tokens.size() == 2);
  71977. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71978. }
  71979. else if (t.startsWithIgnoreCase ("scale"))
  71980. {
  71981. if (tokens.size() == 1)
  71982. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71983. else
  71984. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71985. }
  71986. else if (t.startsWithIgnoreCase ("rotate"))
  71987. {
  71988. if (tokens.size() != 3)
  71989. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71990. else
  71991. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71992. numbers[1], numbers[2]);
  71993. }
  71994. else if (t.startsWithIgnoreCase ("skewX"))
  71995. {
  71996. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71997. 0.0f, 1.0f, 0.0f);
  71998. }
  71999. else if (t.startsWithIgnoreCase ("skewY"))
  72000. {
  72001. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72002. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72003. }
  72004. result = trans.followedBy (result);
  72005. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72006. }
  72007. return result;
  72008. }
  72009. static void endpointToCentreParameters (const double x1, const double y1,
  72010. const double x2, const double y2,
  72011. const double angle,
  72012. const bool largeArc, const bool sweep,
  72013. double& rx, double& ry,
  72014. double& centreX, double& centreY,
  72015. double& startAngle, double& deltaAngle)
  72016. {
  72017. const double midX = (x1 - x2) * 0.5;
  72018. const double midY = (y1 - y2) * 0.5;
  72019. const double cosAngle = cos (angle);
  72020. const double sinAngle = sin (angle);
  72021. const double xp = cosAngle * midX + sinAngle * midY;
  72022. const double yp = cosAngle * midY - sinAngle * midX;
  72023. const double xp2 = xp * xp;
  72024. const double yp2 = yp * yp;
  72025. double rx2 = rx * rx;
  72026. double ry2 = ry * ry;
  72027. const double s = (xp2 / rx2) + (yp2 / ry2);
  72028. double c;
  72029. if (s <= 1.0)
  72030. {
  72031. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72032. / (( rx2 * yp2) + (ry2 * xp2))));
  72033. if (largeArc == sweep)
  72034. c = -c;
  72035. }
  72036. else
  72037. {
  72038. const double s2 = std::sqrt (s);
  72039. rx *= s2;
  72040. ry *= s2;
  72041. rx2 = rx * rx;
  72042. ry2 = ry * ry;
  72043. c = 0;
  72044. }
  72045. const double cpx = ((rx * yp) / ry) * c;
  72046. const double cpy = ((-ry * xp) / rx) * c;
  72047. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72048. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72049. const double ux = (xp - cpx) / rx;
  72050. const double uy = (yp - cpy) / ry;
  72051. const double vx = (-xp - cpx) / rx;
  72052. const double vy = (-yp - cpy) / ry;
  72053. const double length = juce_hypot (ux, uy);
  72054. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72055. if (uy < 0)
  72056. startAngle = -startAngle;
  72057. startAngle += double_Pi * 0.5;
  72058. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72059. / (length * juce_hypot (vx, vy))));
  72060. if ((ux * vy) - (uy * vx) < 0)
  72061. deltaAngle = -deltaAngle;
  72062. if (sweep)
  72063. {
  72064. if (deltaAngle < 0)
  72065. deltaAngle += double_Pi * 2.0;
  72066. }
  72067. else
  72068. {
  72069. if (deltaAngle > 0)
  72070. deltaAngle -= double_Pi * 2.0;
  72071. }
  72072. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72073. }
  72074. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72075. {
  72076. forEachXmlChildElement (*parent, e)
  72077. {
  72078. if (e->compareAttribute ("id", id))
  72079. return e;
  72080. const XmlElement* const found = findElementForId (e, id);
  72081. if (found != 0)
  72082. return found;
  72083. }
  72084. return 0;
  72085. }
  72086. SVGState& operator= (const SVGState&);
  72087. };
  72088. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72089. {
  72090. SVGState state (&svgDocument);
  72091. return state.parseSVGElement (svgDocument);
  72092. }
  72093. END_JUCE_NAMESPACE
  72094. /*** End of inlined file: juce_SVGParser.cpp ***/
  72095. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72096. BEGIN_JUCE_NAMESPACE
  72097. #if JUCE_MSVC && JUCE_DEBUG
  72098. #pragma optimize ("t", on)
  72099. #endif
  72100. DropShadowEffect::DropShadowEffect()
  72101. : offsetX (0),
  72102. offsetY (0),
  72103. radius (4),
  72104. opacity (0.6f)
  72105. {
  72106. }
  72107. DropShadowEffect::~DropShadowEffect()
  72108. {
  72109. }
  72110. void DropShadowEffect::setShadowProperties (const float newRadius,
  72111. const float newOpacity,
  72112. const int newShadowOffsetX,
  72113. const int newShadowOffsetY)
  72114. {
  72115. radius = jmax (1.1f, newRadius);
  72116. offsetX = newShadowOffsetX;
  72117. offsetY = newShadowOffsetY;
  72118. opacity = newOpacity;
  72119. }
  72120. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72121. {
  72122. const int w = image.getWidth();
  72123. const int h = image.getHeight();
  72124. Image shadowImage (Image::SingleChannel, w, h, false);
  72125. const Image::BitmapData srcData (image, false);
  72126. const Image::BitmapData destData (shadowImage, true);
  72127. const int filter = roundToInt (63.0f / radius);
  72128. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72129. for (int x = w; --x >= 0;)
  72130. {
  72131. int shadowAlpha = 0;
  72132. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72133. uint8* shadowPix = destData.data + x;
  72134. for (int y = h; --y >= 0;)
  72135. {
  72136. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72137. *shadowPix = (uint8) shadowAlpha;
  72138. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72139. shadowPix += destData.lineStride;
  72140. }
  72141. }
  72142. for (int y = h; --y >= 0;)
  72143. {
  72144. int shadowAlpha = 0;
  72145. uint8* shadowPix = destData.getLinePointer (y);
  72146. for (int x = w; --x >= 0;)
  72147. {
  72148. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72149. *shadowPix++ = (uint8) shadowAlpha;
  72150. }
  72151. }
  72152. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72153. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72154. g.setOpacity (alpha);
  72155. g.drawImageAt (image, 0, 0);
  72156. }
  72157. #if JUCE_MSVC && JUCE_DEBUG
  72158. #pragma optimize ("", on) // resets optimisations to the project defaults
  72159. #endif
  72160. END_JUCE_NAMESPACE
  72161. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72162. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72163. BEGIN_JUCE_NAMESPACE
  72164. GlowEffect::GlowEffect()
  72165. : radius (2.0f),
  72166. colour (Colours::white)
  72167. {
  72168. }
  72169. GlowEffect::~GlowEffect()
  72170. {
  72171. }
  72172. void GlowEffect::setGlowProperties (const float newRadius,
  72173. const Colour& newColour)
  72174. {
  72175. radius = newRadius;
  72176. colour = newColour;
  72177. }
  72178. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72179. {
  72180. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72181. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72182. blurKernel.createGaussianBlur (radius);
  72183. blurKernel.rescaleAllValues (radius);
  72184. blurKernel.applyToImage (temp, image, image.getBounds());
  72185. g.setColour (colour.withMultipliedAlpha (alpha));
  72186. g.drawImageAt (temp, 0, 0, true);
  72187. g.setOpacity (alpha);
  72188. g.drawImageAt (image, 0, 0, false);
  72189. }
  72190. END_JUCE_NAMESPACE
  72191. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72192. /*** Start of inlined file: juce_Font.cpp ***/
  72193. BEGIN_JUCE_NAMESPACE
  72194. namespace FontValues
  72195. {
  72196. float limitFontHeight (const float height) throw()
  72197. {
  72198. return jlimit (0.1f, 10000.0f, height);
  72199. }
  72200. const float defaultFontHeight = 14.0f;
  72201. String fallbackFont;
  72202. }
  72203. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72204. const float kerning_, const float ascent_, const int styleFlags_,
  72205. Typeface* const typeface_) throw()
  72206. : typefaceName (typefaceName_),
  72207. height (height_),
  72208. horizontalScale (horizontalScale_),
  72209. kerning (kerning_),
  72210. ascent (ascent_),
  72211. styleFlags (styleFlags_),
  72212. typeface (typeface_)
  72213. {
  72214. }
  72215. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72216. : typefaceName (other.typefaceName),
  72217. height (other.height),
  72218. horizontalScale (other.horizontalScale),
  72219. kerning (other.kerning),
  72220. ascent (other.ascent),
  72221. styleFlags (other.styleFlags),
  72222. typeface (other.typeface)
  72223. {
  72224. }
  72225. Font::Font()
  72226. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72227. 1.0f, 0, 0, Font::plain, 0))
  72228. {
  72229. }
  72230. Font::Font (const float fontHeight, const int styleFlags_)
  72231. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72232. 1.0f, 0, 0, styleFlags_, 0))
  72233. {
  72234. }
  72235. Font::Font (const String& typefaceName_,
  72236. const float fontHeight,
  72237. const int styleFlags_)
  72238. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72239. 1.0f, 0, 0, styleFlags_, 0))
  72240. {
  72241. }
  72242. Font::Font (const Font& other) throw()
  72243. : font (other.font)
  72244. {
  72245. }
  72246. Font& Font::operator= (const Font& other) throw()
  72247. {
  72248. font = other.font;
  72249. return *this;
  72250. }
  72251. Font::~Font() throw()
  72252. {
  72253. }
  72254. Font::Font (const Typeface::Ptr& typeface)
  72255. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72256. 1.0f, 0, 0, Font::plain, typeface))
  72257. {
  72258. }
  72259. bool Font::operator== (const Font& other) const throw()
  72260. {
  72261. return font == other.font
  72262. || (font->height == other.font->height
  72263. && font->styleFlags == other.font->styleFlags
  72264. && font->horizontalScale == other.font->horizontalScale
  72265. && font->kerning == other.font->kerning
  72266. && font->typefaceName == other.font->typefaceName);
  72267. }
  72268. bool Font::operator!= (const Font& other) const throw()
  72269. {
  72270. return ! operator== (other);
  72271. }
  72272. void Font::dupeInternalIfShared()
  72273. {
  72274. if (font->getReferenceCount() > 1)
  72275. font = new SharedFontInternal (*font);
  72276. }
  72277. const String Font::getDefaultSansSerifFontName()
  72278. {
  72279. static const String name ("<Sans-Serif>");
  72280. return name;
  72281. }
  72282. const String Font::getDefaultSerifFontName()
  72283. {
  72284. static const String name ("<Serif>");
  72285. return name;
  72286. }
  72287. const String Font::getDefaultMonospacedFontName()
  72288. {
  72289. static const String name ("<Monospaced>");
  72290. return name;
  72291. }
  72292. void Font::setTypefaceName (const String& faceName)
  72293. {
  72294. if (faceName != font->typefaceName)
  72295. {
  72296. dupeInternalIfShared();
  72297. font->typefaceName = faceName;
  72298. font->typeface = 0;
  72299. font->ascent = 0;
  72300. }
  72301. }
  72302. const String Font::getFallbackFontName()
  72303. {
  72304. return FontValues::fallbackFont;
  72305. }
  72306. void Font::setFallbackFontName (const String& name)
  72307. {
  72308. FontValues::fallbackFont = name;
  72309. }
  72310. void Font::setHeight (float newHeight)
  72311. {
  72312. newHeight = FontValues::limitFontHeight (newHeight);
  72313. if (font->height != newHeight)
  72314. {
  72315. dupeInternalIfShared();
  72316. font->height = newHeight;
  72317. }
  72318. }
  72319. void Font::setHeightWithoutChangingWidth (float newHeight)
  72320. {
  72321. newHeight = FontValues::limitFontHeight (newHeight);
  72322. if (font->height != newHeight)
  72323. {
  72324. dupeInternalIfShared();
  72325. font->horizontalScale *= (font->height / newHeight);
  72326. font->height = newHeight;
  72327. }
  72328. }
  72329. void Font::setStyleFlags (const int newFlags)
  72330. {
  72331. if (font->styleFlags != newFlags)
  72332. {
  72333. dupeInternalIfShared();
  72334. font->styleFlags = newFlags;
  72335. font->typeface = 0;
  72336. font->ascent = 0;
  72337. }
  72338. }
  72339. void Font::setSizeAndStyle (float newHeight,
  72340. const int newStyleFlags,
  72341. const float newHorizontalScale,
  72342. const float newKerningAmount)
  72343. {
  72344. newHeight = FontValues::limitFontHeight (newHeight);
  72345. if (font->height != newHeight
  72346. || font->horizontalScale != newHorizontalScale
  72347. || font->kerning != newKerningAmount)
  72348. {
  72349. dupeInternalIfShared();
  72350. font->height = newHeight;
  72351. font->horizontalScale = newHorizontalScale;
  72352. font->kerning = newKerningAmount;
  72353. }
  72354. setStyleFlags (newStyleFlags);
  72355. }
  72356. void Font::setHorizontalScale (const float scaleFactor)
  72357. {
  72358. dupeInternalIfShared();
  72359. font->horizontalScale = scaleFactor;
  72360. }
  72361. void Font::setExtraKerningFactor (const float extraKerning)
  72362. {
  72363. dupeInternalIfShared();
  72364. font->kerning = extraKerning;
  72365. }
  72366. void Font::setBold (const bool shouldBeBold)
  72367. {
  72368. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72369. : (font->styleFlags & ~bold));
  72370. }
  72371. const Font Font::boldened() const
  72372. {
  72373. Font f (*this);
  72374. f.setBold (true);
  72375. return f;
  72376. }
  72377. bool Font::isBold() const throw()
  72378. {
  72379. return (font->styleFlags & bold) != 0;
  72380. }
  72381. void Font::setItalic (const bool shouldBeItalic)
  72382. {
  72383. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72384. : (font->styleFlags & ~italic));
  72385. }
  72386. const Font Font::italicised() const
  72387. {
  72388. Font f (*this);
  72389. f.setItalic (true);
  72390. return f;
  72391. }
  72392. bool Font::isItalic() const throw()
  72393. {
  72394. return (font->styleFlags & italic) != 0;
  72395. }
  72396. void Font::setUnderline (const bool shouldBeUnderlined)
  72397. {
  72398. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72399. : (font->styleFlags & ~underlined));
  72400. }
  72401. bool Font::isUnderlined() const throw()
  72402. {
  72403. return (font->styleFlags & underlined) != 0;
  72404. }
  72405. float Font::getAscent() const
  72406. {
  72407. if (font->ascent == 0)
  72408. font->ascent = getTypeface()->getAscent();
  72409. return font->height * font->ascent;
  72410. }
  72411. float Font::getDescent() const
  72412. {
  72413. return font->height - getAscent();
  72414. }
  72415. int Font::getStringWidth (const String& text) const
  72416. {
  72417. return roundToInt (getStringWidthFloat (text));
  72418. }
  72419. float Font::getStringWidthFloat (const String& text) const
  72420. {
  72421. float w = getTypeface()->getStringWidth (text);
  72422. if (font->kerning != 0)
  72423. w += font->kerning * text.length();
  72424. return w * font->height * font->horizontalScale;
  72425. }
  72426. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72427. {
  72428. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72429. const float scale = font->height * font->horizontalScale;
  72430. const int num = xOffsets.size();
  72431. if (num > 0)
  72432. {
  72433. float* const x = &(xOffsets.getReference(0));
  72434. if (font->kerning != 0)
  72435. {
  72436. for (int i = 0; i < num; ++i)
  72437. x[i] = (x[i] + i * font->kerning) * scale;
  72438. }
  72439. else
  72440. {
  72441. for (int i = 0; i < num; ++i)
  72442. x[i] *= scale;
  72443. }
  72444. }
  72445. }
  72446. void Font::findFonts (Array<Font>& destArray)
  72447. {
  72448. const StringArray names (findAllTypefaceNames());
  72449. for (int i = 0; i < names.size(); ++i)
  72450. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72451. }
  72452. const String Font::toString() const
  72453. {
  72454. String s (getTypefaceName());
  72455. if (s == getDefaultSansSerifFontName())
  72456. s = String::empty;
  72457. else
  72458. s += "; ";
  72459. s += String (getHeight(), 1);
  72460. if (isBold())
  72461. s += " bold";
  72462. if (isItalic())
  72463. s += " italic";
  72464. return s;
  72465. }
  72466. const Font Font::fromString (const String& fontDescription)
  72467. {
  72468. String name;
  72469. const int separator = fontDescription.indexOfChar (';');
  72470. if (separator > 0)
  72471. name = fontDescription.substring (0, separator).trim();
  72472. if (name.isEmpty())
  72473. name = getDefaultSansSerifFontName();
  72474. String sizeAndStyle (fontDescription.substring (separator + 1));
  72475. float height = sizeAndStyle.getFloatValue();
  72476. if (height <= 0)
  72477. height = 10.0f;
  72478. int flags = Font::plain;
  72479. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72480. flags |= Font::bold;
  72481. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72482. flags |= Font::italic;
  72483. return Font (name, height, flags);
  72484. }
  72485. class TypefaceCache : public DeletedAtShutdown
  72486. {
  72487. public:
  72488. TypefaceCache (int numToCache = 10)
  72489. : counter (1)
  72490. {
  72491. while (--numToCache >= 0)
  72492. faces.add (new CachedFace());
  72493. }
  72494. ~TypefaceCache()
  72495. {
  72496. clearSingletonInstance();
  72497. }
  72498. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72499. const Typeface::Ptr findTypefaceFor (const Font& font)
  72500. {
  72501. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72502. const String faceName (font.getTypefaceName());
  72503. int i;
  72504. for (i = faces.size(); --i >= 0;)
  72505. {
  72506. CachedFace* const face = faces.getUnchecked(i);
  72507. if (face->flags == flags
  72508. && face->typefaceName == faceName)
  72509. {
  72510. face->lastUsageCount = ++counter;
  72511. return face->typeFace;
  72512. }
  72513. }
  72514. int replaceIndex = 0;
  72515. int bestLastUsageCount = std::numeric_limits<int>::max();
  72516. for (i = faces.size(); --i >= 0;)
  72517. {
  72518. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72519. if (bestLastUsageCount > lu)
  72520. {
  72521. bestLastUsageCount = lu;
  72522. replaceIndex = i;
  72523. }
  72524. }
  72525. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72526. face->typefaceName = faceName;
  72527. face->flags = flags;
  72528. face->lastUsageCount = ++counter;
  72529. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72530. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72531. return face->typeFace;
  72532. }
  72533. juce_UseDebuggingNewOperator
  72534. private:
  72535. struct CachedFace
  72536. {
  72537. CachedFace() throw()
  72538. : lastUsageCount (0), flags (-1)
  72539. {
  72540. }
  72541. String typefaceName;
  72542. int lastUsageCount;
  72543. int flags;
  72544. Typeface::Ptr typeFace;
  72545. };
  72546. int counter;
  72547. OwnedArray <CachedFace> faces;
  72548. TypefaceCache (const TypefaceCache&);
  72549. TypefaceCache& operator= (const TypefaceCache&);
  72550. };
  72551. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72552. Typeface* Font::getTypeface() const
  72553. {
  72554. if (font->typeface == 0)
  72555. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72556. return font->typeface;
  72557. }
  72558. END_JUCE_NAMESPACE
  72559. /*** End of inlined file: juce_Font.cpp ***/
  72560. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72561. BEGIN_JUCE_NAMESPACE
  72562. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72563. const juce_wchar character_, const int glyph_)
  72564. : x (x_),
  72565. y (y_),
  72566. w (w_),
  72567. font (font_),
  72568. character (character_),
  72569. glyph (glyph_)
  72570. {
  72571. }
  72572. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72573. : x (other.x),
  72574. y (other.y),
  72575. w (other.w),
  72576. font (other.font),
  72577. character (other.character),
  72578. glyph (other.glyph)
  72579. {
  72580. }
  72581. void PositionedGlyph::draw (const Graphics& g) const
  72582. {
  72583. if (! isWhitespace())
  72584. {
  72585. g.getInternalContext()->setFont (font);
  72586. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72587. }
  72588. }
  72589. void PositionedGlyph::draw (const Graphics& g,
  72590. const AffineTransform& transform) const
  72591. {
  72592. if (! isWhitespace())
  72593. {
  72594. g.getInternalContext()->setFont (font);
  72595. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72596. .followedBy (transform));
  72597. }
  72598. }
  72599. void PositionedGlyph::createPath (Path& path) const
  72600. {
  72601. if (! isWhitespace())
  72602. {
  72603. Typeface* const t = font.getTypeface();
  72604. if (t != 0)
  72605. {
  72606. Path p;
  72607. t->getOutlineForGlyph (glyph, p);
  72608. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72609. .translated (x, y));
  72610. }
  72611. }
  72612. }
  72613. bool PositionedGlyph::hitTest (float px, float py) const
  72614. {
  72615. if (getBounds().contains (px, py) && ! isWhitespace())
  72616. {
  72617. Typeface* const t = font.getTypeface();
  72618. if (t != 0)
  72619. {
  72620. Path p;
  72621. t->getOutlineForGlyph (glyph, p);
  72622. AffineTransform::translation (-x, -y)
  72623. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72624. .transformPoint (px, py);
  72625. return p.contains (px, py);
  72626. }
  72627. }
  72628. return false;
  72629. }
  72630. void PositionedGlyph::moveBy (const float deltaX,
  72631. const float deltaY)
  72632. {
  72633. x += deltaX;
  72634. y += deltaY;
  72635. }
  72636. GlyphArrangement::GlyphArrangement()
  72637. {
  72638. glyphs.ensureStorageAllocated (128);
  72639. }
  72640. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72641. {
  72642. addGlyphArrangement (other);
  72643. }
  72644. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72645. {
  72646. if (this != &other)
  72647. {
  72648. clear();
  72649. addGlyphArrangement (other);
  72650. }
  72651. return *this;
  72652. }
  72653. GlyphArrangement::~GlyphArrangement()
  72654. {
  72655. }
  72656. void GlyphArrangement::clear()
  72657. {
  72658. glyphs.clear();
  72659. }
  72660. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72661. {
  72662. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72663. return *glyphs [index];
  72664. }
  72665. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72666. {
  72667. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72668. glyphs.addCopiesOf (other.glyphs);
  72669. }
  72670. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72671. {
  72672. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72673. }
  72674. void GlyphArrangement::addLineOfText (const Font& font,
  72675. const String& text,
  72676. const float xOffset,
  72677. const float yOffset)
  72678. {
  72679. addCurtailedLineOfText (font, text,
  72680. xOffset, yOffset,
  72681. 1.0e10f, false);
  72682. }
  72683. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72684. const String& text,
  72685. float xOffset,
  72686. const float yOffset,
  72687. const float maxWidthPixels,
  72688. const bool useEllipsis)
  72689. {
  72690. if (text.isNotEmpty())
  72691. {
  72692. Array <int> newGlyphs;
  72693. Array <float> xOffsets;
  72694. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72695. const int textLen = newGlyphs.size();
  72696. const juce_wchar* const unicodeText = text;
  72697. for (int i = 0; i < textLen; ++i)
  72698. {
  72699. const float thisX = xOffsets.getUnchecked (i);
  72700. const float nextX = xOffsets.getUnchecked (i + 1);
  72701. if (nextX > maxWidthPixels + 1.0f)
  72702. {
  72703. // curtail the string if it's too wide..
  72704. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72705. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72706. break;
  72707. }
  72708. else
  72709. {
  72710. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72711. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72712. }
  72713. }
  72714. }
  72715. }
  72716. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72717. const int startIndex, int endIndex)
  72718. {
  72719. int numDeleted = 0;
  72720. if (glyphs.size() > 0)
  72721. {
  72722. Array<int> dotGlyphs;
  72723. Array<float> dotXs;
  72724. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72725. const float dx = dotXs[1];
  72726. float xOffset = 0.0f, yOffset = 0.0f;
  72727. while (endIndex > startIndex)
  72728. {
  72729. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72730. xOffset = pg->x;
  72731. yOffset = pg->y;
  72732. glyphs.remove (endIndex);
  72733. ++numDeleted;
  72734. if (xOffset + dx * 3 <= maxXPos)
  72735. break;
  72736. }
  72737. for (int i = 3; --i >= 0;)
  72738. {
  72739. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72740. font, '.', dotGlyphs.getFirst()));
  72741. --numDeleted;
  72742. xOffset += dx;
  72743. if (xOffset > maxXPos)
  72744. break;
  72745. }
  72746. }
  72747. return numDeleted;
  72748. }
  72749. void GlyphArrangement::addJustifiedText (const Font& font,
  72750. const String& text,
  72751. float x, float y,
  72752. const float maxLineWidth,
  72753. const Justification& horizontalLayout)
  72754. {
  72755. int lineStartIndex = glyphs.size();
  72756. addLineOfText (font, text, x, y);
  72757. const float originalY = y;
  72758. while (lineStartIndex < glyphs.size())
  72759. {
  72760. int i = lineStartIndex;
  72761. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72762. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72763. ++i;
  72764. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72765. int lastWordBreakIndex = -1;
  72766. while (i < glyphs.size())
  72767. {
  72768. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72769. const juce_wchar c = pg->getCharacter();
  72770. if (c == '\r' || c == '\n')
  72771. {
  72772. ++i;
  72773. if (c == '\r' && i < glyphs.size()
  72774. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72775. ++i;
  72776. break;
  72777. }
  72778. else if (pg->isWhitespace())
  72779. {
  72780. lastWordBreakIndex = i + 1;
  72781. }
  72782. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72783. {
  72784. if (lastWordBreakIndex >= 0)
  72785. i = lastWordBreakIndex;
  72786. break;
  72787. }
  72788. ++i;
  72789. }
  72790. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72791. float currentLineEndX = currentLineStartX;
  72792. for (int j = i; --j >= lineStartIndex;)
  72793. {
  72794. if (! glyphs.getUnchecked (j)->isWhitespace())
  72795. {
  72796. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72797. break;
  72798. }
  72799. }
  72800. float deltaX = 0.0f;
  72801. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72802. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72803. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72804. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72805. else if (horizontalLayout.testFlags (Justification::right))
  72806. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72807. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72808. x + deltaX - currentLineStartX, y - originalY);
  72809. lineStartIndex = i;
  72810. y += font.getHeight();
  72811. }
  72812. }
  72813. void GlyphArrangement::addFittedText (const Font& f,
  72814. const String& text,
  72815. const float x, const float y,
  72816. const float width, const float height,
  72817. const Justification& layout,
  72818. int maximumLines,
  72819. const float minimumHorizontalScale)
  72820. {
  72821. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72822. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72823. if (text.containsAnyOf ("\r\n"))
  72824. {
  72825. GlyphArrangement ga;
  72826. ga.addJustifiedText (f, text, x, y, width, layout);
  72827. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72828. float dy = y - bb.getY();
  72829. if (layout.testFlags (Justification::verticallyCentred))
  72830. dy += (height - bb.getHeight()) * 0.5f;
  72831. else if (layout.testFlags (Justification::bottom))
  72832. dy += height - bb.getHeight();
  72833. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72834. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72835. for (int i = 0; i < ga.glyphs.size(); ++i)
  72836. glyphs.add (ga.glyphs.getUnchecked (i));
  72837. ga.glyphs.clear (false);
  72838. return;
  72839. }
  72840. int startIndex = glyphs.size();
  72841. addLineOfText (f, text.trim(), x, y);
  72842. if (glyphs.size() > startIndex)
  72843. {
  72844. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72845. - glyphs.getUnchecked (startIndex)->getLeft();
  72846. if (lineWidth <= 0)
  72847. return;
  72848. if (lineWidth * minimumHorizontalScale < width)
  72849. {
  72850. if (lineWidth > width)
  72851. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72852. width / lineWidth);
  72853. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72854. x, y, width, height, layout);
  72855. }
  72856. else if (maximumLines <= 1)
  72857. {
  72858. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72859. x, y, width, height, f, layout, minimumHorizontalScale);
  72860. }
  72861. else
  72862. {
  72863. Font font (f);
  72864. String txt (text.trim());
  72865. const int length = txt.length();
  72866. const int originalStartIndex = startIndex;
  72867. int numLines = 1;
  72868. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72869. maximumLines = 1;
  72870. maximumLines = jmin (maximumLines, length);
  72871. while (numLines < maximumLines)
  72872. {
  72873. ++numLines;
  72874. const float newFontHeight = height / (float) numLines;
  72875. if (newFontHeight < font.getHeight())
  72876. {
  72877. font.setHeight (jmax (8.0f, newFontHeight));
  72878. removeRangeOfGlyphs (startIndex, -1);
  72879. addLineOfText (font, txt, x, y);
  72880. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72881. - glyphs.getUnchecked (startIndex)->getLeft();
  72882. }
  72883. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72884. break;
  72885. }
  72886. if (numLines < 1)
  72887. numLines = 1;
  72888. float lineY = y;
  72889. float widthPerLine = lineWidth / numLines;
  72890. int lastLineStartIndex = 0;
  72891. for (int line = 0; line < numLines; ++line)
  72892. {
  72893. int i = startIndex;
  72894. lastLineStartIndex = i;
  72895. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72896. if (line == numLines - 1)
  72897. {
  72898. widthPerLine = width;
  72899. i = glyphs.size();
  72900. }
  72901. else
  72902. {
  72903. while (i < glyphs.size())
  72904. {
  72905. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72906. if (lineWidth > widthPerLine)
  72907. {
  72908. // got to a point where the line's too long, so skip forward to find a
  72909. // good place to break it..
  72910. const int searchStartIndex = i;
  72911. while (i < glyphs.size())
  72912. {
  72913. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72914. {
  72915. if (glyphs.getUnchecked (i)->isWhitespace()
  72916. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72917. {
  72918. ++i;
  72919. break;
  72920. }
  72921. }
  72922. else
  72923. {
  72924. // can't find a suitable break, so try looking backwards..
  72925. i = searchStartIndex;
  72926. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72927. {
  72928. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72929. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72930. {
  72931. i -= back - 1;
  72932. break;
  72933. }
  72934. }
  72935. break;
  72936. }
  72937. ++i;
  72938. }
  72939. break;
  72940. }
  72941. ++i;
  72942. }
  72943. int wsStart = i;
  72944. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72945. --wsStart;
  72946. int wsEnd = i;
  72947. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72948. ++wsEnd;
  72949. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72950. i = jmax (wsStart, startIndex + 1);
  72951. }
  72952. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72953. x, lineY, width, font.getHeight(), font,
  72954. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72955. minimumHorizontalScale);
  72956. startIndex = i;
  72957. lineY += font.getHeight();
  72958. if (startIndex >= glyphs.size())
  72959. break;
  72960. }
  72961. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72962. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72963. }
  72964. }
  72965. }
  72966. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72967. const float dx, const float dy)
  72968. {
  72969. jassert (startIndex >= 0);
  72970. if (dx != 0.0f || dy != 0.0f)
  72971. {
  72972. if (num < 0 || startIndex + num > glyphs.size())
  72973. num = glyphs.size() - startIndex;
  72974. while (--num >= 0)
  72975. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72976. }
  72977. }
  72978. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72979. const Justification& justification, float minimumHorizontalScale)
  72980. {
  72981. int numDeleted = 0;
  72982. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72983. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72984. if (lineWidth > w)
  72985. {
  72986. if (minimumHorizontalScale < 1.0f)
  72987. {
  72988. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  72989. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  72990. }
  72991. if (lineWidth > w)
  72992. {
  72993. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  72994. numGlyphs -= numDeleted;
  72995. }
  72996. }
  72997. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  72998. return numDeleted;
  72999. }
  73000. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73001. const float horizontalScaleFactor)
  73002. {
  73003. jassert (startIndex >= 0);
  73004. if (num < 0 || startIndex + num > glyphs.size())
  73005. num = glyphs.size() - startIndex;
  73006. if (num > 0)
  73007. {
  73008. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73009. while (--num >= 0)
  73010. {
  73011. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73012. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73013. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73014. pg->w *= horizontalScaleFactor;
  73015. }
  73016. }
  73017. }
  73018. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73019. {
  73020. jassert (startIndex >= 0);
  73021. if (num < 0 || startIndex + num > glyphs.size())
  73022. num = glyphs.size() - startIndex;
  73023. Rectangle<float> result;
  73024. while (--num >= 0)
  73025. {
  73026. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73027. if (includeWhitespace || ! pg->isWhitespace())
  73028. result = result.getUnion (pg->getBounds());
  73029. }
  73030. return result;
  73031. }
  73032. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73033. const float x, const float y, const float width, const float height,
  73034. const Justification& justification)
  73035. {
  73036. jassert (num >= 0 && startIndex >= 0);
  73037. if (glyphs.size() > 0 && num > 0)
  73038. {
  73039. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73040. | Justification::horizontallyCentred)));
  73041. float deltaX = 0.0f;
  73042. if (justification.testFlags (Justification::horizontallyJustified))
  73043. deltaX = x - bb.getX();
  73044. else if (justification.testFlags (Justification::horizontallyCentred))
  73045. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73046. else if (justification.testFlags (Justification::right))
  73047. deltaX = (x + width) - bb.getRight();
  73048. else
  73049. deltaX = x - bb.getX();
  73050. float deltaY = 0.0f;
  73051. if (justification.testFlags (Justification::top))
  73052. deltaY = y - bb.getY();
  73053. else if (justification.testFlags (Justification::bottom))
  73054. deltaY = (y + height) - bb.getBottom();
  73055. else
  73056. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73057. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73058. if (justification.testFlags (Justification::horizontallyJustified))
  73059. {
  73060. int lineStart = 0;
  73061. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73062. int i;
  73063. for (i = 0; i < num; ++i)
  73064. {
  73065. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73066. if (glyphY != baseY)
  73067. {
  73068. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73069. lineStart = i;
  73070. baseY = glyphY;
  73071. }
  73072. }
  73073. if (i > lineStart)
  73074. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73075. }
  73076. }
  73077. }
  73078. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73079. {
  73080. if (start + num < glyphs.size()
  73081. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73082. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73083. {
  73084. int numSpaces = 0;
  73085. int spacesAtEnd = 0;
  73086. for (int i = 0; i < num; ++i)
  73087. {
  73088. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73089. {
  73090. ++spacesAtEnd;
  73091. ++numSpaces;
  73092. }
  73093. else
  73094. {
  73095. spacesAtEnd = 0;
  73096. }
  73097. }
  73098. numSpaces -= spacesAtEnd;
  73099. if (numSpaces > 0)
  73100. {
  73101. const float startX = glyphs.getUnchecked (start)->getLeft();
  73102. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73103. const float extraPaddingBetweenWords
  73104. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73105. float deltaX = 0.0f;
  73106. for (int i = 0; i < num; ++i)
  73107. {
  73108. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73109. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73110. deltaX += extraPaddingBetweenWords;
  73111. }
  73112. }
  73113. }
  73114. }
  73115. void GlyphArrangement::draw (const Graphics& g) const
  73116. {
  73117. for (int i = 0; i < glyphs.size(); ++i)
  73118. {
  73119. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73120. if (pg->font.isUnderlined())
  73121. {
  73122. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73123. float nextX = pg->x + pg->w;
  73124. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73125. nextX = glyphs.getUnchecked (i + 1)->x;
  73126. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73127. nextX - pg->x, lineThickness);
  73128. }
  73129. pg->draw (g);
  73130. }
  73131. }
  73132. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73133. {
  73134. for (int i = 0; i < glyphs.size(); ++i)
  73135. {
  73136. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73137. if (pg->font.isUnderlined())
  73138. {
  73139. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73140. float nextX = pg->x + pg->w;
  73141. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73142. nextX = glyphs.getUnchecked (i + 1)->x;
  73143. Path p;
  73144. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73145. nextX, pg->y + lineThickness * 2.0f),
  73146. lineThickness);
  73147. g.fillPath (p, transform);
  73148. }
  73149. pg->draw (g, transform);
  73150. }
  73151. }
  73152. void GlyphArrangement::createPath (Path& path) const
  73153. {
  73154. for (int i = 0; i < glyphs.size(); ++i)
  73155. glyphs.getUnchecked (i)->createPath (path);
  73156. }
  73157. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73158. {
  73159. for (int i = 0; i < glyphs.size(); ++i)
  73160. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73161. return i;
  73162. return -1;
  73163. }
  73164. END_JUCE_NAMESPACE
  73165. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73166. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73167. BEGIN_JUCE_NAMESPACE
  73168. class TextLayout::Token
  73169. {
  73170. public:
  73171. String text;
  73172. Font font;
  73173. int x, y, w, h;
  73174. int line, lineHeight;
  73175. bool isWhitespace, isNewLine;
  73176. Token (const String& t,
  73177. const Font& f,
  73178. const bool isWhitespace_)
  73179. : text (t),
  73180. font (f),
  73181. x(0),
  73182. y(0),
  73183. isWhitespace (isWhitespace_)
  73184. {
  73185. w = font.getStringWidth (t);
  73186. h = roundToInt (f.getHeight());
  73187. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73188. }
  73189. Token (const Token& other)
  73190. : text (other.text),
  73191. font (other.font),
  73192. x (other.x),
  73193. y (other.y),
  73194. w (other.w),
  73195. h (other.h),
  73196. line (other.line),
  73197. lineHeight (other.lineHeight),
  73198. isWhitespace (other.isWhitespace),
  73199. isNewLine (other.isNewLine)
  73200. {
  73201. }
  73202. ~Token()
  73203. {
  73204. }
  73205. void draw (Graphics& g,
  73206. const int xOffset,
  73207. const int yOffset)
  73208. {
  73209. if (! isWhitespace)
  73210. {
  73211. g.setFont (font);
  73212. g.drawSingleLineText (text.trimEnd(),
  73213. xOffset + x,
  73214. yOffset + y + (lineHeight - h)
  73215. + roundToInt (font.getAscent()));
  73216. }
  73217. }
  73218. juce_UseDebuggingNewOperator
  73219. };
  73220. TextLayout::TextLayout()
  73221. : totalLines (0)
  73222. {
  73223. tokens.ensureStorageAllocated (64);
  73224. }
  73225. TextLayout::TextLayout (const String& text, const Font& font)
  73226. : totalLines (0)
  73227. {
  73228. tokens.ensureStorageAllocated (64);
  73229. appendText (text, font);
  73230. }
  73231. TextLayout::TextLayout (const TextLayout& other)
  73232. : totalLines (0)
  73233. {
  73234. *this = other;
  73235. }
  73236. TextLayout& TextLayout::operator= (const TextLayout& other)
  73237. {
  73238. if (this != &other)
  73239. {
  73240. clear();
  73241. totalLines = other.totalLines;
  73242. tokens.addCopiesOf (other.tokens);
  73243. }
  73244. return *this;
  73245. }
  73246. TextLayout::~TextLayout()
  73247. {
  73248. clear();
  73249. }
  73250. void TextLayout::clear()
  73251. {
  73252. tokens.clear();
  73253. totalLines = 0;
  73254. }
  73255. bool TextLayout::isEmpty() const
  73256. {
  73257. return tokens.size() == 0;
  73258. }
  73259. void TextLayout::appendText (const String& text, const Font& font)
  73260. {
  73261. const juce_wchar* t = text;
  73262. String currentString;
  73263. int lastCharType = 0;
  73264. for (;;)
  73265. {
  73266. const juce_wchar c = *t++;
  73267. if (c == 0)
  73268. break;
  73269. int charType;
  73270. if (c == '\r' || c == '\n')
  73271. {
  73272. charType = 0;
  73273. }
  73274. else if (CharacterFunctions::isWhitespace (c))
  73275. {
  73276. charType = 2;
  73277. }
  73278. else
  73279. {
  73280. charType = 1;
  73281. }
  73282. if (charType == 0 || charType != lastCharType)
  73283. {
  73284. if (currentString.isNotEmpty())
  73285. {
  73286. tokens.add (new Token (currentString, font,
  73287. lastCharType == 2 || lastCharType == 0));
  73288. }
  73289. currentString = String::charToString (c);
  73290. if (c == '\r' && *t == '\n')
  73291. currentString += *t++;
  73292. }
  73293. else
  73294. {
  73295. currentString += c;
  73296. }
  73297. lastCharType = charType;
  73298. }
  73299. if (currentString.isNotEmpty())
  73300. tokens.add (new Token (currentString, font, lastCharType == 2));
  73301. }
  73302. void TextLayout::setText (const String& text, const Font& font)
  73303. {
  73304. clear();
  73305. appendText (text, font);
  73306. }
  73307. void TextLayout::layout (int maxWidth,
  73308. const Justification& justification,
  73309. const bool attemptToBalanceLineLengths)
  73310. {
  73311. if (attemptToBalanceLineLengths)
  73312. {
  73313. const int originalW = maxWidth;
  73314. int bestWidth = maxWidth;
  73315. float bestLineProportion = 0.0f;
  73316. while (maxWidth > originalW / 2)
  73317. {
  73318. layout (maxWidth, justification, false);
  73319. if (getNumLines() <= 1)
  73320. return;
  73321. const int lastLineW = getLineWidth (getNumLines() - 1);
  73322. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73323. const float prop = lastLineW / (float) lastButOneLineW;
  73324. if (prop > 0.9f)
  73325. return;
  73326. if (prop > bestLineProportion)
  73327. {
  73328. bestLineProportion = prop;
  73329. bestWidth = maxWidth;
  73330. }
  73331. maxWidth -= 10;
  73332. }
  73333. layout (bestWidth, justification, false);
  73334. }
  73335. else
  73336. {
  73337. int x = 0;
  73338. int y = 0;
  73339. int h = 0;
  73340. totalLines = 0;
  73341. int i;
  73342. for (i = 0; i < tokens.size(); ++i)
  73343. {
  73344. Token* const t = tokens.getUnchecked(i);
  73345. t->x = x;
  73346. t->y = y;
  73347. t->line = totalLines;
  73348. x += t->w;
  73349. h = jmax (h, t->h);
  73350. const Token* nextTok = tokens [i + 1];
  73351. if (nextTok == 0)
  73352. break;
  73353. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73354. {
  73355. // finished a line, so go back and update the heights of the things on it
  73356. for (int j = i; j >= 0; --j)
  73357. {
  73358. Token* const tok = tokens.getUnchecked(j);
  73359. if (tok->line == totalLines)
  73360. tok->lineHeight = h;
  73361. else
  73362. break;
  73363. }
  73364. x = 0;
  73365. y += h;
  73366. h = 0;
  73367. ++totalLines;
  73368. }
  73369. }
  73370. // finished a line, so go back and update the heights of the things on it
  73371. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73372. {
  73373. Token* const t = tokens.getUnchecked(j);
  73374. if (t->line == totalLines)
  73375. t->lineHeight = h;
  73376. else
  73377. break;
  73378. }
  73379. ++totalLines;
  73380. if (! justification.testFlags (Justification::left))
  73381. {
  73382. int totalW = getWidth();
  73383. for (i = totalLines; --i >= 0;)
  73384. {
  73385. const int lineW = getLineWidth (i);
  73386. int dx = 0;
  73387. if (justification.testFlags (Justification::horizontallyCentred))
  73388. dx = (totalW - lineW) / 2;
  73389. else if (justification.testFlags (Justification::right))
  73390. dx = totalW - lineW;
  73391. for (int j = tokens.size(); --j >= 0;)
  73392. {
  73393. Token* const t = tokens.getUnchecked(j);
  73394. if (t->line == i)
  73395. t->x += dx;
  73396. }
  73397. }
  73398. }
  73399. }
  73400. }
  73401. int TextLayout::getLineWidth (const int lineNumber) const
  73402. {
  73403. int maxW = 0;
  73404. for (int i = tokens.size(); --i >= 0;)
  73405. {
  73406. const Token* const t = tokens.getUnchecked(i);
  73407. if (t->line == lineNumber && ! t->isWhitespace)
  73408. maxW = jmax (maxW, t->x + t->w);
  73409. }
  73410. return maxW;
  73411. }
  73412. int TextLayout::getWidth() const
  73413. {
  73414. int maxW = 0;
  73415. for (int i = tokens.size(); --i >= 0;)
  73416. {
  73417. const Token* const t = tokens.getUnchecked(i);
  73418. if (! t->isWhitespace)
  73419. maxW = jmax (maxW, t->x + t->w);
  73420. }
  73421. return maxW;
  73422. }
  73423. int TextLayout::getHeight() const
  73424. {
  73425. int maxH = 0;
  73426. for (int i = tokens.size(); --i >= 0;)
  73427. {
  73428. const Token* const t = tokens.getUnchecked(i);
  73429. if (! t->isWhitespace)
  73430. maxH = jmax (maxH, t->y + t->h);
  73431. }
  73432. return maxH;
  73433. }
  73434. void TextLayout::draw (Graphics& g,
  73435. const int xOffset,
  73436. const int yOffset) const
  73437. {
  73438. for (int i = tokens.size(); --i >= 0;)
  73439. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73440. }
  73441. void TextLayout::drawWithin (Graphics& g,
  73442. int x, int y, int w, int h,
  73443. const Justification& justification) const
  73444. {
  73445. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73446. x, y, w, h);
  73447. draw (g, x, y);
  73448. }
  73449. END_JUCE_NAMESPACE
  73450. /*** End of inlined file: juce_TextLayout.cpp ***/
  73451. /*** Start of inlined file: juce_Typeface.cpp ***/
  73452. BEGIN_JUCE_NAMESPACE
  73453. Typeface::Typeface (const String& name_) throw()
  73454. : name (name_), isFallbackFont (false)
  73455. {
  73456. }
  73457. Typeface::~Typeface()
  73458. {
  73459. }
  73460. const Typeface::Ptr Typeface::getFallbackTypeface()
  73461. {
  73462. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73463. Typeface* t = fallbackFont.getTypeface();
  73464. t->isFallbackFont = true;
  73465. return t;
  73466. }
  73467. class CustomTypeface::GlyphInfo
  73468. {
  73469. public:
  73470. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73471. : character (character_), path (path_), width (width_)
  73472. {
  73473. }
  73474. ~GlyphInfo() throw()
  73475. {
  73476. }
  73477. struct KerningPair
  73478. {
  73479. juce_wchar character2;
  73480. float kerningAmount;
  73481. };
  73482. void addKerningPair (const juce_wchar subsequentCharacter,
  73483. const float extraKerningAmount) throw()
  73484. {
  73485. KerningPair kp;
  73486. kp.character2 = subsequentCharacter;
  73487. kp.kerningAmount = extraKerningAmount;
  73488. kerningPairs.add (kp);
  73489. }
  73490. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73491. {
  73492. if (subsequentCharacter != 0)
  73493. {
  73494. for (int i = kerningPairs.size(); --i >= 0;)
  73495. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73496. return width + kerningPairs.getReference(i).kerningAmount;
  73497. }
  73498. return width;
  73499. }
  73500. const juce_wchar character;
  73501. const Path path;
  73502. float width;
  73503. Array <KerningPair> kerningPairs;
  73504. juce_UseDebuggingNewOperator
  73505. private:
  73506. GlyphInfo (const GlyphInfo&);
  73507. GlyphInfo& operator= (const GlyphInfo&);
  73508. };
  73509. CustomTypeface::CustomTypeface()
  73510. : Typeface (String::empty)
  73511. {
  73512. clear();
  73513. }
  73514. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73515. : Typeface (String::empty)
  73516. {
  73517. clear();
  73518. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73519. BufferedInputStream in (gzin, 32768);
  73520. name = in.readString();
  73521. isBold = in.readBool();
  73522. isItalic = in.readBool();
  73523. ascent = in.readFloat();
  73524. defaultCharacter = (juce_wchar) in.readShort();
  73525. int i, numChars = in.readInt();
  73526. for (i = 0; i < numChars; ++i)
  73527. {
  73528. const juce_wchar c = (juce_wchar) in.readShort();
  73529. const float width = in.readFloat();
  73530. Path p;
  73531. p.loadPathFromStream (in);
  73532. addGlyph (c, p, width);
  73533. }
  73534. const int numKerningPairs = in.readInt();
  73535. for (i = 0; i < numKerningPairs; ++i)
  73536. {
  73537. const juce_wchar char1 = (juce_wchar) in.readShort();
  73538. const juce_wchar char2 = (juce_wchar) in.readShort();
  73539. addKerningPair (char1, char2, in.readFloat());
  73540. }
  73541. }
  73542. CustomTypeface::~CustomTypeface()
  73543. {
  73544. }
  73545. void CustomTypeface::clear()
  73546. {
  73547. defaultCharacter = 0;
  73548. ascent = 1.0f;
  73549. isBold = isItalic = false;
  73550. zeromem (lookupTable, sizeof (lookupTable));
  73551. glyphs.clear();
  73552. }
  73553. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73554. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73555. {
  73556. name = name_;
  73557. defaultCharacter = defaultCharacter_;
  73558. ascent = ascent_;
  73559. isBold = isBold_;
  73560. isItalic = isItalic_;
  73561. }
  73562. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73563. {
  73564. // Check that you're not trying to add the same character twice..
  73565. jassert (findGlyph (character, false) == 0);
  73566. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73567. lookupTable [character] = (short) glyphs.size();
  73568. glyphs.add (new GlyphInfo (character, path, width));
  73569. }
  73570. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73571. {
  73572. if (extraAmount != 0)
  73573. {
  73574. GlyphInfo* const g = findGlyph (char1, true);
  73575. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73576. if (g != 0)
  73577. g->addKerningPair (char2, extraAmount);
  73578. }
  73579. }
  73580. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73581. {
  73582. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73583. return glyphs [(int) lookupTable [(int) character]];
  73584. for (int i = 0; i < glyphs.size(); ++i)
  73585. {
  73586. GlyphInfo* const g = glyphs.getUnchecked(i);
  73587. if (g->character == character)
  73588. return g;
  73589. }
  73590. if (loadIfNeeded && loadGlyphIfPossible (character))
  73591. return findGlyph (character, false);
  73592. return 0;
  73593. }
  73594. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73595. {
  73596. GlyphInfo* glyph = findGlyph (character, true);
  73597. if (glyph == 0)
  73598. {
  73599. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73600. glyph = findGlyph (L' ', true);
  73601. if (glyph == 0)
  73602. {
  73603. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73604. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73605. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73606. {
  73607. Path path;
  73608. fallbackTypeface->getOutlineForGlyph (character, path);
  73609. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  73610. }
  73611. if (glyph == 0)
  73612. glyph = findGlyph (defaultCharacter, true);
  73613. }
  73614. }
  73615. return glyph;
  73616. }
  73617. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73618. {
  73619. return false;
  73620. }
  73621. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73622. {
  73623. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73624. for (int i = 0; i < numCharacters; ++i)
  73625. {
  73626. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73627. Array <int> glyphIndexes;
  73628. Array <float> offsets;
  73629. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73630. const int glyphIndex = glyphIndexes.getFirst();
  73631. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73632. {
  73633. const float glyphWidth = offsets[1];
  73634. Path p;
  73635. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73636. addGlyph (c, p, glyphWidth);
  73637. for (int j = glyphs.size() - 1; --j >= 0;)
  73638. {
  73639. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73640. glyphIndexes.clearQuick();
  73641. offsets.clearQuick();
  73642. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73643. if (offsets.size() > 1)
  73644. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73645. }
  73646. }
  73647. }
  73648. }
  73649. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73650. {
  73651. GZIPCompressorOutputStream out (&outputStream);
  73652. out.writeString (name);
  73653. out.writeBool (isBold);
  73654. out.writeBool (isItalic);
  73655. out.writeFloat (ascent);
  73656. out.writeShort ((short) (unsigned short) defaultCharacter);
  73657. out.writeInt (glyphs.size());
  73658. int i, numKerningPairs = 0;
  73659. for (i = 0; i < glyphs.size(); ++i)
  73660. {
  73661. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73662. out.writeShort ((short) (unsigned short) g->character);
  73663. out.writeFloat (g->width);
  73664. g->path.writePathToStream (out);
  73665. numKerningPairs += g->kerningPairs.size();
  73666. }
  73667. out.writeInt (numKerningPairs);
  73668. for (i = 0; i < glyphs.size(); ++i)
  73669. {
  73670. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73671. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73672. {
  73673. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73674. out.writeShort ((short) (unsigned short) g->character);
  73675. out.writeShort ((short) (unsigned short) p.character2);
  73676. out.writeFloat (p.kerningAmount);
  73677. }
  73678. }
  73679. return true;
  73680. }
  73681. float CustomTypeface::getAscent() const
  73682. {
  73683. return ascent;
  73684. }
  73685. float CustomTypeface::getDescent() const
  73686. {
  73687. return 1.0f - ascent;
  73688. }
  73689. float CustomTypeface::getStringWidth (const String& text)
  73690. {
  73691. float x = 0;
  73692. const juce_wchar* t = text;
  73693. while (*t != 0)
  73694. {
  73695. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73696. if (glyph == 0 && ! isFallbackFont)
  73697. {
  73698. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73699. if (fallbackTypeface != 0)
  73700. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  73701. }
  73702. if (glyph != 0)
  73703. x += glyph->getHorizontalSpacing (*t);
  73704. }
  73705. return x;
  73706. }
  73707. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73708. {
  73709. xOffsets.add (0);
  73710. float x = 0;
  73711. const juce_wchar* t = text;
  73712. while (*t != 0)
  73713. {
  73714. const juce_wchar c = *t++;
  73715. const GlyphInfo* const glyph = findGlyph (c, true);
  73716. if (glyph == 0 && ! isFallbackFont)
  73717. {
  73718. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73719. if (fallbackTypeface != 0)
  73720. {
  73721. Array <int> subGlyphs;
  73722. Array <float> subOffsets;
  73723. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  73724. if (subGlyphs.size() > 0)
  73725. {
  73726. resultGlyphs.add (subGlyphs.getFirst());
  73727. x += subOffsets[1];
  73728. xOffsets.add (x);
  73729. }
  73730. }
  73731. }
  73732. if (glyph != 0)
  73733. {
  73734. x += glyph->getHorizontalSpacing (*t);
  73735. resultGlyphs.add ((int) glyph->character);
  73736. xOffsets.add (x);
  73737. }
  73738. }
  73739. }
  73740. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73741. {
  73742. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  73743. if (glyph == 0 && ! isFallbackFont)
  73744. {
  73745. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73746. if (fallbackTypeface != 0)
  73747. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  73748. }
  73749. if (glyph != 0)
  73750. {
  73751. path = glyph->path;
  73752. return true;
  73753. }
  73754. return false;
  73755. }
  73756. END_JUCE_NAMESPACE
  73757. /*** End of inlined file: juce_Typeface.cpp ***/
  73758. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73759. BEGIN_JUCE_NAMESPACE
  73760. AffineTransform::AffineTransform() throw()
  73761. : mat00 (1.0f),
  73762. mat01 (0),
  73763. mat02 (0),
  73764. mat10 (0),
  73765. mat11 (1.0f),
  73766. mat12 (0)
  73767. {
  73768. }
  73769. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73770. : mat00 (other.mat00),
  73771. mat01 (other.mat01),
  73772. mat02 (other.mat02),
  73773. mat10 (other.mat10),
  73774. mat11 (other.mat11),
  73775. mat12 (other.mat12)
  73776. {
  73777. }
  73778. AffineTransform::AffineTransform (const float mat00_,
  73779. const float mat01_,
  73780. const float mat02_,
  73781. const float mat10_,
  73782. const float mat11_,
  73783. const float mat12_) throw()
  73784. : mat00 (mat00_),
  73785. mat01 (mat01_),
  73786. mat02 (mat02_),
  73787. mat10 (mat10_),
  73788. mat11 (mat11_),
  73789. mat12 (mat12_)
  73790. {
  73791. }
  73792. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73793. {
  73794. mat00 = other.mat00;
  73795. mat01 = other.mat01;
  73796. mat02 = other.mat02;
  73797. mat10 = other.mat10;
  73798. mat11 = other.mat11;
  73799. mat12 = other.mat12;
  73800. return *this;
  73801. }
  73802. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73803. {
  73804. return mat00 == other.mat00
  73805. && mat01 == other.mat01
  73806. && mat02 == other.mat02
  73807. && mat10 == other.mat10
  73808. && mat11 == other.mat11
  73809. && mat12 == other.mat12;
  73810. }
  73811. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73812. {
  73813. return ! operator== (other);
  73814. }
  73815. bool AffineTransform::isIdentity() const throw()
  73816. {
  73817. return (mat01 == 0)
  73818. && (mat02 == 0)
  73819. && (mat10 == 0)
  73820. && (mat12 == 0)
  73821. && (mat00 == 1.0f)
  73822. && (mat11 == 1.0f);
  73823. }
  73824. const AffineTransform AffineTransform::identity;
  73825. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73826. {
  73827. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73828. other.mat00 * mat01 + other.mat01 * mat11,
  73829. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73830. other.mat10 * mat00 + other.mat11 * mat10,
  73831. other.mat10 * mat01 + other.mat11 * mat11,
  73832. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73833. }
  73834. const AffineTransform AffineTransform::followedBy (const float omat00,
  73835. const float omat01,
  73836. const float omat02,
  73837. const float omat10,
  73838. const float omat11,
  73839. const float omat12) const throw()
  73840. {
  73841. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73842. omat00 * mat01 + omat01 * mat11,
  73843. omat00 * mat02 + omat01 * mat12 + omat02,
  73844. omat10 * mat00 + omat11 * mat10,
  73845. omat10 * mat01 + omat11 * mat11,
  73846. omat10 * mat02 + omat11 * mat12 + omat12);
  73847. }
  73848. const AffineTransform AffineTransform::translated (const float dx,
  73849. const float dy) const throw()
  73850. {
  73851. return AffineTransform (mat00, mat01, mat02 + dx,
  73852. mat10, mat11, mat12 + dy);
  73853. }
  73854. const AffineTransform AffineTransform::translation (const float dx,
  73855. const float dy) throw()
  73856. {
  73857. return AffineTransform (1.0f, 0, dx,
  73858. 0, 1.0f, dy);
  73859. }
  73860. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73861. {
  73862. const float cosRad = std::cos (rad);
  73863. const float sinRad = std::sin (rad);
  73864. return followedBy (cosRad, -sinRad, 0,
  73865. sinRad, cosRad, 0);
  73866. }
  73867. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73868. {
  73869. const float cosRad = std::cos (rad);
  73870. const float sinRad = std::sin (rad);
  73871. return AffineTransform (cosRad, -sinRad, 0,
  73872. sinRad, cosRad, 0);
  73873. }
  73874. const AffineTransform AffineTransform::rotated (const float angle,
  73875. const float pivotX,
  73876. const float pivotY) const throw()
  73877. {
  73878. return translated (-pivotX, -pivotY)
  73879. .rotated (angle)
  73880. .translated (pivotX, pivotY);
  73881. }
  73882. const AffineTransform AffineTransform::rotation (const float angle,
  73883. const float pivotX,
  73884. const float pivotY) throw()
  73885. {
  73886. return translation (-pivotX, -pivotY)
  73887. .rotated (angle)
  73888. .translated (pivotX, pivotY);
  73889. }
  73890. const AffineTransform AffineTransform::scaled (const float factorX,
  73891. const float factorY) const throw()
  73892. {
  73893. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73894. factorY * mat10, factorY * mat11, factorY * mat12);
  73895. }
  73896. const AffineTransform AffineTransform::scale (const float factorX,
  73897. const float factorY) throw()
  73898. {
  73899. return AffineTransform (factorX, 0, 0,
  73900. 0, factorY, 0);
  73901. }
  73902. const AffineTransform AffineTransform::sheared (const float shearX,
  73903. const float shearY) const throw()
  73904. {
  73905. return followedBy (1.0f, shearX, 0,
  73906. shearY, 1.0f, 0);
  73907. }
  73908. const AffineTransform AffineTransform::inverted() const throw()
  73909. {
  73910. double determinant = (mat00 * mat11 - mat10 * mat01);
  73911. if (determinant != 0.0)
  73912. {
  73913. determinant = 1.0 / determinant;
  73914. const float dst00 = (float) (mat11 * determinant);
  73915. const float dst10 = (float) (-mat10 * determinant);
  73916. const float dst01 = (float) (-mat01 * determinant);
  73917. const float dst11 = (float) (mat00 * determinant);
  73918. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73919. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73920. }
  73921. else
  73922. {
  73923. // singularity..
  73924. return *this;
  73925. }
  73926. }
  73927. bool AffineTransform::isSingularity() const throw()
  73928. {
  73929. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73930. }
  73931. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73932. const float x10, const float y10,
  73933. const float x01, const float y01) throw()
  73934. {
  73935. return AffineTransform (x10 - x00, x01 - x00, x00,
  73936. y10 - y00, y01 - y00, y00);
  73937. }
  73938. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73939. const float sx2, const float sy2, const float tx2, const float ty2,
  73940. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73941. {
  73942. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73943. .inverted()
  73944. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73945. }
  73946. bool AffineTransform::isOnlyTranslation() const throw()
  73947. {
  73948. return (mat01 == 0)
  73949. && (mat10 == 0)
  73950. && (mat00 == 1.0f)
  73951. && (mat11 == 1.0f);
  73952. }
  73953. END_JUCE_NAMESPACE
  73954. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73955. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73956. BEGIN_JUCE_NAMESPACE
  73957. BorderSize::BorderSize() throw()
  73958. : top (0),
  73959. left (0),
  73960. bottom (0),
  73961. right (0)
  73962. {
  73963. }
  73964. BorderSize::BorderSize (const BorderSize& other) throw()
  73965. : top (other.top),
  73966. left (other.left),
  73967. bottom (other.bottom),
  73968. right (other.right)
  73969. {
  73970. }
  73971. BorderSize::BorderSize (const int topGap,
  73972. const int leftGap,
  73973. const int bottomGap,
  73974. const int rightGap) throw()
  73975. : top (topGap),
  73976. left (leftGap),
  73977. bottom (bottomGap),
  73978. right (rightGap)
  73979. {
  73980. }
  73981. BorderSize::BorderSize (const int allGaps) throw()
  73982. : top (allGaps),
  73983. left (allGaps),
  73984. bottom (allGaps),
  73985. right (allGaps)
  73986. {
  73987. }
  73988. BorderSize::~BorderSize() throw()
  73989. {
  73990. }
  73991. void BorderSize::setTop (const int newTopGap) throw()
  73992. {
  73993. top = newTopGap;
  73994. }
  73995. void BorderSize::setLeft (const int newLeftGap) throw()
  73996. {
  73997. left = newLeftGap;
  73998. }
  73999. void BorderSize::setBottom (const int newBottomGap) throw()
  74000. {
  74001. bottom = newBottomGap;
  74002. }
  74003. void BorderSize::setRight (const int newRightGap) throw()
  74004. {
  74005. right = newRightGap;
  74006. }
  74007. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  74008. {
  74009. return Rectangle<int> (r.getX() + left,
  74010. r.getY() + top,
  74011. r.getWidth() - (left + right),
  74012. r.getHeight() - (top + bottom));
  74013. }
  74014. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  74015. {
  74016. r.setBounds (r.getX() + left,
  74017. r.getY() + top,
  74018. r.getWidth() - (left + right),
  74019. r.getHeight() - (top + bottom));
  74020. }
  74021. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  74022. {
  74023. return Rectangle<int> (r.getX() - left,
  74024. r.getY() - top,
  74025. r.getWidth() + (left + right),
  74026. r.getHeight() + (top + bottom));
  74027. }
  74028. void BorderSize::addTo (Rectangle<int>& r) const throw()
  74029. {
  74030. r.setBounds (r.getX() - left,
  74031. r.getY() - top,
  74032. r.getWidth() + (left + right),
  74033. r.getHeight() + (top + bottom));
  74034. }
  74035. bool BorderSize::operator== (const BorderSize& other) const throw()
  74036. {
  74037. return top == other.top
  74038. && left == other.left
  74039. && bottom == other.bottom
  74040. && right == other.right;
  74041. }
  74042. bool BorderSize::operator!= (const BorderSize& other) const throw()
  74043. {
  74044. return ! operator== (other);
  74045. }
  74046. END_JUCE_NAMESPACE
  74047. /*** End of inlined file: juce_BorderSize.cpp ***/
  74048. /*** Start of inlined file: juce_Path.cpp ***/
  74049. BEGIN_JUCE_NAMESPACE
  74050. // tests that some co-ords aren't NaNs
  74051. #define CHECK_COORDS_ARE_VALID(x, y) \
  74052. jassert (x == x && y == y);
  74053. namespace PathHelpers
  74054. {
  74055. const float ellipseAngularIncrement = 0.05f;
  74056. const String nextToken (const juce_wchar*& t)
  74057. {
  74058. while (CharacterFunctions::isWhitespace (*t))
  74059. ++t;
  74060. const juce_wchar* const start = t;
  74061. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74062. ++t;
  74063. return String (start, (int) (t - start));
  74064. }
  74065. }
  74066. const float Path::lineMarker = 100001.0f;
  74067. const float Path::moveMarker = 100002.0f;
  74068. const float Path::quadMarker = 100003.0f;
  74069. const float Path::cubicMarker = 100004.0f;
  74070. const float Path::closeSubPathMarker = 100005.0f;
  74071. Path::Path()
  74072. : numElements (0),
  74073. pathXMin (0),
  74074. pathXMax (0),
  74075. pathYMin (0),
  74076. pathYMax (0),
  74077. useNonZeroWinding (true)
  74078. {
  74079. }
  74080. Path::~Path()
  74081. {
  74082. }
  74083. Path::Path (const Path& other)
  74084. : numElements (other.numElements),
  74085. pathXMin (other.pathXMin),
  74086. pathXMax (other.pathXMax),
  74087. pathYMin (other.pathYMin),
  74088. pathYMax (other.pathYMax),
  74089. useNonZeroWinding (other.useNonZeroWinding)
  74090. {
  74091. if (numElements > 0)
  74092. {
  74093. data.setAllocatedSize ((int) numElements);
  74094. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74095. }
  74096. }
  74097. Path& Path::operator= (const Path& other)
  74098. {
  74099. if (this != &other)
  74100. {
  74101. data.ensureAllocatedSize ((int) other.numElements);
  74102. numElements = other.numElements;
  74103. pathXMin = other.pathXMin;
  74104. pathXMax = other.pathXMax;
  74105. pathYMin = other.pathYMin;
  74106. pathYMax = other.pathYMax;
  74107. useNonZeroWinding = other.useNonZeroWinding;
  74108. if (numElements > 0)
  74109. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74110. }
  74111. return *this;
  74112. }
  74113. bool Path::operator== (const Path& other) const throw()
  74114. {
  74115. return ! operator!= (other);
  74116. }
  74117. bool Path::operator!= (const Path& other) const throw()
  74118. {
  74119. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74120. return true;
  74121. for (size_t i = 0; i < numElements; ++i)
  74122. if (data.elements[i] != other.data.elements[i])
  74123. return true;
  74124. return false;
  74125. }
  74126. void Path::clear() throw()
  74127. {
  74128. numElements = 0;
  74129. pathXMin = 0;
  74130. pathYMin = 0;
  74131. pathYMax = 0;
  74132. pathXMax = 0;
  74133. }
  74134. void Path::swapWithPath (Path& other) throw()
  74135. {
  74136. data.swapWith (other.data);
  74137. swapVariables <size_t> (numElements, other.numElements);
  74138. swapVariables <float> (pathXMin, other.pathXMin);
  74139. swapVariables <float> (pathXMax, other.pathXMax);
  74140. swapVariables <float> (pathYMin, other.pathYMin);
  74141. swapVariables <float> (pathYMax, other.pathYMax);
  74142. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74143. }
  74144. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74145. {
  74146. useNonZeroWinding = isNonZero;
  74147. }
  74148. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74149. const bool preserveProportions) throw()
  74150. {
  74151. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74152. }
  74153. bool Path::isEmpty() const throw()
  74154. {
  74155. size_t i = 0;
  74156. while (i < numElements)
  74157. {
  74158. const float type = data.elements [i++];
  74159. if (type == moveMarker)
  74160. {
  74161. i += 2;
  74162. }
  74163. else if (type == lineMarker
  74164. || type == quadMarker
  74165. || type == cubicMarker)
  74166. {
  74167. return false;
  74168. }
  74169. }
  74170. return true;
  74171. }
  74172. const Rectangle<float> Path::getBounds() const throw()
  74173. {
  74174. return Rectangle<float> (pathXMin, pathYMin,
  74175. pathXMax - pathXMin,
  74176. pathYMax - pathYMin);
  74177. }
  74178. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74179. {
  74180. return getBounds().transformed (transform);
  74181. }
  74182. void Path::startNewSubPath (const float x, const float y)
  74183. {
  74184. CHECK_COORDS_ARE_VALID (x, y);
  74185. if (numElements == 0)
  74186. {
  74187. pathXMin = pathXMax = x;
  74188. pathYMin = pathYMax = y;
  74189. }
  74190. else
  74191. {
  74192. pathXMin = jmin (pathXMin, x);
  74193. pathXMax = jmax (pathXMax, x);
  74194. pathYMin = jmin (pathYMin, y);
  74195. pathYMax = jmax (pathYMax, y);
  74196. }
  74197. data.ensureAllocatedSize ((int) numElements + 3);
  74198. data.elements [numElements++] = moveMarker;
  74199. data.elements [numElements++] = x;
  74200. data.elements [numElements++] = y;
  74201. }
  74202. void Path::startNewSubPath (const Point<float>& start)
  74203. {
  74204. startNewSubPath (start.getX(), start.getY());
  74205. }
  74206. void Path::lineTo (const float x, const float y)
  74207. {
  74208. CHECK_COORDS_ARE_VALID (x, y);
  74209. if (numElements == 0)
  74210. startNewSubPath (0, 0);
  74211. data.ensureAllocatedSize ((int) numElements + 3);
  74212. data.elements [numElements++] = lineMarker;
  74213. data.elements [numElements++] = x;
  74214. data.elements [numElements++] = y;
  74215. pathXMin = jmin (pathXMin, x);
  74216. pathXMax = jmax (pathXMax, x);
  74217. pathYMin = jmin (pathYMin, y);
  74218. pathYMax = jmax (pathYMax, y);
  74219. }
  74220. void Path::lineTo (const Point<float>& end)
  74221. {
  74222. lineTo (end.getX(), end.getY());
  74223. }
  74224. void Path::quadraticTo (const float x1, const float y1,
  74225. const float x2, const float y2)
  74226. {
  74227. CHECK_COORDS_ARE_VALID (x1, y1);
  74228. CHECK_COORDS_ARE_VALID (x2, y2);
  74229. if (numElements == 0)
  74230. startNewSubPath (0, 0);
  74231. data.ensureAllocatedSize ((int) numElements + 5);
  74232. data.elements [numElements++] = quadMarker;
  74233. data.elements [numElements++] = x1;
  74234. data.elements [numElements++] = y1;
  74235. data.elements [numElements++] = x2;
  74236. data.elements [numElements++] = y2;
  74237. pathXMin = jmin (pathXMin, x1, x2);
  74238. pathXMax = jmax (pathXMax, x1, x2);
  74239. pathYMin = jmin (pathYMin, y1, y2);
  74240. pathYMax = jmax (pathYMax, y1, y2);
  74241. }
  74242. void Path::quadraticTo (const Point<float>& controlPoint,
  74243. const Point<float>& endPoint)
  74244. {
  74245. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74246. endPoint.getX(), endPoint.getY());
  74247. }
  74248. void Path::cubicTo (const float x1, const float y1,
  74249. const float x2, const float y2,
  74250. const float x3, const float y3)
  74251. {
  74252. CHECK_COORDS_ARE_VALID (x1, y1);
  74253. CHECK_COORDS_ARE_VALID (x2, y2);
  74254. CHECK_COORDS_ARE_VALID (x3, y3);
  74255. if (numElements == 0)
  74256. startNewSubPath (0, 0);
  74257. data.ensureAllocatedSize ((int) numElements + 7);
  74258. data.elements [numElements++] = cubicMarker;
  74259. data.elements [numElements++] = x1;
  74260. data.elements [numElements++] = y1;
  74261. data.elements [numElements++] = x2;
  74262. data.elements [numElements++] = y2;
  74263. data.elements [numElements++] = x3;
  74264. data.elements [numElements++] = y3;
  74265. pathXMin = jmin (pathXMin, x1, x2, x3);
  74266. pathXMax = jmax (pathXMax, x1, x2, x3);
  74267. pathYMin = jmin (pathYMin, y1, y2, y3);
  74268. pathYMax = jmax (pathYMax, y1, y2, y3);
  74269. }
  74270. void Path::cubicTo (const Point<float>& controlPoint1,
  74271. const Point<float>& controlPoint2,
  74272. const Point<float>& endPoint)
  74273. {
  74274. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74275. controlPoint2.getX(), controlPoint2.getY(),
  74276. endPoint.getX(), endPoint.getY());
  74277. }
  74278. void Path::closeSubPath()
  74279. {
  74280. if (numElements > 0
  74281. && data.elements [numElements - 1] != closeSubPathMarker)
  74282. {
  74283. data.ensureAllocatedSize ((int) numElements + 1);
  74284. data.elements [numElements++] = closeSubPathMarker;
  74285. }
  74286. }
  74287. const Point<float> Path::getCurrentPosition() const
  74288. {
  74289. size_t i = numElements - 1;
  74290. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74291. {
  74292. while (i >= 0)
  74293. {
  74294. if (data.elements[i] == moveMarker)
  74295. {
  74296. i += 2;
  74297. break;
  74298. }
  74299. --i;
  74300. }
  74301. }
  74302. if (i > 0)
  74303. return Point<float> (data.elements [i - 1], data.elements [i]);
  74304. return Point<float>();
  74305. }
  74306. void Path::addRectangle (const float x, const float y,
  74307. const float w, const float h)
  74308. {
  74309. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74310. if (w < 0)
  74311. swapVariables (x1, x2);
  74312. if (h < 0)
  74313. swapVariables (y1, y2);
  74314. data.ensureAllocatedSize ((int) numElements + 13);
  74315. if (numElements == 0)
  74316. {
  74317. pathXMin = x1;
  74318. pathXMax = x2;
  74319. pathYMin = y1;
  74320. pathYMax = y2;
  74321. }
  74322. else
  74323. {
  74324. pathXMin = jmin (pathXMin, x1);
  74325. pathXMax = jmax (pathXMax, x2);
  74326. pathYMin = jmin (pathYMin, y1);
  74327. pathYMax = jmax (pathYMax, y2);
  74328. }
  74329. data.elements [numElements++] = moveMarker;
  74330. data.elements [numElements++] = x1;
  74331. data.elements [numElements++] = y2;
  74332. data.elements [numElements++] = lineMarker;
  74333. data.elements [numElements++] = x1;
  74334. data.elements [numElements++] = y1;
  74335. data.elements [numElements++] = lineMarker;
  74336. data.elements [numElements++] = x2;
  74337. data.elements [numElements++] = y1;
  74338. data.elements [numElements++] = lineMarker;
  74339. data.elements [numElements++] = x2;
  74340. data.elements [numElements++] = y2;
  74341. data.elements [numElements++] = closeSubPathMarker;
  74342. }
  74343. void Path::addRoundedRectangle (const float x, const float y,
  74344. const float w, const float h,
  74345. float csx,
  74346. float csy)
  74347. {
  74348. csx = jmin (csx, w * 0.5f);
  74349. csy = jmin (csy, h * 0.5f);
  74350. const float cs45x = csx * 0.45f;
  74351. const float cs45y = csy * 0.45f;
  74352. const float x2 = x + w;
  74353. const float y2 = y + h;
  74354. startNewSubPath (x + csx, y);
  74355. lineTo (x2 - csx, y);
  74356. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74357. lineTo (x2, y2 - csy);
  74358. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74359. lineTo (x + csx, y2);
  74360. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74361. lineTo (x, y + csy);
  74362. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74363. closeSubPath();
  74364. }
  74365. void Path::addRoundedRectangle (const float x, const float y,
  74366. const float w, const float h,
  74367. float cs)
  74368. {
  74369. addRoundedRectangle (x, y, w, h, cs, cs);
  74370. }
  74371. void Path::addTriangle (const float x1, const float y1,
  74372. const float x2, const float y2,
  74373. const float x3, const float y3)
  74374. {
  74375. startNewSubPath (x1, y1);
  74376. lineTo (x2, y2);
  74377. lineTo (x3, y3);
  74378. closeSubPath();
  74379. }
  74380. void Path::addQuadrilateral (const float x1, const float y1,
  74381. const float x2, const float y2,
  74382. const float x3, const float y3,
  74383. const float x4, const float y4)
  74384. {
  74385. startNewSubPath (x1, y1);
  74386. lineTo (x2, y2);
  74387. lineTo (x3, y3);
  74388. lineTo (x4, y4);
  74389. closeSubPath();
  74390. }
  74391. void Path::addEllipse (const float x, const float y,
  74392. const float w, const float h)
  74393. {
  74394. const float hw = w * 0.5f;
  74395. const float hw55 = hw * 0.55f;
  74396. const float hh = h * 0.5f;
  74397. const float hh55 = hh * 0.55f;
  74398. const float cx = x + hw;
  74399. const float cy = y + hh;
  74400. startNewSubPath (cx, cy - hh);
  74401. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74402. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74403. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74404. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74405. closeSubPath();
  74406. }
  74407. void Path::addArc (const float x, const float y,
  74408. const float w, const float h,
  74409. const float fromRadians,
  74410. const float toRadians,
  74411. const bool startAsNewSubPath)
  74412. {
  74413. const float radiusX = w / 2.0f;
  74414. const float radiusY = h / 2.0f;
  74415. addCentredArc (x + radiusX,
  74416. y + radiusY,
  74417. radiusX, radiusY,
  74418. 0.0f,
  74419. fromRadians, toRadians,
  74420. startAsNewSubPath);
  74421. }
  74422. void Path::addCentredArc (const float centreX, const float centreY,
  74423. const float radiusX, const float radiusY,
  74424. const float rotationOfEllipse,
  74425. const float fromRadians,
  74426. const float toRadians,
  74427. const bool startAsNewSubPath)
  74428. {
  74429. if (radiusX > 0.0f && radiusY > 0.0f)
  74430. {
  74431. const Point<float> centre (centreX, centreY);
  74432. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74433. float angle = fromRadians;
  74434. if (startAsNewSubPath)
  74435. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74436. if (fromRadians < toRadians)
  74437. {
  74438. if (startAsNewSubPath)
  74439. angle += PathHelpers::ellipseAngularIncrement;
  74440. while (angle < toRadians)
  74441. {
  74442. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74443. angle += PathHelpers::ellipseAngularIncrement;
  74444. }
  74445. }
  74446. else
  74447. {
  74448. if (startAsNewSubPath)
  74449. angle -= PathHelpers::ellipseAngularIncrement;
  74450. while (angle > toRadians)
  74451. {
  74452. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74453. angle -= PathHelpers::ellipseAngularIncrement;
  74454. }
  74455. }
  74456. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74457. }
  74458. }
  74459. void Path::addPieSegment (const float x, const float y,
  74460. const float width, const float height,
  74461. const float fromRadians,
  74462. const float toRadians,
  74463. const float innerCircleProportionalSize)
  74464. {
  74465. float radiusX = width * 0.5f;
  74466. float radiusY = height * 0.5f;
  74467. const Point<float> centre (x + radiusX, y + radiusY);
  74468. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74469. addArc (x, y, width, height, fromRadians, toRadians);
  74470. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74471. {
  74472. closeSubPath();
  74473. if (innerCircleProportionalSize > 0)
  74474. {
  74475. radiusX *= innerCircleProportionalSize;
  74476. radiusY *= innerCircleProportionalSize;
  74477. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74478. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74479. }
  74480. }
  74481. else
  74482. {
  74483. if (innerCircleProportionalSize > 0)
  74484. {
  74485. radiusX *= innerCircleProportionalSize;
  74486. radiusY *= innerCircleProportionalSize;
  74487. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74488. }
  74489. else
  74490. {
  74491. lineTo (centre);
  74492. }
  74493. }
  74494. closeSubPath();
  74495. }
  74496. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74497. {
  74498. const Line<float> reversed (line.reversed());
  74499. lineThickness *= 0.5f;
  74500. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74501. lineTo (line.getPointAlongLine (0, -lineThickness));
  74502. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74503. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74504. closeSubPath();
  74505. }
  74506. void Path::addArrow (const Line<float>& line, float lineThickness,
  74507. float arrowheadWidth, float arrowheadLength)
  74508. {
  74509. const Line<float> reversed (line.reversed());
  74510. lineThickness *= 0.5f;
  74511. arrowheadWidth *= 0.5f;
  74512. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74513. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74514. lineTo (line.getPointAlongLine (0, -lineThickness));
  74515. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74516. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74517. lineTo (line.getEnd());
  74518. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74519. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74520. closeSubPath();
  74521. }
  74522. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74523. const float radius, const float startAngle)
  74524. {
  74525. jassert (numberOfSides > 1); // this would be silly.
  74526. if (numberOfSides > 1)
  74527. {
  74528. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74529. for (int i = 0; i < numberOfSides; ++i)
  74530. {
  74531. const float angle = startAngle + i * angleBetweenPoints;
  74532. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74533. if (i == 0)
  74534. startNewSubPath (p);
  74535. else
  74536. lineTo (p);
  74537. }
  74538. closeSubPath();
  74539. }
  74540. }
  74541. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74542. const float innerRadius, const float outerRadius, const float startAngle)
  74543. {
  74544. jassert (numberOfPoints > 1); // this would be silly.
  74545. if (numberOfPoints > 1)
  74546. {
  74547. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74548. for (int i = 0; i < numberOfPoints; ++i)
  74549. {
  74550. const float angle = startAngle + i * angleBetweenPoints;
  74551. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74552. if (i == 0)
  74553. startNewSubPath (p);
  74554. else
  74555. lineTo (p);
  74556. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74557. }
  74558. closeSubPath();
  74559. }
  74560. }
  74561. void Path::addBubble (float x, float y,
  74562. float w, float h,
  74563. float cs,
  74564. float tipX,
  74565. float tipY,
  74566. int whichSide,
  74567. float arrowPos,
  74568. float arrowWidth)
  74569. {
  74570. if (w > 1.0f && h > 1.0f)
  74571. {
  74572. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74573. const float cs2 = 2.0f * cs;
  74574. startNewSubPath (x + cs, y);
  74575. if (whichSide == 0)
  74576. {
  74577. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74578. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74579. lineTo (arrowX1, y);
  74580. lineTo (tipX, tipY);
  74581. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74582. }
  74583. lineTo (x + w - cs, y);
  74584. if (cs > 0.0f)
  74585. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74586. if (whichSide == 3)
  74587. {
  74588. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74589. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74590. lineTo (x + w, arrowY1);
  74591. lineTo (tipX, tipY);
  74592. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74593. }
  74594. lineTo (x + w, y + h - cs);
  74595. if (cs > 0.0f)
  74596. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74597. if (whichSide == 2)
  74598. {
  74599. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74600. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74601. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74602. lineTo (tipX, tipY);
  74603. lineTo (arrowX1, y + h);
  74604. }
  74605. lineTo (x + cs, y + h);
  74606. if (cs > 0.0f)
  74607. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74608. if (whichSide == 1)
  74609. {
  74610. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74611. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74612. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74613. lineTo (tipX, tipY);
  74614. lineTo (x, arrowY1);
  74615. }
  74616. lineTo (x, y + cs);
  74617. if (cs > 0.0f)
  74618. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74619. closeSubPath();
  74620. }
  74621. }
  74622. void Path::addPath (const Path& other)
  74623. {
  74624. size_t i = 0;
  74625. while (i < other.numElements)
  74626. {
  74627. const float type = other.data.elements [i++];
  74628. if (type == moveMarker)
  74629. {
  74630. startNewSubPath (other.data.elements [i],
  74631. other.data.elements [i + 1]);
  74632. i += 2;
  74633. }
  74634. else if (type == lineMarker)
  74635. {
  74636. lineTo (other.data.elements [i],
  74637. other.data.elements [i + 1]);
  74638. i += 2;
  74639. }
  74640. else if (type == quadMarker)
  74641. {
  74642. quadraticTo (other.data.elements [i],
  74643. other.data.elements [i + 1],
  74644. other.data.elements [i + 2],
  74645. other.data.elements [i + 3]);
  74646. i += 4;
  74647. }
  74648. else if (type == cubicMarker)
  74649. {
  74650. cubicTo (other.data.elements [i],
  74651. other.data.elements [i + 1],
  74652. other.data.elements [i + 2],
  74653. other.data.elements [i + 3],
  74654. other.data.elements [i + 4],
  74655. other.data.elements [i + 5]);
  74656. i += 6;
  74657. }
  74658. else if (type == closeSubPathMarker)
  74659. {
  74660. closeSubPath();
  74661. }
  74662. else
  74663. {
  74664. // something's gone wrong with the element list!
  74665. jassertfalse;
  74666. }
  74667. }
  74668. }
  74669. void Path::addPath (const Path& other,
  74670. const AffineTransform& transformToApply)
  74671. {
  74672. size_t i = 0;
  74673. while (i < other.numElements)
  74674. {
  74675. const float type = other.data.elements [i++];
  74676. if (type == closeSubPathMarker)
  74677. {
  74678. closeSubPath();
  74679. }
  74680. else
  74681. {
  74682. float x = other.data.elements [i++];
  74683. float y = other.data.elements [i++];
  74684. transformToApply.transformPoint (x, y);
  74685. if (type == moveMarker)
  74686. {
  74687. startNewSubPath (x, y);
  74688. }
  74689. else if (type == lineMarker)
  74690. {
  74691. lineTo (x, y);
  74692. }
  74693. else if (type == quadMarker)
  74694. {
  74695. float x2 = other.data.elements [i++];
  74696. float y2 = other.data.elements [i++];
  74697. transformToApply.transformPoint (x2, y2);
  74698. quadraticTo (x, y, x2, y2);
  74699. }
  74700. else if (type == cubicMarker)
  74701. {
  74702. float x2 = other.data.elements [i++];
  74703. float y2 = other.data.elements [i++];
  74704. float x3 = other.data.elements [i++];
  74705. float y3 = other.data.elements [i++];
  74706. transformToApply.transformPoints (x2, y2, x3, y3);
  74707. cubicTo (x, y, x2, y2, x3, y3);
  74708. }
  74709. else
  74710. {
  74711. // something's gone wrong with the element list!
  74712. jassertfalse;
  74713. }
  74714. }
  74715. }
  74716. }
  74717. void Path::applyTransform (const AffineTransform& transform) throw()
  74718. {
  74719. size_t i = 0;
  74720. pathYMin = pathXMin = 0;
  74721. pathYMax = pathXMax = 0;
  74722. bool setMaxMin = false;
  74723. while (i < numElements)
  74724. {
  74725. const float type = data.elements [i++];
  74726. if (type == moveMarker)
  74727. {
  74728. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74729. if (setMaxMin)
  74730. {
  74731. pathXMin = jmin (pathXMin, data.elements [i]);
  74732. pathXMax = jmax (pathXMax, data.elements [i]);
  74733. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74734. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74735. }
  74736. else
  74737. {
  74738. pathXMin = pathXMax = data.elements [i];
  74739. pathYMin = pathYMax = data.elements [i + 1];
  74740. setMaxMin = true;
  74741. }
  74742. i += 2;
  74743. }
  74744. else if (type == lineMarker)
  74745. {
  74746. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74747. pathXMin = jmin (pathXMin, data.elements [i]);
  74748. pathXMax = jmax (pathXMax, data.elements [i]);
  74749. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74750. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74751. i += 2;
  74752. }
  74753. else if (type == quadMarker)
  74754. {
  74755. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74756. data.elements [i + 2], data.elements [i + 3]);
  74757. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74758. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74759. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74760. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74761. i += 4;
  74762. }
  74763. else if (type == cubicMarker)
  74764. {
  74765. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74766. data.elements [i + 2], data.elements [i + 3],
  74767. data.elements [i + 4], data.elements [i + 5]);
  74768. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74769. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74770. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74771. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74772. i += 6;
  74773. }
  74774. }
  74775. }
  74776. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74777. const float w, const float h,
  74778. const bool preserveProportions,
  74779. const Justification& justification) const
  74780. {
  74781. Rectangle<float> bounds (getBounds());
  74782. if (preserveProportions)
  74783. {
  74784. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74785. return AffineTransform::identity;
  74786. float newW, newH;
  74787. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74788. if (srcRatio > h / w)
  74789. {
  74790. newW = h / srcRatio;
  74791. newH = h;
  74792. }
  74793. else
  74794. {
  74795. newW = w;
  74796. newH = w * srcRatio;
  74797. }
  74798. float newXCentre = x;
  74799. float newYCentre = y;
  74800. if (justification.testFlags (Justification::left))
  74801. newXCentre += newW * 0.5f;
  74802. else if (justification.testFlags (Justification::right))
  74803. newXCentre += w - newW * 0.5f;
  74804. else
  74805. newXCentre += w * 0.5f;
  74806. if (justification.testFlags (Justification::top))
  74807. newYCentre += newH * 0.5f;
  74808. else if (justification.testFlags (Justification::bottom))
  74809. newYCentre += h - newH * 0.5f;
  74810. else
  74811. newYCentre += h * 0.5f;
  74812. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74813. bounds.getHeight() * -0.5f - bounds.getY())
  74814. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74815. .translated (newXCentre, newYCentre);
  74816. }
  74817. else
  74818. {
  74819. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74820. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74821. .translated (x, y);
  74822. }
  74823. }
  74824. bool Path::contains (const float x, const float y, const float tolerence) const
  74825. {
  74826. if (x <= pathXMin || x >= pathXMax
  74827. || y <= pathYMin || y >= pathYMax)
  74828. return false;
  74829. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74830. int positiveCrossings = 0;
  74831. int negativeCrossings = 0;
  74832. while (i.next())
  74833. {
  74834. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74835. {
  74836. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74837. if (intersectX <= x)
  74838. {
  74839. if (i.y1 < i.y2)
  74840. ++positiveCrossings;
  74841. else
  74842. ++negativeCrossings;
  74843. }
  74844. }
  74845. }
  74846. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74847. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74848. }
  74849. bool Path::contains (const Point<float>& point, const float tolerence) const
  74850. {
  74851. return contains (point.getX(), point.getY(), tolerence);
  74852. }
  74853. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74854. {
  74855. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74856. Point<float> intersection;
  74857. while (i.next())
  74858. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74859. return true;
  74860. return false;
  74861. }
  74862. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74863. {
  74864. Line<float> result (line);
  74865. const bool startInside = contains (line.getStart());
  74866. const bool endInside = contains (line.getEnd());
  74867. if (startInside == endInside)
  74868. {
  74869. if (keepSectionOutsidePath == startInside)
  74870. result = Line<float>();
  74871. }
  74872. else
  74873. {
  74874. PathFlatteningIterator i (*this, AffineTransform::identity);
  74875. Point<float> intersection;
  74876. while (i.next())
  74877. {
  74878. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74879. {
  74880. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74881. result.setStart (intersection);
  74882. else
  74883. result.setEnd (intersection);
  74884. }
  74885. }
  74886. }
  74887. return result;
  74888. }
  74889. float Path::getLength (const AffineTransform& transform) const
  74890. {
  74891. float length = 0;
  74892. PathFlatteningIterator i (*this, transform);
  74893. while (i.next())
  74894. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74895. return length;
  74896. }
  74897. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74898. {
  74899. PathFlatteningIterator i (*this, transform);
  74900. while (i.next())
  74901. {
  74902. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74903. const float lineLength = line.getLength();
  74904. if (distanceFromStart <= lineLength)
  74905. return line.getPointAlongLine (distanceFromStart);
  74906. distanceFromStart -= lineLength;
  74907. }
  74908. return Point<float> (i.x2, i.y2);
  74909. }
  74910. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74911. const AffineTransform& transform) const
  74912. {
  74913. PathFlatteningIterator i (*this, transform);
  74914. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74915. float length = 0;
  74916. Point<float> pointOnLine;
  74917. while (i.next())
  74918. {
  74919. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74920. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74921. if (distance < bestDistance)
  74922. {
  74923. bestDistance = distance;
  74924. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74925. pointOnPath = pointOnLine;
  74926. }
  74927. length += line.getLength();
  74928. }
  74929. return bestPosition;
  74930. }
  74931. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74932. {
  74933. if (cornerRadius <= 0.01f)
  74934. return *this;
  74935. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74936. size_t n = 0;
  74937. bool lastWasLine = false, firstWasLine = false;
  74938. Path p;
  74939. while (n < numElements)
  74940. {
  74941. const float type = data.elements [n++];
  74942. if (type == moveMarker)
  74943. {
  74944. indexOfPathStart = p.numElements;
  74945. indexOfPathStartThis = n - 1;
  74946. const float x = data.elements [n++];
  74947. const float y = data.elements [n++];
  74948. p.startNewSubPath (x, y);
  74949. lastWasLine = false;
  74950. firstWasLine = (data.elements [n] == lineMarker);
  74951. }
  74952. else if (type == lineMarker || type == closeSubPathMarker)
  74953. {
  74954. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74955. if (type == lineMarker)
  74956. {
  74957. endX = data.elements [n++];
  74958. endY = data.elements [n++];
  74959. if (n > 8)
  74960. {
  74961. startX = data.elements [n - 8];
  74962. startY = data.elements [n - 7];
  74963. joinX = data.elements [n - 5];
  74964. joinY = data.elements [n - 4];
  74965. }
  74966. }
  74967. else
  74968. {
  74969. endX = data.elements [indexOfPathStartThis + 1];
  74970. endY = data.elements [indexOfPathStartThis + 2];
  74971. if (n > 6)
  74972. {
  74973. startX = data.elements [n - 6];
  74974. startY = data.elements [n - 5];
  74975. joinX = data.elements [n - 3];
  74976. joinY = data.elements [n - 2];
  74977. }
  74978. }
  74979. if (lastWasLine)
  74980. {
  74981. const double len1 = juce_hypot (startX - joinX,
  74982. startY - joinY);
  74983. if (len1 > 0)
  74984. {
  74985. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74986. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74987. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74988. }
  74989. const double len2 = juce_hypot (endX - joinX,
  74990. endY - joinY);
  74991. if (len2 > 0)
  74992. {
  74993. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74994. p.quadraticTo (joinX, joinY,
  74995. (float) (joinX + (endX - joinX) * propNeeded),
  74996. (float) (joinY + (endY - joinY) * propNeeded));
  74997. }
  74998. p.lineTo (endX, endY);
  74999. }
  75000. else if (type == lineMarker)
  75001. {
  75002. p.lineTo (endX, endY);
  75003. lastWasLine = true;
  75004. }
  75005. if (type == closeSubPathMarker)
  75006. {
  75007. if (firstWasLine)
  75008. {
  75009. startX = data.elements [n - 3];
  75010. startY = data.elements [n - 2];
  75011. joinX = endX;
  75012. joinY = endY;
  75013. endX = data.elements [indexOfPathStartThis + 4];
  75014. endY = data.elements [indexOfPathStartThis + 5];
  75015. const double len1 = juce_hypot (startX - joinX,
  75016. startY - joinY);
  75017. if (len1 > 0)
  75018. {
  75019. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75020. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75021. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75022. }
  75023. const double len2 = juce_hypot (endX - joinX,
  75024. endY - joinY);
  75025. if (len2 > 0)
  75026. {
  75027. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75028. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75029. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75030. p.quadraticTo (joinX, joinY, endX, endY);
  75031. p.data.elements [indexOfPathStart + 1] = endX;
  75032. p.data.elements [indexOfPathStart + 2] = endY;
  75033. }
  75034. }
  75035. p.closeSubPath();
  75036. }
  75037. }
  75038. else if (type == quadMarker)
  75039. {
  75040. lastWasLine = false;
  75041. const float x1 = data.elements [n++];
  75042. const float y1 = data.elements [n++];
  75043. const float x2 = data.elements [n++];
  75044. const float y2 = data.elements [n++];
  75045. p.quadraticTo (x1, y1, x2, y2);
  75046. }
  75047. else if (type == cubicMarker)
  75048. {
  75049. lastWasLine = false;
  75050. const float x1 = data.elements [n++];
  75051. const float y1 = data.elements [n++];
  75052. const float x2 = data.elements [n++];
  75053. const float y2 = data.elements [n++];
  75054. const float x3 = data.elements [n++];
  75055. const float y3 = data.elements [n++];
  75056. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75057. }
  75058. }
  75059. return p;
  75060. }
  75061. void Path::loadPathFromStream (InputStream& source)
  75062. {
  75063. while (! source.isExhausted())
  75064. {
  75065. switch (source.readByte())
  75066. {
  75067. case 'm':
  75068. {
  75069. const float x = source.readFloat();
  75070. const float y = source.readFloat();
  75071. startNewSubPath (x, y);
  75072. break;
  75073. }
  75074. case 'l':
  75075. {
  75076. const float x = source.readFloat();
  75077. const float y = source.readFloat();
  75078. lineTo (x, y);
  75079. break;
  75080. }
  75081. case 'q':
  75082. {
  75083. const float x1 = source.readFloat();
  75084. const float y1 = source.readFloat();
  75085. const float x2 = source.readFloat();
  75086. const float y2 = source.readFloat();
  75087. quadraticTo (x1, y1, x2, y2);
  75088. break;
  75089. }
  75090. case 'b':
  75091. {
  75092. const float x1 = source.readFloat();
  75093. const float y1 = source.readFloat();
  75094. const float x2 = source.readFloat();
  75095. const float y2 = source.readFloat();
  75096. const float x3 = source.readFloat();
  75097. const float y3 = source.readFloat();
  75098. cubicTo (x1, y1, x2, y2, x3, y3);
  75099. break;
  75100. }
  75101. case 'c':
  75102. closeSubPath();
  75103. break;
  75104. case 'n':
  75105. useNonZeroWinding = true;
  75106. break;
  75107. case 'z':
  75108. useNonZeroWinding = false;
  75109. break;
  75110. case 'e':
  75111. return; // end of path marker
  75112. default:
  75113. jassertfalse; // illegal char in the stream
  75114. break;
  75115. }
  75116. }
  75117. }
  75118. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75119. {
  75120. MemoryInputStream in (pathData, numberOfBytes, false);
  75121. loadPathFromStream (in);
  75122. }
  75123. void Path::writePathToStream (OutputStream& dest) const
  75124. {
  75125. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75126. size_t i = 0;
  75127. while (i < numElements)
  75128. {
  75129. const float type = data.elements [i++];
  75130. if (type == moveMarker)
  75131. {
  75132. dest.writeByte ('m');
  75133. dest.writeFloat (data.elements [i++]);
  75134. dest.writeFloat (data.elements [i++]);
  75135. }
  75136. else if (type == lineMarker)
  75137. {
  75138. dest.writeByte ('l');
  75139. dest.writeFloat (data.elements [i++]);
  75140. dest.writeFloat (data.elements [i++]);
  75141. }
  75142. else if (type == quadMarker)
  75143. {
  75144. dest.writeByte ('q');
  75145. dest.writeFloat (data.elements [i++]);
  75146. dest.writeFloat (data.elements [i++]);
  75147. dest.writeFloat (data.elements [i++]);
  75148. dest.writeFloat (data.elements [i++]);
  75149. }
  75150. else if (type == cubicMarker)
  75151. {
  75152. dest.writeByte ('b');
  75153. dest.writeFloat (data.elements [i++]);
  75154. dest.writeFloat (data.elements [i++]);
  75155. dest.writeFloat (data.elements [i++]);
  75156. dest.writeFloat (data.elements [i++]);
  75157. dest.writeFloat (data.elements [i++]);
  75158. dest.writeFloat (data.elements [i++]);
  75159. }
  75160. else if (type == closeSubPathMarker)
  75161. {
  75162. dest.writeByte ('c');
  75163. }
  75164. }
  75165. dest.writeByte ('e'); // marks the end-of-path
  75166. }
  75167. const String Path::toString() const
  75168. {
  75169. MemoryOutputStream s (2048);
  75170. if (! useNonZeroWinding)
  75171. s << 'a';
  75172. size_t i = 0;
  75173. float lastMarker = 0.0f;
  75174. while (i < numElements)
  75175. {
  75176. const float marker = data.elements [i++];
  75177. char markerChar = 0;
  75178. int numCoords = 0;
  75179. if (marker == moveMarker)
  75180. {
  75181. markerChar = 'm';
  75182. numCoords = 2;
  75183. }
  75184. else if (marker == lineMarker)
  75185. {
  75186. markerChar = 'l';
  75187. numCoords = 2;
  75188. }
  75189. else if (marker == quadMarker)
  75190. {
  75191. markerChar = 'q';
  75192. numCoords = 4;
  75193. }
  75194. else if (marker == cubicMarker)
  75195. {
  75196. markerChar = 'c';
  75197. numCoords = 6;
  75198. }
  75199. else
  75200. {
  75201. jassert (marker == closeSubPathMarker);
  75202. markerChar = 'z';
  75203. }
  75204. if (marker != lastMarker)
  75205. {
  75206. if (s.getDataSize() != 0)
  75207. s << ' ';
  75208. s << markerChar;
  75209. lastMarker = marker;
  75210. }
  75211. while (--numCoords >= 0 && i < numElements)
  75212. {
  75213. String coord (data.elements [i++], 3);
  75214. while (coord.endsWithChar ('0') && coord != "0")
  75215. coord = coord.dropLastCharacters (1);
  75216. if (coord.endsWithChar ('.'))
  75217. coord = coord.dropLastCharacters (1);
  75218. if (s.getDataSize() != 0)
  75219. s << ' ';
  75220. s << coord;
  75221. }
  75222. }
  75223. return s.toUTF8();
  75224. }
  75225. void Path::restoreFromString (const String& stringVersion)
  75226. {
  75227. clear();
  75228. setUsingNonZeroWinding (true);
  75229. const juce_wchar* t = stringVersion;
  75230. juce_wchar marker = 'm';
  75231. int numValues = 2;
  75232. float values [6];
  75233. for (;;)
  75234. {
  75235. const String token (PathHelpers::nextToken (t));
  75236. const juce_wchar firstChar = token[0];
  75237. int startNum = 0;
  75238. if (firstChar == 0)
  75239. break;
  75240. if (firstChar == 'm' || firstChar == 'l')
  75241. {
  75242. marker = firstChar;
  75243. numValues = 2;
  75244. }
  75245. else if (firstChar == 'q')
  75246. {
  75247. marker = firstChar;
  75248. numValues = 4;
  75249. }
  75250. else if (firstChar == 'c')
  75251. {
  75252. marker = firstChar;
  75253. numValues = 6;
  75254. }
  75255. else if (firstChar == 'z')
  75256. {
  75257. marker = firstChar;
  75258. numValues = 0;
  75259. }
  75260. else if (firstChar == 'a')
  75261. {
  75262. setUsingNonZeroWinding (false);
  75263. continue;
  75264. }
  75265. else
  75266. {
  75267. ++startNum;
  75268. values [0] = token.getFloatValue();
  75269. }
  75270. for (int i = startNum; i < numValues; ++i)
  75271. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75272. switch (marker)
  75273. {
  75274. case 'm': startNewSubPath (values[0], values[1]); break;
  75275. case 'l': lineTo (values[0], values[1]); break;
  75276. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75277. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75278. case 'z': closeSubPath(); break;
  75279. default: jassertfalse; break; // illegal string format?
  75280. }
  75281. }
  75282. }
  75283. Path::Iterator::Iterator (const Path& path_)
  75284. : path (path_),
  75285. index (0)
  75286. {
  75287. }
  75288. Path::Iterator::~Iterator()
  75289. {
  75290. }
  75291. bool Path::Iterator::next()
  75292. {
  75293. const float* const elements = path.data.elements;
  75294. if (index < path.numElements)
  75295. {
  75296. const float type = elements [index++];
  75297. if (type == moveMarker)
  75298. {
  75299. elementType = startNewSubPath;
  75300. x1 = elements [index++];
  75301. y1 = elements [index++];
  75302. }
  75303. else if (type == lineMarker)
  75304. {
  75305. elementType = lineTo;
  75306. x1 = elements [index++];
  75307. y1 = elements [index++];
  75308. }
  75309. else if (type == quadMarker)
  75310. {
  75311. elementType = quadraticTo;
  75312. x1 = elements [index++];
  75313. y1 = elements [index++];
  75314. x2 = elements [index++];
  75315. y2 = elements [index++];
  75316. }
  75317. else if (type == cubicMarker)
  75318. {
  75319. elementType = cubicTo;
  75320. x1 = elements [index++];
  75321. y1 = elements [index++];
  75322. x2 = elements [index++];
  75323. y2 = elements [index++];
  75324. x3 = elements [index++];
  75325. y3 = elements [index++];
  75326. }
  75327. else if (type == closeSubPathMarker)
  75328. {
  75329. elementType = closePath;
  75330. }
  75331. return true;
  75332. }
  75333. return false;
  75334. }
  75335. END_JUCE_NAMESPACE
  75336. /*** End of inlined file: juce_Path.cpp ***/
  75337. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75338. BEGIN_JUCE_NAMESPACE
  75339. #if JUCE_MSVC && JUCE_DEBUG
  75340. #pragma optimize ("t", on)
  75341. #endif
  75342. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75343. const AffineTransform& transform_,
  75344. float tolerence_)
  75345. : x2 (0),
  75346. y2 (0),
  75347. closesSubPath (false),
  75348. subPathIndex (-1),
  75349. path (path_),
  75350. transform (transform_),
  75351. points (path_.data.elements),
  75352. tolerence (tolerence_ * tolerence_),
  75353. subPathCloseX (0),
  75354. subPathCloseY (0),
  75355. isIdentityTransform (transform_.isIdentity()),
  75356. stackBase (32),
  75357. index (0),
  75358. stackSize (32)
  75359. {
  75360. stackPos = stackBase;
  75361. }
  75362. PathFlatteningIterator::~PathFlatteningIterator()
  75363. {
  75364. }
  75365. bool PathFlatteningIterator::next()
  75366. {
  75367. x1 = x2;
  75368. y1 = y2;
  75369. float x3 = 0;
  75370. float y3 = 0;
  75371. float x4 = 0;
  75372. float y4 = 0;
  75373. float type;
  75374. for (;;)
  75375. {
  75376. if (stackPos == stackBase)
  75377. {
  75378. if (index >= path.numElements)
  75379. {
  75380. return false;
  75381. }
  75382. else
  75383. {
  75384. type = points [index++];
  75385. if (type != Path::closeSubPathMarker)
  75386. {
  75387. x2 = points [index++];
  75388. y2 = points [index++];
  75389. if (type == Path::quadMarker)
  75390. {
  75391. x3 = points [index++];
  75392. y3 = points [index++];
  75393. if (! isIdentityTransform)
  75394. transform.transformPoints (x2, y2, x3, y3);
  75395. }
  75396. else if (type == Path::cubicMarker)
  75397. {
  75398. x3 = points [index++];
  75399. y3 = points [index++];
  75400. x4 = points [index++];
  75401. y4 = points [index++];
  75402. if (! isIdentityTransform)
  75403. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75404. }
  75405. else
  75406. {
  75407. if (! isIdentityTransform)
  75408. transform.transformPoint (x2, y2);
  75409. }
  75410. }
  75411. }
  75412. }
  75413. else
  75414. {
  75415. type = *--stackPos;
  75416. if (type != Path::closeSubPathMarker)
  75417. {
  75418. x2 = *--stackPos;
  75419. y2 = *--stackPos;
  75420. if (type == Path::quadMarker)
  75421. {
  75422. x3 = *--stackPos;
  75423. y3 = *--stackPos;
  75424. }
  75425. else if (type == Path::cubicMarker)
  75426. {
  75427. x3 = *--stackPos;
  75428. y3 = *--stackPos;
  75429. x4 = *--stackPos;
  75430. y4 = *--stackPos;
  75431. }
  75432. }
  75433. }
  75434. if (type == Path::lineMarker)
  75435. {
  75436. ++subPathIndex;
  75437. closesSubPath = (stackPos == stackBase)
  75438. && (index < path.numElements)
  75439. && (points [index] == Path::closeSubPathMarker)
  75440. && x2 == subPathCloseX
  75441. && y2 == subPathCloseY;
  75442. return true;
  75443. }
  75444. else if (type == Path::quadMarker)
  75445. {
  75446. const size_t offset = (size_t) (stackPos - stackBase);
  75447. if (offset >= stackSize - 10)
  75448. {
  75449. stackSize <<= 1;
  75450. stackBase.realloc (stackSize);
  75451. stackPos = stackBase + offset;
  75452. }
  75453. const float dx1 = x1 - x2;
  75454. const float dy1 = y1 - y2;
  75455. const float dx2 = x2 - x3;
  75456. const float dy2 = y2 - y3;
  75457. const float m1x = (x1 + x2) * 0.5f;
  75458. const float m1y = (y1 + y2) * 0.5f;
  75459. const float m2x = (x2 + x3) * 0.5f;
  75460. const float m2y = (y2 + y3) * 0.5f;
  75461. const float m3x = (m1x + m2x) * 0.5f;
  75462. const float m3y = (m1y + m2y) * 0.5f;
  75463. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75464. {
  75465. *stackPos++ = y3;
  75466. *stackPos++ = x3;
  75467. *stackPos++ = m2y;
  75468. *stackPos++ = m2x;
  75469. *stackPos++ = Path::quadMarker;
  75470. *stackPos++ = m3y;
  75471. *stackPos++ = m3x;
  75472. *stackPos++ = m1y;
  75473. *stackPos++ = m1x;
  75474. *stackPos++ = Path::quadMarker;
  75475. }
  75476. else
  75477. {
  75478. *stackPos++ = y3;
  75479. *stackPos++ = x3;
  75480. *stackPos++ = Path::lineMarker;
  75481. *stackPos++ = m3y;
  75482. *stackPos++ = m3x;
  75483. *stackPos++ = Path::lineMarker;
  75484. }
  75485. jassert (stackPos < stackBase + stackSize);
  75486. }
  75487. else if (type == Path::cubicMarker)
  75488. {
  75489. const size_t offset = (size_t) (stackPos - stackBase);
  75490. if (offset >= stackSize - 16)
  75491. {
  75492. stackSize <<= 1;
  75493. stackBase.realloc (stackSize);
  75494. stackPos = stackBase + offset;
  75495. }
  75496. const float dx1 = x1 - x2;
  75497. const float dy1 = y1 - y2;
  75498. const float dx2 = x2 - x3;
  75499. const float dy2 = y2 - y3;
  75500. const float dx3 = x3 - x4;
  75501. const float dy3 = y3 - y4;
  75502. const float m1x = (x1 + x2) * 0.5f;
  75503. const float m1y = (y1 + y2) * 0.5f;
  75504. const float m2x = (x3 + x2) * 0.5f;
  75505. const float m2y = (y3 + y2) * 0.5f;
  75506. const float m3x = (x3 + x4) * 0.5f;
  75507. const float m3y = (y3 + y4) * 0.5f;
  75508. const float m4x = (m1x + m2x) * 0.5f;
  75509. const float m4y = (m1y + m2y) * 0.5f;
  75510. const float m5x = (m3x + m2x) * 0.5f;
  75511. const float m5y = (m3y + m2y) * 0.5f;
  75512. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75513. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75514. {
  75515. *stackPos++ = y4;
  75516. *stackPos++ = x4;
  75517. *stackPos++ = m3y;
  75518. *stackPos++ = m3x;
  75519. *stackPos++ = m5y;
  75520. *stackPos++ = m5x;
  75521. *stackPos++ = Path::cubicMarker;
  75522. *stackPos++ = (m4y + m5y) * 0.5f;
  75523. *stackPos++ = (m4x + m5x) * 0.5f;
  75524. *stackPos++ = m4y;
  75525. *stackPos++ = m4x;
  75526. *stackPos++ = m1y;
  75527. *stackPos++ = m1x;
  75528. *stackPos++ = Path::cubicMarker;
  75529. }
  75530. else
  75531. {
  75532. *stackPos++ = y4;
  75533. *stackPos++ = x4;
  75534. *stackPos++ = Path::lineMarker;
  75535. *stackPos++ = m5y;
  75536. *stackPos++ = m5x;
  75537. *stackPos++ = Path::lineMarker;
  75538. *stackPos++ = m4y;
  75539. *stackPos++ = m4x;
  75540. *stackPos++ = Path::lineMarker;
  75541. }
  75542. }
  75543. else if (type == Path::closeSubPathMarker)
  75544. {
  75545. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75546. {
  75547. x1 = x2;
  75548. y1 = y2;
  75549. x2 = subPathCloseX;
  75550. y2 = subPathCloseY;
  75551. closesSubPath = true;
  75552. return true;
  75553. }
  75554. }
  75555. else
  75556. {
  75557. jassert (type == Path::moveMarker);
  75558. subPathIndex = -1;
  75559. subPathCloseX = x1 = x2;
  75560. subPathCloseY = y1 = y2;
  75561. }
  75562. }
  75563. }
  75564. #if JUCE_MSVC && JUCE_DEBUG
  75565. #pragma optimize ("", on) // resets optimisations to the project defaults
  75566. #endif
  75567. END_JUCE_NAMESPACE
  75568. /*** End of inlined file: juce_PathIterator.cpp ***/
  75569. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75570. BEGIN_JUCE_NAMESPACE
  75571. PathStrokeType::PathStrokeType (const float strokeThickness,
  75572. const JointStyle jointStyle_,
  75573. const EndCapStyle endStyle_) throw()
  75574. : thickness (strokeThickness),
  75575. jointStyle (jointStyle_),
  75576. endStyle (endStyle_)
  75577. {
  75578. }
  75579. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75580. : thickness (other.thickness),
  75581. jointStyle (other.jointStyle),
  75582. endStyle (other.endStyle)
  75583. {
  75584. }
  75585. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75586. {
  75587. thickness = other.thickness;
  75588. jointStyle = other.jointStyle;
  75589. endStyle = other.endStyle;
  75590. return *this;
  75591. }
  75592. PathStrokeType::~PathStrokeType() throw()
  75593. {
  75594. }
  75595. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75596. {
  75597. return thickness == other.thickness
  75598. && jointStyle == other.jointStyle
  75599. && endStyle == other.endStyle;
  75600. }
  75601. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75602. {
  75603. return ! operator== (other);
  75604. }
  75605. namespace PathStrokeHelpers
  75606. {
  75607. bool lineIntersection (const float x1, const float y1,
  75608. const float x2, const float y2,
  75609. const float x3, const float y3,
  75610. const float x4, const float y4,
  75611. float& intersectionX,
  75612. float& intersectionY,
  75613. float& distanceBeyondLine1EndSquared) throw()
  75614. {
  75615. if (x2 != x3 || y2 != y3)
  75616. {
  75617. const float dx1 = x2 - x1;
  75618. const float dy1 = y2 - y1;
  75619. const float dx2 = x4 - x3;
  75620. const float dy2 = y4 - y3;
  75621. const float divisor = dx1 * dy2 - dx2 * dy1;
  75622. if (divisor == 0)
  75623. {
  75624. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75625. {
  75626. if (dy1 == 0 && dy2 != 0)
  75627. {
  75628. const float along = (y1 - y3) / dy2;
  75629. intersectionX = x3 + along * dx2;
  75630. intersectionY = y1;
  75631. distanceBeyondLine1EndSquared = intersectionX - x2;
  75632. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75633. if ((x2 > x1) == (intersectionX < x2))
  75634. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75635. return along >= 0 && along <= 1.0f;
  75636. }
  75637. else if (dy2 == 0 && dy1 != 0)
  75638. {
  75639. const float along = (y3 - y1) / dy1;
  75640. intersectionX = x1 + along * dx1;
  75641. intersectionY = y3;
  75642. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75643. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75644. if (along < 1.0f)
  75645. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75646. return along >= 0 && along <= 1.0f;
  75647. }
  75648. else if (dx1 == 0 && dx2 != 0)
  75649. {
  75650. const float along = (x1 - x3) / dx2;
  75651. intersectionX = x1;
  75652. intersectionY = y3 + along * dy2;
  75653. distanceBeyondLine1EndSquared = intersectionY - y2;
  75654. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75655. if ((y2 > y1) == (intersectionY < y2))
  75656. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75657. return along >= 0 && along <= 1.0f;
  75658. }
  75659. else if (dx2 == 0 && dx1 != 0)
  75660. {
  75661. const float along = (x3 - x1) / dx1;
  75662. intersectionX = x3;
  75663. intersectionY = y1 + along * dy1;
  75664. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75665. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75666. if (along < 1.0f)
  75667. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75668. return along >= 0 && along <= 1.0f;
  75669. }
  75670. }
  75671. intersectionX = 0.5f * (x2 + x3);
  75672. intersectionY = 0.5f * (y2 + y3);
  75673. distanceBeyondLine1EndSquared = 0.0f;
  75674. return false;
  75675. }
  75676. else
  75677. {
  75678. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75679. intersectionX = x1 + along1 * dx1;
  75680. intersectionY = y1 + along1 * dy1;
  75681. if (along1 >= 0 && along1 <= 1.0f)
  75682. {
  75683. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75684. if (along2 >= 0 && along2 <= divisor)
  75685. {
  75686. distanceBeyondLine1EndSquared = 0.0f;
  75687. return true;
  75688. }
  75689. }
  75690. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75691. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75692. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75693. if (along1 < 1.0f)
  75694. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75695. return false;
  75696. }
  75697. }
  75698. intersectionX = x2;
  75699. intersectionY = y2;
  75700. distanceBeyondLine1EndSquared = 0.0f;
  75701. return true;
  75702. }
  75703. void addEdgeAndJoint (Path& destPath,
  75704. const PathStrokeType::JointStyle style,
  75705. const float maxMiterExtensionSquared, const float width,
  75706. const float x1, const float y1,
  75707. const float x2, const float y2,
  75708. const float x3, const float y3,
  75709. const float x4, const float y4,
  75710. const float midX, const float midY)
  75711. {
  75712. if (style == PathStrokeType::beveled
  75713. || (x3 == x4 && y3 == y4)
  75714. || (x1 == x2 && y1 == y2))
  75715. {
  75716. destPath.lineTo (x2, y2);
  75717. destPath.lineTo (x3, y3);
  75718. }
  75719. else
  75720. {
  75721. float jx, jy, distanceBeyondLine1EndSquared;
  75722. // if they intersect, use this point..
  75723. if (lineIntersection (x1, y1, x2, y2,
  75724. x3, y3, x4, y4,
  75725. jx, jy, distanceBeyondLine1EndSquared))
  75726. {
  75727. destPath.lineTo (jx, jy);
  75728. }
  75729. else
  75730. {
  75731. if (style == PathStrokeType::mitered)
  75732. {
  75733. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75734. && distanceBeyondLine1EndSquared > 0.0f)
  75735. {
  75736. destPath.lineTo (jx, jy);
  75737. }
  75738. else
  75739. {
  75740. // the end sticks out too far, so just use a blunt joint
  75741. destPath.lineTo (x2, y2);
  75742. destPath.lineTo (x3, y3);
  75743. }
  75744. }
  75745. else
  75746. {
  75747. // curved joints
  75748. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75749. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75750. const float angleIncrement = 0.1f;
  75751. destPath.lineTo (x2, y2);
  75752. if (std::abs (angle1 - angle2) > angleIncrement)
  75753. {
  75754. if (angle2 > angle1 + float_Pi
  75755. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75756. {
  75757. if (angle2 > angle1)
  75758. angle2 -= float_Pi * 2.0f;
  75759. jassert (angle1 <= angle2 + float_Pi);
  75760. angle1 -= angleIncrement;
  75761. while (angle1 > angle2)
  75762. {
  75763. destPath.lineTo (midX + width * std::sin (angle1),
  75764. midY + width * std::cos (angle1));
  75765. angle1 -= angleIncrement;
  75766. }
  75767. }
  75768. else
  75769. {
  75770. if (angle1 > angle2)
  75771. angle1 -= float_Pi * 2.0f;
  75772. jassert (angle1 >= angle2 - float_Pi);
  75773. angle1 += angleIncrement;
  75774. while (angle1 < angle2)
  75775. {
  75776. destPath.lineTo (midX + width * std::sin (angle1),
  75777. midY + width * std::cos (angle1));
  75778. angle1 += angleIncrement;
  75779. }
  75780. }
  75781. }
  75782. destPath.lineTo (x3, y3);
  75783. }
  75784. }
  75785. }
  75786. }
  75787. void addLineEnd (Path& destPath,
  75788. const PathStrokeType::EndCapStyle style,
  75789. const float x1, const float y1,
  75790. const float x2, const float y2,
  75791. const float width)
  75792. {
  75793. if (style == PathStrokeType::butt)
  75794. {
  75795. destPath.lineTo (x2, y2);
  75796. }
  75797. else
  75798. {
  75799. float offx1, offy1, offx2, offy2;
  75800. float dx = x2 - x1;
  75801. float dy = y2 - y1;
  75802. const float len = juce_hypotf (dx, dy);
  75803. if (len == 0)
  75804. {
  75805. offx1 = offx2 = x1;
  75806. offy1 = offy2 = y1;
  75807. }
  75808. else
  75809. {
  75810. const float offset = width / len;
  75811. dx *= offset;
  75812. dy *= offset;
  75813. offx1 = x1 + dy;
  75814. offy1 = y1 - dx;
  75815. offx2 = x2 + dy;
  75816. offy2 = y2 - dx;
  75817. }
  75818. if (style == PathStrokeType::square)
  75819. {
  75820. // sqaure ends
  75821. destPath.lineTo (offx1, offy1);
  75822. destPath.lineTo (offx2, offy2);
  75823. destPath.lineTo (x2, y2);
  75824. }
  75825. else
  75826. {
  75827. // rounded ends
  75828. const float midx = (offx1 + offx2) * 0.5f;
  75829. const float midy = (offy1 + offy2) * 0.5f;
  75830. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75831. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75832. midx, midy);
  75833. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75834. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75835. x2, y2);
  75836. }
  75837. }
  75838. }
  75839. struct Arrowhead
  75840. {
  75841. float startWidth, startLength;
  75842. float endWidth, endLength;
  75843. };
  75844. void addArrowhead (Path& destPath,
  75845. const float x1, const float y1,
  75846. const float x2, const float y2,
  75847. const float tipX, const float tipY,
  75848. const float width,
  75849. const float arrowheadWidth)
  75850. {
  75851. Line<float> line (x1, y1, x2, y2);
  75852. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75853. destPath.lineTo (tipX, tipY);
  75854. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75855. destPath.lineTo (x2, y2);
  75856. }
  75857. struct LineSection
  75858. {
  75859. float x1, y1, x2, y2; // original line
  75860. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75861. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75862. };
  75863. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75864. {
  75865. while (amountAtEnd > 0 && subPath.size() > 0)
  75866. {
  75867. LineSection& l = subPath.getReference (subPath.size() - 1);
  75868. float dx = l.rx2 - l.rx1;
  75869. float dy = l.ry2 - l.ry1;
  75870. const float len = juce_hypotf (dx, dy);
  75871. if (len <= amountAtEnd && subPath.size() > 1)
  75872. {
  75873. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75874. prev.x2 = l.x2;
  75875. prev.y2 = l.y2;
  75876. subPath.removeLast();
  75877. amountAtEnd -= len;
  75878. }
  75879. else
  75880. {
  75881. const float prop = jmin (0.9999f, amountAtEnd / len);
  75882. dx *= prop;
  75883. dy *= prop;
  75884. l.rx1 += dx;
  75885. l.ry1 += dy;
  75886. l.lx2 += dx;
  75887. l.ly2 += dy;
  75888. break;
  75889. }
  75890. }
  75891. while (amountAtStart > 0 && subPath.size() > 0)
  75892. {
  75893. LineSection& l = subPath.getReference (0);
  75894. float dx = l.rx2 - l.rx1;
  75895. float dy = l.ry2 - l.ry1;
  75896. const float len = juce_hypotf (dx, dy);
  75897. if (len <= amountAtStart && subPath.size() > 1)
  75898. {
  75899. LineSection& next = subPath.getReference (1);
  75900. next.x1 = l.x1;
  75901. next.y1 = l.y1;
  75902. subPath.remove (0);
  75903. amountAtStart -= len;
  75904. }
  75905. else
  75906. {
  75907. const float prop = jmin (0.9999f, amountAtStart / len);
  75908. dx *= prop;
  75909. dy *= prop;
  75910. l.rx2 -= dx;
  75911. l.ry2 -= dy;
  75912. l.lx1 -= dx;
  75913. l.ly1 -= dy;
  75914. break;
  75915. }
  75916. }
  75917. }
  75918. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75919. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75920. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75921. const Arrowhead* const arrowhead)
  75922. {
  75923. jassert (subPath.size() > 0);
  75924. if (arrowhead != 0)
  75925. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75926. const LineSection& firstLine = subPath.getReference (0);
  75927. float lastX1 = firstLine.lx1;
  75928. float lastY1 = firstLine.ly1;
  75929. float lastX2 = firstLine.lx2;
  75930. float lastY2 = firstLine.ly2;
  75931. if (isClosed)
  75932. {
  75933. destPath.startNewSubPath (lastX1, lastY1);
  75934. }
  75935. else
  75936. {
  75937. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75938. if (arrowhead != 0)
  75939. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75940. width, arrowhead->startWidth);
  75941. else
  75942. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75943. }
  75944. int i;
  75945. for (i = 1; i < subPath.size(); ++i)
  75946. {
  75947. const LineSection& l = subPath.getReference (i);
  75948. addEdgeAndJoint (destPath, jointStyle,
  75949. maxMiterExtensionSquared, width,
  75950. lastX1, lastY1, lastX2, lastY2,
  75951. l.lx1, l.ly1, l.lx2, l.ly2,
  75952. l.x1, l.y1);
  75953. lastX1 = l.lx1;
  75954. lastY1 = l.ly1;
  75955. lastX2 = l.lx2;
  75956. lastY2 = l.ly2;
  75957. }
  75958. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75959. if (isClosed)
  75960. {
  75961. const LineSection& l = subPath.getReference (0);
  75962. addEdgeAndJoint (destPath, jointStyle,
  75963. maxMiterExtensionSquared, width,
  75964. lastX1, lastY1, lastX2, lastY2,
  75965. l.lx1, l.ly1, l.lx2, l.ly2,
  75966. l.x1, l.y1);
  75967. destPath.closeSubPath();
  75968. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75969. }
  75970. else
  75971. {
  75972. destPath.lineTo (lastX2, lastY2);
  75973. if (arrowhead != 0)
  75974. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75975. width, arrowhead->endWidth);
  75976. else
  75977. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75978. }
  75979. lastX1 = lastLine.rx1;
  75980. lastY1 = lastLine.ry1;
  75981. lastX2 = lastLine.rx2;
  75982. lastY2 = lastLine.ry2;
  75983. for (i = subPath.size() - 1; --i >= 0;)
  75984. {
  75985. const LineSection& l = subPath.getReference (i);
  75986. addEdgeAndJoint (destPath, jointStyle,
  75987. maxMiterExtensionSquared, width,
  75988. lastX1, lastY1, lastX2, lastY2,
  75989. l.rx1, l.ry1, l.rx2, l.ry2,
  75990. l.x2, l.y2);
  75991. lastX1 = l.rx1;
  75992. lastY1 = l.ry1;
  75993. lastX2 = l.rx2;
  75994. lastY2 = l.ry2;
  75995. }
  75996. if (isClosed)
  75997. {
  75998. addEdgeAndJoint (destPath, jointStyle,
  75999. maxMiterExtensionSquared, width,
  76000. lastX1, lastY1, lastX2, lastY2,
  76001. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76002. lastLine.x2, lastLine.y2);
  76003. }
  76004. else
  76005. {
  76006. // do the last line
  76007. destPath.lineTo (lastX2, lastY2);
  76008. }
  76009. destPath.closeSubPath();
  76010. }
  76011. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76012. const PathStrokeType::EndCapStyle endStyle,
  76013. Path& destPath, const Path& source,
  76014. const AffineTransform& transform,
  76015. const float extraAccuracy, const Arrowhead* const arrowhead)
  76016. {
  76017. if (thickness <= 0)
  76018. {
  76019. destPath.clear();
  76020. return;
  76021. }
  76022. const Path* sourcePath = &source;
  76023. Path temp;
  76024. if (sourcePath == &destPath)
  76025. {
  76026. destPath.swapWithPath (temp);
  76027. sourcePath = &temp;
  76028. }
  76029. else
  76030. {
  76031. destPath.clear();
  76032. }
  76033. destPath.setUsingNonZeroWinding (true);
  76034. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76035. const float width = 0.5f * thickness;
  76036. // Iterate the path, creating a list of the
  76037. // left/right-hand lines along either side of it...
  76038. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  76039. Array <LineSection> subPath;
  76040. subPath.ensureStorageAllocated (512);
  76041. LineSection l;
  76042. l.x1 = 0;
  76043. l.y1 = 0;
  76044. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  76045. while (it.next())
  76046. {
  76047. if (it.subPathIndex == 0)
  76048. {
  76049. if (subPath.size() > 0)
  76050. {
  76051. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76052. subPath.clearQuick();
  76053. }
  76054. l.x1 = it.x1;
  76055. l.y1 = it.y1;
  76056. }
  76057. l.x2 = it.x2;
  76058. l.y2 = it.y2;
  76059. float dx = l.x2 - l.x1;
  76060. float dy = l.y2 - l.y1;
  76061. const float hypotSquared = dx*dx + dy*dy;
  76062. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76063. {
  76064. const float len = std::sqrt (hypotSquared);
  76065. if (len == 0)
  76066. {
  76067. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76068. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76069. }
  76070. else
  76071. {
  76072. const float offset = width / len;
  76073. dx *= offset;
  76074. dy *= offset;
  76075. l.rx2 = l.x1 - dy;
  76076. l.ry2 = l.y1 + dx;
  76077. l.lx1 = l.x1 + dy;
  76078. l.ly1 = l.y1 - dx;
  76079. l.lx2 = l.x2 + dy;
  76080. l.ly2 = l.y2 - dx;
  76081. l.rx1 = l.x2 - dy;
  76082. l.ry1 = l.y2 + dx;
  76083. }
  76084. subPath.add (l);
  76085. if (it.closesSubPath)
  76086. {
  76087. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76088. subPath.clearQuick();
  76089. }
  76090. else
  76091. {
  76092. l.x1 = it.x2;
  76093. l.y1 = it.y2;
  76094. }
  76095. }
  76096. }
  76097. if (subPath.size() > 0)
  76098. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76099. }
  76100. }
  76101. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76102. const AffineTransform& transform, const float extraAccuracy) const
  76103. {
  76104. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76105. transform, extraAccuracy, 0);
  76106. }
  76107. void PathStrokeType::createDashedStroke (Path& destPath,
  76108. const Path& sourcePath,
  76109. const float* dashLengths,
  76110. int numDashLengths,
  76111. const AffineTransform& transform,
  76112. const float extraAccuracy) const
  76113. {
  76114. if (thickness <= 0)
  76115. return;
  76116. // this should really be an even number..
  76117. jassert ((numDashLengths & 1) == 0);
  76118. Path newDestPath;
  76119. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  76120. bool first = true;
  76121. int dashNum = 0;
  76122. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76123. float dx = 0.0f, dy = 0.0f;
  76124. for (;;)
  76125. {
  76126. const bool isSolid = ((dashNum & 1) == 0);
  76127. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76128. jassert (dashLen > 0); // must be a positive increment!
  76129. if (dashLen <= 0)
  76130. break;
  76131. pos += dashLen;
  76132. while (pos > lineEndPos)
  76133. {
  76134. if (! it.next())
  76135. {
  76136. if (isSolid && ! first)
  76137. newDestPath.lineTo (it.x2, it.y2);
  76138. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76139. return;
  76140. }
  76141. if (isSolid && ! first)
  76142. newDestPath.lineTo (it.x1, it.y1);
  76143. else
  76144. newDestPath.startNewSubPath (it.x1, it.y1);
  76145. dx = it.x2 - it.x1;
  76146. dy = it.y2 - it.y1;
  76147. lineLen = juce_hypotf (dx, dy);
  76148. lineEndPos += lineLen;
  76149. first = it.closesSubPath;
  76150. }
  76151. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76152. if (isSolid)
  76153. newDestPath.lineTo (it.x1 + dx * alpha,
  76154. it.y1 + dy * alpha);
  76155. else
  76156. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76157. it.y1 + dy * alpha);
  76158. }
  76159. }
  76160. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76161. const Path& sourcePath,
  76162. const float arrowheadStartWidth, const float arrowheadStartLength,
  76163. const float arrowheadEndWidth, const float arrowheadEndLength,
  76164. const AffineTransform& transform,
  76165. const float extraAccuracy) const
  76166. {
  76167. PathStrokeHelpers::Arrowhead head;
  76168. head.startWidth = arrowheadStartWidth;
  76169. head.startLength = arrowheadStartLength;
  76170. head.endWidth = arrowheadEndWidth;
  76171. head.endLength = arrowheadEndLength;
  76172. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76173. destPath, sourcePath, transform, extraAccuracy, &head);
  76174. }
  76175. END_JUCE_NAMESPACE
  76176. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76177. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76178. BEGIN_JUCE_NAMESPACE
  76179. PositionedRectangle::PositionedRectangle() throw()
  76180. : x (0.0),
  76181. y (0.0),
  76182. w (0.0),
  76183. h (0.0),
  76184. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76185. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76186. wMode (absoluteSize),
  76187. hMode (absoluteSize)
  76188. {
  76189. }
  76190. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76191. : x (other.x),
  76192. y (other.y),
  76193. w (other.w),
  76194. h (other.h),
  76195. xMode (other.xMode),
  76196. yMode (other.yMode),
  76197. wMode (other.wMode),
  76198. hMode (other.hMode)
  76199. {
  76200. }
  76201. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76202. {
  76203. x = other.x;
  76204. y = other.y;
  76205. w = other.w;
  76206. h = other.h;
  76207. xMode = other.xMode;
  76208. yMode = other.yMode;
  76209. wMode = other.wMode;
  76210. hMode = other.hMode;
  76211. return *this;
  76212. }
  76213. PositionedRectangle::~PositionedRectangle() throw()
  76214. {
  76215. }
  76216. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76217. {
  76218. return x == other.x
  76219. && y == other.y
  76220. && w == other.w
  76221. && h == other.h
  76222. && xMode == other.xMode
  76223. && yMode == other.yMode
  76224. && wMode == other.wMode
  76225. && hMode == other.hMode;
  76226. }
  76227. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76228. {
  76229. return ! operator== (other);
  76230. }
  76231. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76232. {
  76233. StringArray tokens;
  76234. tokens.addTokens (stringVersion, false);
  76235. decodePosString (tokens [0], xMode, x);
  76236. decodePosString (tokens [1], yMode, y);
  76237. decodeSizeString (tokens [2], wMode, w);
  76238. decodeSizeString (tokens [3], hMode, h);
  76239. }
  76240. const String PositionedRectangle::toString() const throw()
  76241. {
  76242. String s;
  76243. s.preallocateStorage (12);
  76244. addPosDescription (s, xMode, x);
  76245. s << ' ';
  76246. addPosDescription (s, yMode, y);
  76247. s << ' ';
  76248. addSizeDescription (s, wMode, w);
  76249. s << ' ';
  76250. addSizeDescription (s, hMode, h);
  76251. return s;
  76252. }
  76253. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76254. {
  76255. jassert (! target.isEmpty());
  76256. double x_, y_, w_, h_;
  76257. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76258. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76259. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76260. roundToInt (w_), roundToInt (h_));
  76261. }
  76262. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76263. double& x_, double& y_,
  76264. double& w_, double& h_) const throw()
  76265. {
  76266. jassert (! target.isEmpty());
  76267. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76268. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76269. }
  76270. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76271. {
  76272. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76273. }
  76274. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76275. const Rectangle<int>& target) throw()
  76276. {
  76277. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76278. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76279. }
  76280. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76281. const double newW, const double newH,
  76282. const Rectangle<int>& target) throw()
  76283. {
  76284. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76285. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76286. }
  76287. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76288. {
  76289. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76290. updateFrom (comp.getBounds(), Rectangle<int>());
  76291. else
  76292. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76293. }
  76294. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76295. {
  76296. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76297. }
  76298. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76299. {
  76300. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76301. | absoluteFromParentBottomRight
  76302. | absoluteFromParentCentre
  76303. | proportionOfParentSize));
  76304. }
  76305. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76306. {
  76307. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76308. }
  76309. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76310. {
  76311. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76312. | absoluteFromParentBottomRight
  76313. | absoluteFromParentCentre
  76314. | proportionOfParentSize));
  76315. }
  76316. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76317. {
  76318. return (SizeMode) wMode;
  76319. }
  76320. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76321. {
  76322. return (SizeMode) hMode;
  76323. }
  76324. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76325. const PositionMode xMode_,
  76326. const AnchorPoint yAnchor,
  76327. const PositionMode yMode_,
  76328. const SizeMode widthMode,
  76329. const SizeMode heightMode,
  76330. const Rectangle<int>& target) throw()
  76331. {
  76332. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76333. {
  76334. double tx, tw;
  76335. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76336. xMode = (uint8) (xAnchor | xMode_);
  76337. wMode = (uint8) widthMode;
  76338. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76339. }
  76340. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76341. {
  76342. double ty, th;
  76343. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76344. yMode = (uint8) (yAnchor | yMode_);
  76345. hMode = (uint8) heightMode;
  76346. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76347. }
  76348. }
  76349. bool PositionedRectangle::isPositionAbsolute() const throw()
  76350. {
  76351. return xMode == absoluteFromParentTopLeft
  76352. && yMode == absoluteFromParentTopLeft
  76353. && wMode == absoluteSize
  76354. && hMode == absoluteSize;
  76355. }
  76356. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76357. {
  76358. if ((mode & proportionOfParentSize) != 0)
  76359. {
  76360. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76361. }
  76362. else
  76363. {
  76364. s << (roundToInt (value * 100.0) / 100.0);
  76365. if ((mode & absoluteFromParentBottomRight) != 0)
  76366. s << 'R';
  76367. else if ((mode & absoluteFromParentCentre) != 0)
  76368. s << 'C';
  76369. }
  76370. if ((mode & anchorAtRightOrBottom) != 0)
  76371. s << 'r';
  76372. else if ((mode & anchorAtCentre) != 0)
  76373. s << 'c';
  76374. }
  76375. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76376. {
  76377. if (mode == proportionalSize)
  76378. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76379. else if (mode == parentSizeMinusAbsolute)
  76380. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76381. else
  76382. s << (roundToInt (value * 100.0) / 100.0);
  76383. }
  76384. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76385. {
  76386. if (s.containsChar ('r'))
  76387. mode = anchorAtRightOrBottom;
  76388. else if (s.containsChar ('c'))
  76389. mode = anchorAtCentre;
  76390. else
  76391. mode = anchorAtLeftOrTop;
  76392. if (s.containsChar ('%'))
  76393. {
  76394. mode |= proportionOfParentSize;
  76395. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76396. }
  76397. else
  76398. {
  76399. if (s.containsChar ('R'))
  76400. mode |= absoluteFromParentBottomRight;
  76401. else if (s.containsChar ('C'))
  76402. mode |= absoluteFromParentCentre;
  76403. else
  76404. mode |= absoluteFromParentTopLeft;
  76405. value = s.removeCharacters ("rcRC").getDoubleValue();
  76406. }
  76407. }
  76408. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76409. {
  76410. if (s.containsChar ('%'))
  76411. {
  76412. mode = proportionalSize;
  76413. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76414. }
  76415. else if (s.containsChar ('M'))
  76416. {
  76417. mode = parentSizeMinusAbsolute;
  76418. value = s.getDoubleValue();
  76419. }
  76420. else
  76421. {
  76422. mode = absoluteSize;
  76423. value = s.getDoubleValue();
  76424. }
  76425. }
  76426. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76427. const double x_, const double w_,
  76428. const uint8 xMode_, const uint8 wMode_,
  76429. const int parentPos,
  76430. const int parentSize) const throw()
  76431. {
  76432. if (wMode_ == proportionalSize)
  76433. wOut = roundToInt (w_ * parentSize);
  76434. else if (wMode_ == parentSizeMinusAbsolute)
  76435. wOut = jmax (0, parentSize - roundToInt (w_));
  76436. else
  76437. wOut = roundToInt (w_);
  76438. if ((xMode_ & proportionOfParentSize) != 0)
  76439. xOut = parentPos + x_ * parentSize;
  76440. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76441. xOut = (parentPos + parentSize) - x_;
  76442. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76443. xOut = x_ + (parentPos + parentSize / 2);
  76444. else
  76445. xOut = x_ + parentPos;
  76446. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76447. xOut -= wOut;
  76448. else if ((xMode_ & anchorAtCentre) != 0)
  76449. xOut -= wOut / 2;
  76450. }
  76451. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76452. double x_, const double w_,
  76453. const uint8 xMode_, const uint8 wMode_,
  76454. const int parentPos,
  76455. const int parentSize) const throw()
  76456. {
  76457. if (wMode_ == proportionalSize)
  76458. {
  76459. if (parentSize > 0)
  76460. wOut = w_ / parentSize;
  76461. }
  76462. else if (wMode_ == parentSizeMinusAbsolute)
  76463. wOut = parentSize - w_;
  76464. else
  76465. wOut = w_;
  76466. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76467. x_ += w_;
  76468. else if ((xMode_ & anchorAtCentre) != 0)
  76469. x_ += w_ / 2;
  76470. if ((xMode_ & proportionOfParentSize) != 0)
  76471. {
  76472. if (parentSize > 0)
  76473. xOut = (x_ - parentPos) / parentSize;
  76474. }
  76475. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76476. xOut = (parentPos + parentSize) - x_;
  76477. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76478. xOut = x_ - (parentPos + parentSize / 2);
  76479. else
  76480. xOut = x_ - parentPos;
  76481. }
  76482. END_JUCE_NAMESPACE
  76483. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76484. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76485. BEGIN_JUCE_NAMESPACE
  76486. RectangleList::RectangleList() throw()
  76487. {
  76488. }
  76489. RectangleList::RectangleList (const Rectangle<int>& rect)
  76490. {
  76491. if (! rect.isEmpty())
  76492. rects.add (rect);
  76493. }
  76494. RectangleList::RectangleList (const RectangleList& other)
  76495. : rects (other.rects)
  76496. {
  76497. }
  76498. RectangleList& RectangleList::operator= (const RectangleList& other)
  76499. {
  76500. rects = other.rects;
  76501. return *this;
  76502. }
  76503. RectangleList::~RectangleList()
  76504. {
  76505. }
  76506. void RectangleList::clear()
  76507. {
  76508. rects.clearQuick();
  76509. }
  76510. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76511. {
  76512. if (((unsigned int) index) < (unsigned int) rects.size())
  76513. return rects.getReference (index);
  76514. return Rectangle<int>();
  76515. }
  76516. bool RectangleList::isEmpty() const throw()
  76517. {
  76518. return rects.size() == 0;
  76519. }
  76520. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76521. : current (0),
  76522. owner (list),
  76523. index (list.rects.size())
  76524. {
  76525. }
  76526. RectangleList::Iterator::~Iterator()
  76527. {
  76528. }
  76529. bool RectangleList::Iterator::next() throw()
  76530. {
  76531. if (--index >= 0)
  76532. {
  76533. current = & (owner.rects.getReference (index));
  76534. return true;
  76535. }
  76536. return false;
  76537. }
  76538. void RectangleList::add (const Rectangle<int>& rect)
  76539. {
  76540. if (! rect.isEmpty())
  76541. {
  76542. if (rects.size() == 0)
  76543. {
  76544. rects.add (rect);
  76545. }
  76546. else
  76547. {
  76548. bool anyOverlaps = false;
  76549. int i;
  76550. for (i = rects.size(); --i >= 0;)
  76551. {
  76552. Rectangle<int>& ourRect = rects.getReference (i);
  76553. if (rect.intersects (ourRect))
  76554. {
  76555. if (rect.contains (ourRect))
  76556. rects.remove (i);
  76557. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76558. anyOverlaps = true;
  76559. }
  76560. }
  76561. if (anyOverlaps && rects.size() > 0)
  76562. {
  76563. RectangleList r (rect);
  76564. for (i = rects.size(); --i >= 0;)
  76565. {
  76566. const Rectangle<int>& ourRect = rects.getReference (i);
  76567. if (rect.intersects (ourRect))
  76568. {
  76569. r.subtract (ourRect);
  76570. if (r.rects.size() == 0)
  76571. return;
  76572. }
  76573. }
  76574. for (i = r.getNumRectangles(); --i >= 0;)
  76575. rects.add (r.rects.getReference (i));
  76576. }
  76577. else
  76578. {
  76579. rects.add (rect);
  76580. }
  76581. }
  76582. }
  76583. }
  76584. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76585. {
  76586. if (! rect.isEmpty())
  76587. rects.add (rect);
  76588. }
  76589. void RectangleList::add (const int x, const int y, const int w, const int h)
  76590. {
  76591. if (rects.size() == 0)
  76592. {
  76593. if (w > 0 && h > 0)
  76594. rects.add (Rectangle<int> (x, y, w, h));
  76595. }
  76596. else
  76597. {
  76598. add (Rectangle<int> (x, y, w, h));
  76599. }
  76600. }
  76601. void RectangleList::add (const RectangleList& other)
  76602. {
  76603. for (int i = 0; i < other.rects.size(); ++i)
  76604. add (other.rects.getReference (i));
  76605. }
  76606. void RectangleList::subtract (const Rectangle<int>& rect)
  76607. {
  76608. const int originalNumRects = rects.size();
  76609. if (originalNumRects > 0)
  76610. {
  76611. const int x1 = rect.x;
  76612. const int y1 = rect.y;
  76613. const int x2 = x1 + rect.w;
  76614. const int y2 = y1 + rect.h;
  76615. for (int i = getNumRectangles(); --i >= 0;)
  76616. {
  76617. Rectangle<int>& r = rects.getReference (i);
  76618. const int rx1 = r.x;
  76619. const int ry1 = r.y;
  76620. const int rx2 = rx1 + r.w;
  76621. const int ry2 = ry1 + r.h;
  76622. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76623. {
  76624. if (x1 > rx1 && x1 < rx2)
  76625. {
  76626. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76627. {
  76628. r.w = x1 - rx1;
  76629. }
  76630. else
  76631. {
  76632. r.x = x1;
  76633. r.w = rx2 - x1;
  76634. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76635. i += 2;
  76636. }
  76637. }
  76638. else if (x2 > rx1 && x2 < rx2)
  76639. {
  76640. r.x = x2;
  76641. r.w = rx2 - x2;
  76642. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76643. {
  76644. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76645. i += 2;
  76646. }
  76647. }
  76648. else if (y1 > ry1 && y1 < ry2)
  76649. {
  76650. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76651. {
  76652. r.h = y1 - ry1;
  76653. }
  76654. else
  76655. {
  76656. r.y = y1;
  76657. r.h = ry2 - y1;
  76658. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76659. i += 2;
  76660. }
  76661. }
  76662. else if (y2 > ry1 && y2 < ry2)
  76663. {
  76664. r.y = y2;
  76665. r.h = ry2 - y2;
  76666. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76667. {
  76668. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76669. i += 2;
  76670. }
  76671. }
  76672. else
  76673. {
  76674. rects.remove (i);
  76675. }
  76676. }
  76677. }
  76678. }
  76679. }
  76680. bool RectangleList::subtract (const RectangleList& otherList)
  76681. {
  76682. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76683. subtract (otherList.rects.getReference (i));
  76684. return rects.size() > 0;
  76685. }
  76686. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76687. {
  76688. bool notEmpty = false;
  76689. if (rect.isEmpty())
  76690. {
  76691. clear();
  76692. }
  76693. else
  76694. {
  76695. for (int i = rects.size(); --i >= 0;)
  76696. {
  76697. Rectangle<int>& r = rects.getReference (i);
  76698. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76699. rects.remove (i);
  76700. else
  76701. notEmpty = true;
  76702. }
  76703. }
  76704. return notEmpty;
  76705. }
  76706. bool RectangleList::clipTo (const RectangleList& other)
  76707. {
  76708. if (rects.size() == 0)
  76709. return false;
  76710. RectangleList result;
  76711. for (int j = 0; j < rects.size(); ++j)
  76712. {
  76713. const Rectangle<int>& rect = rects.getReference (j);
  76714. for (int i = other.rects.size(); --i >= 0;)
  76715. {
  76716. Rectangle<int> r (other.rects.getReference (i));
  76717. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76718. result.rects.add (r);
  76719. }
  76720. }
  76721. swapWith (result);
  76722. return ! isEmpty();
  76723. }
  76724. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76725. {
  76726. destRegion.clear();
  76727. if (! rect.isEmpty())
  76728. {
  76729. for (int i = rects.size(); --i >= 0;)
  76730. {
  76731. Rectangle<int> r (rects.getReference (i));
  76732. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76733. destRegion.rects.add (r);
  76734. }
  76735. }
  76736. return destRegion.rects.size() > 0;
  76737. }
  76738. void RectangleList::swapWith (RectangleList& otherList) throw()
  76739. {
  76740. rects.swapWithArray (otherList.rects);
  76741. }
  76742. void RectangleList::consolidate()
  76743. {
  76744. int i;
  76745. for (i = 0; i < getNumRectangles() - 1; ++i)
  76746. {
  76747. Rectangle<int>& r = rects.getReference (i);
  76748. const int rx1 = r.x;
  76749. const int ry1 = r.y;
  76750. const int rx2 = rx1 + r.w;
  76751. const int ry2 = ry1 + r.h;
  76752. for (int j = rects.size(); --j > i;)
  76753. {
  76754. Rectangle<int>& r2 = rects.getReference (j);
  76755. const int jrx1 = r2.x;
  76756. const int jry1 = r2.y;
  76757. const int jrx2 = jrx1 + r2.w;
  76758. const int jry2 = jry1 + r2.h;
  76759. // if the vertical edges of any blocks are touching and their horizontals don't
  76760. // line up, split them horizontally..
  76761. if (jrx1 == rx2 || jrx2 == rx1)
  76762. {
  76763. if (jry1 > ry1 && jry1 < ry2)
  76764. {
  76765. r.h = jry1 - ry1;
  76766. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76767. i = -1;
  76768. break;
  76769. }
  76770. if (jry2 > ry1 && jry2 < ry2)
  76771. {
  76772. r.h = jry2 - ry1;
  76773. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76774. i = -1;
  76775. break;
  76776. }
  76777. else if (ry1 > jry1 && ry1 < jry2)
  76778. {
  76779. r2.h = ry1 - jry1;
  76780. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76781. i = -1;
  76782. break;
  76783. }
  76784. else if (ry2 > jry1 && ry2 < jry2)
  76785. {
  76786. r2.h = ry2 - jry1;
  76787. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76788. i = -1;
  76789. break;
  76790. }
  76791. }
  76792. }
  76793. }
  76794. for (i = 0; i < rects.size() - 1; ++i)
  76795. {
  76796. Rectangle<int>& r = rects.getReference (i);
  76797. for (int j = rects.size(); --j > i;)
  76798. {
  76799. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76800. {
  76801. rects.remove (j);
  76802. i = -1;
  76803. break;
  76804. }
  76805. }
  76806. }
  76807. }
  76808. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76809. {
  76810. for (int i = getNumRectangles(); --i >= 0;)
  76811. if (rects.getReference (i).contains (x, y))
  76812. return true;
  76813. return false;
  76814. }
  76815. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76816. {
  76817. if (rects.size() > 1)
  76818. {
  76819. RectangleList r (rectangleToCheck);
  76820. for (int i = rects.size(); --i >= 0;)
  76821. {
  76822. r.subtract (rects.getReference (i));
  76823. if (r.rects.size() == 0)
  76824. return true;
  76825. }
  76826. }
  76827. else if (rects.size() > 0)
  76828. {
  76829. return rects.getReference (0).contains (rectangleToCheck);
  76830. }
  76831. return false;
  76832. }
  76833. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76834. {
  76835. for (int i = rects.size(); --i >= 0;)
  76836. if (rects.getReference (i).intersects (rectangleToCheck))
  76837. return true;
  76838. return false;
  76839. }
  76840. bool RectangleList::intersects (const RectangleList& other) const throw()
  76841. {
  76842. for (int i = rects.size(); --i >= 0;)
  76843. if (other.intersectsRectangle (rects.getReference (i)))
  76844. return true;
  76845. return false;
  76846. }
  76847. const Rectangle<int> RectangleList::getBounds() const throw()
  76848. {
  76849. if (rects.size() <= 1)
  76850. {
  76851. if (rects.size() == 0)
  76852. return Rectangle<int>();
  76853. else
  76854. return rects.getReference (0);
  76855. }
  76856. else
  76857. {
  76858. const Rectangle<int>& r = rects.getReference (0);
  76859. int minX = r.x;
  76860. int minY = r.y;
  76861. int maxX = minX + r.w;
  76862. int maxY = minY + r.h;
  76863. for (int i = rects.size(); --i > 0;)
  76864. {
  76865. const Rectangle<int>& r2 = rects.getReference (i);
  76866. minX = jmin (minX, r2.x);
  76867. minY = jmin (minY, r2.y);
  76868. maxX = jmax (maxX, r2.getRight());
  76869. maxY = jmax (maxY, r2.getBottom());
  76870. }
  76871. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76872. }
  76873. }
  76874. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76875. {
  76876. for (int i = rects.size(); --i >= 0;)
  76877. {
  76878. Rectangle<int>& r = rects.getReference (i);
  76879. r.x += dx;
  76880. r.y += dy;
  76881. }
  76882. }
  76883. const Path RectangleList::toPath() const
  76884. {
  76885. Path p;
  76886. for (int i = rects.size(); --i >= 0;)
  76887. {
  76888. const Rectangle<int>& r = rects.getReference (i);
  76889. p.addRectangle ((float) r.x,
  76890. (float) r.y,
  76891. (float) r.w,
  76892. (float) r.h);
  76893. }
  76894. return p;
  76895. }
  76896. END_JUCE_NAMESPACE
  76897. /*** End of inlined file: juce_RectangleList.cpp ***/
  76898. /*** Start of inlined file: juce_Image.cpp ***/
  76899. BEGIN_JUCE_NAMESPACE
  76900. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76901. : format (format_), width (width_), height (height_)
  76902. {
  76903. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76904. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76905. }
  76906. Image::SharedImage::~SharedImage()
  76907. {
  76908. }
  76909. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76910. {
  76911. return imageData + lineStride * y + pixelStride * x;
  76912. }
  76913. class SoftwareSharedImage : public Image::SharedImage
  76914. {
  76915. public:
  76916. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76917. : Image::SharedImage (format_, width_, height_)
  76918. {
  76919. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76920. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76921. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76922. imageData = imageDataAllocated;
  76923. }
  76924. ~SoftwareSharedImage()
  76925. {
  76926. }
  76927. Image::ImageType getType() const
  76928. {
  76929. return Image::SoftwareImage;
  76930. }
  76931. LowLevelGraphicsContext* createLowLevelContext()
  76932. {
  76933. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76934. }
  76935. Image::SharedImage* clone()
  76936. {
  76937. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76938. memcpy (s->imageData, imageData, lineStride * height);
  76939. return s;
  76940. }
  76941. private:
  76942. HeapBlock<uint8> imageDataAllocated;
  76943. };
  76944. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76945. {
  76946. return new SoftwareSharedImage (format, width, height, clearImage);
  76947. }
  76948. class SubsectionSharedImage : public Image::SharedImage
  76949. {
  76950. public:
  76951. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76952. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76953. image (image_), area (area_)
  76954. {
  76955. pixelStride = image_->getPixelStride();
  76956. lineStride = image_->getLineStride();
  76957. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76958. }
  76959. ~SubsectionSharedImage() {}
  76960. Image::ImageType getType() const
  76961. {
  76962. return Image::SoftwareImage;
  76963. }
  76964. LowLevelGraphicsContext* createLowLevelContext()
  76965. {
  76966. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76967. g->clipToRectangle (area);
  76968. g->setOrigin (area.getX(), area.getY());
  76969. return g;
  76970. }
  76971. Image::SharedImage* clone()
  76972. {
  76973. return new SubsectionSharedImage (image->clone(), area);
  76974. }
  76975. private:
  76976. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76977. const Rectangle<int> area;
  76978. SubsectionSharedImage (const SubsectionSharedImage&);
  76979. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  76980. };
  76981. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76982. {
  76983. if (area.contains (getBounds()))
  76984. return *this;
  76985. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76986. if (validArea.isEmpty())
  76987. return Image::null;
  76988. return Image (new SubsectionSharedImage (image, validArea));
  76989. }
  76990. Image::Image()
  76991. {
  76992. }
  76993. Image::Image (SharedImage* const instance)
  76994. : image (instance)
  76995. {
  76996. }
  76997. Image::Image (const PixelFormat format,
  76998. const int width, const int height,
  76999. const bool clearImage, const ImageType type)
  77000. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  77001. : new SoftwareSharedImage (format, width, height, clearImage))
  77002. {
  77003. }
  77004. Image::Image (const Image& other)
  77005. : image (other.image)
  77006. {
  77007. }
  77008. Image& Image::operator= (const Image& other)
  77009. {
  77010. image = other.image;
  77011. return *this;
  77012. }
  77013. Image::~Image()
  77014. {
  77015. }
  77016. const Image Image::null;
  77017. LowLevelGraphicsContext* Image::createLowLevelContext() const
  77018. {
  77019. return image == 0 ? 0 : image->createLowLevelContext();
  77020. }
  77021. void Image::duplicateIfShared()
  77022. {
  77023. if (image != 0 && image->getReferenceCount() > 1)
  77024. image = image->clone();
  77025. }
  77026. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77027. {
  77028. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77029. return *this;
  77030. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77031. Graphics g (newImage);
  77032. g.setImageResamplingQuality (quality);
  77033. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77034. return newImage;
  77035. }
  77036. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77037. {
  77038. if (image == 0 || newFormat == image->format)
  77039. return *this;
  77040. Image newImage (newFormat, image->width, image->height, false, image->getType());
  77041. if (newFormat == SingleChannel)
  77042. {
  77043. if (! hasAlphaChannel())
  77044. {
  77045. newImage.clear (getBounds(), Colours::black);
  77046. }
  77047. else
  77048. {
  77049. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77050. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77051. for (int y = 0; y < image->height; ++y)
  77052. {
  77053. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77054. uint8* dst = destData.getLinePointer (y);
  77055. for (int x = image->width; --x >= 0;)
  77056. {
  77057. *dst++ = src->getAlpha();
  77058. ++src;
  77059. }
  77060. }
  77061. }
  77062. }
  77063. else
  77064. {
  77065. if (hasAlphaChannel())
  77066. newImage.clear (getBounds());
  77067. Graphics g (newImage);
  77068. g.drawImageAt (*this, 0, 0);
  77069. }
  77070. return newImage;
  77071. }
  77072. NamedValueSet* Image::getProperties() const
  77073. {
  77074. return image == 0 ? 0 : &(image->userData);
  77075. }
  77076. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77077. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77078. pixelFormat (image.getFormat()),
  77079. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77080. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77081. width (w),
  77082. height (h)
  77083. {
  77084. jassert (data != 0);
  77085. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77086. }
  77087. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77088. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77089. pixelFormat (image.getFormat()),
  77090. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77091. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77092. width (w),
  77093. height (h)
  77094. {
  77095. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77096. }
  77097. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77098. : data (image.image == 0 ? 0 : image.image->imageData),
  77099. pixelFormat (image.getFormat()),
  77100. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77101. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77102. width (image.getWidth()),
  77103. height (image.getHeight())
  77104. {
  77105. }
  77106. Image::BitmapData::~BitmapData()
  77107. {
  77108. }
  77109. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77110. {
  77111. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77112. const uint8* const pixel = getPixelPointer (x, y);
  77113. switch (pixelFormat)
  77114. {
  77115. case Image::ARGB:
  77116. {
  77117. PixelARGB p (*(const PixelARGB*) pixel);
  77118. p.unpremultiply();
  77119. return Colour (p.getARGB());
  77120. }
  77121. case Image::RGB:
  77122. return Colour (((const PixelRGB*) pixel)->getARGB());
  77123. case Image::SingleChannel:
  77124. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77125. default:
  77126. jassertfalse;
  77127. break;
  77128. }
  77129. return Colour();
  77130. }
  77131. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77132. {
  77133. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77134. uint8* const pixel = getPixelPointer (x, y);
  77135. const PixelARGB col (colour.getPixelARGB());
  77136. switch (pixelFormat)
  77137. {
  77138. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77139. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77140. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77141. default: jassertfalse; break;
  77142. }
  77143. }
  77144. void Image::setPixelData (int x, int y, int w, int h,
  77145. const uint8* const sourcePixelData, const int sourceLineStride)
  77146. {
  77147. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77148. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77149. {
  77150. const BitmapData dest (*this, x, y, w, h, true);
  77151. for (int i = 0; i < h; ++i)
  77152. {
  77153. memcpy (dest.getLinePointer(i),
  77154. sourcePixelData + sourceLineStride * i,
  77155. w * dest.pixelStride);
  77156. }
  77157. }
  77158. }
  77159. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77160. {
  77161. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77162. if (! clipped.isEmpty())
  77163. {
  77164. const PixelARGB col (colourToClearTo.getPixelARGB());
  77165. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77166. uint8* dest = destData.data;
  77167. int dh = clipped.getHeight();
  77168. while (--dh >= 0)
  77169. {
  77170. uint8* line = dest;
  77171. dest += destData.lineStride;
  77172. if (isARGB())
  77173. {
  77174. for (int x = clipped.getWidth(); --x >= 0;)
  77175. {
  77176. ((PixelARGB*) line)->set (col);
  77177. line += destData.pixelStride;
  77178. }
  77179. }
  77180. else if (isRGB())
  77181. {
  77182. for (int x = clipped.getWidth(); --x >= 0;)
  77183. {
  77184. ((PixelRGB*) line)->set (col);
  77185. line += destData.pixelStride;
  77186. }
  77187. }
  77188. else
  77189. {
  77190. for (int x = clipped.getWidth(); --x >= 0;)
  77191. {
  77192. *line = col.getAlpha();
  77193. line += destData.pixelStride;
  77194. }
  77195. }
  77196. }
  77197. }
  77198. }
  77199. const Colour Image::getPixelAt (const int x, const int y) const
  77200. {
  77201. if (((unsigned int) x) < (unsigned int) getWidth()
  77202. && ((unsigned int) y) < (unsigned int) getHeight())
  77203. {
  77204. const BitmapData srcData (*this, x, y, 1, 1);
  77205. return srcData.getPixelColour (0, 0);
  77206. }
  77207. return Colour();
  77208. }
  77209. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77210. {
  77211. if (((unsigned int) x) < (unsigned int) getWidth()
  77212. && ((unsigned int) y) < (unsigned int) getHeight())
  77213. {
  77214. const BitmapData destData (*this, x, y, 1, 1, true);
  77215. destData.setPixelColour (0, 0, colour);
  77216. }
  77217. }
  77218. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77219. {
  77220. if (((unsigned int) x) < (unsigned int) getWidth()
  77221. && ((unsigned int) y) < (unsigned int) getHeight()
  77222. && hasAlphaChannel())
  77223. {
  77224. const BitmapData destData (*this, x, y, 1, 1, true);
  77225. if (isARGB())
  77226. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77227. else
  77228. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77229. }
  77230. }
  77231. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77232. {
  77233. if (hasAlphaChannel())
  77234. {
  77235. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77236. if (isARGB())
  77237. {
  77238. for (int y = 0; y < destData.height; ++y)
  77239. {
  77240. uint8* p = destData.getLinePointer (y);
  77241. for (int x = 0; x < destData.width; ++x)
  77242. {
  77243. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77244. p += destData.pixelStride;
  77245. }
  77246. }
  77247. }
  77248. else
  77249. {
  77250. for (int y = 0; y < destData.height; ++y)
  77251. {
  77252. uint8* p = destData.getLinePointer (y);
  77253. for (int x = 0; x < destData.width; ++x)
  77254. {
  77255. *p = (uint8) (*p * amountToMultiplyBy);
  77256. p += destData.pixelStride;
  77257. }
  77258. }
  77259. }
  77260. }
  77261. else
  77262. {
  77263. jassertfalse; // can't do this without an alpha-channel!
  77264. }
  77265. }
  77266. void Image::desaturate()
  77267. {
  77268. if (isARGB() || isRGB())
  77269. {
  77270. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77271. if (isARGB())
  77272. {
  77273. for (int y = 0; y < destData.height; ++y)
  77274. {
  77275. uint8* p = destData.getLinePointer (y);
  77276. for (int x = 0; x < destData.width; ++x)
  77277. {
  77278. ((PixelARGB*) p)->desaturate();
  77279. p += destData.pixelStride;
  77280. }
  77281. }
  77282. }
  77283. else
  77284. {
  77285. for (int y = 0; y < destData.height; ++y)
  77286. {
  77287. uint8* p = destData.getLinePointer (y);
  77288. for (int x = 0; x < destData.width; ++x)
  77289. {
  77290. ((PixelRGB*) p)->desaturate();
  77291. p += destData.pixelStride;
  77292. }
  77293. }
  77294. }
  77295. }
  77296. }
  77297. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77298. {
  77299. if (hasAlphaChannel())
  77300. {
  77301. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77302. SparseSet<int> pixelsOnRow;
  77303. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77304. for (int y = 0; y < srcData.height; ++y)
  77305. {
  77306. pixelsOnRow.clear();
  77307. const uint8* lineData = srcData.getLinePointer (y);
  77308. if (isARGB())
  77309. {
  77310. for (int x = 0; x < srcData.width; ++x)
  77311. {
  77312. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77313. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77314. lineData += srcData.pixelStride;
  77315. }
  77316. }
  77317. else
  77318. {
  77319. for (int x = 0; x < srcData.width; ++x)
  77320. {
  77321. if (*lineData >= threshold)
  77322. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77323. lineData += srcData.pixelStride;
  77324. }
  77325. }
  77326. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77327. {
  77328. const Range<int> range (pixelsOnRow.getRange (i));
  77329. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77330. }
  77331. result.consolidate();
  77332. }
  77333. }
  77334. else
  77335. {
  77336. result.add (0, 0, getWidth(), getHeight());
  77337. }
  77338. }
  77339. void Image::moveImageSection (int dx, int dy,
  77340. int sx, int sy,
  77341. int w, int h)
  77342. {
  77343. if (dx < 0)
  77344. {
  77345. w += dx;
  77346. sx -= dx;
  77347. dx = 0;
  77348. }
  77349. if (dy < 0)
  77350. {
  77351. h += dy;
  77352. sy -= dy;
  77353. dy = 0;
  77354. }
  77355. if (sx < 0)
  77356. {
  77357. w += sx;
  77358. dx -= sx;
  77359. sx = 0;
  77360. }
  77361. if (sy < 0)
  77362. {
  77363. h += sy;
  77364. dy -= sy;
  77365. sy = 0;
  77366. }
  77367. const int minX = jmin (dx, sx);
  77368. const int minY = jmin (dy, sy);
  77369. w = jmin (w, getWidth() - jmax (sx, dx));
  77370. h = jmin (h, getHeight() - jmax (sy, dy));
  77371. if (w > 0 && h > 0)
  77372. {
  77373. const int maxX = jmax (dx, sx) + w;
  77374. const int maxY = jmax (dy, sy) + h;
  77375. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77376. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77377. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77378. const int lineSize = destData.pixelStride * w;
  77379. if (dy > sy)
  77380. {
  77381. while (--h >= 0)
  77382. {
  77383. const int offset = h * destData.lineStride;
  77384. memmove (dst + offset, src + offset, lineSize);
  77385. }
  77386. }
  77387. else if (dst != src)
  77388. {
  77389. while (--h >= 0)
  77390. {
  77391. memmove (dst, src, lineSize);
  77392. dst += destData.lineStride;
  77393. src += destData.lineStride;
  77394. }
  77395. }
  77396. }
  77397. }
  77398. END_JUCE_NAMESPACE
  77399. /*** End of inlined file: juce_Image.cpp ***/
  77400. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77401. BEGIN_JUCE_NAMESPACE
  77402. class ImageCache::Pimpl : public Timer,
  77403. public DeletedAtShutdown
  77404. {
  77405. public:
  77406. Pimpl()
  77407. : cacheTimeout (5000)
  77408. {
  77409. }
  77410. ~Pimpl()
  77411. {
  77412. clearSingletonInstance();
  77413. }
  77414. const Image getFromHashCode (const int64 hashCode)
  77415. {
  77416. const ScopedLock sl (lock);
  77417. for (int i = images.size(); --i >= 0;)
  77418. {
  77419. Item* const item = images.getUnchecked(i);
  77420. if (item->hashCode == hashCode)
  77421. return item->image;
  77422. }
  77423. return Image::null;
  77424. }
  77425. void addImageToCache (const Image& image, const int64 hashCode)
  77426. {
  77427. if (image.isValid())
  77428. {
  77429. if (! isTimerRunning())
  77430. startTimer (2000);
  77431. Item* const item = new Item();
  77432. item->hashCode = hashCode;
  77433. item->image = image;
  77434. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77435. const ScopedLock sl (lock);
  77436. images.add (item);
  77437. }
  77438. }
  77439. void timerCallback()
  77440. {
  77441. const uint32 now = Time::getApproximateMillisecondCounter();
  77442. const ScopedLock sl (lock);
  77443. for (int i = images.size(); --i >= 0;)
  77444. {
  77445. Item* const item = images.getUnchecked(i);
  77446. if (item->image.getReferenceCount() <= 1)
  77447. {
  77448. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77449. images.remove (i);
  77450. }
  77451. else
  77452. {
  77453. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77454. }
  77455. }
  77456. if (images.size() == 0)
  77457. stopTimer();
  77458. }
  77459. struct Item
  77460. {
  77461. Image image;
  77462. int64 hashCode;
  77463. uint32 lastUseTime;
  77464. };
  77465. int cacheTimeout;
  77466. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77467. private:
  77468. OwnedArray<Item> images;
  77469. CriticalSection lock;
  77470. Pimpl (const Pimpl&);
  77471. Pimpl& operator= (const Pimpl&);
  77472. };
  77473. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77474. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77475. {
  77476. if (Pimpl::getInstanceWithoutCreating() != 0)
  77477. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77478. return Image::null;
  77479. }
  77480. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77481. {
  77482. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77483. }
  77484. const Image ImageCache::getFromFile (const File& file)
  77485. {
  77486. const int64 hashCode = file.hashCode64();
  77487. Image image (getFromHashCode (hashCode));
  77488. if (image.isNull())
  77489. {
  77490. image = ImageFileFormat::loadFrom (file);
  77491. addImageToCache (image, hashCode);
  77492. }
  77493. return image;
  77494. }
  77495. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77496. {
  77497. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77498. Image image (getFromHashCode (hashCode));
  77499. if (image.isNull())
  77500. {
  77501. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77502. addImageToCache (image, hashCode);
  77503. }
  77504. return image;
  77505. }
  77506. void ImageCache::setCacheTimeout (const int millisecs)
  77507. {
  77508. Pimpl::getInstance()->cacheTimeout = millisecs;
  77509. }
  77510. END_JUCE_NAMESPACE
  77511. /*** End of inlined file: juce_ImageCache.cpp ***/
  77512. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77513. BEGIN_JUCE_NAMESPACE
  77514. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77515. : values (size_ * size_),
  77516. size (size_)
  77517. {
  77518. clear();
  77519. }
  77520. ImageConvolutionKernel::~ImageConvolutionKernel()
  77521. {
  77522. }
  77523. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77524. {
  77525. if (((unsigned int) x) < (unsigned int) size
  77526. && ((unsigned int) y) < (unsigned int) size)
  77527. {
  77528. return values [x + y * size];
  77529. }
  77530. else
  77531. {
  77532. jassertfalse;
  77533. return 0;
  77534. }
  77535. }
  77536. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77537. {
  77538. if (((unsigned int) x) < (unsigned int) size
  77539. && ((unsigned int) y) < (unsigned int) size)
  77540. {
  77541. values [x + y * size] = value;
  77542. }
  77543. else
  77544. {
  77545. jassertfalse;
  77546. }
  77547. }
  77548. void ImageConvolutionKernel::clear()
  77549. {
  77550. for (int i = size * size; --i >= 0;)
  77551. values[i] = 0;
  77552. }
  77553. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77554. {
  77555. double currentTotal = 0.0;
  77556. for (int i = size * size; --i >= 0;)
  77557. currentTotal += values[i];
  77558. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77559. }
  77560. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77561. {
  77562. for (int i = size * size; --i >= 0;)
  77563. values[i] *= multiplier;
  77564. }
  77565. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77566. {
  77567. const double radiusFactor = -1.0 / (radius * radius * 2);
  77568. const int centre = size >> 1;
  77569. for (int y = size; --y >= 0;)
  77570. {
  77571. for (int x = size; --x >= 0;)
  77572. {
  77573. const int cx = x - centre;
  77574. const int cy = y - centre;
  77575. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77576. }
  77577. }
  77578. setOverallSum (1.0f);
  77579. }
  77580. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77581. const Image& sourceImage,
  77582. const Rectangle<int>& destinationArea) const
  77583. {
  77584. if (sourceImage == destImage)
  77585. {
  77586. destImage.duplicateIfShared();
  77587. }
  77588. else
  77589. {
  77590. if (sourceImage.getWidth() != destImage.getWidth()
  77591. || sourceImage.getHeight() != destImage.getHeight()
  77592. || sourceImage.getFormat() != destImage.getFormat())
  77593. {
  77594. jassertfalse;
  77595. return;
  77596. }
  77597. }
  77598. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77599. if (area.isEmpty())
  77600. return;
  77601. const int right = area.getRight();
  77602. const int bottom = area.getBottom();
  77603. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77604. uint8* line = destData.data;
  77605. const Image::BitmapData srcData (sourceImage, false);
  77606. if (destData.pixelStride == 4)
  77607. {
  77608. for (int y = area.getY(); y < bottom; ++y)
  77609. {
  77610. uint8* dest = line;
  77611. line += destData.lineStride;
  77612. for (int x = area.getX(); x < right; ++x)
  77613. {
  77614. float c1 = 0;
  77615. float c2 = 0;
  77616. float c3 = 0;
  77617. float c4 = 0;
  77618. for (int yy = 0; yy < size; ++yy)
  77619. {
  77620. const int sy = y + yy - (size >> 1);
  77621. if (sy >= srcData.height)
  77622. break;
  77623. if (sy >= 0)
  77624. {
  77625. int sx = x - (size >> 1);
  77626. const uint8* src = srcData.getPixelPointer (sx, sy);
  77627. for (int xx = 0; xx < size; ++xx)
  77628. {
  77629. if (sx >= srcData.width)
  77630. break;
  77631. if (sx >= 0)
  77632. {
  77633. const float kernelMult = values [xx + yy * size];
  77634. c1 += kernelMult * *src++;
  77635. c2 += kernelMult * *src++;
  77636. c3 += kernelMult * *src++;
  77637. c4 += kernelMult * *src++;
  77638. }
  77639. else
  77640. {
  77641. src += 4;
  77642. }
  77643. ++sx;
  77644. }
  77645. }
  77646. }
  77647. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77648. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77649. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77650. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77651. }
  77652. }
  77653. }
  77654. else if (destData.pixelStride == 3)
  77655. {
  77656. for (int y = area.getY(); y < bottom; ++y)
  77657. {
  77658. uint8* dest = line;
  77659. line += destData.lineStride;
  77660. for (int x = area.getX(); x < right; ++x)
  77661. {
  77662. float c1 = 0;
  77663. float c2 = 0;
  77664. float c3 = 0;
  77665. for (int yy = 0; yy < size; ++yy)
  77666. {
  77667. const int sy = y + yy - (size >> 1);
  77668. if (sy >= srcData.height)
  77669. break;
  77670. if (sy >= 0)
  77671. {
  77672. int sx = x - (size >> 1);
  77673. const uint8* src = srcData.getPixelPointer (sx, sy);
  77674. for (int xx = 0; xx < size; ++xx)
  77675. {
  77676. if (sx >= srcData.width)
  77677. break;
  77678. if (sx >= 0)
  77679. {
  77680. const float kernelMult = values [xx + yy * size];
  77681. c1 += kernelMult * *src++;
  77682. c2 += kernelMult * *src++;
  77683. c3 += kernelMult * *src++;
  77684. }
  77685. else
  77686. {
  77687. src += 3;
  77688. }
  77689. ++sx;
  77690. }
  77691. }
  77692. }
  77693. *dest++ = (uint8) roundToInt (c1);
  77694. *dest++ = (uint8) roundToInt (c2);
  77695. *dest++ = (uint8) roundToInt (c3);
  77696. }
  77697. }
  77698. }
  77699. }
  77700. END_JUCE_NAMESPACE
  77701. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77702. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77703. BEGIN_JUCE_NAMESPACE
  77704. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77705. {
  77706. static PNGImageFormat png;
  77707. static JPEGImageFormat jpg;
  77708. static GIFImageFormat gif;
  77709. ImageFileFormat* formats[4];
  77710. int numFormats = 0;
  77711. formats [numFormats++] = &png;
  77712. formats [numFormats++] = &jpg;
  77713. formats [numFormats++] = &gif;
  77714. const int64 streamPos = input.getPosition();
  77715. for (int i = 0; i < numFormats; ++i)
  77716. {
  77717. const bool found = formats[i]->canUnderstand (input);
  77718. input.setPosition (streamPos);
  77719. if (found)
  77720. return formats[i];
  77721. }
  77722. return 0;
  77723. }
  77724. const Image ImageFileFormat::loadFrom (InputStream& input)
  77725. {
  77726. ImageFileFormat* const format = findImageFormatForStream (input);
  77727. if (format != 0)
  77728. return format->decodeImage (input);
  77729. return Image::null;
  77730. }
  77731. const Image ImageFileFormat::loadFrom (const File& file)
  77732. {
  77733. InputStream* const in = file.createInputStream();
  77734. if (in != 0)
  77735. {
  77736. BufferedInputStream b (in, 8192, true);
  77737. return loadFrom (b);
  77738. }
  77739. return Image::null;
  77740. }
  77741. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77742. {
  77743. if (rawData != 0 && numBytes > 4)
  77744. {
  77745. MemoryInputStream stream (rawData, numBytes, false);
  77746. return loadFrom (stream);
  77747. }
  77748. return Image::null;
  77749. }
  77750. END_JUCE_NAMESPACE
  77751. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77752. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77753. BEGIN_JUCE_NAMESPACE
  77754. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77755. const Image juce_loadWithCoreImage (InputStream& input);
  77756. #else
  77757. class GIFLoader
  77758. {
  77759. public:
  77760. GIFLoader (InputStream& in)
  77761. : input (in),
  77762. dataBlockIsZero (false),
  77763. fresh (false),
  77764. finished (false)
  77765. {
  77766. currentBit = lastBit = lastByteIndex = 0;
  77767. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77768. firstcode = oldcode = 0;
  77769. clearCode = end_code = 0;
  77770. int imageWidth, imageHeight;
  77771. int transparent = -1;
  77772. if (! getSizeFromHeader (imageWidth, imageHeight))
  77773. return;
  77774. if ((imageWidth <= 0) || (imageHeight <= 0))
  77775. return;
  77776. unsigned char buf [16];
  77777. if (in.read (buf, 3) != 3)
  77778. return;
  77779. int numColours = 2 << (buf[0] & 7);
  77780. if ((buf[0] & 0x80) != 0)
  77781. readPalette (numColours);
  77782. for (;;)
  77783. {
  77784. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77785. break;
  77786. if (buf[0] == '!')
  77787. {
  77788. if (input.read (buf, 1) != 1)
  77789. break;
  77790. if (processExtension (buf[0], transparent) < 0)
  77791. break;
  77792. continue;
  77793. }
  77794. if (buf[0] != ',')
  77795. continue;
  77796. if (input.read (buf, 9) != 9)
  77797. break;
  77798. imageWidth = makeWord (buf[4], buf[5]);
  77799. imageHeight = makeWord (buf[6], buf[7]);
  77800. numColours = 2 << (buf[8] & 7);
  77801. if ((buf[8] & 0x80) != 0)
  77802. if (! readPalette (numColours))
  77803. break;
  77804. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77805. imageWidth, imageHeight, (transparent >= 0));
  77806. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77807. readImage ((buf[8] & 0x40) != 0, transparent);
  77808. break;
  77809. }
  77810. }
  77811. ~GIFLoader() {}
  77812. Image image;
  77813. private:
  77814. InputStream& input;
  77815. uint8 buffer [300];
  77816. uint8 palette [256][4];
  77817. bool dataBlockIsZero, fresh, finished;
  77818. int currentBit, lastBit, lastByteIndex;
  77819. int codeSize, setCodeSize;
  77820. int maxCode, maxCodeSize;
  77821. int firstcode, oldcode;
  77822. int clearCode, end_code;
  77823. enum { maxGifCode = 1 << 12 };
  77824. int table [2] [maxGifCode];
  77825. int stack [2 * maxGifCode];
  77826. int *sp;
  77827. bool getSizeFromHeader (int& w, int& h)
  77828. {
  77829. char b[8];
  77830. if (input.read (b, 6) == 6)
  77831. {
  77832. if ((strncmp ("GIF87a", b, 6) == 0)
  77833. || (strncmp ("GIF89a", b, 6) == 0))
  77834. {
  77835. if (input.read (b, 4) == 4)
  77836. {
  77837. w = makeWord (b[0], b[1]);
  77838. h = makeWord (b[2], b[3]);
  77839. return true;
  77840. }
  77841. }
  77842. }
  77843. return false;
  77844. }
  77845. bool readPalette (const int numCols)
  77846. {
  77847. unsigned char rgb[4];
  77848. for (int i = 0; i < numCols; ++i)
  77849. {
  77850. input.read (rgb, 3);
  77851. palette [i][0] = rgb[0];
  77852. palette [i][1] = rgb[1];
  77853. palette [i][2] = rgb[2];
  77854. palette [i][3] = 0xff;
  77855. }
  77856. return true;
  77857. }
  77858. int readDataBlock (unsigned char* dest)
  77859. {
  77860. unsigned char n;
  77861. if (input.read (&n, 1) == 1)
  77862. {
  77863. dataBlockIsZero = (n == 0);
  77864. if (dataBlockIsZero || (input.read (dest, n) == n))
  77865. return n;
  77866. }
  77867. return -1;
  77868. }
  77869. int processExtension (const int type, int& transparent)
  77870. {
  77871. unsigned char b [300];
  77872. int n = 0;
  77873. if (type == 0xf9)
  77874. {
  77875. n = readDataBlock (b);
  77876. if (n < 0)
  77877. return 1;
  77878. if ((b[0] & 0x1) != 0)
  77879. transparent = b[3];
  77880. }
  77881. do
  77882. {
  77883. n = readDataBlock (b);
  77884. }
  77885. while (n > 0);
  77886. return n;
  77887. }
  77888. int readLZWByte (const bool initialise, const int inputCodeSize)
  77889. {
  77890. int code, incode, i;
  77891. if (initialise)
  77892. {
  77893. setCodeSize = inputCodeSize;
  77894. codeSize = setCodeSize + 1;
  77895. clearCode = 1 << setCodeSize;
  77896. end_code = clearCode + 1;
  77897. maxCodeSize = 2 * clearCode;
  77898. maxCode = clearCode + 2;
  77899. getCode (0, true);
  77900. fresh = true;
  77901. for (i = 0; i < clearCode; ++i)
  77902. {
  77903. table[0][i] = 0;
  77904. table[1][i] = i;
  77905. }
  77906. for (; i < maxGifCode; ++i)
  77907. {
  77908. table[0][i] = 0;
  77909. table[1][i] = 0;
  77910. }
  77911. sp = stack;
  77912. return 0;
  77913. }
  77914. else if (fresh)
  77915. {
  77916. fresh = false;
  77917. do
  77918. {
  77919. firstcode = oldcode
  77920. = getCode (codeSize, false);
  77921. }
  77922. while (firstcode == clearCode);
  77923. return firstcode;
  77924. }
  77925. if (sp > stack)
  77926. return *--sp;
  77927. while ((code = getCode (codeSize, false)) >= 0)
  77928. {
  77929. if (code == clearCode)
  77930. {
  77931. for (i = 0; i < clearCode; ++i)
  77932. {
  77933. table[0][i] = 0;
  77934. table[1][i] = i;
  77935. }
  77936. for (; i < maxGifCode; ++i)
  77937. {
  77938. table[0][i] = 0;
  77939. table[1][i] = 0;
  77940. }
  77941. codeSize = setCodeSize + 1;
  77942. maxCodeSize = 2 * clearCode;
  77943. maxCode = clearCode + 2;
  77944. sp = stack;
  77945. firstcode = oldcode = getCode (codeSize, false);
  77946. return firstcode;
  77947. }
  77948. else if (code == end_code)
  77949. {
  77950. if (dataBlockIsZero)
  77951. return -2;
  77952. unsigned char buf [260];
  77953. int n;
  77954. while ((n = readDataBlock (buf)) > 0)
  77955. {}
  77956. if (n != 0)
  77957. return -2;
  77958. }
  77959. incode = code;
  77960. if (code >= maxCode)
  77961. {
  77962. *sp++ = firstcode;
  77963. code = oldcode;
  77964. }
  77965. while (code >= clearCode)
  77966. {
  77967. *sp++ = table[1][code];
  77968. if (code == table[0][code])
  77969. return -2;
  77970. code = table[0][code];
  77971. }
  77972. *sp++ = firstcode = table[1][code];
  77973. if ((code = maxCode) < maxGifCode)
  77974. {
  77975. table[0][code] = oldcode;
  77976. table[1][code] = firstcode;
  77977. ++maxCode;
  77978. if ((maxCode >= maxCodeSize)
  77979. && (maxCodeSize < maxGifCode))
  77980. {
  77981. maxCodeSize <<= 1;
  77982. ++codeSize;
  77983. }
  77984. }
  77985. oldcode = incode;
  77986. if (sp > stack)
  77987. return *--sp;
  77988. }
  77989. return code;
  77990. }
  77991. int getCode (const int codeSize_, const bool initialise)
  77992. {
  77993. if (initialise)
  77994. {
  77995. currentBit = 0;
  77996. lastBit = 0;
  77997. finished = false;
  77998. return 0;
  77999. }
  78000. if ((currentBit + codeSize_) >= lastBit)
  78001. {
  78002. if (finished)
  78003. return -1;
  78004. buffer[0] = buffer [lastByteIndex - 2];
  78005. buffer[1] = buffer [lastByteIndex - 1];
  78006. const int n = readDataBlock (&buffer[2]);
  78007. if (n == 0)
  78008. finished = true;
  78009. lastByteIndex = 2 + n;
  78010. currentBit = (currentBit - lastBit) + 16;
  78011. lastBit = (2 + n) * 8 ;
  78012. }
  78013. int result = 0;
  78014. int i = currentBit;
  78015. for (int j = 0; j < codeSize_; ++j)
  78016. {
  78017. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  78018. ++i;
  78019. }
  78020. currentBit += codeSize_;
  78021. return result;
  78022. }
  78023. bool readImage (const int interlace, const int transparent)
  78024. {
  78025. unsigned char c;
  78026. if (input.read (&c, 1) != 1
  78027. || readLZWByte (true, c) < 0)
  78028. return false;
  78029. if (transparent >= 0)
  78030. {
  78031. palette [transparent][0] = 0;
  78032. palette [transparent][1] = 0;
  78033. palette [transparent][2] = 0;
  78034. palette [transparent][3] = 0;
  78035. }
  78036. int index;
  78037. int xpos = 0, ypos = 0, pass = 0;
  78038. const Image::BitmapData destData (image, true);
  78039. uint8* p = destData.data;
  78040. const bool hasAlpha = image.hasAlphaChannel();
  78041. while ((index = readLZWByte (false, c)) >= 0)
  78042. {
  78043. const uint8* const paletteEntry = palette [index];
  78044. if (hasAlpha)
  78045. {
  78046. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78047. paletteEntry[0],
  78048. paletteEntry[1],
  78049. paletteEntry[2]);
  78050. ((PixelARGB*) p)->premultiply();
  78051. }
  78052. else
  78053. {
  78054. ((PixelRGB*) p)->setARGB (0,
  78055. paletteEntry[0],
  78056. paletteEntry[1],
  78057. paletteEntry[2]);
  78058. }
  78059. p += destData.pixelStride;
  78060. ++xpos;
  78061. if (xpos == destData.width)
  78062. {
  78063. xpos = 0;
  78064. if (interlace)
  78065. {
  78066. switch (pass)
  78067. {
  78068. case 0:
  78069. case 1: ypos += 8; break;
  78070. case 2: ypos += 4; break;
  78071. case 3: ypos += 2; break;
  78072. }
  78073. while (ypos >= destData.height)
  78074. {
  78075. ++pass;
  78076. switch (pass)
  78077. {
  78078. case 1: ypos = 4; break;
  78079. case 2: ypos = 2; break;
  78080. case 3: ypos = 1; break;
  78081. default: return true;
  78082. }
  78083. }
  78084. }
  78085. else
  78086. {
  78087. ++ypos;
  78088. }
  78089. p = destData.getPixelPointer (xpos, ypos);
  78090. }
  78091. if (ypos >= destData.height)
  78092. break;
  78093. }
  78094. return true;
  78095. }
  78096. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78097. GIFLoader (const GIFLoader&);
  78098. GIFLoader& operator= (const GIFLoader&);
  78099. };
  78100. #endif
  78101. GIFImageFormat::GIFImageFormat() {}
  78102. GIFImageFormat::~GIFImageFormat() {}
  78103. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78104. bool GIFImageFormat::canUnderstand (InputStream& in)
  78105. {
  78106. char header [4];
  78107. return (in.read (header, sizeof (header)) == sizeof (header))
  78108. && header[0] == 'G'
  78109. && header[1] == 'I'
  78110. && header[2] == 'F';
  78111. }
  78112. const Image GIFImageFormat::decodeImage (InputStream& in)
  78113. {
  78114. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78115. return juce_loadWithCoreImage (in);
  78116. #else
  78117. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78118. return loader->image;
  78119. #endif
  78120. }
  78121. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78122. {
  78123. jassertfalse; // writing isn't implemented for GIFs!
  78124. return false;
  78125. }
  78126. END_JUCE_NAMESPACE
  78127. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78128. #endif
  78129. //==============================================================================
  78130. // some files include lots of library code, so leave them to the end to avoid cluttering
  78131. // up the build for the clean files.
  78132. #if JUCE_BUILD_CORE
  78133. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78134. namespace zlibNamespace
  78135. {
  78136. #if JUCE_INCLUDE_ZLIB_CODE
  78137. #undef OS_CODE
  78138. #undef fdopen
  78139. /*** Start of inlined file: zlib.h ***/
  78140. #ifndef ZLIB_H
  78141. #define ZLIB_H
  78142. /*** Start of inlined file: zconf.h ***/
  78143. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78144. #ifndef ZCONF_H
  78145. #define ZCONF_H
  78146. // *** Just a few hacks here to make it compile nicely with Juce..
  78147. #define Z_PREFIX 1
  78148. #undef __MACTYPES__
  78149. #ifdef _MSC_VER
  78150. #pragma warning (disable : 4131 4127 4244 4267)
  78151. #endif
  78152. /*
  78153. * If you *really* need a unique prefix for all types and library functions,
  78154. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78155. */
  78156. #ifdef Z_PREFIX
  78157. # define deflateInit_ z_deflateInit_
  78158. # define deflate z_deflate
  78159. # define deflateEnd z_deflateEnd
  78160. # define inflateInit_ z_inflateInit_
  78161. # define inflate z_inflate
  78162. # define inflateEnd z_inflateEnd
  78163. # define inflatePrime z_inflatePrime
  78164. # define inflateGetHeader z_inflateGetHeader
  78165. # define adler32_combine z_adler32_combine
  78166. # define crc32_combine z_crc32_combine
  78167. # define deflateInit2_ z_deflateInit2_
  78168. # define deflateSetDictionary z_deflateSetDictionary
  78169. # define deflateCopy z_deflateCopy
  78170. # define deflateReset z_deflateReset
  78171. # define deflateParams z_deflateParams
  78172. # define deflateBound z_deflateBound
  78173. # define deflatePrime z_deflatePrime
  78174. # define inflateInit2_ z_inflateInit2_
  78175. # define inflateSetDictionary z_inflateSetDictionary
  78176. # define inflateSync z_inflateSync
  78177. # define inflateSyncPoint z_inflateSyncPoint
  78178. # define inflateCopy z_inflateCopy
  78179. # define inflateReset z_inflateReset
  78180. # define inflateBack z_inflateBack
  78181. # define inflateBackEnd z_inflateBackEnd
  78182. # define compress z_compress
  78183. # define compress2 z_compress2
  78184. # define compressBound z_compressBound
  78185. # define uncompress z_uncompress
  78186. # define adler32 z_adler32
  78187. # define crc32 z_crc32
  78188. # define get_crc_table z_get_crc_table
  78189. # define zError z_zError
  78190. # define alloc_func z_alloc_func
  78191. # define free_func z_free_func
  78192. # define in_func z_in_func
  78193. # define out_func z_out_func
  78194. # define Byte z_Byte
  78195. # define uInt z_uInt
  78196. # define uLong z_uLong
  78197. # define Bytef z_Bytef
  78198. # define charf z_charf
  78199. # define intf z_intf
  78200. # define uIntf z_uIntf
  78201. # define uLongf z_uLongf
  78202. # define voidpf z_voidpf
  78203. # define voidp z_voidp
  78204. #endif
  78205. #if defined(__MSDOS__) && !defined(MSDOS)
  78206. # define MSDOS
  78207. #endif
  78208. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78209. # define OS2
  78210. #endif
  78211. #if defined(_WINDOWS) && !defined(WINDOWS)
  78212. # define WINDOWS
  78213. #endif
  78214. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78215. # ifndef WIN32
  78216. # define WIN32
  78217. # endif
  78218. #endif
  78219. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78220. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78221. # ifndef SYS16BIT
  78222. # define SYS16BIT
  78223. # endif
  78224. # endif
  78225. #endif
  78226. /*
  78227. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78228. * than 64k bytes at a time (needed on systems with 16-bit int).
  78229. */
  78230. #ifdef SYS16BIT
  78231. # define MAXSEG_64K
  78232. #endif
  78233. #ifdef MSDOS
  78234. # define UNALIGNED_OK
  78235. #endif
  78236. #ifdef __STDC_VERSION__
  78237. # ifndef STDC
  78238. # define STDC
  78239. # endif
  78240. # if __STDC_VERSION__ >= 199901L
  78241. # ifndef STDC99
  78242. # define STDC99
  78243. # endif
  78244. # endif
  78245. #endif
  78246. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78247. # define STDC
  78248. #endif
  78249. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78250. # define STDC
  78251. #endif
  78252. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78253. # define STDC
  78254. #endif
  78255. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78256. # define STDC
  78257. #endif
  78258. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78259. # define STDC
  78260. #endif
  78261. #ifndef STDC
  78262. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78263. # define const /* note: need a more gentle solution here */
  78264. # endif
  78265. #endif
  78266. /* Some Mac compilers merge all .h files incorrectly: */
  78267. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78268. # define NO_DUMMY_DECL
  78269. #endif
  78270. /* Maximum value for memLevel in deflateInit2 */
  78271. #ifndef MAX_MEM_LEVEL
  78272. # ifdef MAXSEG_64K
  78273. # define MAX_MEM_LEVEL 8
  78274. # else
  78275. # define MAX_MEM_LEVEL 9
  78276. # endif
  78277. #endif
  78278. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78279. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78280. * created by gzip. (Files created by minigzip can still be extracted by
  78281. * gzip.)
  78282. */
  78283. #ifndef MAX_WBITS
  78284. # define MAX_WBITS 15 /* 32K LZ77 window */
  78285. #endif
  78286. /* The memory requirements for deflate are (in bytes):
  78287. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78288. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78289. plus a few kilobytes for small objects. For example, if you want to reduce
  78290. the default memory requirements from 256K to 128K, compile with
  78291. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78292. Of course this will generally degrade compression (there's no free lunch).
  78293. The memory requirements for inflate are (in bytes) 1 << windowBits
  78294. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78295. for small objects.
  78296. */
  78297. /* Type declarations */
  78298. #ifndef OF /* function prototypes */
  78299. # ifdef STDC
  78300. # define OF(args) args
  78301. # else
  78302. # define OF(args) ()
  78303. # endif
  78304. #endif
  78305. /* The following definitions for FAR are needed only for MSDOS mixed
  78306. * model programming (small or medium model with some far allocations).
  78307. * This was tested only with MSC; for other MSDOS compilers you may have
  78308. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78309. * just define FAR to be empty.
  78310. */
  78311. #ifdef SYS16BIT
  78312. # if defined(M_I86SM) || defined(M_I86MM)
  78313. /* MSC small or medium model */
  78314. # define SMALL_MEDIUM
  78315. # ifdef _MSC_VER
  78316. # define FAR _far
  78317. # else
  78318. # define FAR far
  78319. # endif
  78320. # endif
  78321. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78322. /* Turbo C small or medium model */
  78323. # define SMALL_MEDIUM
  78324. # ifdef __BORLANDC__
  78325. # define FAR _far
  78326. # else
  78327. # define FAR far
  78328. # endif
  78329. # endif
  78330. #endif
  78331. #if defined(WINDOWS) || defined(WIN32)
  78332. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78333. * This is not mandatory, but it offers a little performance increase.
  78334. */
  78335. # ifdef ZLIB_DLL
  78336. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78337. # ifdef ZLIB_INTERNAL
  78338. # define ZEXTERN extern __declspec(dllexport)
  78339. # else
  78340. # define ZEXTERN extern __declspec(dllimport)
  78341. # endif
  78342. # endif
  78343. # endif /* ZLIB_DLL */
  78344. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78345. * define ZLIB_WINAPI.
  78346. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78347. */
  78348. # ifdef ZLIB_WINAPI
  78349. # ifdef FAR
  78350. # undef FAR
  78351. # endif
  78352. # include <windows.h>
  78353. /* No need for _export, use ZLIB.DEF instead. */
  78354. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78355. # define ZEXPORT WINAPI
  78356. # ifdef WIN32
  78357. # define ZEXPORTVA WINAPIV
  78358. # else
  78359. # define ZEXPORTVA FAR CDECL
  78360. # endif
  78361. # endif
  78362. #endif
  78363. #if defined (__BEOS__)
  78364. # ifdef ZLIB_DLL
  78365. # ifdef ZLIB_INTERNAL
  78366. # define ZEXPORT __declspec(dllexport)
  78367. # define ZEXPORTVA __declspec(dllexport)
  78368. # else
  78369. # define ZEXPORT __declspec(dllimport)
  78370. # define ZEXPORTVA __declspec(dllimport)
  78371. # endif
  78372. # endif
  78373. #endif
  78374. #ifndef ZEXTERN
  78375. # define ZEXTERN extern
  78376. #endif
  78377. #ifndef ZEXPORT
  78378. # define ZEXPORT
  78379. #endif
  78380. #ifndef ZEXPORTVA
  78381. # define ZEXPORTVA
  78382. #endif
  78383. #ifndef FAR
  78384. # define FAR
  78385. #endif
  78386. #if !defined(__MACTYPES__)
  78387. typedef unsigned char Byte; /* 8 bits */
  78388. #endif
  78389. typedef unsigned int uInt; /* 16 bits or more */
  78390. typedef unsigned long uLong; /* 32 bits or more */
  78391. #ifdef SMALL_MEDIUM
  78392. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78393. # define Bytef Byte FAR
  78394. #else
  78395. typedef Byte FAR Bytef;
  78396. #endif
  78397. typedef char FAR charf;
  78398. typedef int FAR intf;
  78399. typedef uInt FAR uIntf;
  78400. typedef uLong FAR uLongf;
  78401. #ifdef STDC
  78402. typedef void const *voidpc;
  78403. typedef void FAR *voidpf;
  78404. typedef void *voidp;
  78405. #else
  78406. typedef Byte const *voidpc;
  78407. typedef Byte FAR *voidpf;
  78408. typedef Byte *voidp;
  78409. #endif
  78410. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78411. # include <sys/types.h> /* for off_t */
  78412. # include <unistd.h> /* for SEEK_* and off_t */
  78413. # ifdef VMS
  78414. # include <unixio.h> /* for off_t */
  78415. # endif
  78416. # define z_off_t off_t
  78417. #endif
  78418. #ifndef SEEK_SET
  78419. # define SEEK_SET 0 /* Seek from beginning of file. */
  78420. # define SEEK_CUR 1 /* Seek from current position. */
  78421. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78422. #endif
  78423. #ifndef z_off_t
  78424. # define z_off_t long
  78425. #endif
  78426. #if defined(__OS400__)
  78427. # define NO_vsnprintf
  78428. #endif
  78429. #if defined(__MVS__)
  78430. # define NO_vsnprintf
  78431. # ifdef FAR
  78432. # undef FAR
  78433. # endif
  78434. #endif
  78435. /* MVS linker does not support external names larger than 8 bytes */
  78436. #if defined(__MVS__)
  78437. # pragma map(deflateInit_,"DEIN")
  78438. # pragma map(deflateInit2_,"DEIN2")
  78439. # pragma map(deflateEnd,"DEEND")
  78440. # pragma map(deflateBound,"DEBND")
  78441. # pragma map(inflateInit_,"ININ")
  78442. # pragma map(inflateInit2_,"ININ2")
  78443. # pragma map(inflateEnd,"INEND")
  78444. # pragma map(inflateSync,"INSY")
  78445. # pragma map(inflateSetDictionary,"INSEDI")
  78446. # pragma map(compressBound,"CMBND")
  78447. # pragma map(inflate_table,"INTABL")
  78448. # pragma map(inflate_fast,"INFA")
  78449. # pragma map(inflate_copyright,"INCOPY")
  78450. #endif
  78451. #endif /* ZCONF_H */
  78452. /*** End of inlined file: zconf.h ***/
  78453. #ifdef __cplusplus
  78454. //extern "C" {
  78455. #endif
  78456. #define ZLIB_VERSION "1.2.3"
  78457. #define ZLIB_VERNUM 0x1230
  78458. /*
  78459. The 'zlib' compression library provides in-memory compression and
  78460. decompression functions, including integrity checks of the uncompressed
  78461. data. This version of the library supports only one compression method
  78462. (deflation) but other algorithms will be added later and will have the same
  78463. stream interface.
  78464. Compression can be done in a single step if the buffers are large
  78465. enough (for example if an input file is mmap'ed), or can be done by
  78466. repeated calls of the compression function. In the latter case, the
  78467. application must provide more input and/or consume the output
  78468. (providing more output space) before each call.
  78469. The compressed data format used by default by the in-memory functions is
  78470. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78471. around a deflate stream, which is itself documented in RFC 1951.
  78472. The library also supports reading and writing files in gzip (.gz) format
  78473. with an interface similar to that of stdio using the functions that start
  78474. with "gz". The gzip format is different from the zlib format. gzip is a
  78475. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78476. This library can optionally read and write gzip streams in memory as well.
  78477. The zlib format was designed to be compact and fast for use in memory
  78478. and on communications channels. The gzip format was designed for single-
  78479. file compression on file systems, has a larger header than zlib to maintain
  78480. directory information, and uses a different, slower check method than zlib.
  78481. The library does not install any signal handler. The decoder checks
  78482. the consistency of the compressed data, so the library should never
  78483. crash even in case of corrupted input.
  78484. */
  78485. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78486. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78487. struct internal_state;
  78488. typedef struct z_stream_s {
  78489. Bytef *next_in; /* next input byte */
  78490. uInt avail_in; /* number of bytes available at next_in */
  78491. uLong total_in; /* total nb of input bytes read so far */
  78492. Bytef *next_out; /* next output byte should be put there */
  78493. uInt avail_out; /* remaining free space at next_out */
  78494. uLong total_out; /* total nb of bytes output so far */
  78495. char *msg; /* last error message, NULL if no error */
  78496. struct internal_state FAR *state; /* not visible by applications */
  78497. alloc_func zalloc; /* used to allocate the internal state */
  78498. free_func zfree; /* used to free the internal state */
  78499. voidpf opaque; /* private data object passed to zalloc and zfree */
  78500. int data_type; /* best guess about the data type: binary or text */
  78501. uLong adler; /* adler32 value of the uncompressed data */
  78502. uLong reserved; /* reserved for future use */
  78503. } z_stream;
  78504. typedef z_stream FAR *z_streamp;
  78505. /*
  78506. gzip header information passed to and from zlib routines. See RFC 1952
  78507. for more details on the meanings of these fields.
  78508. */
  78509. typedef struct gz_header_s {
  78510. int text; /* true if compressed data believed to be text */
  78511. uLong time; /* modification time */
  78512. int xflags; /* extra flags (not used when writing a gzip file) */
  78513. int os; /* operating system */
  78514. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78515. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78516. uInt extra_max; /* space at extra (only when reading header) */
  78517. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78518. uInt name_max; /* space at name (only when reading header) */
  78519. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78520. uInt comm_max; /* space at comment (only when reading header) */
  78521. int hcrc; /* true if there was or will be a header crc */
  78522. int done; /* true when done reading gzip header (not used
  78523. when writing a gzip file) */
  78524. } gz_header;
  78525. typedef gz_header FAR *gz_headerp;
  78526. /*
  78527. The application must update next_in and avail_in when avail_in has
  78528. dropped to zero. It must update next_out and avail_out when avail_out
  78529. has dropped to zero. The application must initialize zalloc, zfree and
  78530. opaque before calling the init function. All other fields are set by the
  78531. compression library and must not be updated by the application.
  78532. The opaque value provided by the application will be passed as the first
  78533. parameter for calls of zalloc and zfree. This can be useful for custom
  78534. memory management. The compression library attaches no meaning to the
  78535. opaque value.
  78536. zalloc must return Z_NULL if there is not enough memory for the object.
  78537. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78538. thread safe.
  78539. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78540. exactly 65536 bytes, but will not be required to allocate more than this
  78541. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78542. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78543. have their offset normalized to zero. The default allocation function
  78544. provided by this library ensures this (see zutil.c). To reduce memory
  78545. requirements and avoid any allocation of 64K objects, at the expense of
  78546. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78547. The fields total_in and total_out can be used for statistics or
  78548. progress reports. After compression, total_in holds the total size of
  78549. the uncompressed data and may be saved for use in the decompressor
  78550. (particularly if the decompressor wants to decompress everything in
  78551. a single step).
  78552. */
  78553. /* constants */
  78554. #define Z_NO_FLUSH 0
  78555. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78556. #define Z_SYNC_FLUSH 2
  78557. #define Z_FULL_FLUSH 3
  78558. #define Z_FINISH 4
  78559. #define Z_BLOCK 5
  78560. /* Allowed flush values; see deflate() and inflate() below for details */
  78561. #define Z_OK 0
  78562. #define Z_STREAM_END 1
  78563. #define Z_NEED_DICT 2
  78564. #define Z_ERRNO (-1)
  78565. #define Z_STREAM_ERROR (-2)
  78566. #define Z_DATA_ERROR (-3)
  78567. #define Z_MEM_ERROR (-4)
  78568. #define Z_BUF_ERROR (-5)
  78569. #define Z_VERSION_ERROR (-6)
  78570. /* Return codes for the compression/decompression functions. Negative
  78571. * values are errors, positive values are used for special but normal events.
  78572. */
  78573. #define Z_NO_COMPRESSION 0
  78574. #define Z_BEST_SPEED 1
  78575. #define Z_BEST_COMPRESSION 9
  78576. #define Z_DEFAULT_COMPRESSION (-1)
  78577. /* compression levels */
  78578. #define Z_FILTERED 1
  78579. #define Z_HUFFMAN_ONLY 2
  78580. #define Z_RLE 3
  78581. #define Z_FIXED 4
  78582. #define Z_DEFAULT_STRATEGY 0
  78583. /* compression strategy; see deflateInit2() below for details */
  78584. #define Z_BINARY 0
  78585. #define Z_TEXT 1
  78586. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78587. #define Z_UNKNOWN 2
  78588. /* Possible values of the data_type field (though see inflate()) */
  78589. #define Z_DEFLATED 8
  78590. /* The deflate compression method (the only one supported in this version) */
  78591. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78592. #define zlib_version zlibVersion()
  78593. /* for compatibility with versions < 1.0.2 */
  78594. /* basic functions */
  78595. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78596. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78597. If the first character differs, the library code actually used is
  78598. not compatible with the zlib.h header file used by the application.
  78599. This check is automatically made by deflateInit and inflateInit.
  78600. */
  78601. /*
  78602. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78603. Initializes the internal stream state for compression. The fields
  78604. zalloc, zfree and opaque must be initialized before by the caller.
  78605. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78606. use default allocation functions.
  78607. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78608. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78609. all (the input data is simply copied a block at a time).
  78610. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78611. compression (currently equivalent to level 6).
  78612. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78613. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78614. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78615. with the version assumed by the caller (ZLIB_VERSION).
  78616. msg is set to null if there is no error message. deflateInit does not
  78617. perform any compression: this will be done by deflate().
  78618. */
  78619. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78620. /*
  78621. deflate compresses as much data as possible, and stops when the input
  78622. buffer becomes empty or the output buffer becomes full. It may introduce some
  78623. output latency (reading input without producing any output) except when
  78624. forced to flush.
  78625. The detailed semantics are as follows. deflate performs one or both of the
  78626. following actions:
  78627. - Compress more input starting at next_in and update next_in and avail_in
  78628. accordingly. If not all input can be processed (because there is not
  78629. enough room in the output buffer), next_in and avail_in are updated and
  78630. processing will resume at this point for the next call of deflate().
  78631. - Provide more output starting at next_out and update next_out and avail_out
  78632. accordingly. This action is forced if the parameter flush is non zero.
  78633. Forcing flush frequently degrades the compression ratio, so this parameter
  78634. should be set only when necessary (in interactive applications).
  78635. Some output may be provided even if flush is not set.
  78636. Before the call of deflate(), the application should ensure that at least
  78637. one of the actions is possible, by providing more input and/or consuming
  78638. more output, and updating avail_in or avail_out accordingly; avail_out
  78639. should never be zero before the call. The application can consume the
  78640. compressed output when it wants, for example when the output buffer is full
  78641. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78642. and with zero avail_out, it must be called again after making room in the
  78643. output buffer because there might be more output pending.
  78644. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78645. decide how much data to accumualte before producing output, in order to
  78646. maximize compression.
  78647. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78648. flushed to the output buffer and the output is aligned on a byte boundary, so
  78649. that the decompressor can get all input data available so far. (In particular
  78650. avail_in is zero after the call if enough output space has been provided
  78651. before the call.) Flushing may degrade compression for some compression
  78652. algorithms and so it should be used only when necessary.
  78653. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78654. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78655. restart from this point if previous compressed data has been damaged or if
  78656. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78657. compression.
  78658. If deflate returns with avail_out == 0, this function must be called again
  78659. with the same value of the flush parameter and more output space (updated
  78660. avail_out), until the flush is complete (deflate returns with non-zero
  78661. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78662. avail_out is greater than six to avoid repeated flush markers due to
  78663. avail_out == 0 on return.
  78664. If the parameter flush is set to Z_FINISH, pending input is processed,
  78665. pending output is flushed and deflate returns with Z_STREAM_END if there
  78666. was enough output space; if deflate returns with Z_OK, this function must be
  78667. called again with Z_FINISH and more output space (updated avail_out) but no
  78668. more input data, until it returns with Z_STREAM_END or an error. After
  78669. deflate has returned Z_STREAM_END, the only possible operations on the
  78670. stream are deflateReset or deflateEnd.
  78671. Z_FINISH can be used immediately after deflateInit if all the compression
  78672. is to be done in a single step. In this case, avail_out must be at least
  78673. the value returned by deflateBound (see below). If deflate does not return
  78674. Z_STREAM_END, then it must be called again as described above.
  78675. deflate() sets strm->adler to the adler32 checksum of all input read
  78676. so far (that is, total_in bytes).
  78677. deflate() may update strm->data_type if it can make a good guess about
  78678. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78679. binary. This field is only for information purposes and does not affect
  78680. the compression algorithm in any manner.
  78681. deflate() returns Z_OK if some progress has been made (more input
  78682. processed or more output produced), Z_STREAM_END if all input has been
  78683. consumed and all output has been produced (only when flush is set to
  78684. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78685. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78686. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78687. fatal, and deflate() can be called again with more input and more output
  78688. space to continue compressing.
  78689. */
  78690. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78691. /*
  78692. All dynamically allocated data structures for this stream are freed.
  78693. This function discards any unprocessed input and does not flush any
  78694. pending output.
  78695. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78696. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78697. prematurely (some input or output was discarded). In the error case,
  78698. msg may be set but then points to a static string (which must not be
  78699. deallocated).
  78700. */
  78701. /*
  78702. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78703. Initializes the internal stream state for decompression. The fields
  78704. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78705. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78706. value depends on the compression method), inflateInit determines the
  78707. compression method from the zlib header and allocates all data structures
  78708. accordingly; otherwise the allocation will be deferred to the first call of
  78709. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78710. use default allocation functions.
  78711. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78712. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78713. version assumed by the caller. msg is set to null if there is no error
  78714. message. inflateInit does not perform any decompression apart from reading
  78715. the zlib header if present: this will be done by inflate(). (So next_in and
  78716. avail_in may be modified, but next_out and avail_out are unchanged.)
  78717. */
  78718. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78719. /*
  78720. inflate decompresses as much data as possible, and stops when the input
  78721. buffer becomes empty or the output buffer becomes full. It may introduce
  78722. some output latency (reading input without producing any output) except when
  78723. forced to flush.
  78724. The detailed semantics are as follows. inflate performs one or both of the
  78725. following actions:
  78726. - Decompress more input starting at next_in and update next_in and avail_in
  78727. accordingly. If not all input can be processed (because there is not
  78728. enough room in the output buffer), next_in is updated and processing
  78729. will resume at this point for the next call of inflate().
  78730. - Provide more output starting at next_out and update next_out and avail_out
  78731. accordingly. inflate() provides as much output as possible, until there
  78732. is no more input data or no more space in the output buffer (see below
  78733. about the flush parameter).
  78734. Before the call of inflate(), the application should ensure that at least
  78735. one of the actions is possible, by providing more input and/or consuming
  78736. more output, and updating the next_* and avail_* values accordingly.
  78737. The application can consume the uncompressed output when it wants, for
  78738. example when the output buffer is full (avail_out == 0), or after each
  78739. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78740. must be called again after making room in the output buffer because there
  78741. might be more output pending.
  78742. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78743. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78744. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78745. if and when it gets to the next deflate block boundary. When decoding the
  78746. zlib or gzip format, this will cause inflate() to return immediately after
  78747. the header and before the first block. When doing a raw inflate, inflate()
  78748. will go ahead and process the first block, and will return when it gets to
  78749. the end of that block, or when it runs out of data.
  78750. The Z_BLOCK option assists in appending to or combining deflate streams.
  78751. Also to assist in this, on return inflate() will set strm->data_type to the
  78752. number of unused bits in the last byte taken from strm->next_in, plus 64
  78753. if inflate() is currently decoding the last block in the deflate stream,
  78754. plus 128 if inflate() returned immediately after decoding an end-of-block
  78755. code or decoding the complete header up to just before the first byte of the
  78756. deflate stream. The end-of-block will not be indicated until all of the
  78757. uncompressed data from that block has been written to strm->next_out. The
  78758. number of unused bits may in general be greater than seven, except when
  78759. bit 7 of data_type is set, in which case the number of unused bits will be
  78760. less than eight.
  78761. inflate() should normally be called until it returns Z_STREAM_END or an
  78762. error. However if all decompression is to be performed in a single step
  78763. (a single call of inflate), the parameter flush should be set to
  78764. Z_FINISH. In this case all pending input is processed and all pending
  78765. output is flushed; avail_out must be large enough to hold all the
  78766. uncompressed data. (The size of the uncompressed data may have been saved
  78767. by the compressor for this purpose.) The next operation on this stream must
  78768. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78769. is never required, but can be used to inform inflate that a faster approach
  78770. may be used for the single inflate() call.
  78771. In this implementation, inflate() always flushes as much output as
  78772. possible to the output buffer, and always uses the faster approach on the
  78773. first call. So the only effect of the flush parameter in this implementation
  78774. is on the return value of inflate(), as noted below, or when it returns early
  78775. because Z_BLOCK is used.
  78776. If a preset dictionary is needed after this call (see inflateSetDictionary
  78777. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78778. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78779. strm->adler to the adler32 checksum of all output produced so far (that is,
  78780. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78781. below. At the end of the stream, inflate() checks that its computed adler32
  78782. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78783. only if the checksum is correct.
  78784. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78785. deflate data. The header type is detected automatically. Any information
  78786. contained in the gzip header is not retained, so applications that need that
  78787. information should instead use raw inflate, see inflateInit2() below, or
  78788. inflateBack() and perform their own processing of the gzip header and
  78789. trailer.
  78790. inflate() returns Z_OK if some progress has been made (more input processed
  78791. or more output produced), Z_STREAM_END if the end of the compressed data has
  78792. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78793. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78794. corrupted (input stream not conforming to the zlib format or incorrect check
  78795. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78796. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78797. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78798. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78799. inflate() can be called again with more input and more output space to
  78800. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78801. call inflateSync() to look for a good compression block if a partial recovery
  78802. of the data is desired.
  78803. */
  78804. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78805. /*
  78806. All dynamically allocated data structures for this stream are freed.
  78807. This function discards any unprocessed input and does not flush any
  78808. pending output.
  78809. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78810. was inconsistent. In the error case, msg may be set but then points to a
  78811. static string (which must not be deallocated).
  78812. */
  78813. /* Advanced functions */
  78814. /*
  78815. The following functions are needed only in some special applications.
  78816. */
  78817. /*
  78818. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78819. int level,
  78820. int method,
  78821. int windowBits,
  78822. int memLevel,
  78823. int strategy));
  78824. This is another version of deflateInit with more compression options. The
  78825. fields next_in, zalloc, zfree and opaque must be initialized before by
  78826. the caller.
  78827. The method parameter is the compression method. It must be Z_DEFLATED in
  78828. this version of the library.
  78829. The windowBits parameter is the base two logarithm of the window size
  78830. (the size of the history buffer). It should be in the range 8..15 for this
  78831. version of the library. Larger values of this parameter result in better
  78832. compression at the expense of memory usage. The default value is 15 if
  78833. deflateInit is used instead.
  78834. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78835. determines the window size. deflate() will then generate raw deflate data
  78836. with no zlib header or trailer, and will not compute an adler32 check value.
  78837. windowBits can also be greater than 15 for optional gzip encoding. Add
  78838. 16 to windowBits to write a simple gzip header and trailer around the
  78839. compressed data instead of a zlib wrapper. The gzip header will have no
  78840. file name, no extra data, no comment, no modification time (set to zero),
  78841. no header crc, and the operating system will be set to 255 (unknown). If a
  78842. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78843. The memLevel parameter specifies how much memory should be allocated
  78844. for the internal compression state. memLevel=1 uses minimum memory but
  78845. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78846. for optimal speed. The default value is 8. See zconf.h for total memory
  78847. usage as a function of windowBits and memLevel.
  78848. The strategy parameter is used to tune the compression algorithm. Use the
  78849. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78850. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78851. string match), or Z_RLE to limit match distances to one (run-length
  78852. encoding). Filtered data consists mostly of small values with a somewhat
  78853. random distribution. In this case, the compression algorithm is tuned to
  78854. compress them better. The effect of Z_FILTERED is to force more Huffman
  78855. coding and less string matching; it is somewhat intermediate between
  78856. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78857. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78858. parameter only affects the compression ratio but not the correctness of the
  78859. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78860. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78861. applications.
  78862. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78863. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78864. method). msg is set to null if there is no error message. deflateInit2 does
  78865. not perform any compression: this will be done by deflate().
  78866. */
  78867. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78868. const Bytef *dictionary,
  78869. uInt dictLength));
  78870. /*
  78871. Initializes the compression dictionary from the given byte sequence
  78872. without producing any compressed output. This function must be called
  78873. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78874. call of deflate. The compressor and decompressor must use exactly the same
  78875. dictionary (see inflateSetDictionary).
  78876. The dictionary should consist of strings (byte sequences) that are likely
  78877. to be encountered later in the data to be compressed, with the most commonly
  78878. used strings preferably put towards the end of the dictionary. Using a
  78879. dictionary is most useful when the data to be compressed is short and can be
  78880. predicted with good accuracy; the data can then be compressed better than
  78881. with the default empty dictionary.
  78882. Depending on the size of the compression data structures selected by
  78883. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78884. discarded, for example if the dictionary is larger than the window size in
  78885. deflate or deflate2. Thus the strings most likely to be useful should be
  78886. put at the end of the dictionary, not at the front. In addition, the
  78887. current implementation of deflate will use at most the window size minus
  78888. 262 bytes of the provided dictionary.
  78889. Upon return of this function, strm->adler is set to the adler32 value
  78890. of the dictionary; the decompressor may later use this value to determine
  78891. which dictionary has been used by the compressor. (The adler32 value
  78892. applies to the whole dictionary even if only a subset of the dictionary is
  78893. actually used by the compressor.) If a raw deflate was requested, then the
  78894. adler32 value is not computed and strm->adler is not set.
  78895. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78896. parameter is invalid (such as NULL dictionary) or the stream state is
  78897. inconsistent (for example if deflate has already been called for this stream
  78898. or if the compression method is bsort). deflateSetDictionary does not
  78899. perform any compression: this will be done by deflate().
  78900. */
  78901. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78902. z_streamp source));
  78903. /*
  78904. Sets the destination stream as a complete copy of the source stream.
  78905. This function can be useful when several compression strategies will be
  78906. tried, for example when there are several ways of pre-processing the input
  78907. data with a filter. The streams that will be discarded should then be freed
  78908. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78909. compression state which can be quite large, so this strategy is slow and
  78910. can consume lots of memory.
  78911. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78912. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78913. (such as zalloc being NULL). msg is left unchanged in both source and
  78914. destination.
  78915. */
  78916. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78917. /*
  78918. This function is equivalent to deflateEnd followed by deflateInit,
  78919. but does not free and reallocate all the internal compression state.
  78920. The stream will keep the same compression level and any other attributes
  78921. that may have been set by deflateInit2.
  78922. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78923. stream state was inconsistent (such as zalloc or state being NULL).
  78924. */
  78925. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78926. int level,
  78927. int strategy));
  78928. /*
  78929. Dynamically update the compression level and compression strategy. The
  78930. interpretation of level and strategy is as in deflateInit2. This can be
  78931. used to switch between compression and straight copy of the input data, or
  78932. to switch to a different kind of input data requiring a different
  78933. strategy. If the compression level is changed, the input available so far
  78934. is compressed with the old level (and may be flushed); the new level will
  78935. take effect only at the next call of deflate().
  78936. Before the call of deflateParams, the stream state must be set as for
  78937. a call of deflate(), since the currently available input may have to
  78938. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78939. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78940. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78941. if strm->avail_out was zero.
  78942. */
  78943. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78944. int good_length,
  78945. int max_lazy,
  78946. int nice_length,
  78947. int max_chain));
  78948. /*
  78949. Fine tune deflate's internal compression parameters. This should only be
  78950. used by someone who understands the algorithm used by zlib's deflate for
  78951. searching for the best matching string, and even then only by the most
  78952. fanatic optimizer trying to squeeze out the last compressed bit for their
  78953. specific input data. Read the deflate.c source code for the meaning of the
  78954. max_lazy, good_length, nice_length, and max_chain parameters.
  78955. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78956. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78957. */
  78958. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78959. uLong sourceLen));
  78960. /*
  78961. deflateBound() returns an upper bound on the compressed size after
  78962. deflation of sourceLen bytes. It must be called after deflateInit()
  78963. or deflateInit2(). This would be used to allocate an output buffer
  78964. for deflation in a single pass, and so would be called before deflate().
  78965. */
  78966. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78967. int bits,
  78968. int value));
  78969. /*
  78970. deflatePrime() inserts bits in the deflate output stream. The intent
  78971. is that this function is used to start off the deflate output with the
  78972. bits leftover from a previous deflate stream when appending to it. As such,
  78973. this function can only be used for raw deflate, and must be used before the
  78974. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78975. less than or equal to 16, and that many of the least significant bits of
  78976. value will be inserted in the output.
  78977. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78978. stream state was inconsistent.
  78979. */
  78980. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78981. gz_headerp head));
  78982. /*
  78983. deflateSetHeader() provides gzip header information for when a gzip
  78984. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78985. after deflateInit2() or deflateReset() and before the first call of
  78986. deflate(). The text, time, os, extra field, name, and comment information
  78987. in the provided gz_header structure are written to the gzip header (xflag is
  78988. ignored -- the extra flags are set according to the compression level). The
  78989. caller must assure that, if not Z_NULL, name and comment are terminated with
  78990. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78991. available there. If hcrc is true, a gzip header crc is included. Note that
  78992. the current versions of the command-line version of gzip (up through version
  78993. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78994. gzip file" and give up.
  78995. If deflateSetHeader is not used, the default gzip header has text false,
  78996. the time set to zero, and os set to 255, with no extra, name, or comment
  78997. fields. The gzip header is returned to the default state by deflateReset().
  78998. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78999. stream state was inconsistent.
  79000. */
  79001. /*
  79002. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  79003. int windowBits));
  79004. This is another version of inflateInit with an extra parameter. The
  79005. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  79006. before by the caller.
  79007. The windowBits parameter is the base two logarithm of the maximum window
  79008. size (the size of the history buffer). It should be in the range 8..15 for
  79009. this version of the library. The default value is 15 if inflateInit is used
  79010. instead. windowBits must be greater than or equal to the windowBits value
  79011. provided to deflateInit2() while compressing, or it must be equal to 15 if
  79012. deflateInit2() was not used. If a compressed stream with a larger window
  79013. size is given as input, inflate() will return with the error code
  79014. Z_DATA_ERROR instead of trying to allocate a larger window.
  79015. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  79016. determines the window size. inflate() will then process raw deflate data,
  79017. not looking for a zlib or gzip header, not generating a check value, and not
  79018. looking for any check values for comparison at the end of the stream. This
  79019. is for use with other formats that use the deflate compressed data format
  79020. such as zip. Those formats provide their own check values. If a custom
  79021. format is developed using the raw deflate format for compressed data, it is
  79022. recommended that a check value such as an adler32 or a crc32 be applied to
  79023. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79024. most applications, the zlib format should be used as is. Note that comments
  79025. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79026. windowBits can also be greater than 15 for optional gzip decoding. Add
  79027. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79028. detection, or add 16 to decode only the gzip format (the zlib format will
  79029. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79030. a crc32 instead of an adler32.
  79031. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79032. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79033. is set to null if there is no error message. inflateInit2 does not perform
  79034. any decompression apart from reading the zlib header if present: this will
  79035. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79036. and avail_out are unchanged.)
  79037. */
  79038. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79039. const Bytef *dictionary,
  79040. uInt dictLength));
  79041. /*
  79042. Initializes the decompression dictionary from the given uncompressed byte
  79043. sequence. This function must be called immediately after a call of inflate,
  79044. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79045. can be determined from the adler32 value returned by that call of inflate.
  79046. The compressor and decompressor must use exactly the same dictionary (see
  79047. deflateSetDictionary). For raw inflate, this function can be called
  79048. immediately after inflateInit2() or inflateReset() and before any call of
  79049. inflate() to set the dictionary. The application must insure that the
  79050. dictionary that was used for compression is provided.
  79051. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79052. parameter is invalid (such as NULL dictionary) or the stream state is
  79053. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79054. expected one (incorrect adler32 value). inflateSetDictionary does not
  79055. perform any decompression: this will be done by subsequent calls of
  79056. inflate().
  79057. */
  79058. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79059. /*
  79060. Skips invalid compressed data until a full flush point (see above the
  79061. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79062. available input is skipped. No output is provided.
  79063. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79064. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79065. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79066. case, the application may save the current current value of total_in which
  79067. indicates where valid compressed data was found. In the error case, the
  79068. application may repeatedly call inflateSync, providing more input each time,
  79069. until success or end of the input data.
  79070. */
  79071. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79072. z_streamp source));
  79073. /*
  79074. Sets the destination stream as a complete copy of the source stream.
  79075. This function can be useful when randomly accessing a large stream. The
  79076. first pass through the stream can periodically record the inflate state,
  79077. allowing restarting inflate at those points when randomly accessing the
  79078. stream.
  79079. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79080. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79081. (such as zalloc being NULL). msg is left unchanged in both source and
  79082. destination.
  79083. */
  79084. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79085. /*
  79086. This function is equivalent to inflateEnd followed by inflateInit,
  79087. but does not free and reallocate all the internal decompression state.
  79088. The stream will keep attributes that may have been set by inflateInit2.
  79089. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79090. stream state was inconsistent (such as zalloc or state being NULL).
  79091. */
  79092. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79093. int bits,
  79094. int value));
  79095. /*
  79096. This function inserts bits in the inflate input stream. The intent is
  79097. that this function is used to start inflating at a bit position in the
  79098. middle of a byte. The provided bits will be used before any bytes are used
  79099. from next_in. This function should only be used with raw inflate, and
  79100. should be used before the first inflate() call after inflateInit2() or
  79101. inflateReset(). bits must be less than or equal to 16, and that many of the
  79102. least significant bits of value will be inserted in the input.
  79103. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79104. stream state was inconsistent.
  79105. */
  79106. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79107. gz_headerp head));
  79108. /*
  79109. inflateGetHeader() requests that gzip header information be stored in the
  79110. provided gz_header structure. inflateGetHeader() may be called after
  79111. inflateInit2() or inflateReset(), and before the first call of inflate().
  79112. As inflate() processes the gzip stream, head->done is zero until the header
  79113. is completed, at which time head->done is set to one. If a zlib stream is
  79114. being decoded, then head->done is set to -1 to indicate that there will be
  79115. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79116. force inflate() to return immediately after header processing is complete
  79117. and before any actual data is decompressed.
  79118. The text, time, xflags, and os fields are filled in with the gzip header
  79119. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79120. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79121. contains the maximum number of bytes to write to extra. Once done is true,
  79122. extra_len contains the actual extra field length, and extra contains the
  79123. extra field, or that field truncated if extra_max is less than extra_len.
  79124. If name is not Z_NULL, then up to name_max characters are written there,
  79125. terminated with a zero unless the length is greater than name_max. If
  79126. comment is not Z_NULL, then up to comm_max characters are written there,
  79127. terminated with a zero unless the length is greater than comm_max. When
  79128. any of extra, name, or comment are not Z_NULL and the respective field is
  79129. not present in the header, then that field is set to Z_NULL to signal its
  79130. absence. This allows the use of deflateSetHeader() with the returned
  79131. structure to duplicate the header. However if those fields are set to
  79132. allocated memory, then the application will need to save those pointers
  79133. elsewhere so that they can be eventually freed.
  79134. If inflateGetHeader is not used, then the header information is simply
  79135. discarded. The header is always checked for validity, including the header
  79136. CRC if present. inflateReset() will reset the process to discard the header
  79137. information. The application would need to call inflateGetHeader() again to
  79138. retrieve the header from the next gzip stream.
  79139. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79140. stream state was inconsistent.
  79141. */
  79142. /*
  79143. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79144. unsigned char FAR *window));
  79145. Initialize the internal stream state for decompression using inflateBack()
  79146. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79147. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79148. derived memory allocation routines are used. windowBits is the base two
  79149. logarithm of the window size, in the range 8..15. window is a caller
  79150. supplied buffer of that size. Except for special applications where it is
  79151. assured that deflate was used with small window sizes, windowBits must be 15
  79152. and a 32K byte window must be supplied to be able to decompress general
  79153. deflate streams.
  79154. See inflateBack() for the usage of these routines.
  79155. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79156. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79157. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79158. match the version of the header file.
  79159. */
  79160. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79161. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79162. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79163. in_func in, void FAR *in_desc,
  79164. out_func out, void FAR *out_desc));
  79165. /*
  79166. inflateBack() does a raw inflate with a single call using a call-back
  79167. interface for input and output. This is more efficient than inflate() for
  79168. file i/o applications in that it avoids copying between the output and the
  79169. sliding window by simply making the window itself the output buffer. This
  79170. function trusts the application to not change the output buffer passed by
  79171. the output function, at least until inflateBack() returns.
  79172. inflateBackInit() must be called first to allocate the internal state
  79173. and to initialize the state with the user-provided window buffer.
  79174. inflateBack() may then be used multiple times to inflate a complete, raw
  79175. deflate stream with each call. inflateBackEnd() is then called to free
  79176. the allocated state.
  79177. A raw deflate stream is one with no zlib or gzip header or trailer.
  79178. This routine would normally be used in a utility that reads zip or gzip
  79179. files and writes out uncompressed files. The utility would decode the
  79180. header and process the trailer on its own, hence this routine expects
  79181. only the raw deflate stream to decompress. This is different from the
  79182. normal behavior of inflate(), which expects either a zlib or gzip header and
  79183. trailer around the deflate stream.
  79184. inflateBack() uses two subroutines supplied by the caller that are then
  79185. called by inflateBack() for input and output. inflateBack() calls those
  79186. routines until it reads a complete deflate stream and writes out all of the
  79187. uncompressed data, or until it encounters an error. The function's
  79188. parameters and return types are defined above in the in_func and out_func
  79189. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79190. number of bytes of provided input, and a pointer to that input in buf. If
  79191. there is no input available, in() must return zero--buf is ignored in that
  79192. case--and inflateBack() will return a buffer error. inflateBack() will call
  79193. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79194. should return zero on success, or non-zero on failure. If out() returns
  79195. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79196. are permitted to change the contents of the window provided to
  79197. inflateBackInit(), which is also the buffer that out() uses to write from.
  79198. The length written by out() will be at most the window size. Any non-zero
  79199. amount of input may be provided by in().
  79200. For convenience, inflateBack() can be provided input on the first call by
  79201. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79202. in() will be called. Therefore strm->next_in must be initialized before
  79203. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79204. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79205. must also be initialized, and then if strm->avail_in is not zero, input will
  79206. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79207. The in_desc and out_desc parameters of inflateBack() is passed as the
  79208. first parameter of in() and out() respectively when they are called. These
  79209. descriptors can be optionally used to pass any information that the caller-
  79210. supplied in() and out() functions need to do their job.
  79211. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79212. pass back any unused input that was provided by the last in() call. The
  79213. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79214. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79215. error in the deflate stream (in which case strm->msg is set to indicate the
  79216. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79217. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79218. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79219. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79220. out() returning non-zero. (in() will always be called before out(), so
  79221. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79222. that inflateBack() cannot return Z_OK.
  79223. */
  79224. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79225. /*
  79226. All memory allocated by inflateBackInit() is freed.
  79227. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79228. state was inconsistent.
  79229. */
  79230. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79231. /* Return flags indicating compile-time options.
  79232. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79233. 1.0: size of uInt
  79234. 3.2: size of uLong
  79235. 5.4: size of voidpf (pointer)
  79236. 7.6: size of z_off_t
  79237. Compiler, assembler, and debug options:
  79238. 8: DEBUG
  79239. 9: ASMV or ASMINF -- use ASM code
  79240. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79241. 11: 0 (reserved)
  79242. One-time table building (smaller code, but not thread-safe if true):
  79243. 12: BUILDFIXED -- build static block decoding tables when needed
  79244. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79245. 14,15: 0 (reserved)
  79246. Library content (indicates missing functionality):
  79247. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79248. deflate code when not needed)
  79249. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79250. and decode gzip streams (to avoid linking crc code)
  79251. 18-19: 0 (reserved)
  79252. Operation variations (changes in library functionality):
  79253. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79254. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79255. 22,23: 0 (reserved)
  79256. The sprintf variant used by gzprintf (zero is best):
  79257. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79258. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79259. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79260. Remainder:
  79261. 27-31: 0 (reserved)
  79262. */
  79263. /* utility functions */
  79264. /*
  79265. The following utility functions are implemented on top of the
  79266. basic stream-oriented functions. To simplify the interface, some
  79267. default options are assumed (compression level and memory usage,
  79268. standard memory allocation functions). The source code of these
  79269. utility functions can easily be modified if you need special options.
  79270. */
  79271. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79272. const Bytef *source, uLong sourceLen));
  79273. /*
  79274. Compresses the source buffer into the destination buffer. sourceLen is
  79275. the byte length of the source buffer. Upon entry, destLen is the total
  79276. size of the destination buffer, which must be at least the value returned
  79277. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79278. compressed buffer.
  79279. This function can be used to compress a whole file at once if the
  79280. input file is mmap'ed.
  79281. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79282. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79283. buffer.
  79284. */
  79285. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79286. const Bytef *source, uLong sourceLen,
  79287. int level));
  79288. /*
  79289. Compresses the source buffer into the destination buffer. The level
  79290. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79291. length of the source buffer. Upon entry, destLen is the total size of the
  79292. destination buffer, which must be at least the value returned by
  79293. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79294. compressed buffer.
  79295. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79296. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79297. Z_STREAM_ERROR if the level parameter is invalid.
  79298. */
  79299. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79300. /*
  79301. compressBound() returns an upper bound on the compressed size after
  79302. compress() or compress2() on sourceLen bytes. It would be used before
  79303. a compress() or compress2() call to allocate the destination buffer.
  79304. */
  79305. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79306. const Bytef *source, uLong sourceLen));
  79307. /*
  79308. Decompresses the source buffer into the destination buffer. sourceLen is
  79309. the byte length of the source buffer. Upon entry, destLen is the total
  79310. size of the destination buffer, which must be large enough to hold the
  79311. entire uncompressed data. (The size of the uncompressed data must have
  79312. been saved previously by the compressor and transmitted to the decompressor
  79313. by some mechanism outside the scope of this compression library.)
  79314. Upon exit, destLen is the actual size of the compressed buffer.
  79315. This function can be used to decompress a whole file at once if the
  79316. input file is mmap'ed.
  79317. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79318. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79319. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79320. */
  79321. typedef voidp gzFile;
  79322. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79323. /*
  79324. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79325. is as in fopen ("rb" or "wb") but can also include a compression level
  79326. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79327. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79328. as in "wb1R". (See the description of deflateInit2 for more information
  79329. about the strategy parameter.)
  79330. gzopen can be used to read a file which is not in gzip format; in this
  79331. case gzread will directly read from the file without decompression.
  79332. gzopen returns NULL if the file could not be opened or if there was
  79333. insufficient memory to allocate the (de)compression state; errno
  79334. can be checked to distinguish the two cases (if errno is zero, the
  79335. zlib error is Z_MEM_ERROR). */
  79336. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79337. /*
  79338. gzdopen() associates a gzFile with the file descriptor fd. File
  79339. descriptors are obtained from calls like open, dup, creat, pipe or
  79340. fileno (in the file has been previously opened with fopen).
  79341. The mode parameter is as in gzopen.
  79342. The next call of gzclose on the returned gzFile will also close the
  79343. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79344. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79345. gzdopen returns NULL if there was insufficient memory to allocate
  79346. the (de)compression state.
  79347. */
  79348. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79349. /*
  79350. Dynamically update the compression level or strategy. See the description
  79351. of deflateInit2 for the meaning of these parameters.
  79352. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79353. opened for writing.
  79354. */
  79355. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79356. /*
  79357. Reads the given number of uncompressed bytes from the compressed file.
  79358. If the input file was not in gzip format, gzread copies the given number
  79359. of bytes into the buffer.
  79360. gzread returns the number of uncompressed bytes actually read (0 for
  79361. end of file, -1 for error). */
  79362. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79363. voidpc buf, unsigned len));
  79364. /*
  79365. Writes the given number of uncompressed bytes into the compressed file.
  79366. gzwrite returns the number of uncompressed bytes actually written
  79367. (0 in case of error).
  79368. */
  79369. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79370. /*
  79371. Converts, formats, and writes the args to the compressed file under
  79372. control of the format string, as in fprintf. gzprintf returns the number of
  79373. uncompressed bytes actually written (0 in case of error). The number of
  79374. uncompressed bytes written is limited to 4095. The caller should assure that
  79375. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79376. return an error (0) with nothing written. In this case, there may also be a
  79377. buffer overflow with unpredictable consequences, which is possible only if
  79378. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79379. because the secure snprintf() or vsnprintf() functions were not available.
  79380. */
  79381. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79382. /*
  79383. Writes the given null-terminated string to the compressed file, excluding
  79384. the terminating null character.
  79385. gzputs returns the number of characters written, or -1 in case of error.
  79386. */
  79387. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79388. /*
  79389. Reads bytes from the compressed file until len-1 characters are read, or
  79390. a newline character is read and transferred to buf, or an end-of-file
  79391. condition is encountered. The string is then terminated with a null
  79392. character.
  79393. gzgets returns buf, or Z_NULL in case of error.
  79394. */
  79395. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79396. /*
  79397. Writes c, converted to an unsigned char, into the compressed file.
  79398. gzputc returns the value that was written, or -1 in case of error.
  79399. */
  79400. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79401. /*
  79402. Reads one byte from the compressed file. gzgetc returns this byte
  79403. or -1 in case of end of file or error.
  79404. */
  79405. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79406. /*
  79407. Push one character back onto the stream to be read again later.
  79408. Only one character of push-back is allowed. gzungetc() returns the
  79409. character pushed, or -1 on failure. gzungetc() will fail if a
  79410. character has been pushed but not read yet, or if c is -1. The pushed
  79411. character will be discarded if the stream is repositioned with gzseek()
  79412. or gzrewind().
  79413. */
  79414. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79415. /*
  79416. Flushes all pending output into the compressed file. The parameter
  79417. flush is as in the deflate() function. The return value is the zlib
  79418. error number (see function gzerror below). gzflush returns Z_OK if
  79419. the flush parameter is Z_FINISH and all output could be flushed.
  79420. gzflush should be called only when strictly necessary because it can
  79421. degrade compression.
  79422. */
  79423. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79424. z_off_t offset, int whence));
  79425. /*
  79426. Sets the starting position for the next gzread or gzwrite on the
  79427. given compressed file. The offset represents a number of bytes in the
  79428. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79429. the value SEEK_END is not supported.
  79430. If the file is opened for reading, this function is emulated but can be
  79431. extremely slow. If the file is opened for writing, only forward seeks are
  79432. supported; gzseek then compresses a sequence of zeroes up to the new
  79433. starting position.
  79434. gzseek returns the resulting offset location as measured in bytes from
  79435. the beginning of the uncompressed stream, or -1 in case of error, in
  79436. particular if the file is opened for writing and the new starting position
  79437. would be before the current position.
  79438. */
  79439. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79440. /*
  79441. Rewinds the given file. This function is supported only for reading.
  79442. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79443. */
  79444. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79445. /*
  79446. Returns the starting position for the next gzread or gzwrite on the
  79447. given compressed file. This position represents a number of bytes in the
  79448. uncompressed data stream.
  79449. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79450. */
  79451. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79452. /*
  79453. Returns 1 when EOF has previously been detected reading the given
  79454. input stream, otherwise zero.
  79455. */
  79456. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79457. /*
  79458. Returns 1 if file is being read directly without decompression, otherwise
  79459. zero.
  79460. */
  79461. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79462. /*
  79463. Flushes all pending output if necessary, closes the compressed file
  79464. and deallocates all the (de)compression state. The return value is the zlib
  79465. error number (see function gzerror below).
  79466. */
  79467. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79468. /*
  79469. Returns the error message for the last error which occurred on the
  79470. given compressed file. errnum is set to zlib error number. If an
  79471. error occurred in the file system and not in the compression library,
  79472. errnum is set to Z_ERRNO and the application may consult errno
  79473. to get the exact error code.
  79474. */
  79475. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79476. /*
  79477. Clears the error and end-of-file flags for file. This is analogous to the
  79478. clearerr() function in stdio. This is useful for continuing to read a gzip
  79479. file that is being written concurrently.
  79480. */
  79481. /* checksum functions */
  79482. /*
  79483. These functions are not related to compression but are exported
  79484. anyway because they might be useful in applications using the
  79485. compression library.
  79486. */
  79487. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79488. /*
  79489. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79490. return the updated checksum. If buf is NULL, this function returns
  79491. the required initial value for the checksum.
  79492. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79493. much faster. Usage example:
  79494. uLong adler = adler32(0L, Z_NULL, 0);
  79495. while (read_buffer(buffer, length) != EOF) {
  79496. adler = adler32(adler, buffer, length);
  79497. }
  79498. if (adler != original_adler) error();
  79499. */
  79500. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79501. z_off_t len2));
  79502. /*
  79503. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79504. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79505. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79506. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79507. */
  79508. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79509. /*
  79510. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79511. updated CRC-32. If buf is NULL, this function returns the required initial
  79512. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79513. performed within this function so it shouldn't be done by the application.
  79514. Usage example:
  79515. uLong crc = crc32(0L, Z_NULL, 0);
  79516. while (read_buffer(buffer, length) != EOF) {
  79517. crc = crc32(crc, buffer, length);
  79518. }
  79519. if (crc != original_crc) error();
  79520. */
  79521. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79522. /*
  79523. Combine two CRC-32 check values into one. For two sequences of bytes,
  79524. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79525. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79526. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79527. len2.
  79528. */
  79529. /* various hacks, don't look :) */
  79530. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79531. * and the compiler's view of z_stream:
  79532. */
  79533. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79534. const char *version, int stream_size));
  79535. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79536. const char *version, int stream_size));
  79537. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79538. int windowBits, int memLevel,
  79539. int strategy, const char *version,
  79540. int stream_size));
  79541. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79542. const char *version, int stream_size));
  79543. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79544. unsigned char FAR *window,
  79545. const char *version,
  79546. int stream_size));
  79547. #define deflateInit(strm, level) \
  79548. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79549. #define inflateInit(strm) \
  79550. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79551. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79552. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79553. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79554. #define inflateInit2(strm, windowBits) \
  79555. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79556. #define inflateBackInit(strm, windowBits, window) \
  79557. inflateBackInit_((strm), (windowBits), (window), \
  79558. ZLIB_VERSION, sizeof(z_stream))
  79559. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79560. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79561. #endif
  79562. ZEXTERN const char * ZEXPORT zError OF((int));
  79563. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79564. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79565. #ifdef __cplusplus
  79566. //}
  79567. #endif
  79568. #endif /* ZLIB_H */
  79569. /*** End of inlined file: zlib.h ***/
  79570. #undef OS_CODE
  79571. #else
  79572. #include <zlib.h>
  79573. #endif
  79574. }
  79575. BEGIN_JUCE_NAMESPACE
  79576. // internal helper object that holds the zlib structures so they don't have to be
  79577. // included publicly.
  79578. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79579. {
  79580. public:
  79581. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79582. : data (0),
  79583. dataSize (0),
  79584. compLevel (compressionLevel),
  79585. strategy (0),
  79586. setParams (true),
  79587. streamIsValid (false),
  79588. finished (false),
  79589. shouldFinish (false)
  79590. {
  79591. using namespace zlibNamespace;
  79592. zerostruct (stream);
  79593. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79594. nowrap ? -MAX_WBITS : MAX_WBITS,
  79595. 8, strategy) == Z_OK);
  79596. }
  79597. ~GZIPCompressorHelper()
  79598. {
  79599. using namespace zlibNamespace;
  79600. if (streamIsValid)
  79601. deflateEnd (&stream);
  79602. }
  79603. bool needsInput() const throw()
  79604. {
  79605. return dataSize <= 0;
  79606. }
  79607. void setInput (const uint8* const newData, const int size) throw()
  79608. {
  79609. data = newData;
  79610. dataSize = size;
  79611. }
  79612. int doNextBlock (uint8* const dest, const int destSize) throw()
  79613. {
  79614. using namespace zlibNamespace;
  79615. if (streamIsValid)
  79616. {
  79617. stream.next_in = const_cast <uint8*> (data);
  79618. stream.next_out = dest;
  79619. stream.avail_in = dataSize;
  79620. stream.avail_out = destSize;
  79621. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79622. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79623. setParams = false;
  79624. switch (result)
  79625. {
  79626. case Z_STREAM_END:
  79627. finished = true;
  79628. // Deliberate fall-through..
  79629. case Z_OK:
  79630. data += dataSize - stream.avail_in;
  79631. dataSize = stream.avail_in;
  79632. return destSize - stream.avail_out;
  79633. default:
  79634. break;
  79635. }
  79636. }
  79637. return 0;
  79638. }
  79639. enum { gzipCompBufferSize = 32768 };
  79640. private:
  79641. zlibNamespace::z_stream stream;
  79642. const uint8* data;
  79643. int dataSize, compLevel, strategy;
  79644. bool setParams, streamIsValid;
  79645. public:
  79646. bool finished, shouldFinish;
  79647. };
  79648. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79649. int compressionLevel,
  79650. const bool deleteDestStream,
  79651. const bool noWrap)
  79652. : destStream (destStream_),
  79653. streamToDelete (deleteDestStream ? destStream_ : 0),
  79654. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79655. {
  79656. if (compressionLevel < 1 || compressionLevel > 9)
  79657. compressionLevel = -1;
  79658. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79659. }
  79660. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79661. {
  79662. flush();
  79663. }
  79664. void GZIPCompressorOutputStream::flush()
  79665. {
  79666. if (! helper->finished)
  79667. {
  79668. helper->shouldFinish = true;
  79669. while (! helper->finished)
  79670. doNextBlock();
  79671. }
  79672. destStream->flush();
  79673. }
  79674. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79675. {
  79676. if (! helper->finished)
  79677. {
  79678. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79679. while (! helper->needsInput())
  79680. {
  79681. if (! doNextBlock())
  79682. return false;
  79683. }
  79684. }
  79685. return true;
  79686. }
  79687. bool GZIPCompressorOutputStream::doNextBlock()
  79688. {
  79689. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79690. if (len > 0)
  79691. return destStream->write (buffer, len);
  79692. else
  79693. return true;
  79694. }
  79695. int64 GZIPCompressorOutputStream::getPosition()
  79696. {
  79697. return destStream->getPosition();
  79698. }
  79699. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79700. {
  79701. jassertfalse; // can't do it!
  79702. return false;
  79703. }
  79704. END_JUCE_NAMESPACE
  79705. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79706. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79707. #if JUCE_MSVC
  79708. #pragma warning (push)
  79709. #pragma warning (disable: 4309 4305)
  79710. #endif
  79711. namespace zlibNamespace
  79712. {
  79713. #if JUCE_INCLUDE_ZLIB_CODE
  79714. #undef OS_CODE
  79715. #undef fdopen
  79716. #define ZLIB_INTERNAL
  79717. #define NO_DUMMY_DECL
  79718. /*** Start of inlined file: adler32.c ***/
  79719. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79720. #define ZLIB_INTERNAL
  79721. #define BASE 65521UL /* largest prime smaller than 65536 */
  79722. #define NMAX 5552
  79723. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79724. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79725. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79726. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79727. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79728. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79729. /* use NO_DIVIDE if your processor does not do division in hardware */
  79730. #ifdef NO_DIVIDE
  79731. # define MOD(a) \
  79732. do { \
  79733. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79734. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79735. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79736. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79737. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79738. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79739. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79740. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79741. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79742. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79743. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79744. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79745. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79746. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79747. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79748. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79749. if (a >= BASE) a -= BASE; \
  79750. } while (0)
  79751. # define MOD4(a) \
  79752. do { \
  79753. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79754. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79755. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79756. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79757. if (a >= BASE) a -= BASE; \
  79758. } while (0)
  79759. #else
  79760. # define MOD(a) a %= BASE
  79761. # define MOD4(a) a %= BASE
  79762. #endif
  79763. /* ========================================================================= */
  79764. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79765. {
  79766. unsigned long sum2;
  79767. unsigned n;
  79768. /* split Adler-32 into component sums */
  79769. sum2 = (adler >> 16) & 0xffff;
  79770. adler &= 0xffff;
  79771. /* in case user likes doing a byte at a time, keep it fast */
  79772. if (len == 1) {
  79773. adler += buf[0];
  79774. if (adler >= BASE)
  79775. adler -= BASE;
  79776. sum2 += adler;
  79777. if (sum2 >= BASE)
  79778. sum2 -= BASE;
  79779. return adler | (sum2 << 16);
  79780. }
  79781. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79782. if (buf == Z_NULL)
  79783. return 1L;
  79784. /* in case short lengths are provided, keep it somewhat fast */
  79785. if (len < 16) {
  79786. while (len--) {
  79787. adler += *buf++;
  79788. sum2 += adler;
  79789. }
  79790. if (adler >= BASE)
  79791. adler -= BASE;
  79792. MOD4(sum2); /* only added so many BASE's */
  79793. return adler | (sum2 << 16);
  79794. }
  79795. /* do length NMAX blocks -- requires just one modulo operation */
  79796. while (len >= NMAX) {
  79797. len -= NMAX;
  79798. n = NMAX / 16; /* NMAX is divisible by 16 */
  79799. do {
  79800. DO16(buf); /* 16 sums unrolled */
  79801. buf += 16;
  79802. } while (--n);
  79803. MOD(adler);
  79804. MOD(sum2);
  79805. }
  79806. /* do remaining bytes (less than NMAX, still just one modulo) */
  79807. if (len) { /* avoid modulos if none remaining */
  79808. while (len >= 16) {
  79809. len -= 16;
  79810. DO16(buf);
  79811. buf += 16;
  79812. }
  79813. while (len--) {
  79814. adler += *buf++;
  79815. sum2 += adler;
  79816. }
  79817. MOD(adler);
  79818. MOD(sum2);
  79819. }
  79820. /* return recombined sums */
  79821. return adler | (sum2 << 16);
  79822. }
  79823. /* ========================================================================= */
  79824. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79825. {
  79826. unsigned long sum1;
  79827. unsigned long sum2;
  79828. unsigned rem;
  79829. /* the derivation of this formula is left as an exercise for the reader */
  79830. rem = (unsigned)(len2 % BASE);
  79831. sum1 = adler1 & 0xffff;
  79832. sum2 = rem * sum1;
  79833. MOD(sum2);
  79834. sum1 += (adler2 & 0xffff) + BASE - 1;
  79835. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79836. if (sum1 > BASE) sum1 -= BASE;
  79837. if (sum1 > BASE) sum1 -= BASE;
  79838. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79839. if (sum2 > BASE) sum2 -= BASE;
  79840. return sum1 | (sum2 << 16);
  79841. }
  79842. /*** End of inlined file: adler32.c ***/
  79843. /*** Start of inlined file: compress.c ***/
  79844. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79845. #define ZLIB_INTERNAL
  79846. /* ===========================================================================
  79847. Compresses the source buffer into the destination buffer. The level
  79848. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79849. length of the source buffer. Upon entry, destLen is the total size of the
  79850. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79851. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79852. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79853. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79854. Z_STREAM_ERROR if the level parameter is invalid.
  79855. */
  79856. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79857. uLong sourceLen, int level)
  79858. {
  79859. z_stream stream;
  79860. int err;
  79861. stream.next_in = (Bytef*)source;
  79862. stream.avail_in = (uInt)sourceLen;
  79863. #ifdef MAXSEG_64K
  79864. /* Check for source > 64K on 16-bit machine: */
  79865. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79866. #endif
  79867. stream.next_out = dest;
  79868. stream.avail_out = (uInt)*destLen;
  79869. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79870. stream.zalloc = (alloc_func)0;
  79871. stream.zfree = (free_func)0;
  79872. stream.opaque = (voidpf)0;
  79873. err = deflateInit(&stream, level);
  79874. if (err != Z_OK) return err;
  79875. err = deflate(&stream, Z_FINISH);
  79876. if (err != Z_STREAM_END) {
  79877. deflateEnd(&stream);
  79878. return err == Z_OK ? Z_BUF_ERROR : err;
  79879. }
  79880. *destLen = stream.total_out;
  79881. err = deflateEnd(&stream);
  79882. return err;
  79883. }
  79884. /* ===========================================================================
  79885. */
  79886. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79887. {
  79888. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79889. }
  79890. /* ===========================================================================
  79891. If the default memLevel or windowBits for deflateInit() is changed, then
  79892. this function needs to be updated.
  79893. */
  79894. uLong ZEXPORT compressBound (uLong sourceLen)
  79895. {
  79896. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79897. }
  79898. /*** End of inlined file: compress.c ***/
  79899. #undef DO1
  79900. #undef DO8
  79901. /*** Start of inlined file: crc32.c ***/
  79902. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79903. /*
  79904. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79905. protection on the static variables used to control the first-use generation
  79906. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79907. first call get_crc_table() to initialize the tables before allowing more than
  79908. one thread to use crc32().
  79909. */
  79910. #ifdef MAKECRCH
  79911. # include <stdio.h>
  79912. # ifndef DYNAMIC_CRC_TABLE
  79913. # define DYNAMIC_CRC_TABLE
  79914. # endif /* !DYNAMIC_CRC_TABLE */
  79915. #endif /* MAKECRCH */
  79916. /*** Start of inlined file: zutil.h ***/
  79917. /* WARNING: this file should *not* be used by applications. It is
  79918. part of the implementation of the compression library and is
  79919. subject to change. Applications should only use zlib.h.
  79920. */
  79921. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79922. #ifndef ZUTIL_H
  79923. #define ZUTIL_H
  79924. #define ZLIB_INTERNAL
  79925. #ifdef STDC
  79926. # ifndef _WIN32_WCE
  79927. # include <stddef.h>
  79928. # endif
  79929. # include <string.h>
  79930. # include <stdlib.h>
  79931. #endif
  79932. #ifdef NO_ERRNO_H
  79933. # ifdef _WIN32_WCE
  79934. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79935. * errno. We define it as a global variable to simplify porting.
  79936. * Its value is always 0 and should not be used. We rename it to
  79937. * avoid conflict with other libraries that use the same workaround.
  79938. */
  79939. # define errno z_errno
  79940. # endif
  79941. extern int errno;
  79942. #else
  79943. # ifndef _WIN32_WCE
  79944. # include <errno.h>
  79945. # endif
  79946. #endif
  79947. #ifndef local
  79948. # define local static
  79949. #endif
  79950. /* compile with -Dlocal if your debugger can't find static symbols */
  79951. typedef unsigned char uch;
  79952. typedef uch FAR uchf;
  79953. typedef unsigned short ush;
  79954. typedef ush FAR ushf;
  79955. typedef unsigned long ulg;
  79956. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79957. /* (size given to avoid silly warnings with Visual C++) */
  79958. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79959. #define ERR_RETURN(strm,err) \
  79960. return (strm->msg = (char*)ERR_MSG(err), (err))
  79961. /* To be used only when the state is known to be valid */
  79962. /* common constants */
  79963. #ifndef DEF_WBITS
  79964. # define DEF_WBITS MAX_WBITS
  79965. #endif
  79966. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79967. #if MAX_MEM_LEVEL >= 8
  79968. # define DEF_MEM_LEVEL 8
  79969. #else
  79970. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79971. #endif
  79972. /* default memLevel */
  79973. #define STORED_BLOCK 0
  79974. #define STATIC_TREES 1
  79975. #define DYN_TREES 2
  79976. /* The three kinds of block type */
  79977. #define MIN_MATCH 3
  79978. #define MAX_MATCH 258
  79979. /* The minimum and maximum match lengths */
  79980. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79981. /* target dependencies */
  79982. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79983. # define OS_CODE 0x00
  79984. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79985. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79986. /* Allow compilation with ANSI keywords only enabled */
  79987. void _Cdecl farfree( void *block );
  79988. void *_Cdecl farmalloc( unsigned long nbytes );
  79989. # else
  79990. # include <alloc.h>
  79991. # endif
  79992. # else /* MSC or DJGPP */
  79993. # include <malloc.h>
  79994. # endif
  79995. #endif
  79996. #ifdef AMIGA
  79997. # define OS_CODE 0x01
  79998. #endif
  79999. #if defined(VAXC) || defined(VMS)
  80000. # define OS_CODE 0x02
  80001. # define F_OPEN(name, mode) \
  80002. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  80003. #endif
  80004. #if defined(ATARI) || defined(atarist)
  80005. # define OS_CODE 0x05
  80006. #endif
  80007. #ifdef OS2
  80008. # define OS_CODE 0x06
  80009. # ifdef M_I86
  80010. #include <malloc.h>
  80011. # endif
  80012. #endif
  80013. #if defined(MACOS) || TARGET_OS_MAC
  80014. # define OS_CODE 0x07
  80015. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  80016. # include <unix.h> /* for fdopen */
  80017. # else
  80018. # ifndef fdopen
  80019. # define fdopen(fd,mode) NULL /* No fdopen() */
  80020. # endif
  80021. # endif
  80022. #endif
  80023. #ifdef TOPS20
  80024. # define OS_CODE 0x0a
  80025. #endif
  80026. #ifdef WIN32
  80027. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80028. # define OS_CODE 0x0b
  80029. # endif
  80030. #endif
  80031. #ifdef __50SERIES /* Prime/PRIMOS */
  80032. # define OS_CODE 0x0f
  80033. #endif
  80034. #if defined(_BEOS_) || defined(RISCOS)
  80035. # define fdopen(fd,mode) NULL /* No fdopen() */
  80036. #endif
  80037. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80038. # if defined(_WIN32_WCE)
  80039. # define fdopen(fd,mode) NULL /* No fdopen() */
  80040. # ifndef _PTRDIFF_T_DEFINED
  80041. typedef int ptrdiff_t;
  80042. # define _PTRDIFF_T_DEFINED
  80043. # endif
  80044. # else
  80045. # define fdopen(fd,type) _fdopen(fd,type)
  80046. # endif
  80047. #endif
  80048. /* common defaults */
  80049. #ifndef OS_CODE
  80050. # define OS_CODE 0x03 /* assume Unix */
  80051. #endif
  80052. #ifndef F_OPEN
  80053. # define F_OPEN(name, mode) fopen((name), (mode))
  80054. #endif
  80055. /* functions */
  80056. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80057. # ifndef HAVE_VSNPRINTF
  80058. # define HAVE_VSNPRINTF
  80059. # endif
  80060. #endif
  80061. #if defined(__CYGWIN__)
  80062. # ifndef HAVE_VSNPRINTF
  80063. # define HAVE_VSNPRINTF
  80064. # endif
  80065. #endif
  80066. #ifndef HAVE_VSNPRINTF
  80067. # ifdef MSDOS
  80068. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80069. but for now we just assume it doesn't. */
  80070. # define NO_vsnprintf
  80071. # endif
  80072. # ifdef __TURBOC__
  80073. # define NO_vsnprintf
  80074. # endif
  80075. # ifdef WIN32
  80076. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80077. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80078. # define vsnprintf _vsnprintf
  80079. # endif
  80080. # endif
  80081. # ifdef __SASC
  80082. # define NO_vsnprintf
  80083. # endif
  80084. #endif
  80085. #ifdef VMS
  80086. # define NO_vsnprintf
  80087. #endif
  80088. #if defined(pyr)
  80089. # define NO_MEMCPY
  80090. #endif
  80091. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80092. /* Use our own functions for small and medium model with MSC <= 5.0.
  80093. * You may have to use the same strategy for Borland C (untested).
  80094. * The __SC__ check is for Symantec.
  80095. */
  80096. # define NO_MEMCPY
  80097. #endif
  80098. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80099. # define HAVE_MEMCPY
  80100. #endif
  80101. #ifdef HAVE_MEMCPY
  80102. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80103. # define zmemcpy _fmemcpy
  80104. # define zmemcmp _fmemcmp
  80105. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80106. # else
  80107. # define zmemcpy memcpy
  80108. # define zmemcmp memcmp
  80109. # define zmemzero(dest, len) memset(dest, 0, len)
  80110. # endif
  80111. #else
  80112. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80113. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80114. extern void zmemzero OF((Bytef* dest, uInt len));
  80115. #endif
  80116. /* Diagnostic functions */
  80117. #ifdef DEBUG
  80118. # include <stdio.h>
  80119. extern int z_verbose;
  80120. extern void z_error OF((const char *m));
  80121. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80122. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80123. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80124. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80125. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80126. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80127. #else
  80128. # define Assert(cond,msg)
  80129. # define Trace(x)
  80130. # define Tracev(x)
  80131. # define Tracevv(x)
  80132. # define Tracec(c,x)
  80133. # define Tracecv(c,x)
  80134. #endif
  80135. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80136. void zcfree OF((voidpf opaque, voidpf ptr));
  80137. #define ZALLOC(strm, items, size) \
  80138. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80139. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80140. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80141. #endif /* ZUTIL_H */
  80142. /*** End of inlined file: zutil.h ***/
  80143. /* for STDC and FAR definitions */
  80144. #define local static
  80145. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80146. #ifndef NOBYFOUR
  80147. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80148. # include <limits.h>
  80149. # define BYFOUR
  80150. # if (UINT_MAX == 0xffffffffUL)
  80151. typedef unsigned int u4;
  80152. # else
  80153. # if (ULONG_MAX == 0xffffffffUL)
  80154. typedef unsigned long u4;
  80155. # else
  80156. # if (USHRT_MAX == 0xffffffffUL)
  80157. typedef unsigned short u4;
  80158. # else
  80159. # undef BYFOUR /* can't find a four-byte integer type! */
  80160. # endif
  80161. # endif
  80162. # endif
  80163. # endif /* STDC */
  80164. #endif /* !NOBYFOUR */
  80165. /* Definitions for doing the crc four data bytes at a time. */
  80166. #ifdef BYFOUR
  80167. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80168. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80169. local unsigned long crc32_little OF((unsigned long,
  80170. const unsigned char FAR *, unsigned));
  80171. local unsigned long crc32_big OF((unsigned long,
  80172. const unsigned char FAR *, unsigned));
  80173. # define TBLS 8
  80174. #else
  80175. # define TBLS 1
  80176. #endif /* BYFOUR */
  80177. /* Local functions for crc concatenation */
  80178. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80179. unsigned long vec));
  80180. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80181. #ifdef DYNAMIC_CRC_TABLE
  80182. local volatile int crc_table_empty = 1;
  80183. local unsigned long FAR crc_table[TBLS][256];
  80184. local void make_crc_table OF((void));
  80185. #ifdef MAKECRCH
  80186. local void write_table OF((FILE *, const unsigned long FAR *));
  80187. #endif /* MAKECRCH */
  80188. /*
  80189. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80190. 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.
  80191. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80192. with the lowest powers in the most significant bit. Then adding polynomials
  80193. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80194. one. If we call the above polynomial p, and represent a byte as the
  80195. polynomial q, also with the lowest power in the most significant bit (so the
  80196. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80197. where a mod b means the remainder after dividing a by b.
  80198. This calculation is done using the shift-register method of multiplying and
  80199. taking the remainder. The register is initialized to zero, and for each
  80200. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80201. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80202. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80203. out is a one). We start with the highest power (least significant bit) of
  80204. q and repeat for all eight bits of q.
  80205. The first table is simply the CRC of all possible eight bit values. This is
  80206. all the information needed to generate CRCs on data a byte at a time for all
  80207. combinations of CRC register values and incoming bytes. The remaining tables
  80208. allow for word-at-a-time CRC calculation for both big-endian and little-
  80209. endian machines, where a word is four bytes.
  80210. */
  80211. local void make_crc_table()
  80212. {
  80213. unsigned long c;
  80214. int n, k;
  80215. unsigned long poly; /* polynomial exclusive-or pattern */
  80216. /* terms of polynomial defining this crc (except x^32): */
  80217. static volatile int first = 1; /* flag to limit concurrent making */
  80218. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80219. /* See if another task is already doing this (not thread-safe, but better
  80220. than nothing -- significantly reduces duration of vulnerability in
  80221. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80222. if (first) {
  80223. first = 0;
  80224. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80225. poly = 0UL;
  80226. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80227. poly |= 1UL << (31 - p[n]);
  80228. /* generate a crc for every 8-bit value */
  80229. for (n = 0; n < 256; n++) {
  80230. c = (unsigned long)n;
  80231. for (k = 0; k < 8; k++)
  80232. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80233. crc_table[0][n] = c;
  80234. }
  80235. #ifdef BYFOUR
  80236. /* generate crc for each value followed by one, two, and three zeros,
  80237. and then the byte reversal of those as well as the first table */
  80238. for (n = 0; n < 256; n++) {
  80239. c = crc_table[0][n];
  80240. crc_table[4][n] = REV(c);
  80241. for (k = 1; k < 4; k++) {
  80242. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80243. crc_table[k][n] = c;
  80244. crc_table[k + 4][n] = REV(c);
  80245. }
  80246. }
  80247. #endif /* BYFOUR */
  80248. crc_table_empty = 0;
  80249. }
  80250. else { /* not first */
  80251. /* wait for the other guy to finish (not efficient, but rare) */
  80252. while (crc_table_empty)
  80253. ;
  80254. }
  80255. #ifdef MAKECRCH
  80256. /* write out CRC tables to crc32.h */
  80257. {
  80258. FILE *out;
  80259. out = fopen("crc32.h", "w");
  80260. if (out == NULL) return;
  80261. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80262. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80263. fprintf(out, "local const unsigned long FAR ");
  80264. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80265. write_table(out, crc_table[0]);
  80266. # ifdef BYFOUR
  80267. fprintf(out, "#ifdef BYFOUR\n");
  80268. for (k = 1; k < 8; k++) {
  80269. fprintf(out, " },\n {\n");
  80270. write_table(out, crc_table[k]);
  80271. }
  80272. fprintf(out, "#endif\n");
  80273. # endif /* BYFOUR */
  80274. fprintf(out, " }\n};\n");
  80275. fclose(out);
  80276. }
  80277. #endif /* MAKECRCH */
  80278. }
  80279. #ifdef MAKECRCH
  80280. local void write_table(out, table)
  80281. FILE *out;
  80282. const unsigned long FAR *table;
  80283. {
  80284. int n;
  80285. for (n = 0; n < 256; n++)
  80286. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80287. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80288. }
  80289. #endif /* MAKECRCH */
  80290. #else /* !DYNAMIC_CRC_TABLE */
  80291. /* ========================================================================
  80292. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80293. */
  80294. /*** Start of inlined file: crc32.h ***/
  80295. local const unsigned long FAR crc_table[TBLS][256] =
  80296. {
  80297. {
  80298. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80299. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80300. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80301. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80302. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80303. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80304. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80305. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80306. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80307. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80308. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80309. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80310. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80311. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80312. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80313. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80314. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80315. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80316. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80317. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80318. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80319. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80320. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80321. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80322. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80323. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80324. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80325. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80326. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80327. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80328. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80329. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80330. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80331. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80332. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80333. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80334. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80335. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80336. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80337. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80338. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80339. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80340. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80341. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80342. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80343. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80344. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80345. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80346. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80347. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80348. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80349. 0x2d02ef8dUL
  80350. #ifdef BYFOUR
  80351. },
  80352. {
  80353. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80354. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80355. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80356. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80357. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80358. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80359. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80360. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80361. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80362. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80363. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80364. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80365. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80366. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80367. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80368. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80369. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80370. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80371. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80372. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80373. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80374. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80375. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80376. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80377. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80378. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80379. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80380. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80381. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80382. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80383. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80384. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80385. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80386. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80387. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80388. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80389. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80390. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80391. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80392. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80393. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80394. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80395. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80396. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80397. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80398. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80399. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80400. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80401. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80402. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80403. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80404. 0x9324fd72UL
  80405. },
  80406. {
  80407. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80408. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80409. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80410. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80411. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80412. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80413. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80414. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80415. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80416. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80417. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80418. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80419. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80420. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80421. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80422. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80423. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80424. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80425. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80426. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80427. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80428. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80429. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80430. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80431. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80432. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80433. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80434. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80435. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80436. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80437. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80438. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80439. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80440. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80441. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80442. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80443. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80444. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80445. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80446. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80447. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80448. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80449. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80450. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80451. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80452. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80453. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80454. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80455. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80456. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80457. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80458. 0xbe9834edUL
  80459. },
  80460. {
  80461. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80462. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80463. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80464. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80465. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80466. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80467. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80468. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80469. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80470. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80471. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80472. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80473. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80474. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80475. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80476. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80477. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80478. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80479. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80480. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80481. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80482. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80483. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80484. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80485. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80486. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80487. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80488. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80489. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80490. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80491. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80492. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80493. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80494. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80495. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80496. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80497. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80498. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80499. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80500. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80501. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80502. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80503. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80504. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80505. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80506. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80507. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80508. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80509. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80510. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80511. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80512. 0xde0506f1UL
  80513. },
  80514. {
  80515. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80516. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80517. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80518. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80519. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80520. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80521. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80522. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80523. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80524. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80525. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80526. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80527. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80528. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80529. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80530. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80531. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80532. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80533. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80534. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80535. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80536. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80537. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80538. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80539. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80540. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80541. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80542. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80543. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80544. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80545. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80546. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80547. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80548. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80549. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80550. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80551. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80552. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80553. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80554. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80555. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80556. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80557. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80558. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80559. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80560. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80561. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80562. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80563. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80564. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80565. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80566. 0x8def022dUL
  80567. },
  80568. {
  80569. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80570. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80571. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80572. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80573. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80574. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80575. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80576. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80577. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80578. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80579. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80580. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80581. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80582. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80583. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80584. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80585. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80586. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80587. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80588. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80589. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80590. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80591. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80592. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80593. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80594. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80595. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80596. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80597. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80598. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80599. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80600. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80601. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80602. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80603. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80604. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80605. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80606. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80607. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80608. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80609. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80610. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80611. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80612. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80613. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80614. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80615. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80616. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80617. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80618. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80619. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80620. 0x72fd2493UL
  80621. },
  80622. {
  80623. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80624. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80625. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80626. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80627. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80628. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80629. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80630. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80631. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80632. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80633. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80634. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80635. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80636. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80637. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80638. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80639. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80640. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80641. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80642. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80643. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80644. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80645. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80646. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80647. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80648. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80649. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80650. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80651. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80652. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80653. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80654. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80655. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80656. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80657. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80658. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80659. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80660. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80661. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80662. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80663. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80664. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80665. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80666. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80667. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80668. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80669. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80670. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80671. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80672. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80673. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80674. 0xed3498beUL
  80675. },
  80676. {
  80677. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80678. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80679. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80680. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80681. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80682. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80683. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80684. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80685. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80686. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80687. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80688. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80689. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80690. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80691. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80692. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80693. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80694. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80695. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80696. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80697. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80698. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80699. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80700. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80701. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80702. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80703. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80704. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80705. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80706. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80707. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80708. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80709. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80710. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80711. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80712. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80713. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80714. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80715. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80716. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80717. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80718. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80719. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80720. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80721. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80722. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80723. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80724. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80725. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80726. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80727. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80728. 0xf10605deUL
  80729. #endif
  80730. }
  80731. };
  80732. /*** End of inlined file: crc32.h ***/
  80733. #endif /* DYNAMIC_CRC_TABLE */
  80734. /* =========================================================================
  80735. * This function can be used by asm versions of crc32()
  80736. */
  80737. const unsigned long FAR * ZEXPORT get_crc_table()
  80738. {
  80739. #ifdef DYNAMIC_CRC_TABLE
  80740. if (crc_table_empty)
  80741. make_crc_table();
  80742. #endif /* DYNAMIC_CRC_TABLE */
  80743. return (const unsigned long FAR *)crc_table;
  80744. }
  80745. /* ========================================================================= */
  80746. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80747. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80748. /* ========================================================================= */
  80749. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80750. {
  80751. if (buf == Z_NULL) return 0UL;
  80752. #ifdef DYNAMIC_CRC_TABLE
  80753. if (crc_table_empty)
  80754. make_crc_table();
  80755. #endif /* DYNAMIC_CRC_TABLE */
  80756. #ifdef BYFOUR
  80757. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80758. u4 endian;
  80759. endian = 1;
  80760. if (*((unsigned char *)(&endian)))
  80761. return crc32_little(crc, buf, len);
  80762. else
  80763. return crc32_big(crc, buf, len);
  80764. }
  80765. #endif /* BYFOUR */
  80766. crc = crc ^ 0xffffffffUL;
  80767. while (len >= 8) {
  80768. DO8;
  80769. len -= 8;
  80770. }
  80771. if (len) do {
  80772. DO1;
  80773. } while (--len);
  80774. return crc ^ 0xffffffffUL;
  80775. }
  80776. #ifdef BYFOUR
  80777. /* ========================================================================= */
  80778. #define DOLIT4 c ^= *buf4++; \
  80779. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80780. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80781. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80782. /* ========================================================================= */
  80783. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80784. {
  80785. register u4 c;
  80786. register const u4 FAR *buf4;
  80787. c = (u4)crc;
  80788. c = ~c;
  80789. while (len && ((ptrdiff_t)buf & 3)) {
  80790. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80791. len--;
  80792. }
  80793. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80794. while (len >= 32) {
  80795. DOLIT32;
  80796. len -= 32;
  80797. }
  80798. while (len >= 4) {
  80799. DOLIT4;
  80800. len -= 4;
  80801. }
  80802. buf = (const unsigned char FAR *)buf4;
  80803. if (len) do {
  80804. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80805. } while (--len);
  80806. c = ~c;
  80807. return (unsigned long)c;
  80808. }
  80809. /* ========================================================================= */
  80810. #define DOBIG4 c ^= *++buf4; \
  80811. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80812. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80813. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80814. /* ========================================================================= */
  80815. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80816. {
  80817. register u4 c;
  80818. register const u4 FAR *buf4;
  80819. c = REV((u4)crc);
  80820. c = ~c;
  80821. while (len && ((ptrdiff_t)buf & 3)) {
  80822. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80823. len--;
  80824. }
  80825. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80826. buf4--;
  80827. while (len >= 32) {
  80828. DOBIG32;
  80829. len -= 32;
  80830. }
  80831. while (len >= 4) {
  80832. DOBIG4;
  80833. len -= 4;
  80834. }
  80835. buf4++;
  80836. buf = (const unsigned char FAR *)buf4;
  80837. if (len) do {
  80838. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80839. } while (--len);
  80840. c = ~c;
  80841. return (unsigned long)(REV(c));
  80842. }
  80843. #endif /* BYFOUR */
  80844. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80845. /* ========================================================================= */
  80846. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80847. {
  80848. unsigned long sum;
  80849. sum = 0;
  80850. while (vec) {
  80851. if (vec & 1)
  80852. sum ^= *mat;
  80853. vec >>= 1;
  80854. mat++;
  80855. }
  80856. return sum;
  80857. }
  80858. /* ========================================================================= */
  80859. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80860. {
  80861. int n;
  80862. for (n = 0; n < GF2_DIM; n++)
  80863. square[n] = gf2_matrix_times(mat, mat[n]);
  80864. }
  80865. /* ========================================================================= */
  80866. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80867. {
  80868. int n;
  80869. unsigned long row;
  80870. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80871. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80872. /* degenerate case */
  80873. if (len2 == 0)
  80874. return crc1;
  80875. /* put operator for one zero bit in odd */
  80876. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80877. row = 1;
  80878. for (n = 1; n < GF2_DIM; n++) {
  80879. odd[n] = row;
  80880. row <<= 1;
  80881. }
  80882. /* put operator for two zero bits in even */
  80883. gf2_matrix_square(even, odd);
  80884. /* put operator for four zero bits in odd */
  80885. gf2_matrix_square(odd, even);
  80886. /* apply len2 zeros to crc1 (first square will put the operator for one
  80887. zero byte, eight zero bits, in even) */
  80888. do {
  80889. /* apply zeros operator for this bit of len2 */
  80890. gf2_matrix_square(even, odd);
  80891. if (len2 & 1)
  80892. crc1 = gf2_matrix_times(even, crc1);
  80893. len2 >>= 1;
  80894. /* if no more bits set, then done */
  80895. if (len2 == 0)
  80896. break;
  80897. /* another iteration of the loop with odd and even swapped */
  80898. gf2_matrix_square(odd, even);
  80899. if (len2 & 1)
  80900. crc1 = gf2_matrix_times(odd, crc1);
  80901. len2 >>= 1;
  80902. /* if no more bits set, then done */
  80903. } while (len2 != 0);
  80904. /* return combined crc */
  80905. crc1 ^= crc2;
  80906. return crc1;
  80907. }
  80908. /*** End of inlined file: crc32.c ***/
  80909. /*** Start of inlined file: deflate.c ***/
  80910. /*
  80911. * ALGORITHM
  80912. *
  80913. * The "deflation" process depends on being able to identify portions
  80914. * of the input text which are identical to earlier input (within a
  80915. * sliding window trailing behind the input currently being processed).
  80916. *
  80917. * The most straightforward technique turns out to be the fastest for
  80918. * most input files: try all possible matches and select the longest.
  80919. * The key feature of this algorithm is that insertions into the string
  80920. * dictionary are very simple and thus fast, and deletions are avoided
  80921. * completely. Insertions are performed at each input character, whereas
  80922. * string matches are performed only when the previous match ends. So it
  80923. * is preferable to spend more time in matches to allow very fast string
  80924. * insertions and avoid deletions. The matching algorithm for small
  80925. * strings is inspired from that of Rabin & Karp. A brute force approach
  80926. * is used to find longer strings when a small match has been found.
  80927. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80928. * (by Leonid Broukhis).
  80929. * A previous version of this file used a more sophisticated algorithm
  80930. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80931. * time, but has a larger average cost, uses more memory and is patented.
  80932. * However the F&G algorithm may be faster for some highly redundant
  80933. * files if the parameter max_chain_length (described below) is too large.
  80934. *
  80935. * ACKNOWLEDGEMENTS
  80936. *
  80937. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80938. * I found it in 'freeze' written by Leonid Broukhis.
  80939. * Thanks to many people for bug reports and testing.
  80940. *
  80941. * REFERENCES
  80942. *
  80943. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80944. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80945. *
  80946. * A description of the Rabin and Karp algorithm is given in the book
  80947. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80948. *
  80949. * Fiala,E.R., and Greene,D.H.
  80950. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80951. *
  80952. */
  80953. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80954. /*** Start of inlined file: deflate.h ***/
  80955. /* WARNING: this file should *not* be used by applications. It is
  80956. part of the implementation of the compression library and is
  80957. subject to change. Applications should only use zlib.h.
  80958. */
  80959. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80960. #ifndef DEFLATE_H
  80961. #define DEFLATE_H
  80962. /* define NO_GZIP when compiling if you want to disable gzip header and
  80963. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80964. the crc code when it is not needed. For shared libraries, gzip encoding
  80965. should be left enabled. */
  80966. #ifndef NO_GZIP
  80967. # define GZIP
  80968. #endif
  80969. #define NO_DUMMY_DECL
  80970. /* ===========================================================================
  80971. * Internal compression state.
  80972. */
  80973. #define LENGTH_CODES 29
  80974. /* number of length codes, not counting the special END_BLOCK code */
  80975. #define LITERALS 256
  80976. /* number of literal bytes 0..255 */
  80977. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80978. /* number of Literal or Length codes, including the END_BLOCK code */
  80979. #define D_CODES 30
  80980. /* number of distance codes */
  80981. #define BL_CODES 19
  80982. /* number of codes used to transfer the bit lengths */
  80983. #define HEAP_SIZE (2*L_CODES+1)
  80984. /* maximum heap size */
  80985. #define MAX_BITS 15
  80986. /* All codes must not exceed MAX_BITS bits */
  80987. #define INIT_STATE 42
  80988. #define EXTRA_STATE 69
  80989. #define NAME_STATE 73
  80990. #define COMMENT_STATE 91
  80991. #define HCRC_STATE 103
  80992. #define BUSY_STATE 113
  80993. #define FINISH_STATE 666
  80994. /* Stream status */
  80995. /* Data structure describing a single value and its code string. */
  80996. typedef struct ct_data_s {
  80997. union {
  80998. ush freq; /* frequency count */
  80999. ush code; /* bit string */
  81000. } fc;
  81001. union {
  81002. ush dad; /* father node in Huffman tree */
  81003. ush len; /* length of bit string */
  81004. } dl;
  81005. } FAR ct_data;
  81006. #define Freq fc.freq
  81007. #define Code fc.code
  81008. #define Dad dl.dad
  81009. #define Len dl.len
  81010. typedef struct static_tree_desc_s static_tree_desc;
  81011. typedef struct tree_desc_s {
  81012. ct_data *dyn_tree; /* the dynamic tree */
  81013. int max_code; /* largest code with non zero frequency */
  81014. static_tree_desc *stat_desc; /* the corresponding static tree */
  81015. } FAR tree_desc;
  81016. typedef ush Pos;
  81017. typedef Pos FAR Posf;
  81018. typedef unsigned IPos;
  81019. /* A Pos is an index in the character window. We use short instead of int to
  81020. * save space in the various tables. IPos is used only for parameter passing.
  81021. */
  81022. typedef struct internal_state {
  81023. z_streamp strm; /* pointer back to this zlib stream */
  81024. int status; /* as the name implies */
  81025. Bytef *pending_buf; /* output still pending */
  81026. ulg pending_buf_size; /* size of pending_buf */
  81027. Bytef *pending_out; /* next pending byte to output to the stream */
  81028. uInt pending; /* nb of bytes in the pending buffer */
  81029. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81030. gz_headerp gzhead; /* gzip header information to write */
  81031. uInt gzindex; /* where in extra, name, or comment */
  81032. Byte method; /* STORED (for zip only) or DEFLATED */
  81033. int last_flush; /* value of flush param for previous deflate call */
  81034. /* used by deflate.c: */
  81035. uInt w_size; /* LZ77 window size (32K by default) */
  81036. uInt w_bits; /* log2(w_size) (8..16) */
  81037. uInt w_mask; /* w_size - 1 */
  81038. Bytef *window;
  81039. /* Sliding window. Input bytes are read into the second half of the window,
  81040. * and move to the first half later to keep a dictionary of at least wSize
  81041. * bytes. With this organization, matches are limited to a distance of
  81042. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81043. * performed with a length multiple of the block size. Also, it limits
  81044. * the window size to 64K, which is quite useful on MSDOS.
  81045. * To do: use the user input buffer as sliding window.
  81046. */
  81047. ulg window_size;
  81048. /* Actual size of window: 2*wSize, except when the user input buffer
  81049. * is directly used as sliding window.
  81050. */
  81051. Posf *prev;
  81052. /* Link to older string with same hash index. To limit the size of this
  81053. * array to 64K, this link is maintained only for the last 32K strings.
  81054. * An index in this array is thus a window index modulo 32K.
  81055. */
  81056. Posf *head; /* Heads of the hash chains or NIL. */
  81057. uInt ins_h; /* hash index of string to be inserted */
  81058. uInt hash_size; /* number of elements in hash table */
  81059. uInt hash_bits; /* log2(hash_size) */
  81060. uInt hash_mask; /* hash_size-1 */
  81061. uInt hash_shift;
  81062. /* Number of bits by which ins_h must be shifted at each input
  81063. * step. It must be such that after MIN_MATCH steps, the oldest
  81064. * byte no longer takes part in the hash key, that is:
  81065. * hash_shift * MIN_MATCH >= hash_bits
  81066. */
  81067. long block_start;
  81068. /* Window position at the beginning of the current output block. Gets
  81069. * negative when the window is moved backwards.
  81070. */
  81071. uInt match_length; /* length of best match */
  81072. IPos prev_match; /* previous match */
  81073. int match_available; /* set if previous match exists */
  81074. uInt strstart; /* start of string to insert */
  81075. uInt match_start; /* start of matching string */
  81076. uInt lookahead; /* number of valid bytes ahead in window */
  81077. uInt prev_length;
  81078. /* Length of the best match at previous step. Matches not greater than this
  81079. * are discarded. This is used in the lazy match evaluation.
  81080. */
  81081. uInt max_chain_length;
  81082. /* To speed up deflation, hash chains are never searched beyond this
  81083. * length. A higher limit improves compression ratio but degrades the
  81084. * speed.
  81085. */
  81086. uInt max_lazy_match;
  81087. /* Attempt to find a better match only when the current match is strictly
  81088. * smaller than this value. This mechanism is used only for compression
  81089. * levels >= 4.
  81090. */
  81091. # define max_insert_length max_lazy_match
  81092. /* Insert new strings in the hash table only if the match length is not
  81093. * greater than this length. This saves time but degrades compression.
  81094. * max_insert_length is used only for compression levels <= 3.
  81095. */
  81096. int level; /* compression level (1..9) */
  81097. int strategy; /* favor or force Huffman coding*/
  81098. uInt good_match;
  81099. /* Use a faster search when the previous match is longer than this */
  81100. int nice_match; /* Stop searching when current match exceeds this */
  81101. /* used by trees.c: */
  81102. /* Didn't use ct_data typedef below to supress compiler warning */
  81103. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81104. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81105. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81106. struct tree_desc_s l_desc; /* desc. for literal tree */
  81107. struct tree_desc_s d_desc; /* desc. for distance tree */
  81108. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81109. ush bl_count[MAX_BITS+1];
  81110. /* number of codes at each bit length for an optimal tree */
  81111. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81112. int heap_len; /* number of elements in the heap */
  81113. int heap_max; /* element of largest frequency */
  81114. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81115. * The same heap array is used to build all trees.
  81116. */
  81117. uch depth[2*L_CODES+1];
  81118. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81119. */
  81120. uchf *l_buf; /* buffer for literals or lengths */
  81121. uInt lit_bufsize;
  81122. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81123. * limiting lit_bufsize to 64K:
  81124. * - frequencies can be kept in 16 bit counters
  81125. * - if compression is not successful for the first block, all input
  81126. * data is still in the window so we can still emit a stored block even
  81127. * when input comes from standard input. (This can also be done for
  81128. * all blocks if lit_bufsize is not greater than 32K.)
  81129. * - if compression is not successful for a file smaller than 64K, we can
  81130. * even emit a stored file instead of a stored block (saving 5 bytes).
  81131. * This is applicable only for zip (not gzip or zlib).
  81132. * - creating new Huffman trees less frequently may not provide fast
  81133. * adaptation to changes in the input data statistics. (Take for
  81134. * example a binary file with poorly compressible code followed by
  81135. * a highly compressible string table.) Smaller buffer sizes give
  81136. * fast adaptation but have of course the overhead of transmitting
  81137. * trees more frequently.
  81138. * - I can't count above 4
  81139. */
  81140. uInt last_lit; /* running index in l_buf */
  81141. ushf *d_buf;
  81142. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81143. * the same number of elements. To use different lengths, an extra flag
  81144. * array would be necessary.
  81145. */
  81146. ulg opt_len; /* bit length of current block with optimal trees */
  81147. ulg static_len; /* bit length of current block with static trees */
  81148. uInt matches; /* number of string matches in current block */
  81149. int last_eob_len; /* bit length of EOB code for last block */
  81150. #ifdef DEBUG
  81151. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81152. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81153. #endif
  81154. ush bi_buf;
  81155. /* Output buffer. bits are inserted starting at the bottom (least
  81156. * significant bits).
  81157. */
  81158. int bi_valid;
  81159. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81160. * are always zero.
  81161. */
  81162. } FAR deflate_state;
  81163. /* Output a byte on the stream.
  81164. * IN assertion: there is enough room in pending_buf.
  81165. */
  81166. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81167. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81168. /* Minimum amount of lookahead, except at the end of the input file.
  81169. * See deflate.c for comments about the MIN_MATCH+1.
  81170. */
  81171. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81172. /* In order to simplify the code, particularly on 16 bit machines, match
  81173. * distances are limited to MAX_DIST instead of WSIZE.
  81174. */
  81175. /* in trees.c */
  81176. void _tr_init OF((deflate_state *s));
  81177. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81178. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81179. int eof));
  81180. void _tr_align OF((deflate_state *s));
  81181. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81182. int eof));
  81183. #define d_code(dist) \
  81184. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81185. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81186. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81187. * used.
  81188. */
  81189. #ifndef DEBUG
  81190. /* Inline versions of _tr_tally for speed: */
  81191. #if defined(GEN_TREES_H) || !defined(STDC)
  81192. extern uch _length_code[];
  81193. extern uch _dist_code[];
  81194. #else
  81195. extern const uch _length_code[];
  81196. extern const uch _dist_code[];
  81197. #endif
  81198. # define _tr_tally_lit(s, c, flush) \
  81199. { uch cc = (c); \
  81200. s->d_buf[s->last_lit] = 0; \
  81201. s->l_buf[s->last_lit++] = cc; \
  81202. s->dyn_ltree[cc].Freq++; \
  81203. flush = (s->last_lit == s->lit_bufsize-1); \
  81204. }
  81205. # define _tr_tally_dist(s, distance, length, flush) \
  81206. { uch len = (length); \
  81207. ush dist = (distance); \
  81208. s->d_buf[s->last_lit] = dist; \
  81209. s->l_buf[s->last_lit++] = len; \
  81210. dist--; \
  81211. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81212. s->dyn_dtree[d_code(dist)].Freq++; \
  81213. flush = (s->last_lit == s->lit_bufsize-1); \
  81214. }
  81215. #else
  81216. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81217. # define _tr_tally_dist(s, distance, length, flush) \
  81218. flush = _tr_tally(s, distance, length)
  81219. #endif
  81220. #endif /* DEFLATE_H */
  81221. /*** End of inlined file: deflate.h ***/
  81222. const char deflate_copyright[] =
  81223. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81224. /*
  81225. If you use the zlib library in a product, an acknowledgment is welcome
  81226. in the documentation of your product. If for some reason you cannot
  81227. include such an acknowledgment, I would appreciate that you keep this
  81228. copyright string in the executable of your product.
  81229. */
  81230. /* ===========================================================================
  81231. * Function prototypes.
  81232. */
  81233. typedef enum {
  81234. need_more, /* block not completed, need more input or more output */
  81235. block_done, /* block flush performed */
  81236. finish_started, /* finish started, need only more output at next deflate */
  81237. finish_done /* finish done, accept no more input or output */
  81238. } block_state;
  81239. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81240. /* Compression function. Returns the block state after the call. */
  81241. local void fill_window OF((deflate_state *s));
  81242. local block_state deflate_stored OF((deflate_state *s, int flush));
  81243. local block_state deflate_fast OF((deflate_state *s, int flush));
  81244. #ifndef FASTEST
  81245. local block_state deflate_slow OF((deflate_state *s, int flush));
  81246. #endif
  81247. local void lm_init OF((deflate_state *s));
  81248. local void putShortMSB OF((deflate_state *s, uInt b));
  81249. local void flush_pending OF((z_streamp strm));
  81250. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81251. #ifndef FASTEST
  81252. #ifdef ASMV
  81253. void match_init OF((void)); /* asm code initialization */
  81254. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81255. #else
  81256. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81257. #endif
  81258. #endif
  81259. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81260. #ifdef DEBUG
  81261. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81262. int length));
  81263. #endif
  81264. /* ===========================================================================
  81265. * Local data
  81266. */
  81267. #define NIL 0
  81268. /* Tail of hash chains */
  81269. #ifndef TOO_FAR
  81270. # define TOO_FAR 4096
  81271. #endif
  81272. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81273. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81274. /* Minimum amount of lookahead, except at the end of the input file.
  81275. * See deflate.c for comments about the MIN_MATCH+1.
  81276. */
  81277. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81278. * the desired pack level (0..9). The values given below have been tuned to
  81279. * exclude worst case performance for pathological files. Better values may be
  81280. * found for specific files.
  81281. */
  81282. typedef struct config_s {
  81283. ush good_length; /* reduce lazy search above this match length */
  81284. ush max_lazy; /* do not perform lazy search above this match length */
  81285. ush nice_length; /* quit search above this match length */
  81286. ush max_chain;
  81287. compress_func func;
  81288. } config;
  81289. #ifdef FASTEST
  81290. local const config configuration_table[2] = {
  81291. /* good lazy nice chain */
  81292. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81293. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81294. #else
  81295. local const config configuration_table[10] = {
  81296. /* good lazy nice chain */
  81297. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81298. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81299. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81300. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81301. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81302. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81303. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81304. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81305. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81306. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81307. #endif
  81308. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81309. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81310. * meaning.
  81311. */
  81312. #define EQUAL 0
  81313. /* result of memcmp for equal strings */
  81314. #ifndef NO_DUMMY_DECL
  81315. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81316. #endif
  81317. /* ===========================================================================
  81318. * Update a hash value with the given input byte
  81319. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81320. * input characters, so that a running hash key can be computed from the
  81321. * previous key instead of complete recalculation each time.
  81322. */
  81323. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81324. /* ===========================================================================
  81325. * Insert string str in the dictionary and set match_head to the previous head
  81326. * of the hash chain (the most recent string with same hash key). Return
  81327. * the previous length of the hash chain.
  81328. * If this file is compiled with -DFASTEST, the compression level is forced
  81329. * to 1, and no hash chains are maintained.
  81330. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81331. * input characters and the first MIN_MATCH bytes of str are valid
  81332. * (except for the last MIN_MATCH-1 bytes of the input file).
  81333. */
  81334. #ifdef FASTEST
  81335. #define INSERT_STRING(s, str, match_head) \
  81336. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81337. match_head = s->head[s->ins_h], \
  81338. s->head[s->ins_h] = (Pos)(str))
  81339. #else
  81340. #define INSERT_STRING(s, str, match_head) \
  81341. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81342. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81343. s->head[s->ins_h] = (Pos)(str))
  81344. #endif
  81345. /* ===========================================================================
  81346. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81347. * prev[] will be initialized on the fly.
  81348. */
  81349. #define CLEAR_HASH(s) \
  81350. s->head[s->hash_size-1] = NIL; \
  81351. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81352. /* ========================================================================= */
  81353. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81354. {
  81355. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81356. Z_DEFAULT_STRATEGY, version, stream_size);
  81357. /* To do: ignore strm->next_in if we use it as window */
  81358. }
  81359. /* ========================================================================= */
  81360. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81361. {
  81362. deflate_state *s;
  81363. int wrap = 1;
  81364. static const char my_version[] = ZLIB_VERSION;
  81365. ushf *overlay;
  81366. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81367. * output size for (length,distance) codes is <= 24 bits.
  81368. */
  81369. if (version == Z_NULL || version[0] != my_version[0] ||
  81370. stream_size != sizeof(z_stream)) {
  81371. return Z_VERSION_ERROR;
  81372. }
  81373. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81374. strm->msg = Z_NULL;
  81375. if (strm->zalloc == (alloc_func)0) {
  81376. strm->zalloc = zcalloc;
  81377. strm->opaque = (voidpf)0;
  81378. }
  81379. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81380. #ifdef FASTEST
  81381. if (level != 0) level = 1;
  81382. #else
  81383. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81384. #endif
  81385. if (windowBits < 0) { /* suppress zlib wrapper */
  81386. wrap = 0;
  81387. windowBits = -windowBits;
  81388. }
  81389. #ifdef GZIP
  81390. else if (windowBits > 15) {
  81391. wrap = 2; /* write gzip wrapper instead */
  81392. windowBits -= 16;
  81393. }
  81394. #endif
  81395. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81396. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81397. strategy < 0 || strategy > Z_FIXED) {
  81398. return Z_STREAM_ERROR;
  81399. }
  81400. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81401. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81402. if (s == Z_NULL) return Z_MEM_ERROR;
  81403. strm->state = (struct internal_state FAR *)s;
  81404. s->strm = strm;
  81405. s->wrap = wrap;
  81406. s->gzhead = Z_NULL;
  81407. s->w_bits = windowBits;
  81408. s->w_size = 1 << s->w_bits;
  81409. s->w_mask = s->w_size - 1;
  81410. s->hash_bits = memLevel + 7;
  81411. s->hash_size = 1 << s->hash_bits;
  81412. s->hash_mask = s->hash_size - 1;
  81413. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81414. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81415. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81416. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81417. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81418. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81419. s->pending_buf = (uchf *) overlay;
  81420. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81421. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81422. s->pending_buf == Z_NULL) {
  81423. s->status = FINISH_STATE;
  81424. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81425. deflateEnd (strm);
  81426. return Z_MEM_ERROR;
  81427. }
  81428. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81429. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81430. s->level = level;
  81431. s->strategy = strategy;
  81432. s->method = (Byte)method;
  81433. return deflateReset(strm);
  81434. }
  81435. /* ========================================================================= */
  81436. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81437. {
  81438. deflate_state *s;
  81439. uInt length = dictLength;
  81440. uInt n;
  81441. IPos hash_head = 0;
  81442. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81443. strm->state->wrap == 2 ||
  81444. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81445. return Z_STREAM_ERROR;
  81446. s = strm->state;
  81447. if (s->wrap)
  81448. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81449. if (length < MIN_MATCH) return Z_OK;
  81450. if (length > MAX_DIST(s)) {
  81451. length = MAX_DIST(s);
  81452. dictionary += dictLength - length; /* use the tail of the dictionary */
  81453. }
  81454. zmemcpy(s->window, dictionary, length);
  81455. s->strstart = length;
  81456. s->block_start = (long)length;
  81457. /* Insert all strings in the hash table (except for the last two bytes).
  81458. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81459. * call of fill_window.
  81460. */
  81461. s->ins_h = s->window[0];
  81462. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81463. for (n = 0; n <= length - MIN_MATCH; n++) {
  81464. INSERT_STRING(s, n, hash_head);
  81465. }
  81466. if (hash_head) hash_head = 0; /* to make compiler happy */
  81467. return Z_OK;
  81468. }
  81469. /* ========================================================================= */
  81470. int ZEXPORT deflateReset (z_streamp strm)
  81471. {
  81472. deflate_state *s;
  81473. if (strm == Z_NULL || strm->state == Z_NULL ||
  81474. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81475. return Z_STREAM_ERROR;
  81476. }
  81477. strm->total_in = strm->total_out = 0;
  81478. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81479. strm->data_type = Z_UNKNOWN;
  81480. s = (deflate_state *)strm->state;
  81481. s->pending = 0;
  81482. s->pending_out = s->pending_buf;
  81483. if (s->wrap < 0) {
  81484. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81485. }
  81486. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81487. strm->adler =
  81488. #ifdef GZIP
  81489. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81490. #endif
  81491. adler32(0L, Z_NULL, 0);
  81492. s->last_flush = Z_NO_FLUSH;
  81493. _tr_init(s);
  81494. lm_init(s);
  81495. return Z_OK;
  81496. }
  81497. /* ========================================================================= */
  81498. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81499. {
  81500. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81501. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81502. strm->state->gzhead = head;
  81503. return Z_OK;
  81504. }
  81505. /* ========================================================================= */
  81506. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81507. {
  81508. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81509. strm->state->bi_valid = bits;
  81510. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81511. return Z_OK;
  81512. }
  81513. /* ========================================================================= */
  81514. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81515. {
  81516. deflate_state *s;
  81517. compress_func func;
  81518. int err = Z_OK;
  81519. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81520. s = strm->state;
  81521. #ifdef FASTEST
  81522. if (level != 0) level = 1;
  81523. #else
  81524. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81525. #endif
  81526. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81527. return Z_STREAM_ERROR;
  81528. }
  81529. func = configuration_table[s->level].func;
  81530. if (func != configuration_table[level].func && strm->total_in != 0) {
  81531. /* Flush the last buffer: */
  81532. err = deflate(strm, Z_PARTIAL_FLUSH);
  81533. }
  81534. if (s->level != level) {
  81535. s->level = level;
  81536. s->max_lazy_match = configuration_table[level].max_lazy;
  81537. s->good_match = configuration_table[level].good_length;
  81538. s->nice_match = configuration_table[level].nice_length;
  81539. s->max_chain_length = configuration_table[level].max_chain;
  81540. }
  81541. s->strategy = strategy;
  81542. return err;
  81543. }
  81544. /* ========================================================================= */
  81545. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81546. {
  81547. deflate_state *s;
  81548. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81549. s = strm->state;
  81550. s->good_match = good_length;
  81551. s->max_lazy_match = max_lazy;
  81552. s->nice_match = nice_length;
  81553. s->max_chain_length = max_chain;
  81554. return Z_OK;
  81555. }
  81556. /* =========================================================================
  81557. * For the default windowBits of 15 and memLevel of 8, this function returns
  81558. * a close to exact, as well as small, upper bound on the compressed size.
  81559. * They are coded as constants here for a reason--if the #define's are
  81560. * changed, then this function needs to be changed as well. The return
  81561. * value for 15 and 8 only works for those exact settings.
  81562. *
  81563. * For any setting other than those defaults for windowBits and memLevel,
  81564. * the value returned is a conservative worst case for the maximum expansion
  81565. * resulting from using fixed blocks instead of stored blocks, which deflate
  81566. * can emit on compressed data for some combinations of the parameters.
  81567. *
  81568. * This function could be more sophisticated to provide closer upper bounds
  81569. * for every combination of windowBits and memLevel, as well as wrap.
  81570. * But even the conservative upper bound of about 14% expansion does not
  81571. * seem onerous for output buffer allocation.
  81572. */
  81573. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81574. {
  81575. deflate_state *s;
  81576. uLong destLen;
  81577. /* conservative upper bound */
  81578. destLen = sourceLen +
  81579. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81580. /* if can't get parameters, return conservative bound */
  81581. if (strm == Z_NULL || strm->state == Z_NULL)
  81582. return destLen;
  81583. /* if not default parameters, return conservative bound */
  81584. s = strm->state;
  81585. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81586. return destLen;
  81587. /* default settings: return tight bound for that case */
  81588. return compressBound(sourceLen);
  81589. }
  81590. /* =========================================================================
  81591. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81592. * IN assertion: the stream state is correct and there is enough room in
  81593. * pending_buf.
  81594. */
  81595. local void putShortMSB (deflate_state *s, uInt b)
  81596. {
  81597. put_byte(s, (Byte)(b >> 8));
  81598. put_byte(s, (Byte)(b & 0xff));
  81599. }
  81600. /* =========================================================================
  81601. * Flush as much pending output as possible. All deflate() output goes
  81602. * through this function so some applications may wish to modify it
  81603. * to avoid allocating a large strm->next_out buffer and copying into it.
  81604. * (See also read_buf()).
  81605. */
  81606. local void flush_pending (z_streamp strm)
  81607. {
  81608. unsigned len = strm->state->pending;
  81609. if (len > strm->avail_out) len = strm->avail_out;
  81610. if (len == 0) return;
  81611. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81612. strm->next_out += len;
  81613. strm->state->pending_out += len;
  81614. strm->total_out += len;
  81615. strm->avail_out -= len;
  81616. strm->state->pending -= len;
  81617. if (strm->state->pending == 0) {
  81618. strm->state->pending_out = strm->state->pending_buf;
  81619. }
  81620. }
  81621. /* ========================================================================= */
  81622. int ZEXPORT deflate (z_streamp strm, int flush)
  81623. {
  81624. int old_flush; /* value of flush param for previous deflate call */
  81625. deflate_state *s;
  81626. if (strm == Z_NULL || strm->state == Z_NULL ||
  81627. flush > Z_FINISH || flush < 0) {
  81628. return Z_STREAM_ERROR;
  81629. }
  81630. s = strm->state;
  81631. if (strm->next_out == Z_NULL ||
  81632. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81633. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81634. ERR_RETURN(strm, Z_STREAM_ERROR);
  81635. }
  81636. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81637. s->strm = strm; /* just in case */
  81638. old_flush = s->last_flush;
  81639. s->last_flush = flush;
  81640. /* Write the header */
  81641. if (s->status == INIT_STATE) {
  81642. #ifdef GZIP
  81643. if (s->wrap == 2) {
  81644. strm->adler = crc32(0L, Z_NULL, 0);
  81645. put_byte(s, 31);
  81646. put_byte(s, 139);
  81647. put_byte(s, 8);
  81648. if (s->gzhead == NULL) {
  81649. put_byte(s, 0);
  81650. put_byte(s, 0);
  81651. put_byte(s, 0);
  81652. put_byte(s, 0);
  81653. put_byte(s, 0);
  81654. put_byte(s, s->level == 9 ? 2 :
  81655. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81656. 4 : 0));
  81657. put_byte(s, OS_CODE);
  81658. s->status = BUSY_STATE;
  81659. }
  81660. else {
  81661. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81662. (s->gzhead->hcrc ? 2 : 0) +
  81663. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81664. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81665. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81666. );
  81667. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81668. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81669. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81670. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81671. put_byte(s, s->level == 9 ? 2 :
  81672. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81673. 4 : 0));
  81674. put_byte(s, s->gzhead->os & 0xff);
  81675. if (s->gzhead->extra != NULL) {
  81676. put_byte(s, s->gzhead->extra_len & 0xff);
  81677. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81678. }
  81679. if (s->gzhead->hcrc)
  81680. strm->adler = crc32(strm->adler, s->pending_buf,
  81681. s->pending);
  81682. s->gzindex = 0;
  81683. s->status = EXTRA_STATE;
  81684. }
  81685. }
  81686. else
  81687. #endif
  81688. {
  81689. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81690. uInt level_flags;
  81691. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81692. level_flags = 0;
  81693. else if (s->level < 6)
  81694. level_flags = 1;
  81695. else if (s->level == 6)
  81696. level_flags = 2;
  81697. else
  81698. level_flags = 3;
  81699. header |= (level_flags << 6);
  81700. if (s->strstart != 0) header |= PRESET_DICT;
  81701. header += 31 - (header % 31);
  81702. s->status = BUSY_STATE;
  81703. putShortMSB(s, header);
  81704. /* Save the adler32 of the preset dictionary: */
  81705. if (s->strstart != 0) {
  81706. putShortMSB(s, (uInt)(strm->adler >> 16));
  81707. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81708. }
  81709. strm->adler = adler32(0L, Z_NULL, 0);
  81710. }
  81711. }
  81712. #ifdef GZIP
  81713. if (s->status == EXTRA_STATE) {
  81714. if (s->gzhead->extra != NULL) {
  81715. uInt beg = s->pending; /* start of bytes to update crc */
  81716. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81717. if (s->pending == s->pending_buf_size) {
  81718. if (s->gzhead->hcrc && s->pending > beg)
  81719. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81720. s->pending - beg);
  81721. flush_pending(strm);
  81722. beg = s->pending;
  81723. if (s->pending == s->pending_buf_size)
  81724. break;
  81725. }
  81726. put_byte(s, s->gzhead->extra[s->gzindex]);
  81727. s->gzindex++;
  81728. }
  81729. if (s->gzhead->hcrc && s->pending > beg)
  81730. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81731. s->pending - beg);
  81732. if (s->gzindex == s->gzhead->extra_len) {
  81733. s->gzindex = 0;
  81734. s->status = NAME_STATE;
  81735. }
  81736. }
  81737. else
  81738. s->status = NAME_STATE;
  81739. }
  81740. if (s->status == NAME_STATE) {
  81741. if (s->gzhead->name != NULL) {
  81742. uInt beg = s->pending; /* start of bytes to update crc */
  81743. int val;
  81744. do {
  81745. if (s->pending == s->pending_buf_size) {
  81746. if (s->gzhead->hcrc && s->pending > beg)
  81747. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81748. s->pending - beg);
  81749. flush_pending(strm);
  81750. beg = s->pending;
  81751. if (s->pending == s->pending_buf_size) {
  81752. val = 1;
  81753. break;
  81754. }
  81755. }
  81756. val = s->gzhead->name[s->gzindex++];
  81757. put_byte(s, val);
  81758. } while (val != 0);
  81759. if (s->gzhead->hcrc && s->pending > beg)
  81760. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81761. s->pending - beg);
  81762. if (val == 0) {
  81763. s->gzindex = 0;
  81764. s->status = COMMENT_STATE;
  81765. }
  81766. }
  81767. else
  81768. s->status = COMMENT_STATE;
  81769. }
  81770. if (s->status == COMMENT_STATE) {
  81771. if (s->gzhead->comment != NULL) {
  81772. uInt beg = s->pending; /* start of bytes to update crc */
  81773. int val;
  81774. do {
  81775. if (s->pending == s->pending_buf_size) {
  81776. if (s->gzhead->hcrc && s->pending > beg)
  81777. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81778. s->pending - beg);
  81779. flush_pending(strm);
  81780. beg = s->pending;
  81781. if (s->pending == s->pending_buf_size) {
  81782. val = 1;
  81783. break;
  81784. }
  81785. }
  81786. val = s->gzhead->comment[s->gzindex++];
  81787. put_byte(s, val);
  81788. } while (val != 0);
  81789. if (s->gzhead->hcrc && s->pending > beg)
  81790. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81791. s->pending - beg);
  81792. if (val == 0)
  81793. s->status = HCRC_STATE;
  81794. }
  81795. else
  81796. s->status = HCRC_STATE;
  81797. }
  81798. if (s->status == HCRC_STATE) {
  81799. if (s->gzhead->hcrc) {
  81800. if (s->pending + 2 > s->pending_buf_size)
  81801. flush_pending(strm);
  81802. if (s->pending + 2 <= s->pending_buf_size) {
  81803. put_byte(s, (Byte)(strm->adler & 0xff));
  81804. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81805. strm->adler = crc32(0L, Z_NULL, 0);
  81806. s->status = BUSY_STATE;
  81807. }
  81808. }
  81809. else
  81810. s->status = BUSY_STATE;
  81811. }
  81812. #endif
  81813. /* Flush as much pending output as possible */
  81814. if (s->pending != 0) {
  81815. flush_pending(strm);
  81816. if (strm->avail_out == 0) {
  81817. /* Since avail_out is 0, deflate will be called again with
  81818. * more output space, but possibly with both pending and
  81819. * avail_in equal to zero. There won't be anything to do,
  81820. * but this is not an error situation so make sure we
  81821. * return OK instead of BUF_ERROR at next call of deflate:
  81822. */
  81823. s->last_flush = -1;
  81824. return Z_OK;
  81825. }
  81826. /* Make sure there is something to do and avoid duplicate consecutive
  81827. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81828. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81829. */
  81830. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81831. flush != Z_FINISH) {
  81832. ERR_RETURN(strm, Z_BUF_ERROR);
  81833. }
  81834. /* User must not provide more input after the first FINISH: */
  81835. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81836. ERR_RETURN(strm, Z_BUF_ERROR);
  81837. }
  81838. /* Start a new block or continue the current one.
  81839. */
  81840. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81841. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81842. block_state bstate;
  81843. bstate = (*(configuration_table[s->level].func))(s, flush);
  81844. if (bstate == finish_started || bstate == finish_done) {
  81845. s->status = FINISH_STATE;
  81846. }
  81847. if (bstate == need_more || bstate == finish_started) {
  81848. if (strm->avail_out == 0) {
  81849. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81850. }
  81851. return Z_OK;
  81852. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81853. * of deflate should use the same flush parameter to make sure
  81854. * that the flush is complete. So we don't have to output an
  81855. * empty block here, this will be done at next call. This also
  81856. * ensures that for a very small output buffer, we emit at most
  81857. * one empty block.
  81858. */
  81859. }
  81860. if (bstate == block_done) {
  81861. if (flush == Z_PARTIAL_FLUSH) {
  81862. _tr_align(s);
  81863. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81864. _tr_stored_block(s, (char*)0, 0L, 0);
  81865. /* For a full flush, this empty block will be recognized
  81866. * as a special marker by inflate_sync().
  81867. */
  81868. if (flush == Z_FULL_FLUSH) {
  81869. CLEAR_HASH(s); /* forget history */
  81870. }
  81871. }
  81872. flush_pending(strm);
  81873. if (strm->avail_out == 0) {
  81874. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81875. return Z_OK;
  81876. }
  81877. }
  81878. }
  81879. Assert(strm->avail_out > 0, "bug2");
  81880. if (flush != Z_FINISH) return Z_OK;
  81881. if (s->wrap <= 0) return Z_STREAM_END;
  81882. /* Write the trailer */
  81883. #ifdef GZIP
  81884. if (s->wrap == 2) {
  81885. put_byte(s, (Byte)(strm->adler & 0xff));
  81886. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81887. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81888. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81889. put_byte(s, (Byte)(strm->total_in & 0xff));
  81890. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81891. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81892. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81893. }
  81894. else
  81895. #endif
  81896. {
  81897. putShortMSB(s, (uInt)(strm->adler >> 16));
  81898. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81899. }
  81900. flush_pending(strm);
  81901. /* If avail_out is zero, the application will call deflate again
  81902. * to flush the rest.
  81903. */
  81904. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81905. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81906. }
  81907. /* ========================================================================= */
  81908. int ZEXPORT deflateEnd (z_streamp strm)
  81909. {
  81910. int status;
  81911. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81912. status = strm->state->status;
  81913. if (status != INIT_STATE &&
  81914. status != EXTRA_STATE &&
  81915. status != NAME_STATE &&
  81916. status != COMMENT_STATE &&
  81917. status != HCRC_STATE &&
  81918. status != BUSY_STATE &&
  81919. status != FINISH_STATE) {
  81920. return Z_STREAM_ERROR;
  81921. }
  81922. /* Deallocate in reverse order of allocations: */
  81923. TRY_FREE(strm, strm->state->pending_buf);
  81924. TRY_FREE(strm, strm->state->head);
  81925. TRY_FREE(strm, strm->state->prev);
  81926. TRY_FREE(strm, strm->state->window);
  81927. ZFREE(strm, strm->state);
  81928. strm->state = Z_NULL;
  81929. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81930. }
  81931. /* =========================================================================
  81932. * Copy the source state to the destination state.
  81933. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81934. * doesn't have enough memory anyway to duplicate compression states).
  81935. */
  81936. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81937. {
  81938. #ifdef MAXSEG_64K
  81939. return Z_STREAM_ERROR;
  81940. #else
  81941. deflate_state *ds;
  81942. deflate_state *ss;
  81943. ushf *overlay;
  81944. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81945. return Z_STREAM_ERROR;
  81946. }
  81947. ss = source->state;
  81948. zmemcpy(dest, source, sizeof(z_stream));
  81949. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81950. if (ds == Z_NULL) return Z_MEM_ERROR;
  81951. dest->state = (struct internal_state FAR *) ds;
  81952. zmemcpy(ds, ss, sizeof(deflate_state));
  81953. ds->strm = dest;
  81954. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81955. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81956. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81957. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81958. ds->pending_buf = (uchf *) overlay;
  81959. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81960. ds->pending_buf == Z_NULL) {
  81961. deflateEnd (dest);
  81962. return Z_MEM_ERROR;
  81963. }
  81964. /* following zmemcpy do not work for 16-bit MSDOS */
  81965. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81966. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81967. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81968. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81969. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81970. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81971. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81972. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81973. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81974. ds->bl_desc.dyn_tree = ds->bl_tree;
  81975. return Z_OK;
  81976. #endif /* MAXSEG_64K */
  81977. }
  81978. /* ===========================================================================
  81979. * Read a new buffer from the current input stream, update the adler32
  81980. * and total number of bytes read. All deflate() input goes through
  81981. * this function so some applications may wish to modify it to avoid
  81982. * allocating a large strm->next_in buffer and copying from it.
  81983. * (See also flush_pending()).
  81984. */
  81985. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81986. {
  81987. unsigned len = strm->avail_in;
  81988. if (len > size) len = size;
  81989. if (len == 0) return 0;
  81990. strm->avail_in -= len;
  81991. if (strm->state->wrap == 1) {
  81992. strm->adler = adler32(strm->adler, strm->next_in, len);
  81993. }
  81994. #ifdef GZIP
  81995. else if (strm->state->wrap == 2) {
  81996. strm->adler = crc32(strm->adler, strm->next_in, len);
  81997. }
  81998. #endif
  81999. zmemcpy(buf, strm->next_in, len);
  82000. strm->next_in += len;
  82001. strm->total_in += len;
  82002. return (int)len;
  82003. }
  82004. /* ===========================================================================
  82005. * Initialize the "longest match" routines for a new zlib stream
  82006. */
  82007. local void lm_init (deflate_state *s)
  82008. {
  82009. s->window_size = (ulg)2L*s->w_size;
  82010. CLEAR_HASH(s);
  82011. /* Set the default configuration parameters:
  82012. */
  82013. s->max_lazy_match = configuration_table[s->level].max_lazy;
  82014. s->good_match = configuration_table[s->level].good_length;
  82015. s->nice_match = configuration_table[s->level].nice_length;
  82016. s->max_chain_length = configuration_table[s->level].max_chain;
  82017. s->strstart = 0;
  82018. s->block_start = 0L;
  82019. s->lookahead = 0;
  82020. s->match_length = s->prev_length = MIN_MATCH-1;
  82021. s->match_available = 0;
  82022. s->ins_h = 0;
  82023. #ifndef FASTEST
  82024. #ifdef ASMV
  82025. match_init(); /* initialize the asm code */
  82026. #endif
  82027. #endif
  82028. }
  82029. #ifndef FASTEST
  82030. /* ===========================================================================
  82031. * Set match_start to the longest match starting at the given string and
  82032. * return its length. Matches shorter or equal to prev_length are discarded,
  82033. * in which case the result is equal to prev_length and match_start is
  82034. * garbage.
  82035. * IN assertions: cur_match is the head of the hash chain for the current
  82036. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82037. * OUT assertion: the match length is not greater than s->lookahead.
  82038. */
  82039. #ifndef ASMV
  82040. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82041. * match.S. The code will be functionally equivalent.
  82042. */
  82043. local uInt longest_match(deflate_state *s, IPos cur_match)
  82044. {
  82045. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82046. register Bytef *scan = s->window + s->strstart; /* current string */
  82047. register Bytef *match; /* matched string */
  82048. register int len; /* length of current match */
  82049. int best_len = s->prev_length; /* best match length so far */
  82050. int nice_match = s->nice_match; /* stop if match long enough */
  82051. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82052. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82053. /* Stop when cur_match becomes <= limit. To simplify the code,
  82054. * we prevent matches with the string of window index 0.
  82055. */
  82056. Posf *prev = s->prev;
  82057. uInt wmask = s->w_mask;
  82058. #ifdef UNALIGNED_OK
  82059. /* Compare two bytes at a time. Note: this is not always beneficial.
  82060. * Try with and without -DUNALIGNED_OK to check.
  82061. */
  82062. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82063. register ush scan_start = *(ushf*)scan;
  82064. register ush scan_end = *(ushf*)(scan+best_len-1);
  82065. #else
  82066. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82067. register Byte scan_end1 = scan[best_len-1];
  82068. register Byte scan_end = scan[best_len];
  82069. #endif
  82070. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82071. * It is easy to get rid of this optimization if necessary.
  82072. */
  82073. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82074. /* Do not waste too much time if we already have a good match: */
  82075. if (s->prev_length >= s->good_match) {
  82076. chain_length >>= 2;
  82077. }
  82078. /* Do not look for matches beyond the end of the input. This is necessary
  82079. * to make deflate deterministic.
  82080. */
  82081. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82082. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82083. do {
  82084. Assert(cur_match < s->strstart, "no future");
  82085. match = s->window + cur_match;
  82086. /* Skip to next match if the match length cannot increase
  82087. * or if the match length is less than 2. Note that the checks below
  82088. * for insufficient lookahead only occur occasionally for performance
  82089. * reasons. Therefore uninitialized memory will be accessed, and
  82090. * conditional jumps will be made that depend on those values.
  82091. * However the length of the match is limited to the lookahead, so
  82092. * the output of deflate is not affected by the uninitialized values.
  82093. */
  82094. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82095. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82096. * UNALIGNED_OK if your compiler uses a different size.
  82097. */
  82098. if (*(ushf*)(match+best_len-1) != scan_end ||
  82099. *(ushf*)match != scan_start) continue;
  82100. /* It is not necessary to compare scan[2] and match[2] since they are
  82101. * always equal when the other bytes match, given that the hash keys
  82102. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82103. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82104. * lookahead only every 4th comparison; the 128th check will be made
  82105. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82106. * necessary to put more guard bytes at the end of the window, or
  82107. * to check more often for insufficient lookahead.
  82108. */
  82109. Assert(scan[2] == match[2], "scan[2]?");
  82110. scan++, match++;
  82111. do {
  82112. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82113. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82114. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82115. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82116. scan < strend);
  82117. /* The funny "do {}" generates better code on most compilers */
  82118. /* Here, scan <= window+strstart+257 */
  82119. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82120. if (*scan == *match) scan++;
  82121. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82122. scan = strend - (MAX_MATCH-1);
  82123. #else /* UNALIGNED_OK */
  82124. if (match[best_len] != scan_end ||
  82125. match[best_len-1] != scan_end1 ||
  82126. *match != *scan ||
  82127. *++match != scan[1]) continue;
  82128. /* The check at best_len-1 can be removed because it will be made
  82129. * again later. (This heuristic is not always a win.)
  82130. * It is not necessary to compare scan[2] and match[2] since they
  82131. * are always equal when the other bytes match, given that
  82132. * the hash keys are equal and that HASH_BITS >= 8.
  82133. */
  82134. scan += 2, match++;
  82135. Assert(*scan == *match, "match[2]?");
  82136. /* We check for insufficient lookahead only every 8th comparison;
  82137. * the 256th check will be made at strstart+258.
  82138. */
  82139. do {
  82140. } while (*++scan == *++match && *++scan == *++match &&
  82141. *++scan == *++match && *++scan == *++match &&
  82142. *++scan == *++match && *++scan == *++match &&
  82143. *++scan == *++match && *++scan == *++match &&
  82144. scan < strend);
  82145. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82146. len = MAX_MATCH - (int)(strend - scan);
  82147. scan = strend - MAX_MATCH;
  82148. #endif /* UNALIGNED_OK */
  82149. if (len > best_len) {
  82150. s->match_start = cur_match;
  82151. best_len = len;
  82152. if (len >= nice_match) break;
  82153. #ifdef UNALIGNED_OK
  82154. scan_end = *(ushf*)(scan+best_len-1);
  82155. #else
  82156. scan_end1 = scan[best_len-1];
  82157. scan_end = scan[best_len];
  82158. #endif
  82159. }
  82160. } while ((cur_match = prev[cur_match & wmask]) > limit
  82161. && --chain_length != 0);
  82162. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82163. return s->lookahead;
  82164. }
  82165. #endif /* ASMV */
  82166. #endif /* FASTEST */
  82167. /* ---------------------------------------------------------------------------
  82168. * Optimized version for level == 1 or strategy == Z_RLE only
  82169. */
  82170. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82171. {
  82172. register Bytef *scan = s->window + s->strstart; /* current string */
  82173. register Bytef *match; /* matched string */
  82174. register int len; /* length of current match */
  82175. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82176. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82177. * It is easy to get rid of this optimization if necessary.
  82178. */
  82179. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82180. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82181. Assert(cur_match < s->strstart, "no future");
  82182. match = s->window + cur_match;
  82183. /* Return failure if the match length is less than 2:
  82184. */
  82185. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82186. /* The check at best_len-1 can be removed because it will be made
  82187. * again later. (This heuristic is not always a win.)
  82188. * It is not necessary to compare scan[2] and match[2] since they
  82189. * are always equal when the other bytes match, given that
  82190. * the hash keys are equal and that HASH_BITS >= 8.
  82191. */
  82192. scan += 2, match += 2;
  82193. Assert(*scan == *match, "match[2]?");
  82194. /* We check for insufficient lookahead only every 8th comparison;
  82195. * the 256th check will be made at strstart+258.
  82196. */
  82197. do {
  82198. } while (*++scan == *++match && *++scan == *++match &&
  82199. *++scan == *++match && *++scan == *++match &&
  82200. *++scan == *++match && *++scan == *++match &&
  82201. *++scan == *++match && *++scan == *++match &&
  82202. scan < strend);
  82203. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82204. len = MAX_MATCH - (int)(strend - scan);
  82205. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82206. s->match_start = cur_match;
  82207. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82208. }
  82209. #ifdef DEBUG
  82210. /* ===========================================================================
  82211. * Check that the match at match_start is indeed a match.
  82212. */
  82213. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82214. {
  82215. /* check that the match is indeed a match */
  82216. if (zmemcmp(s->window + match,
  82217. s->window + start, length) != EQUAL) {
  82218. fprintf(stderr, " start %u, match %u, length %d\n",
  82219. start, match, length);
  82220. do {
  82221. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82222. } while (--length != 0);
  82223. z_error("invalid match");
  82224. }
  82225. if (z_verbose > 1) {
  82226. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82227. do { putc(s->window[start++], stderr); } while (--length != 0);
  82228. }
  82229. }
  82230. #else
  82231. # define check_match(s, start, match, length)
  82232. #endif /* DEBUG */
  82233. /* ===========================================================================
  82234. * Fill the window when the lookahead becomes insufficient.
  82235. * Updates strstart and lookahead.
  82236. *
  82237. * IN assertion: lookahead < MIN_LOOKAHEAD
  82238. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82239. * At least one byte has been read, or avail_in == 0; reads are
  82240. * performed for at least two bytes (required for the zip translate_eol
  82241. * option -- not supported here).
  82242. */
  82243. local void fill_window (deflate_state *s)
  82244. {
  82245. register unsigned n, m;
  82246. register Posf *p;
  82247. unsigned more; /* Amount of free space at the end of the window. */
  82248. uInt wsize = s->w_size;
  82249. do {
  82250. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82251. /* Deal with !@#$% 64K limit: */
  82252. if (sizeof(int) <= 2) {
  82253. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82254. more = wsize;
  82255. } else if (more == (unsigned)(-1)) {
  82256. /* Very unlikely, but possible on 16 bit machine if
  82257. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82258. */
  82259. more--;
  82260. }
  82261. }
  82262. /* If the window is almost full and there is insufficient lookahead,
  82263. * move the upper half to the lower one to make room in the upper half.
  82264. */
  82265. if (s->strstart >= wsize+MAX_DIST(s)) {
  82266. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82267. s->match_start -= wsize;
  82268. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82269. s->block_start -= (long) wsize;
  82270. /* Slide the hash table (could be avoided with 32 bit values
  82271. at the expense of memory usage). We slide even when level == 0
  82272. to keep the hash table consistent if we switch back to level > 0
  82273. later. (Using level 0 permanently is not an optimal usage of
  82274. zlib, so we don't care about this pathological case.)
  82275. */
  82276. /* %%% avoid this when Z_RLE */
  82277. n = s->hash_size;
  82278. p = &s->head[n];
  82279. do {
  82280. m = *--p;
  82281. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82282. } while (--n);
  82283. n = wsize;
  82284. #ifndef FASTEST
  82285. p = &s->prev[n];
  82286. do {
  82287. m = *--p;
  82288. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82289. /* If n is not on any hash chain, prev[n] is garbage but
  82290. * its value will never be used.
  82291. */
  82292. } while (--n);
  82293. #endif
  82294. more += wsize;
  82295. }
  82296. if (s->strm->avail_in == 0) return;
  82297. /* If there was no sliding:
  82298. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82299. * more == window_size - lookahead - strstart
  82300. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82301. * => more >= window_size - 2*WSIZE + 2
  82302. * In the BIG_MEM or MMAP case (not yet supported),
  82303. * window_size == input_size + MIN_LOOKAHEAD &&
  82304. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82305. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82306. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82307. */
  82308. Assert(more >= 2, "more < 2");
  82309. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82310. s->lookahead += n;
  82311. /* Initialize the hash value now that we have some input: */
  82312. if (s->lookahead >= MIN_MATCH) {
  82313. s->ins_h = s->window[s->strstart];
  82314. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82315. #if MIN_MATCH != 3
  82316. Call UPDATE_HASH() MIN_MATCH-3 more times
  82317. #endif
  82318. }
  82319. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82320. * but this is not important since only literal bytes will be emitted.
  82321. */
  82322. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82323. }
  82324. /* ===========================================================================
  82325. * Flush the current block, with given end-of-file flag.
  82326. * IN assertion: strstart is set to the end of the current match.
  82327. */
  82328. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82329. _tr_flush_block(s, (s->block_start >= 0L ? \
  82330. (charf *)&s->window[(unsigned)s->block_start] : \
  82331. (charf *)Z_NULL), \
  82332. (ulg)((long)s->strstart - s->block_start), \
  82333. (eof)); \
  82334. s->block_start = s->strstart; \
  82335. flush_pending(s->strm); \
  82336. Tracev((stderr,"[FLUSH]")); \
  82337. }
  82338. /* Same but force premature exit if necessary. */
  82339. #define FLUSH_BLOCK(s, eof) { \
  82340. FLUSH_BLOCK_ONLY(s, eof); \
  82341. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82342. }
  82343. /* ===========================================================================
  82344. * Copy without compression as much as possible from the input stream, return
  82345. * the current block state.
  82346. * This function does not insert new strings in the dictionary since
  82347. * uncompressible data is probably not useful. This function is used
  82348. * only for the level=0 compression option.
  82349. * NOTE: this function should be optimized to avoid extra copying from
  82350. * window to pending_buf.
  82351. */
  82352. local block_state deflate_stored(deflate_state *s, int flush)
  82353. {
  82354. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82355. * to pending_buf_size, and each stored block has a 5 byte header:
  82356. */
  82357. ulg max_block_size = 0xffff;
  82358. ulg max_start;
  82359. if (max_block_size > s->pending_buf_size - 5) {
  82360. max_block_size = s->pending_buf_size - 5;
  82361. }
  82362. /* Copy as much as possible from input to output: */
  82363. for (;;) {
  82364. /* Fill the window as much as possible: */
  82365. if (s->lookahead <= 1) {
  82366. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82367. s->block_start >= (long)s->w_size, "slide too late");
  82368. fill_window(s);
  82369. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82370. if (s->lookahead == 0) break; /* flush the current block */
  82371. }
  82372. Assert(s->block_start >= 0L, "block gone");
  82373. s->strstart += s->lookahead;
  82374. s->lookahead = 0;
  82375. /* Emit a stored block if pending_buf will be full: */
  82376. max_start = s->block_start + max_block_size;
  82377. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82378. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82379. s->lookahead = (uInt)(s->strstart - max_start);
  82380. s->strstart = (uInt)max_start;
  82381. FLUSH_BLOCK(s, 0);
  82382. }
  82383. /* Flush if we may have to slide, otherwise block_start may become
  82384. * negative and the data will be gone:
  82385. */
  82386. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82387. FLUSH_BLOCK(s, 0);
  82388. }
  82389. }
  82390. FLUSH_BLOCK(s, flush == Z_FINISH);
  82391. return flush == Z_FINISH ? finish_done : block_done;
  82392. }
  82393. /* ===========================================================================
  82394. * Compress as much as possible from the input stream, return the current
  82395. * block state.
  82396. * This function does not perform lazy evaluation of matches and inserts
  82397. * new strings in the dictionary only for unmatched strings or for short
  82398. * matches. It is used only for the fast compression options.
  82399. */
  82400. local block_state deflate_fast(deflate_state *s, int flush)
  82401. {
  82402. IPos hash_head = NIL; /* head of the hash chain */
  82403. int bflush; /* set if current block must be flushed */
  82404. for (;;) {
  82405. /* Make sure that we always have enough lookahead, except
  82406. * at the end of the input file. We need MAX_MATCH bytes
  82407. * for the next match, plus MIN_MATCH bytes to insert the
  82408. * string following the next match.
  82409. */
  82410. if (s->lookahead < MIN_LOOKAHEAD) {
  82411. fill_window(s);
  82412. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82413. return need_more;
  82414. }
  82415. if (s->lookahead == 0) break; /* flush the current block */
  82416. }
  82417. /* Insert the string window[strstart .. strstart+2] in the
  82418. * dictionary, and set hash_head to the head of the hash chain:
  82419. */
  82420. if (s->lookahead >= MIN_MATCH) {
  82421. INSERT_STRING(s, s->strstart, hash_head);
  82422. }
  82423. /* Find the longest match, discarding those <= prev_length.
  82424. * At this point we have always match_length < MIN_MATCH
  82425. */
  82426. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82427. /* To simplify the code, we prevent matches with the string
  82428. * of window index 0 (in particular we have to avoid a match
  82429. * of the string with itself at the start of the input file).
  82430. */
  82431. #ifdef FASTEST
  82432. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82433. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82434. s->match_length = longest_match_fast (s, hash_head);
  82435. }
  82436. #else
  82437. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82438. s->match_length = longest_match (s, hash_head);
  82439. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82440. s->match_length = longest_match_fast (s, hash_head);
  82441. }
  82442. #endif
  82443. /* longest_match() or longest_match_fast() sets match_start */
  82444. }
  82445. if (s->match_length >= MIN_MATCH) {
  82446. check_match(s, s->strstart, s->match_start, s->match_length);
  82447. _tr_tally_dist(s, s->strstart - s->match_start,
  82448. s->match_length - MIN_MATCH, bflush);
  82449. s->lookahead -= s->match_length;
  82450. /* Insert new strings in the hash table only if the match length
  82451. * is not too large. This saves time but degrades compression.
  82452. */
  82453. #ifndef FASTEST
  82454. if (s->match_length <= s->max_insert_length &&
  82455. s->lookahead >= MIN_MATCH) {
  82456. s->match_length--; /* string at strstart already in table */
  82457. do {
  82458. s->strstart++;
  82459. INSERT_STRING(s, s->strstart, hash_head);
  82460. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82461. * always MIN_MATCH bytes ahead.
  82462. */
  82463. } while (--s->match_length != 0);
  82464. s->strstart++;
  82465. } else
  82466. #endif
  82467. {
  82468. s->strstart += s->match_length;
  82469. s->match_length = 0;
  82470. s->ins_h = s->window[s->strstart];
  82471. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82472. #if MIN_MATCH != 3
  82473. Call UPDATE_HASH() MIN_MATCH-3 more times
  82474. #endif
  82475. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82476. * matter since it will be recomputed at next deflate call.
  82477. */
  82478. }
  82479. } else {
  82480. /* No match, output a literal byte */
  82481. Tracevv((stderr,"%c", s->window[s->strstart]));
  82482. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82483. s->lookahead--;
  82484. s->strstart++;
  82485. }
  82486. if (bflush) FLUSH_BLOCK(s, 0);
  82487. }
  82488. FLUSH_BLOCK(s, flush == Z_FINISH);
  82489. return flush == Z_FINISH ? finish_done : block_done;
  82490. }
  82491. #ifndef FASTEST
  82492. /* ===========================================================================
  82493. * Same as above, but achieves better compression. We use a lazy
  82494. * evaluation for matches: a match is finally adopted only if there is
  82495. * no better match at the next window position.
  82496. */
  82497. local block_state deflate_slow(deflate_state *s, int flush)
  82498. {
  82499. IPos hash_head = NIL; /* head of hash chain */
  82500. int bflush; /* set if current block must be flushed */
  82501. /* Process the input block. */
  82502. for (;;) {
  82503. /* Make sure that we always have enough lookahead, except
  82504. * at the end of the input file. We need MAX_MATCH bytes
  82505. * for the next match, plus MIN_MATCH bytes to insert the
  82506. * string following the next match.
  82507. */
  82508. if (s->lookahead < MIN_LOOKAHEAD) {
  82509. fill_window(s);
  82510. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82511. return need_more;
  82512. }
  82513. if (s->lookahead == 0) break; /* flush the current block */
  82514. }
  82515. /* Insert the string window[strstart .. strstart+2] in the
  82516. * dictionary, and set hash_head to the head of the hash chain:
  82517. */
  82518. if (s->lookahead >= MIN_MATCH) {
  82519. INSERT_STRING(s, s->strstart, hash_head);
  82520. }
  82521. /* Find the longest match, discarding those <= prev_length.
  82522. */
  82523. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82524. s->match_length = MIN_MATCH-1;
  82525. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82526. s->strstart - hash_head <= MAX_DIST(s)) {
  82527. /* To simplify the code, we prevent matches with the string
  82528. * of window index 0 (in particular we have to avoid a match
  82529. * of the string with itself at the start of the input file).
  82530. */
  82531. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82532. s->match_length = longest_match (s, hash_head);
  82533. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82534. s->match_length = longest_match_fast (s, hash_head);
  82535. }
  82536. /* longest_match() or longest_match_fast() sets match_start */
  82537. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82538. #if TOO_FAR <= 32767
  82539. || (s->match_length == MIN_MATCH &&
  82540. s->strstart - s->match_start > TOO_FAR)
  82541. #endif
  82542. )) {
  82543. /* If prev_match is also MIN_MATCH, match_start is garbage
  82544. * but we will ignore the current match anyway.
  82545. */
  82546. s->match_length = MIN_MATCH-1;
  82547. }
  82548. }
  82549. /* If there was a match at the previous step and the current
  82550. * match is not better, output the previous match:
  82551. */
  82552. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82553. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82554. /* Do not insert strings in hash table beyond this. */
  82555. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82556. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82557. s->prev_length - MIN_MATCH, bflush);
  82558. /* Insert in hash table all strings up to the end of the match.
  82559. * strstart-1 and strstart are already inserted. If there is not
  82560. * enough lookahead, the last two strings are not inserted in
  82561. * the hash table.
  82562. */
  82563. s->lookahead -= s->prev_length-1;
  82564. s->prev_length -= 2;
  82565. do {
  82566. if (++s->strstart <= max_insert) {
  82567. INSERT_STRING(s, s->strstart, hash_head);
  82568. }
  82569. } while (--s->prev_length != 0);
  82570. s->match_available = 0;
  82571. s->match_length = MIN_MATCH-1;
  82572. s->strstart++;
  82573. if (bflush) FLUSH_BLOCK(s, 0);
  82574. } else if (s->match_available) {
  82575. /* If there was no match at the previous position, output a
  82576. * single literal. If there was a match but the current match
  82577. * is longer, truncate the previous match to a single literal.
  82578. */
  82579. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82580. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82581. if (bflush) {
  82582. FLUSH_BLOCK_ONLY(s, 0);
  82583. }
  82584. s->strstart++;
  82585. s->lookahead--;
  82586. if (s->strm->avail_out == 0) return need_more;
  82587. } else {
  82588. /* There is no previous match to compare with, wait for
  82589. * the next step to decide.
  82590. */
  82591. s->match_available = 1;
  82592. s->strstart++;
  82593. s->lookahead--;
  82594. }
  82595. }
  82596. Assert (flush != Z_NO_FLUSH, "no flush?");
  82597. if (s->match_available) {
  82598. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82599. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82600. s->match_available = 0;
  82601. }
  82602. FLUSH_BLOCK(s, flush == Z_FINISH);
  82603. return flush == Z_FINISH ? finish_done : block_done;
  82604. }
  82605. #endif /* FASTEST */
  82606. #if 0
  82607. /* ===========================================================================
  82608. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82609. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82610. * deflate switches away from Z_RLE.)
  82611. */
  82612. local block_state deflate_rle(s, flush)
  82613. deflate_state *s;
  82614. int flush;
  82615. {
  82616. int bflush; /* set if current block must be flushed */
  82617. uInt run; /* length of run */
  82618. uInt max; /* maximum length of run */
  82619. uInt prev; /* byte at distance one to match */
  82620. Bytef *scan; /* scan for end of run */
  82621. for (;;) {
  82622. /* Make sure that we always have enough lookahead, except
  82623. * at the end of the input file. We need MAX_MATCH bytes
  82624. * for the longest encodable run.
  82625. */
  82626. if (s->lookahead < MAX_MATCH) {
  82627. fill_window(s);
  82628. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82629. return need_more;
  82630. }
  82631. if (s->lookahead == 0) break; /* flush the current block */
  82632. }
  82633. /* See how many times the previous byte repeats */
  82634. run = 0;
  82635. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82636. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82637. scan = s->window + s->strstart - 1;
  82638. prev = *scan++;
  82639. do {
  82640. if (*scan++ != prev)
  82641. break;
  82642. } while (++run < max);
  82643. }
  82644. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82645. if (run >= MIN_MATCH) {
  82646. check_match(s, s->strstart, s->strstart - 1, run);
  82647. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82648. s->lookahead -= run;
  82649. s->strstart += run;
  82650. } else {
  82651. /* No match, output a literal byte */
  82652. Tracevv((stderr,"%c", s->window[s->strstart]));
  82653. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82654. s->lookahead--;
  82655. s->strstart++;
  82656. }
  82657. if (bflush) FLUSH_BLOCK(s, 0);
  82658. }
  82659. FLUSH_BLOCK(s, flush == Z_FINISH);
  82660. return flush == Z_FINISH ? finish_done : block_done;
  82661. }
  82662. #endif
  82663. /*** End of inlined file: deflate.c ***/
  82664. /*** Start of inlined file: inffast.c ***/
  82665. /*** Start of inlined file: inftrees.h ***/
  82666. /* WARNING: this file should *not* be used by applications. It is
  82667. part of the implementation of the compression library and is
  82668. subject to change. Applications should only use zlib.h.
  82669. */
  82670. #ifndef _INFTREES_H_
  82671. #define _INFTREES_H_
  82672. /* Structure for decoding tables. Each entry provides either the
  82673. information needed to do the operation requested by the code that
  82674. indexed that table entry, or it provides a pointer to another
  82675. table that indexes more bits of the code. op indicates whether
  82676. the entry is a pointer to another table, a literal, a length or
  82677. distance, an end-of-block, or an invalid code. For a table
  82678. pointer, the low four bits of op is the number of index bits of
  82679. that table. For a length or distance, the low four bits of op
  82680. is the number of extra bits to get after the code. bits is
  82681. the number of bits in this code or part of the code to drop off
  82682. of the bit buffer. val is the actual byte to output in the case
  82683. of a literal, the base length or distance, or the offset from
  82684. the current table to the next table. Each entry is four bytes. */
  82685. typedef struct {
  82686. unsigned char op; /* operation, extra bits, table bits */
  82687. unsigned char bits; /* bits in this part of the code */
  82688. unsigned short val; /* offset in table or code value */
  82689. } code;
  82690. /* op values as set by inflate_table():
  82691. 00000000 - literal
  82692. 0000tttt - table link, tttt != 0 is the number of table index bits
  82693. 0001eeee - length or distance, eeee is the number of extra bits
  82694. 01100000 - end of block
  82695. 01000000 - invalid code
  82696. */
  82697. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82698. exhaustive search was 1444 code structures (852 for length/literals
  82699. and 592 for distances, the latter actually the result of an
  82700. exhaustive search). The true maximum is not known, but the value
  82701. below is more than safe. */
  82702. #define ENOUGH 2048
  82703. #define MAXD 592
  82704. /* Type of code to build for inftable() */
  82705. typedef enum {
  82706. CODES,
  82707. LENS,
  82708. DISTS
  82709. } codetype;
  82710. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82711. unsigned codes, code FAR * FAR *table,
  82712. unsigned FAR *bits, unsigned short FAR *work));
  82713. #endif
  82714. /*** End of inlined file: inftrees.h ***/
  82715. /*** Start of inlined file: inflate.h ***/
  82716. /* WARNING: this file should *not* be used by applications. It is
  82717. part of the implementation of the compression library and is
  82718. subject to change. Applications should only use zlib.h.
  82719. */
  82720. #ifndef _INFLATE_H_
  82721. #define _INFLATE_H_
  82722. /* define NO_GZIP when compiling if you want to disable gzip header and
  82723. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82724. the crc code when it is not needed. For shared libraries, gzip decoding
  82725. should be left enabled. */
  82726. #ifndef NO_GZIP
  82727. # define GUNZIP
  82728. #endif
  82729. /* Possible inflate modes between inflate() calls */
  82730. typedef enum {
  82731. HEAD, /* i: waiting for magic header */
  82732. FLAGS, /* i: waiting for method and flags (gzip) */
  82733. TIME, /* i: waiting for modification time (gzip) */
  82734. OS, /* i: waiting for extra flags and operating system (gzip) */
  82735. EXLEN, /* i: waiting for extra length (gzip) */
  82736. EXTRA, /* i: waiting for extra bytes (gzip) */
  82737. NAME, /* i: waiting for end of file name (gzip) */
  82738. COMMENT, /* i: waiting for end of comment (gzip) */
  82739. HCRC, /* i: waiting for header crc (gzip) */
  82740. DICTID, /* i: waiting for dictionary check value */
  82741. DICT, /* waiting for inflateSetDictionary() call */
  82742. TYPE, /* i: waiting for type bits, including last-flag bit */
  82743. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82744. STORED, /* i: waiting for stored size (length and complement) */
  82745. COPY, /* i/o: waiting for input or output to copy stored block */
  82746. TABLE, /* i: waiting for dynamic block table lengths */
  82747. LENLENS, /* i: waiting for code length code lengths */
  82748. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82749. LEN, /* i: waiting for length/lit code */
  82750. LENEXT, /* i: waiting for length extra bits */
  82751. DIST, /* i: waiting for distance code */
  82752. DISTEXT, /* i: waiting for distance extra bits */
  82753. MATCH, /* o: waiting for output space to copy string */
  82754. LIT, /* o: waiting for output space to write literal */
  82755. CHECK, /* i: waiting for 32-bit check value */
  82756. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82757. DONE, /* finished check, done -- remain here until reset */
  82758. BAD, /* got a data error -- remain here until reset */
  82759. MEM, /* got an inflate() memory error -- remain here until reset */
  82760. SYNC /* looking for synchronization bytes to restart inflate() */
  82761. } inflate_mode;
  82762. /*
  82763. State transitions between above modes -
  82764. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82765. Process header:
  82766. HEAD -> (gzip) or (zlib)
  82767. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82768. NAME -> COMMENT -> HCRC -> TYPE
  82769. (zlib) -> DICTID or TYPE
  82770. DICTID -> DICT -> TYPE
  82771. Read deflate blocks:
  82772. TYPE -> STORED or TABLE or LEN or CHECK
  82773. STORED -> COPY -> TYPE
  82774. TABLE -> LENLENS -> CODELENS -> LEN
  82775. Read deflate codes:
  82776. LEN -> LENEXT or LIT or TYPE
  82777. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82778. LIT -> LEN
  82779. Process trailer:
  82780. CHECK -> LENGTH -> DONE
  82781. */
  82782. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82783. struct inflate_state {
  82784. inflate_mode mode; /* current inflate mode */
  82785. int last; /* true if processing last block */
  82786. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82787. int havedict; /* true if dictionary provided */
  82788. int flags; /* gzip header method and flags (0 if zlib) */
  82789. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82790. unsigned long check; /* protected copy of check value */
  82791. unsigned long total; /* protected copy of output count */
  82792. gz_headerp head; /* where to save gzip header information */
  82793. /* sliding window */
  82794. unsigned wbits; /* log base 2 of requested window size */
  82795. unsigned wsize; /* window size or zero if not using window */
  82796. unsigned whave; /* valid bytes in the window */
  82797. unsigned write; /* window write index */
  82798. unsigned char FAR *window; /* allocated sliding window, if needed */
  82799. /* bit accumulator */
  82800. unsigned long hold; /* input bit accumulator */
  82801. unsigned bits; /* number of bits in "in" */
  82802. /* for string and stored block copying */
  82803. unsigned length; /* literal or length of data to copy */
  82804. unsigned offset; /* distance back to copy string from */
  82805. /* for table and code decoding */
  82806. unsigned extra; /* extra bits needed */
  82807. /* fixed and dynamic code tables */
  82808. code const FAR *lencode; /* starting table for length/literal codes */
  82809. code const FAR *distcode; /* starting table for distance codes */
  82810. unsigned lenbits; /* index bits for lencode */
  82811. unsigned distbits; /* index bits for distcode */
  82812. /* dynamic table building */
  82813. unsigned ncode; /* number of code length code lengths */
  82814. unsigned nlen; /* number of length code lengths */
  82815. unsigned ndist; /* number of distance code lengths */
  82816. unsigned have; /* number of code lengths in lens[] */
  82817. code FAR *next; /* next available space in codes[] */
  82818. unsigned short lens[320]; /* temporary storage for code lengths */
  82819. unsigned short work[288]; /* work area for code table building */
  82820. code codes[ENOUGH]; /* space for code tables */
  82821. };
  82822. #endif
  82823. /*** End of inlined file: inflate.h ***/
  82824. /*** Start of inlined file: inffast.h ***/
  82825. /* WARNING: this file should *not* be used by applications. It is
  82826. part of the implementation of the compression library and is
  82827. subject to change. Applications should only use zlib.h.
  82828. */
  82829. void inflate_fast OF((z_streamp strm, unsigned start));
  82830. /*** End of inlined file: inffast.h ***/
  82831. #ifndef ASMINF
  82832. /* Allow machine dependent optimization for post-increment or pre-increment.
  82833. Based on testing to date,
  82834. Pre-increment preferred for:
  82835. - PowerPC G3 (Adler)
  82836. - MIPS R5000 (Randers-Pehrson)
  82837. Post-increment preferred for:
  82838. - none
  82839. No measurable difference:
  82840. - Pentium III (Anderson)
  82841. - M68060 (Nikl)
  82842. */
  82843. #ifdef POSTINC
  82844. # define OFF 0
  82845. # define PUP(a) *(a)++
  82846. #else
  82847. # define OFF 1
  82848. # define PUP(a) *++(a)
  82849. #endif
  82850. /*
  82851. Decode literal, length, and distance codes and write out the resulting
  82852. literal and match bytes until either not enough input or output is
  82853. available, an end-of-block is encountered, or a data error is encountered.
  82854. When large enough input and output buffers are supplied to inflate(), for
  82855. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82856. inflate execution time is spent in this routine.
  82857. Entry assumptions:
  82858. state->mode == LEN
  82859. strm->avail_in >= 6
  82860. strm->avail_out >= 258
  82861. start >= strm->avail_out
  82862. state->bits < 8
  82863. On return, state->mode is one of:
  82864. LEN -- ran out of enough output space or enough available input
  82865. TYPE -- reached end of block code, inflate() to interpret next block
  82866. BAD -- error in block data
  82867. Notes:
  82868. - The maximum input bits used by a length/distance pair is 15 bits for the
  82869. length code, 5 bits for the length extra, 15 bits for the distance code,
  82870. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82871. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82872. checking for available input while decoding.
  82873. - The maximum bytes that a single length/distance pair can output is 258
  82874. bytes, which is the maximum length that can be coded. inflate_fast()
  82875. requires strm->avail_out >= 258 for each loop to avoid checking for
  82876. output space.
  82877. */
  82878. void inflate_fast (z_streamp strm, unsigned start)
  82879. {
  82880. struct inflate_state FAR *state;
  82881. unsigned char FAR *in; /* local strm->next_in */
  82882. unsigned char FAR *last; /* while in < last, enough input available */
  82883. unsigned char FAR *out; /* local strm->next_out */
  82884. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82885. unsigned char FAR *end; /* while out < end, enough space available */
  82886. #ifdef INFLATE_STRICT
  82887. unsigned dmax; /* maximum distance from zlib header */
  82888. #endif
  82889. unsigned wsize; /* window size or zero if not using window */
  82890. unsigned whave; /* valid bytes in the window */
  82891. unsigned write; /* window write index */
  82892. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82893. unsigned long hold; /* local strm->hold */
  82894. unsigned bits; /* local strm->bits */
  82895. code const FAR *lcode; /* local strm->lencode */
  82896. code const FAR *dcode; /* local strm->distcode */
  82897. unsigned lmask; /* mask for first level of length codes */
  82898. unsigned dmask; /* mask for first level of distance codes */
  82899. code thisx; /* retrieved table entry */
  82900. unsigned op; /* code bits, operation, extra bits, or */
  82901. /* window position, window bytes to copy */
  82902. unsigned len; /* match length, unused bytes */
  82903. unsigned dist; /* match distance */
  82904. unsigned char FAR *from; /* where to copy match from */
  82905. /* copy state to local variables */
  82906. state = (struct inflate_state FAR *)strm->state;
  82907. in = strm->next_in - OFF;
  82908. last = in + (strm->avail_in - 5);
  82909. out = strm->next_out - OFF;
  82910. beg = out - (start - strm->avail_out);
  82911. end = out + (strm->avail_out - 257);
  82912. #ifdef INFLATE_STRICT
  82913. dmax = state->dmax;
  82914. #endif
  82915. wsize = state->wsize;
  82916. whave = state->whave;
  82917. write = state->write;
  82918. window = state->window;
  82919. hold = state->hold;
  82920. bits = state->bits;
  82921. lcode = state->lencode;
  82922. dcode = state->distcode;
  82923. lmask = (1U << state->lenbits) - 1;
  82924. dmask = (1U << state->distbits) - 1;
  82925. /* decode literals and length/distances until end-of-block or not enough
  82926. input data or output space */
  82927. do {
  82928. if (bits < 15) {
  82929. hold += (unsigned long)(PUP(in)) << bits;
  82930. bits += 8;
  82931. hold += (unsigned long)(PUP(in)) << bits;
  82932. bits += 8;
  82933. }
  82934. thisx = lcode[hold & lmask];
  82935. dolen:
  82936. op = (unsigned)(thisx.bits);
  82937. hold >>= op;
  82938. bits -= op;
  82939. op = (unsigned)(thisx.op);
  82940. if (op == 0) { /* literal */
  82941. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82942. "inflate: literal '%c'\n" :
  82943. "inflate: literal 0x%02x\n", thisx.val));
  82944. PUP(out) = (unsigned char)(thisx.val);
  82945. }
  82946. else if (op & 16) { /* length base */
  82947. len = (unsigned)(thisx.val);
  82948. op &= 15; /* number of extra bits */
  82949. if (op) {
  82950. if (bits < op) {
  82951. hold += (unsigned long)(PUP(in)) << bits;
  82952. bits += 8;
  82953. }
  82954. len += (unsigned)hold & ((1U << op) - 1);
  82955. hold >>= op;
  82956. bits -= op;
  82957. }
  82958. Tracevv((stderr, "inflate: length %u\n", len));
  82959. if (bits < 15) {
  82960. hold += (unsigned long)(PUP(in)) << bits;
  82961. bits += 8;
  82962. hold += (unsigned long)(PUP(in)) << bits;
  82963. bits += 8;
  82964. }
  82965. thisx = dcode[hold & dmask];
  82966. dodist:
  82967. op = (unsigned)(thisx.bits);
  82968. hold >>= op;
  82969. bits -= op;
  82970. op = (unsigned)(thisx.op);
  82971. if (op & 16) { /* distance base */
  82972. dist = (unsigned)(thisx.val);
  82973. op &= 15; /* number of extra bits */
  82974. if (bits < op) {
  82975. hold += (unsigned long)(PUP(in)) << bits;
  82976. bits += 8;
  82977. if (bits < op) {
  82978. hold += (unsigned long)(PUP(in)) << bits;
  82979. bits += 8;
  82980. }
  82981. }
  82982. dist += (unsigned)hold & ((1U << op) - 1);
  82983. #ifdef INFLATE_STRICT
  82984. if (dist > dmax) {
  82985. strm->msg = (char *)"invalid distance too far back";
  82986. state->mode = BAD;
  82987. break;
  82988. }
  82989. #endif
  82990. hold >>= op;
  82991. bits -= op;
  82992. Tracevv((stderr, "inflate: distance %u\n", dist));
  82993. op = (unsigned)(out - beg); /* max distance in output */
  82994. if (dist > op) { /* see if copy from window */
  82995. op = dist - op; /* distance back in window */
  82996. if (op > whave) {
  82997. strm->msg = (char *)"invalid distance too far back";
  82998. state->mode = BAD;
  82999. break;
  83000. }
  83001. from = window - OFF;
  83002. if (write == 0) { /* very common case */
  83003. from += wsize - op;
  83004. if (op < len) { /* some from window */
  83005. len -= op;
  83006. do {
  83007. PUP(out) = PUP(from);
  83008. } while (--op);
  83009. from = out - dist; /* rest from output */
  83010. }
  83011. }
  83012. else if (write < op) { /* wrap around window */
  83013. from += wsize + write - op;
  83014. op -= write;
  83015. if (op < len) { /* some from end of window */
  83016. len -= op;
  83017. do {
  83018. PUP(out) = PUP(from);
  83019. } while (--op);
  83020. from = window - OFF;
  83021. if (write < len) { /* some from start of window */
  83022. op = write;
  83023. len -= op;
  83024. do {
  83025. PUP(out) = PUP(from);
  83026. } while (--op);
  83027. from = out - dist; /* rest from output */
  83028. }
  83029. }
  83030. }
  83031. else { /* contiguous in window */
  83032. from += write - op;
  83033. if (op < len) { /* some from window */
  83034. len -= op;
  83035. do {
  83036. PUP(out) = PUP(from);
  83037. } while (--op);
  83038. from = out - dist; /* rest from output */
  83039. }
  83040. }
  83041. while (len > 2) {
  83042. PUP(out) = PUP(from);
  83043. PUP(out) = PUP(from);
  83044. PUP(out) = PUP(from);
  83045. len -= 3;
  83046. }
  83047. if (len) {
  83048. PUP(out) = PUP(from);
  83049. if (len > 1)
  83050. PUP(out) = PUP(from);
  83051. }
  83052. }
  83053. else {
  83054. from = out - dist; /* copy direct from output */
  83055. do { /* minimum length is three */
  83056. PUP(out) = PUP(from);
  83057. PUP(out) = PUP(from);
  83058. PUP(out) = PUP(from);
  83059. len -= 3;
  83060. } while (len > 2);
  83061. if (len) {
  83062. PUP(out) = PUP(from);
  83063. if (len > 1)
  83064. PUP(out) = PUP(from);
  83065. }
  83066. }
  83067. }
  83068. else if ((op & 64) == 0) { /* 2nd level distance code */
  83069. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83070. goto dodist;
  83071. }
  83072. else {
  83073. strm->msg = (char *)"invalid distance code";
  83074. state->mode = BAD;
  83075. break;
  83076. }
  83077. }
  83078. else if ((op & 64) == 0) { /* 2nd level length code */
  83079. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83080. goto dolen;
  83081. }
  83082. else if (op & 32) { /* end-of-block */
  83083. Tracevv((stderr, "inflate: end of block\n"));
  83084. state->mode = TYPE;
  83085. break;
  83086. }
  83087. else {
  83088. strm->msg = (char *)"invalid literal/length code";
  83089. state->mode = BAD;
  83090. break;
  83091. }
  83092. } while (in < last && out < end);
  83093. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83094. len = bits >> 3;
  83095. in -= len;
  83096. bits -= len << 3;
  83097. hold &= (1U << bits) - 1;
  83098. /* update state and return */
  83099. strm->next_in = in + OFF;
  83100. strm->next_out = out + OFF;
  83101. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83102. strm->avail_out = (unsigned)(out < end ?
  83103. 257 + (end - out) : 257 - (out - end));
  83104. state->hold = hold;
  83105. state->bits = bits;
  83106. return;
  83107. }
  83108. /*
  83109. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83110. - Using bit fields for code structure
  83111. - Different op definition to avoid & for extra bits (do & for table bits)
  83112. - Three separate decoding do-loops for direct, window, and write == 0
  83113. - Special case for distance > 1 copies to do overlapped load and store copy
  83114. - Explicit branch predictions (based on measured branch probabilities)
  83115. - Deferring match copy and interspersed it with decoding subsequent codes
  83116. - Swapping literal/length else
  83117. - Swapping window/direct else
  83118. - Larger unrolled copy loops (three is about right)
  83119. - Moving len -= 3 statement into middle of loop
  83120. */
  83121. #endif /* !ASMINF */
  83122. /*** End of inlined file: inffast.c ***/
  83123. #undef PULLBYTE
  83124. #undef LOAD
  83125. #undef RESTORE
  83126. #undef INITBITS
  83127. #undef NEEDBITS
  83128. #undef DROPBITS
  83129. #undef BYTEBITS
  83130. /*** Start of inlined file: inflate.c ***/
  83131. /*
  83132. * Change history:
  83133. *
  83134. * 1.2.beta0 24 Nov 2002
  83135. * - First version -- complete rewrite of inflate to simplify code, avoid
  83136. * creation of window when not needed, minimize use of window when it is
  83137. * needed, make inffast.c even faster, implement gzip decoding, and to
  83138. * improve code readability and style over the previous zlib inflate code
  83139. *
  83140. * 1.2.beta1 25 Nov 2002
  83141. * - Use pointers for available input and output checking in inffast.c
  83142. * - Remove input and output counters in inffast.c
  83143. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83144. * - Remove unnecessary second byte pull from length extra in inffast.c
  83145. * - Unroll direct copy to three copies per loop in inffast.c
  83146. *
  83147. * 1.2.beta2 4 Dec 2002
  83148. * - Change external routine names to reduce potential conflicts
  83149. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83150. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83151. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83152. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83153. *
  83154. * 1.2.beta3 22 Dec 2002
  83155. * - Add comments on state->bits assertion in inffast.c
  83156. * - Add comments on op field in inftrees.h
  83157. * - Fix bug in reuse of allocated window after inflateReset()
  83158. * - Remove bit fields--back to byte structure for speed
  83159. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83160. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83161. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83162. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83163. * - Use local copies of stream next and avail values, as well as local bit
  83164. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83165. *
  83166. * 1.2.beta4 1 Jan 2003
  83167. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83168. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83169. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83170. * - Rearrange window copies in inflate_fast() for speed and simplification
  83171. * - Unroll last copy for window match in inflate_fast()
  83172. * - Use local copies of window variables in inflate_fast() for speed
  83173. * - Pull out common write == 0 case for speed in inflate_fast()
  83174. * - Make op and len in inflate_fast() unsigned for consistency
  83175. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83176. * - Simplified bad distance check in inflate_fast()
  83177. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83178. * source file infback.c to provide a call-back interface to inflate for
  83179. * programs like gzip and unzip -- uses window as output buffer to avoid
  83180. * window copying
  83181. *
  83182. * 1.2.beta5 1 Jan 2003
  83183. * - Improved inflateBack() interface to allow the caller to provide initial
  83184. * input in strm.
  83185. * - Fixed stored blocks bug in inflateBack()
  83186. *
  83187. * 1.2.beta6 4 Jan 2003
  83188. * - Added comments in inffast.c on effectiveness of POSTINC
  83189. * - Typecasting all around to reduce compiler warnings
  83190. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83191. * make compilers happy
  83192. * - Changed type of window in inflateBackInit() to unsigned char *
  83193. *
  83194. * 1.2.beta7 27 Jan 2003
  83195. * - Changed many types to unsigned or unsigned short to avoid warnings
  83196. * - Added inflateCopy() function
  83197. *
  83198. * 1.2.0 9 Mar 2003
  83199. * - Changed inflateBack() interface to provide separate opaque descriptors
  83200. * for the in() and out() functions
  83201. * - Changed inflateBack() argument and in_func typedef to swap the length
  83202. * and buffer address return values for the input function
  83203. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83204. *
  83205. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83206. */
  83207. /*** Start of inlined file: inffast.h ***/
  83208. /* WARNING: this file should *not* be used by applications. It is
  83209. part of the implementation of the compression library and is
  83210. subject to change. Applications should only use zlib.h.
  83211. */
  83212. void inflate_fast OF((z_streamp strm, unsigned start));
  83213. /*** End of inlined file: inffast.h ***/
  83214. #ifdef MAKEFIXED
  83215. # ifndef BUILDFIXED
  83216. # define BUILDFIXED
  83217. # endif
  83218. #endif
  83219. /* function prototypes */
  83220. local void fixedtables OF((struct inflate_state FAR *state));
  83221. local int updatewindow OF((z_streamp strm, unsigned out));
  83222. #ifdef BUILDFIXED
  83223. void makefixed OF((void));
  83224. #endif
  83225. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83226. unsigned len));
  83227. int ZEXPORT inflateReset (z_streamp strm)
  83228. {
  83229. struct inflate_state FAR *state;
  83230. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83231. state = (struct inflate_state FAR *)strm->state;
  83232. strm->total_in = strm->total_out = state->total = 0;
  83233. strm->msg = Z_NULL;
  83234. strm->adler = 1; /* to support ill-conceived Java test suite */
  83235. state->mode = HEAD;
  83236. state->last = 0;
  83237. state->havedict = 0;
  83238. state->dmax = 32768U;
  83239. state->head = Z_NULL;
  83240. state->wsize = 0;
  83241. state->whave = 0;
  83242. state->write = 0;
  83243. state->hold = 0;
  83244. state->bits = 0;
  83245. state->lencode = state->distcode = state->next = state->codes;
  83246. Tracev((stderr, "inflate: reset\n"));
  83247. return Z_OK;
  83248. }
  83249. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83250. {
  83251. struct inflate_state FAR *state;
  83252. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83253. state = (struct inflate_state FAR *)strm->state;
  83254. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83255. value &= (1L << bits) - 1;
  83256. state->hold += value << state->bits;
  83257. state->bits += bits;
  83258. return Z_OK;
  83259. }
  83260. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83261. {
  83262. struct inflate_state FAR *state;
  83263. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83264. stream_size != (int)(sizeof(z_stream)))
  83265. return Z_VERSION_ERROR;
  83266. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83267. strm->msg = Z_NULL; /* in case we return an error */
  83268. if (strm->zalloc == (alloc_func)0) {
  83269. strm->zalloc = zcalloc;
  83270. strm->opaque = (voidpf)0;
  83271. }
  83272. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83273. state = (struct inflate_state FAR *)
  83274. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83275. if (state == Z_NULL) return Z_MEM_ERROR;
  83276. Tracev((stderr, "inflate: allocated\n"));
  83277. strm->state = (struct internal_state FAR *)state;
  83278. if (windowBits < 0) {
  83279. state->wrap = 0;
  83280. windowBits = -windowBits;
  83281. }
  83282. else {
  83283. state->wrap = (windowBits >> 4) + 1;
  83284. #ifdef GUNZIP
  83285. if (windowBits < 48) windowBits &= 15;
  83286. #endif
  83287. }
  83288. if (windowBits < 8 || windowBits > 15) {
  83289. ZFREE(strm, state);
  83290. strm->state = Z_NULL;
  83291. return Z_STREAM_ERROR;
  83292. }
  83293. state->wbits = (unsigned)windowBits;
  83294. state->window = Z_NULL;
  83295. return inflateReset(strm);
  83296. }
  83297. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83298. {
  83299. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83300. }
  83301. /*
  83302. Return state with length and distance decoding tables and index sizes set to
  83303. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83304. If BUILDFIXED is defined, then instead this routine builds the tables the
  83305. first time it's called, and returns those tables the first time and
  83306. thereafter. This reduces the size of the code by about 2K bytes, in
  83307. exchange for a little execution time. However, BUILDFIXED should not be
  83308. used for threaded applications, since the rewriting of the tables and virgin
  83309. may not be thread-safe.
  83310. */
  83311. local void fixedtables (struct inflate_state FAR *state)
  83312. {
  83313. #ifdef BUILDFIXED
  83314. static int virgin = 1;
  83315. static code *lenfix, *distfix;
  83316. static code fixed[544];
  83317. /* build fixed huffman tables if first call (may not be thread safe) */
  83318. if (virgin) {
  83319. unsigned sym, bits;
  83320. static code *next;
  83321. /* literal/length table */
  83322. sym = 0;
  83323. while (sym < 144) state->lens[sym++] = 8;
  83324. while (sym < 256) state->lens[sym++] = 9;
  83325. while (sym < 280) state->lens[sym++] = 7;
  83326. while (sym < 288) state->lens[sym++] = 8;
  83327. next = fixed;
  83328. lenfix = next;
  83329. bits = 9;
  83330. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83331. /* distance table */
  83332. sym = 0;
  83333. while (sym < 32) state->lens[sym++] = 5;
  83334. distfix = next;
  83335. bits = 5;
  83336. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83337. /* do this just once */
  83338. virgin = 0;
  83339. }
  83340. #else /* !BUILDFIXED */
  83341. /*** Start of inlined file: inffixed.h ***/
  83342. /* WARNING: this file should *not* be used by applications. It
  83343. is part of the implementation of the compression library and
  83344. is subject to change. Applications should only use zlib.h.
  83345. */
  83346. static const code lenfix[512] = {
  83347. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83348. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83349. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83350. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83351. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83352. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83353. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83354. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83355. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83356. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83357. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83358. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83359. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83360. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83361. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83362. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83363. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83364. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83365. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83366. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83367. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83368. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83369. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83370. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83371. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83372. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83373. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83374. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83375. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83376. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83377. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83378. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83379. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83380. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83381. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83382. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83383. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83384. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83385. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83386. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83387. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83388. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83389. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83390. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83391. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83392. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83393. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83394. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83395. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83396. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83397. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83398. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83399. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83400. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83401. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83402. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83403. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83404. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83405. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83406. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83407. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83408. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83409. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83410. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83411. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83412. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83413. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83414. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83415. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83416. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83417. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83418. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83419. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83420. {0,9,255}
  83421. };
  83422. static const code distfix[32] = {
  83423. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83424. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83425. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83426. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83427. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83428. {22,5,193},{64,5,0}
  83429. };
  83430. /*** End of inlined file: inffixed.h ***/
  83431. #endif /* BUILDFIXED */
  83432. state->lencode = lenfix;
  83433. state->lenbits = 9;
  83434. state->distcode = distfix;
  83435. state->distbits = 5;
  83436. }
  83437. #ifdef MAKEFIXED
  83438. #include <stdio.h>
  83439. /*
  83440. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83441. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83442. those tables to stdout, which would be piped to inffixed.h. A small program
  83443. can simply call makefixed to do this:
  83444. void makefixed(void);
  83445. int main(void)
  83446. {
  83447. makefixed();
  83448. return 0;
  83449. }
  83450. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83451. a.out > inffixed.h
  83452. */
  83453. void makefixed()
  83454. {
  83455. unsigned low, size;
  83456. struct inflate_state state;
  83457. fixedtables(&state);
  83458. puts(" /* inffixed.h -- table for decoding fixed codes");
  83459. puts(" * Generated automatically by makefixed().");
  83460. puts(" */");
  83461. puts("");
  83462. puts(" /* WARNING: this file should *not* be used by applications.");
  83463. puts(" It is part of the implementation of this library and is");
  83464. puts(" subject to change. Applications should only use zlib.h.");
  83465. puts(" */");
  83466. puts("");
  83467. size = 1U << 9;
  83468. printf(" static const code lenfix[%u] = {", size);
  83469. low = 0;
  83470. for (;;) {
  83471. if ((low % 7) == 0) printf("\n ");
  83472. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83473. state.lencode[low].val);
  83474. if (++low == size) break;
  83475. putchar(',');
  83476. }
  83477. puts("\n };");
  83478. size = 1U << 5;
  83479. printf("\n static const code distfix[%u] = {", size);
  83480. low = 0;
  83481. for (;;) {
  83482. if ((low % 6) == 0) printf("\n ");
  83483. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83484. state.distcode[low].val);
  83485. if (++low == size) break;
  83486. putchar(',');
  83487. }
  83488. puts("\n };");
  83489. }
  83490. #endif /* MAKEFIXED */
  83491. /*
  83492. Update the window with the last wsize (normally 32K) bytes written before
  83493. returning. If window does not exist yet, create it. This is only called
  83494. when a window is already in use, or when output has been written during this
  83495. inflate call, but the end of the deflate stream has not been reached yet.
  83496. It is also called to create a window for dictionary data when a dictionary
  83497. is loaded.
  83498. Providing output buffers larger than 32K to inflate() should provide a speed
  83499. advantage, since only the last 32K of output is copied to the sliding window
  83500. upon return from inflate(), and since all distances after the first 32K of
  83501. output will fall in the output data, making match copies simpler and faster.
  83502. The advantage may be dependent on the size of the processor's data caches.
  83503. */
  83504. local int updatewindow (z_streamp strm, unsigned out)
  83505. {
  83506. struct inflate_state FAR *state;
  83507. unsigned copy, dist;
  83508. state = (struct inflate_state FAR *)strm->state;
  83509. /* if it hasn't been done already, allocate space for the window */
  83510. if (state->window == Z_NULL) {
  83511. state->window = (unsigned char FAR *)
  83512. ZALLOC(strm, 1U << state->wbits,
  83513. sizeof(unsigned char));
  83514. if (state->window == Z_NULL) return 1;
  83515. }
  83516. /* if window not in use yet, initialize */
  83517. if (state->wsize == 0) {
  83518. state->wsize = 1U << state->wbits;
  83519. state->write = 0;
  83520. state->whave = 0;
  83521. }
  83522. /* copy state->wsize or less output bytes into the circular window */
  83523. copy = out - strm->avail_out;
  83524. if (copy >= state->wsize) {
  83525. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83526. state->write = 0;
  83527. state->whave = state->wsize;
  83528. }
  83529. else {
  83530. dist = state->wsize - state->write;
  83531. if (dist > copy) dist = copy;
  83532. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83533. copy -= dist;
  83534. if (copy) {
  83535. zmemcpy(state->window, strm->next_out - copy, copy);
  83536. state->write = copy;
  83537. state->whave = state->wsize;
  83538. }
  83539. else {
  83540. state->write += dist;
  83541. if (state->write == state->wsize) state->write = 0;
  83542. if (state->whave < state->wsize) state->whave += dist;
  83543. }
  83544. }
  83545. return 0;
  83546. }
  83547. /* Macros for inflate(): */
  83548. /* check function to use adler32() for zlib or crc32() for gzip */
  83549. #ifdef GUNZIP
  83550. # define UPDATE(check, buf, len) \
  83551. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83552. #else
  83553. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83554. #endif
  83555. /* check macros for header crc */
  83556. #ifdef GUNZIP
  83557. # define CRC2(check, word) \
  83558. do { \
  83559. hbuf[0] = (unsigned char)(word); \
  83560. hbuf[1] = (unsigned char)((word) >> 8); \
  83561. check = crc32(check, hbuf, 2); \
  83562. } while (0)
  83563. # define CRC4(check, word) \
  83564. do { \
  83565. hbuf[0] = (unsigned char)(word); \
  83566. hbuf[1] = (unsigned char)((word) >> 8); \
  83567. hbuf[2] = (unsigned char)((word) >> 16); \
  83568. hbuf[3] = (unsigned char)((word) >> 24); \
  83569. check = crc32(check, hbuf, 4); \
  83570. } while (0)
  83571. #endif
  83572. /* Load registers with state in inflate() for speed */
  83573. #define LOAD() \
  83574. do { \
  83575. put = strm->next_out; \
  83576. left = strm->avail_out; \
  83577. next = strm->next_in; \
  83578. have = strm->avail_in; \
  83579. hold = state->hold; \
  83580. bits = state->bits; \
  83581. } while (0)
  83582. /* Restore state from registers in inflate() */
  83583. #define RESTORE() \
  83584. do { \
  83585. strm->next_out = put; \
  83586. strm->avail_out = left; \
  83587. strm->next_in = next; \
  83588. strm->avail_in = have; \
  83589. state->hold = hold; \
  83590. state->bits = bits; \
  83591. } while (0)
  83592. /* Clear the input bit accumulator */
  83593. #define INITBITS() \
  83594. do { \
  83595. hold = 0; \
  83596. bits = 0; \
  83597. } while (0)
  83598. /* Get a byte of input into the bit accumulator, or return from inflate()
  83599. if there is no input available. */
  83600. #define PULLBYTE() \
  83601. do { \
  83602. if (have == 0) goto inf_leave; \
  83603. have--; \
  83604. hold += (unsigned long)(*next++) << bits; \
  83605. bits += 8; \
  83606. } while (0)
  83607. /* Assure that there are at least n bits in the bit accumulator. If there is
  83608. not enough available input to do that, then return from inflate(). */
  83609. #define NEEDBITS(n) \
  83610. do { \
  83611. while (bits < (unsigned)(n)) \
  83612. PULLBYTE(); \
  83613. } while (0)
  83614. /* Return the low n bits of the bit accumulator (n < 16) */
  83615. #define BITS(n) \
  83616. ((unsigned)hold & ((1U << (n)) - 1))
  83617. /* Remove n bits from the bit accumulator */
  83618. #define DROPBITS(n) \
  83619. do { \
  83620. hold >>= (n); \
  83621. bits -= (unsigned)(n); \
  83622. } while (0)
  83623. /* Remove zero to seven bits as needed to go to a byte boundary */
  83624. #define BYTEBITS() \
  83625. do { \
  83626. hold >>= bits & 7; \
  83627. bits -= bits & 7; \
  83628. } while (0)
  83629. /* Reverse the bytes in a 32-bit value */
  83630. #define REVERSE(q) \
  83631. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83632. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83633. /*
  83634. inflate() uses a state machine to process as much input data and generate as
  83635. much output data as possible before returning. The state machine is
  83636. structured roughly as follows:
  83637. for (;;) switch (state) {
  83638. ...
  83639. case STATEn:
  83640. if (not enough input data or output space to make progress)
  83641. return;
  83642. ... make progress ...
  83643. state = STATEm;
  83644. break;
  83645. ...
  83646. }
  83647. so when inflate() is called again, the same case is attempted again, and
  83648. if the appropriate resources are provided, the machine proceeds to the
  83649. next state. The NEEDBITS() macro is usually the way the state evaluates
  83650. whether it can proceed or should return. NEEDBITS() does the return if
  83651. the requested bits are not available. The typical use of the BITS macros
  83652. is:
  83653. NEEDBITS(n);
  83654. ... do something with BITS(n) ...
  83655. DROPBITS(n);
  83656. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83657. input left to load n bits into the accumulator, or it continues. BITS(n)
  83658. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83659. the low n bits off the accumulator. INITBITS() clears the accumulator
  83660. and sets the number of available bits to zero. BYTEBITS() discards just
  83661. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83662. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83663. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83664. if there is no input available. The decoding of variable length codes uses
  83665. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83666. code, and no more.
  83667. Some states loop until they get enough input, making sure that enough
  83668. state information is maintained to continue the loop where it left off
  83669. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83670. would all have to actually be part of the saved state in case NEEDBITS()
  83671. returns:
  83672. case STATEw:
  83673. while (want < need) {
  83674. NEEDBITS(n);
  83675. keep[want++] = BITS(n);
  83676. DROPBITS(n);
  83677. }
  83678. state = STATEx;
  83679. case STATEx:
  83680. As shown above, if the next state is also the next case, then the break
  83681. is omitted.
  83682. A state may also return if there is not enough output space available to
  83683. complete that state. Those states are copying stored data, writing a
  83684. literal byte, and copying a matching string.
  83685. When returning, a "goto inf_leave" is used to update the total counters,
  83686. update the check value, and determine whether any progress has been made
  83687. during that inflate() call in order to return the proper return code.
  83688. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83689. When there is a window, goto inf_leave will update the window with the last
  83690. output written. If a goto inf_leave occurs in the middle of decompression
  83691. and there is no window currently, goto inf_leave will create one and copy
  83692. output to the window for the next call of inflate().
  83693. In this implementation, the flush parameter of inflate() only affects the
  83694. return code (per zlib.h). inflate() always writes as much as possible to
  83695. strm->next_out, given the space available and the provided input--the effect
  83696. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83697. the allocation of and copying into a sliding window until necessary, which
  83698. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83699. stream available. So the only thing the flush parameter actually does is:
  83700. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83701. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83702. */
  83703. int ZEXPORT inflate (z_streamp strm, int flush)
  83704. {
  83705. struct inflate_state FAR *state;
  83706. unsigned char FAR *next; /* next input */
  83707. unsigned char FAR *put; /* next output */
  83708. unsigned have, left; /* available input and output */
  83709. unsigned long hold; /* bit buffer */
  83710. unsigned bits; /* bits in bit buffer */
  83711. unsigned in, out; /* save starting available input and output */
  83712. unsigned copy; /* number of stored or match bytes to copy */
  83713. unsigned char FAR *from; /* where to copy match bytes from */
  83714. code thisx; /* current decoding table entry */
  83715. code last; /* parent table entry */
  83716. unsigned len; /* length to copy for repeats, bits to drop */
  83717. int ret; /* return code */
  83718. #ifdef GUNZIP
  83719. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83720. #endif
  83721. static const unsigned short order[19] = /* permutation of code lengths */
  83722. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83723. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83724. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83725. return Z_STREAM_ERROR;
  83726. state = (struct inflate_state FAR *)strm->state;
  83727. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83728. LOAD();
  83729. in = have;
  83730. out = left;
  83731. ret = Z_OK;
  83732. for (;;)
  83733. switch (state->mode) {
  83734. case HEAD:
  83735. if (state->wrap == 0) {
  83736. state->mode = TYPEDO;
  83737. break;
  83738. }
  83739. NEEDBITS(16);
  83740. #ifdef GUNZIP
  83741. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83742. state->check = crc32(0L, Z_NULL, 0);
  83743. CRC2(state->check, hold);
  83744. INITBITS();
  83745. state->mode = FLAGS;
  83746. break;
  83747. }
  83748. state->flags = 0; /* expect zlib header */
  83749. if (state->head != Z_NULL)
  83750. state->head->done = -1;
  83751. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83752. #else
  83753. if (
  83754. #endif
  83755. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83756. strm->msg = (char *)"incorrect header check";
  83757. state->mode = BAD;
  83758. break;
  83759. }
  83760. if (BITS(4) != Z_DEFLATED) {
  83761. strm->msg = (char *)"unknown compression method";
  83762. state->mode = BAD;
  83763. break;
  83764. }
  83765. DROPBITS(4);
  83766. len = BITS(4) + 8;
  83767. if (len > state->wbits) {
  83768. strm->msg = (char *)"invalid window size";
  83769. state->mode = BAD;
  83770. break;
  83771. }
  83772. state->dmax = 1U << len;
  83773. Tracev((stderr, "inflate: zlib header ok\n"));
  83774. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83775. state->mode = hold & 0x200 ? DICTID : TYPE;
  83776. INITBITS();
  83777. break;
  83778. #ifdef GUNZIP
  83779. case FLAGS:
  83780. NEEDBITS(16);
  83781. state->flags = (int)(hold);
  83782. if ((state->flags & 0xff) != Z_DEFLATED) {
  83783. strm->msg = (char *)"unknown compression method";
  83784. state->mode = BAD;
  83785. break;
  83786. }
  83787. if (state->flags & 0xe000) {
  83788. strm->msg = (char *)"unknown header flags set";
  83789. state->mode = BAD;
  83790. break;
  83791. }
  83792. if (state->head != Z_NULL)
  83793. state->head->text = (int)((hold >> 8) & 1);
  83794. if (state->flags & 0x0200) CRC2(state->check, hold);
  83795. INITBITS();
  83796. state->mode = TIME;
  83797. case TIME:
  83798. NEEDBITS(32);
  83799. if (state->head != Z_NULL)
  83800. state->head->time = hold;
  83801. if (state->flags & 0x0200) CRC4(state->check, hold);
  83802. INITBITS();
  83803. state->mode = OS;
  83804. case OS:
  83805. NEEDBITS(16);
  83806. if (state->head != Z_NULL) {
  83807. state->head->xflags = (int)(hold & 0xff);
  83808. state->head->os = (int)(hold >> 8);
  83809. }
  83810. if (state->flags & 0x0200) CRC2(state->check, hold);
  83811. INITBITS();
  83812. state->mode = EXLEN;
  83813. case EXLEN:
  83814. if (state->flags & 0x0400) {
  83815. NEEDBITS(16);
  83816. state->length = (unsigned)(hold);
  83817. if (state->head != Z_NULL)
  83818. state->head->extra_len = (unsigned)hold;
  83819. if (state->flags & 0x0200) CRC2(state->check, hold);
  83820. INITBITS();
  83821. }
  83822. else if (state->head != Z_NULL)
  83823. state->head->extra = Z_NULL;
  83824. state->mode = EXTRA;
  83825. case EXTRA:
  83826. if (state->flags & 0x0400) {
  83827. copy = state->length;
  83828. if (copy > have) copy = have;
  83829. if (copy) {
  83830. if (state->head != Z_NULL &&
  83831. state->head->extra != Z_NULL) {
  83832. len = state->head->extra_len - state->length;
  83833. zmemcpy(state->head->extra + len, next,
  83834. len + copy > state->head->extra_max ?
  83835. state->head->extra_max - len : copy);
  83836. }
  83837. if (state->flags & 0x0200)
  83838. state->check = crc32(state->check, next, copy);
  83839. have -= copy;
  83840. next += copy;
  83841. state->length -= copy;
  83842. }
  83843. if (state->length) goto inf_leave;
  83844. }
  83845. state->length = 0;
  83846. state->mode = NAME;
  83847. case NAME:
  83848. if (state->flags & 0x0800) {
  83849. if (have == 0) goto inf_leave;
  83850. copy = 0;
  83851. do {
  83852. len = (unsigned)(next[copy++]);
  83853. if (state->head != Z_NULL &&
  83854. state->head->name != Z_NULL &&
  83855. state->length < state->head->name_max)
  83856. state->head->name[state->length++] = len;
  83857. } while (len && copy < have);
  83858. if (state->flags & 0x0200)
  83859. state->check = crc32(state->check, next, copy);
  83860. have -= copy;
  83861. next += copy;
  83862. if (len) goto inf_leave;
  83863. }
  83864. else if (state->head != Z_NULL)
  83865. state->head->name = Z_NULL;
  83866. state->length = 0;
  83867. state->mode = COMMENT;
  83868. case COMMENT:
  83869. if (state->flags & 0x1000) {
  83870. if (have == 0) goto inf_leave;
  83871. copy = 0;
  83872. do {
  83873. len = (unsigned)(next[copy++]);
  83874. if (state->head != Z_NULL &&
  83875. state->head->comment != Z_NULL &&
  83876. state->length < state->head->comm_max)
  83877. state->head->comment[state->length++] = len;
  83878. } while (len && copy < have);
  83879. if (state->flags & 0x0200)
  83880. state->check = crc32(state->check, next, copy);
  83881. have -= copy;
  83882. next += copy;
  83883. if (len) goto inf_leave;
  83884. }
  83885. else if (state->head != Z_NULL)
  83886. state->head->comment = Z_NULL;
  83887. state->mode = HCRC;
  83888. case HCRC:
  83889. if (state->flags & 0x0200) {
  83890. NEEDBITS(16);
  83891. if (hold != (state->check & 0xffff)) {
  83892. strm->msg = (char *)"header crc mismatch";
  83893. state->mode = BAD;
  83894. break;
  83895. }
  83896. INITBITS();
  83897. }
  83898. if (state->head != Z_NULL) {
  83899. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83900. state->head->done = 1;
  83901. }
  83902. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83903. state->mode = TYPE;
  83904. break;
  83905. #endif
  83906. case DICTID:
  83907. NEEDBITS(32);
  83908. strm->adler = state->check = REVERSE(hold);
  83909. INITBITS();
  83910. state->mode = DICT;
  83911. case DICT:
  83912. if (state->havedict == 0) {
  83913. RESTORE();
  83914. return Z_NEED_DICT;
  83915. }
  83916. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83917. state->mode = TYPE;
  83918. case TYPE:
  83919. if (flush == Z_BLOCK) goto inf_leave;
  83920. case TYPEDO:
  83921. if (state->last) {
  83922. BYTEBITS();
  83923. state->mode = CHECK;
  83924. break;
  83925. }
  83926. NEEDBITS(3);
  83927. state->last = BITS(1);
  83928. DROPBITS(1);
  83929. switch (BITS(2)) {
  83930. case 0: /* stored block */
  83931. Tracev((stderr, "inflate: stored block%s\n",
  83932. state->last ? " (last)" : ""));
  83933. state->mode = STORED;
  83934. break;
  83935. case 1: /* fixed block */
  83936. fixedtables(state);
  83937. Tracev((stderr, "inflate: fixed codes block%s\n",
  83938. state->last ? " (last)" : ""));
  83939. state->mode = LEN; /* decode codes */
  83940. break;
  83941. case 2: /* dynamic block */
  83942. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83943. state->last ? " (last)" : ""));
  83944. state->mode = TABLE;
  83945. break;
  83946. case 3:
  83947. strm->msg = (char *)"invalid block type";
  83948. state->mode = BAD;
  83949. }
  83950. DROPBITS(2);
  83951. break;
  83952. case STORED:
  83953. BYTEBITS(); /* go to byte boundary */
  83954. NEEDBITS(32);
  83955. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83956. strm->msg = (char *)"invalid stored block lengths";
  83957. state->mode = BAD;
  83958. break;
  83959. }
  83960. state->length = (unsigned)hold & 0xffff;
  83961. Tracev((stderr, "inflate: stored length %u\n",
  83962. state->length));
  83963. INITBITS();
  83964. state->mode = COPY;
  83965. case COPY:
  83966. copy = state->length;
  83967. if (copy) {
  83968. if (copy > have) copy = have;
  83969. if (copy > left) copy = left;
  83970. if (copy == 0) goto inf_leave;
  83971. zmemcpy(put, next, copy);
  83972. have -= copy;
  83973. next += copy;
  83974. left -= copy;
  83975. put += copy;
  83976. state->length -= copy;
  83977. break;
  83978. }
  83979. Tracev((stderr, "inflate: stored end\n"));
  83980. state->mode = TYPE;
  83981. break;
  83982. case TABLE:
  83983. NEEDBITS(14);
  83984. state->nlen = BITS(5) + 257;
  83985. DROPBITS(5);
  83986. state->ndist = BITS(5) + 1;
  83987. DROPBITS(5);
  83988. state->ncode = BITS(4) + 4;
  83989. DROPBITS(4);
  83990. #ifndef PKZIP_BUG_WORKAROUND
  83991. if (state->nlen > 286 || state->ndist > 30) {
  83992. strm->msg = (char *)"too many length or distance symbols";
  83993. state->mode = BAD;
  83994. break;
  83995. }
  83996. #endif
  83997. Tracev((stderr, "inflate: table sizes ok\n"));
  83998. state->have = 0;
  83999. state->mode = LENLENS;
  84000. case LENLENS:
  84001. while (state->have < state->ncode) {
  84002. NEEDBITS(3);
  84003. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  84004. DROPBITS(3);
  84005. }
  84006. while (state->have < 19)
  84007. state->lens[order[state->have++]] = 0;
  84008. state->next = state->codes;
  84009. state->lencode = (code const FAR *)(state->next);
  84010. state->lenbits = 7;
  84011. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  84012. &(state->lenbits), state->work);
  84013. if (ret) {
  84014. strm->msg = (char *)"invalid code lengths set";
  84015. state->mode = BAD;
  84016. break;
  84017. }
  84018. Tracev((stderr, "inflate: code lengths ok\n"));
  84019. state->have = 0;
  84020. state->mode = CODELENS;
  84021. case CODELENS:
  84022. while (state->have < state->nlen + state->ndist) {
  84023. for (;;) {
  84024. thisx = state->lencode[BITS(state->lenbits)];
  84025. if ((unsigned)(thisx.bits) <= bits) break;
  84026. PULLBYTE();
  84027. }
  84028. if (thisx.val < 16) {
  84029. NEEDBITS(thisx.bits);
  84030. DROPBITS(thisx.bits);
  84031. state->lens[state->have++] = thisx.val;
  84032. }
  84033. else {
  84034. if (thisx.val == 16) {
  84035. NEEDBITS(thisx.bits + 2);
  84036. DROPBITS(thisx.bits);
  84037. if (state->have == 0) {
  84038. strm->msg = (char *)"invalid bit length repeat";
  84039. state->mode = BAD;
  84040. break;
  84041. }
  84042. len = state->lens[state->have - 1];
  84043. copy = 3 + BITS(2);
  84044. DROPBITS(2);
  84045. }
  84046. else if (thisx.val == 17) {
  84047. NEEDBITS(thisx.bits + 3);
  84048. DROPBITS(thisx.bits);
  84049. len = 0;
  84050. copy = 3 + BITS(3);
  84051. DROPBITS(3);
  84052. }
  84053. else {
  84054. NEEDBITS(thisx.bits + 7);
  84055. DROPBITS(thisx.bits);
  84056. len = 0;
  84057. copy = 11 + BITS(7);
  84058. DROPBITS(7);
  84059. }
  84060. if (state->have + copy > state->nlen + state->ndist) {
  84061. strm->msg = (char *)"invalid bit length repeat";
  84062. state->mode = BAD;
  84063. break;
  84064. }
  84065. while (copy--)
  84066. state->lens[state->have++] = (unsigned short)len;
  84067. }
  84068. }
  84069. /* handle error breaks in while */
  84070. if (state->mode == BAD) break;
  84071. /* build code tables */
  84072. state->next = state->codes;
  84073. state->lencode = (code const FAR *)(state->next);
  84074. state->lenbits = 9;
  84075. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84076. &(state->lenbits), state->work);
  84077. if (ret) {
  84078. strm->msg = (char *)"invalid literal/lengths set";
  84079. state->mode = BAD;
  84080. break;
  84081. }
  84082. state->distcode = (code const FAR *)(state->next);
  84083. state->distbits = 6;
  84084. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84085. &(state->next), &(state->distbits), state->work);
  84086. if (ret) {
  84087. strm->msg = (char *)"invalid distances set";
  84088. state->mode = BAD;
  84089. break;
  84090. }
  84091. Tracev((stderr, "inflate: codes ok\n"));
  84092. state->mode = LEN;
  84093. case LEN:
  84094. if (have >= 6 && left >= 258) {
  84095. RESTORE();
  84096. inflate_fast(strm, out);
  84097. LOAD();
  84098. break;
  84099. }
  84100. for (;;) {
  84101. thisx = state->lencode[BITS(state->lenbits)];
  84102. if ((unsigned)(thisx.bits) <= bits) break;
  84103. PULLBYTE();
  84104. }
  84105. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84106. last = thisx;
  84107. for (;;) {
  84108. thisx = state->lencode[last.val +
  84109. (BITS(last.bits + last.op) >> last.bits)];
  84110. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84111. PULLBYTE();
  84112. }
  84113. DROPBITS(last.bits);
  84114. }
  84115. DROPBITS(thisx.bits);
  84116. state->length = (unsigned)thisx.val;
  84117. if ((int)(thisx.op) == 0) {
  84118. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84119. "inflate: literal '%c'\n" :
  84120. "inflate: literal 0x%02x\n", thisx.val));
  84121. state->mode = LIT;
  84122. break;
  84123. }
  84124. if (thisx.op & 32) {
  84125. Tracevv((stderr, "inflate: end of block\n"));
  84126. state->mode = TYPE;
  84127. break;
  84128. }
  84129. if (thisx.op & 64) {
  84130. strm->msg = (char *)"invalid literal/length code";
  84131. state->mode = BAD;
  84132. break;
  84133. }
  84134. state->extra = (unsigned)(thisx.op) & 15;
  84135. state->mode = LENEXT;
  84136. case LENEXT:
  84137. if (state->extra) {
  84138. NEEDBITS(state->extra);
  84139. state->length += BITS(state->extra);
  84140. DROPBITS(state->extra);
  84141. }
  84142. Tracevv((stderr, "inflate: length %u\n", state->length));
  84143. state->mode = DIST;
  84144. case DIST:
  84145. for (;;) {
  84146. thisx = state->distcode[BITS(state->distbits)];
  84147. if ((unsigned)(thisx.bits) <= bits) break;
  84148. PULLBYTE();
  84149. }
  84150. if ((thisx.op & 0xf0) == 0) {
  84151. last = thisx;
  84152. for (;;) {
  84153. thisx = state->distcode[last.val +
  84154. (BITS(last.bits + last.op) >> last.bits)];
  84155. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84156. PULLBYTE();
  84157. }
  84158. DROPBITS(last.bits);
  84159. }
  84160. DROPBITS(thisx.bits);
  84161. if (thisx.op & 64) {
  84162. strm->msg = (char *)"invalid distance code";
  84163. state->mode = BAD;
  84164. break;
  84165. }
  84166. state->offset = (unsigned)thisx.val;
  84167. state->extra = (unsigned)(thisx.op) & 15;
  84168. state->mode = DISTEXT;
  84169. case DISTEXT:
  84170. if (state->extra) {
  84171. NEEDBITS(state->extra);
  84172. state->offset += BITS(state->extra);
  84173. DROPBITS(state->extra);
  84174. }
  84175. #ifdef INFLATE_STRICT
  84176. if (state->offset > state->dmax) {
  84177. strm->msg = (char *)"invalid distance too far back";
  84178. state->mode = BAD;
  84179. break;
  84180. }
  84181. #endif
  84182. if (state->offset > state->whave + out - left) {
  84183. strm->msg = (char *)"invalid distance too far back";
  84184. state->mode = BAD;
  84185. break;
  84186. }
  84187. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84188. state->mode = MATCH;
  84189. case MATCH:
  84190. if (left == 0) goto inf_leave;
  84191. copy = out - left;
  84192. if (state->offset > copy) { /* copy from window */
  84193. copy = state->offset - copy;
  84194. if (copy > state->write) {
  84195. copy -= state->write;
  84196. from = state->window + (state->wsize - copy);
  84197. }
  84198. else
  84199. from = state->window + (state->write - copy);
  84200. if (copy > state->length) copy = state->length;
  84201. }
  84202. else { /* copy from output */
  84203. from = put - state->offset;
  84204. copy = state->length;
  84205. }
  84206. if (copy > left) copy = left;
  84207. left -= copy;
  84208. state->length -= copy;
  84209. do {
  84210. *put++ = *from++;
  84211. } while (--copy);
  84212. if (state->length == 0) state->mode = LEN;
  84213. break;
  84214. case LIT:
  84215. if (left == 0) goto inf_leave;
  84216. *put++ = (unsigned char)(state->length);
  84217. left--;
  84218. state->mode = LEN;
  84219. break;
  84220. case CHECK:
  84221. if (state->wrap) {
  84222. NEEDBITS(32);
  84223. out -= left;
  84224. strm->total_out += out;
  84225. state->total += out;
  84226. if (out)
  84227. strm->adler = state->check =
  84228. UPDATE(state->check, put - out, out);
  84229. out = left;
  84230. if ((
  84231. #ifdef GUNZIP
  84232. state->flags ? hold :
  84233. #endif
  84234. REVERSE(hold)) != state->check) {
  84235. strm->msg = (char *)"incorrect data check";
  84236. state->mode = BAD;
  84237. break;
  84238. }
  84239. INITBITS();
  84240. Tracev((stderr, "inflate: check matches trailer\n"));
  84241. }
  84242. #ifdef GUNZIP
  84243. state->mode = LENGTH;
  84244. case LENGTH:
  84245. if (state->wrap && state->flags) {
  84246. NEEDBITS(32);
  84247. if (hold != (state->total & 0xffffffffUL)) {
  84248. strm->msg = (char *)"incorrect length check";
  84249. state->mode = BAD;
  84250. break;
  84251. }
  84252. INITBITS();
  84253. Tracev((stderr, "inflate: length matches trailer\n"));
  84254. }
  84255. #endif
  84256. state->mode = DONE;
  84257. case DONE:
  84258. ret = Z_STREAM_END;
  84259. goto inf_leave;
  84260. case BAD:
  84261. ret = Z_DATA_ERROR;
  84262. goto inf_leave;
  84263. case MEM:
  84264. return Z_MEM_ERROR;
  84265. case SYNC:
  84266. default:
  84267. return Z_STREAM_ERROR;
  84268. }
  84269. /*
  84270. Return from inflate(), updating the total counts and the check value.
  84271. If there was no progress during the inflate() call, return a buffer
  84272. error. Call updatewindow() to create and/or update the window state.
  84273. Note: a memory error from inflate() is non-recoverable.
  84274. */
  84275. inf_leave:
  84276. RESTORE();
  84277. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84278. if (updatewindow(strm, out)) {
  84279. state->mode = MEM;
  84280. return Z_MEM_ERROR;
  84281. }
  84282. in -= strm->avail_in;
  84283. out -= strm->avail_out;
  84284. strm->total_in += in;
  84285. strm->total_out += out;
  84286. state->total += out;
  84287. if (state->wrap && out)
  84288. strm->adler = state->check =
  84289. UPDATE(state->check, strm->next_out - out, out);
  84290. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84291. (state->mode == TYPE ? 128 : 0);
  84292. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84293. ret = Z_BUF_ERROR;
  84294. return ret;
  84295. }
  84296. int ZEXPORT inflateEnd (z_streamp strm)
  84297. {
  84298. struct inflate_state FAR *state;
  84299. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84300. return Z_STREAM_ERROR;
  84301. state = (struct inflate_state FAR *)strm->state;
  84302. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84303. ZFREE(strm, strm->state);
  84304. strm->state = Z_NULL;
  84305. Tracev((stderr, "inflate: end\n"));
  84306. return Z_OK;
  84307. }
  84308. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84309. {
  84310. struct inflate_state FAR *state;
  84311. unsigned long id_;
  84312. /* check state */
  84313. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84314. state = (struct inflate_state FAR *)strm->state;
  84315. if (state->wrap != 0 && state->mode != DICT)
  84316. return Z_STREAM_ERROR;
  84317. /* check for correct dictionary id */
  84318. if (state->mode == DICT) {
  84319. id_ = adler32(0L, Z_NULL, 0);
  84320. id_ = adler32(id_, dictionary, dictLength);
  84321. if (id_ != state->check)
  84322. return Z_DATA_ERROR;
  84323. }
  84324. /* copy dictionary to window */
  84325. if (updatewindow(strm, strm->avail_out)) {
  84326. state->mode = MEM;
  84327. return Z_MEM_ERROR;
  84328. }
  84329. if (dictLength > state->wsize) {
  84330. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84331. state->wsize);
  84332. state->whave = state->wsize;
  84333. }
  84334. else {
  84335. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84336. dictLength);
  84337. state->whave = dictLength;
  84338. }
  84339. state->havedict = 1;
  84340. Tracev((stderr, "inflate: dictionary set\n"));
  84341. return Z_OK;
  84342. }
  84343. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84344. {
  84345. struct inflate_state FAR *state;
  84346. /* check state */
  84347. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84348. state = (struct inflate_state FAR *)strm->state;
  84349. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84350. /* save header structure */
  84351. state->head = head;
  84352. head->done = 0;
  84353. return Z_OK;
  84354. }
  84355. /*
  84356. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84357. or when out of input. When called, *have is the number of pattern bytes
  84358. found in order so far, in 0..3. On return *have is updated to the new
  84359. state. If on return *have equals four, then the pattern was found and the
  84360. return value is how many bytes were read including the last byte of the
  84361. pattern. If *have is less than four, then the pattern has not been found
  84362. yet and the return value is len. In the latter case, syncsearch() can be
  84363. called again with more data and the *have state. *have is initialized to
  84364. zero for the first call.
  84365. */
  84366. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84367. {
  84368. unsigned got;
  84369. unsigned next;
  84370. got = *have;
  84371. next = 0;
  84372. while (next < len && got < 4) {
  84373. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84374. got++;
  84375. else if (buf[next])
  84376. got = 0;
  84377. else
  84378. got = 4 - got;
  84379. next++;
  84380. }
  84381. *have = got;
  84382. return next;
  84383. }
  84384. int ZEXPORT inflateSync (z_streamp strm)
  84385. {
  84386. unsigned len; /* number of bytes to look at or looked at */
  84387. unsigned long in, out; /* temporary to save total_in and total_out */
  84388. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84389. struct inflate_state FAR *state;
  84390. /* check parameters */
  84391. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84392. state = (struct inflate_state FAR *)strm->state;
  84393. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84394. /* if first time, start search in bit buffer */
  84395. if (state->mode != SYNC) {
  84396. state->mode = SYNC;
  84397. state->hold <<= state->bits & 7;
  84398. state->bits -= state->bits & 7;
  84399. len = 0;
  84400. while (state->bits >= 8) {
  84401. buf[len++] = (unsigned char)(state->hold);
  84402. state->hold >>= 8;
  84403. state->bits -= 8;
  84404. }
  84405. state->have = 0;
  84406. syncsearch(&(state->have), buf, len);
  84407. }
  84408. /* search available input */
  84409. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84410. strm->avail_in -= len;
  84411. strm->next_in += len;
  84412. strm->total_in += len;
  84413. /* return no joy or set up to restart inflate() on a new block */
  84414. if (state->have != 4) return Z_DATA_ERROR;
  84415. in = strm->total_in; out = strm->total_out;
  84416. inflateReset(strm);
  84417. strm->total_in = in; strm->total_out = out;
  84418. state->mode = TYPE;
  84419. return Z_OK;
  84420. }
  84421. /*
  84422. Returns true if inflate is currently at the end of a block generated by
  84423. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84424. implementation to provide an additional safety check. PPP uses
  84425. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84426. block. When decompressing, PPP checks that at the end of input packet,
  84427. inflate is waiting for these length bytes.
  84428. */
  84429. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84430. {
  84431. struct inflate_state FAR *state;
  84432. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84433. state = (struct inflate_state FAR *)strm->state;
  84434. return state->mode == STORED && state->bits == 0;
  84435. }
  84436. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84437. {
  84438. struct inflate_state FAR *state;
  84439. struct inflate_state FAR *copy;
  84440. unsigned char FAR *window;
  84441. unsigned wsize;
  84442. /* check input */
  84443. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84444. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84445. return Z_STREAM_ERROR;
  84446. state = (struct inflate_state FAR *)source->state;
  84447. /* allocate space */
  84448. copy = (struct inflate_state FAR *)
  84449. ZALLOC(source, 1, sizeof(struct inflate_state));
  84450. if (copy == Z_NULL) return Z_MEM_ERROR;
  84451. window = Z_NULL;
  84452. if (state->window != Z_NULL) {
  84453. window = (unsigned char FAR *)
  84454. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84455. if (window == Z_NULL) {
  84456. ZFREE(source, copy);
  84457. return Z_MEM_ERROR;
  84458. }
  84459. }
  84460. /* copy state */
  84461. zmemcpy(dest, source, sizeof(z_stream));
  84462. zmemcpy(copy, state, sizeof(struct inflate_state));
  84463. if (state->lencode >= state->codes &&
  84464. state->lencode <= state->codes + ENOUGH - 1) {
  84465. copy->lencode = copy->codes + (state->lencode - state->codes);
  84466. copy->distcode = copy->codes + (state->distcode - state->codes);
  84467. }
  84468. copy->next = copy->codes + (state->next - state->codes);
  84469. if (window != Z_NULL) {
  84470. wsize = 1U << state->wbits;
  84471. zmemcpy(window, state->window, wsize);
  84472. }
  84473. copy->window = window;
  84474. dest->state = (struct internal_state FAR *)copy;
  84475. return Z_OK;
  84476. }
  84477. /*** End of inlined file: inflate.c ***/
  84478. /*** Start of inlined file: inftrees.c ***/
  84479. #define MAXBITS 15
  84480. const char inflate_copyright[] =
  84481. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84482. /*
  84483. If you use the zlib library in a product, an acknowledgment is welcome
  84484. in the documentation of your product. If for some reason you cannot
  84485. include such an acknowledgment, I would appreciate that you keep this
  84486. copyright string in the executable of your product.
  84487. */
  84488. /*
  84489. Build a set of tables to decode the provided canonical Huffman code.
  84490. The code lengths are lens[0..codes-1]. The result starts at *table,
  84491. whose indices are 0..2^bits-1. work is a writable array of at least
  84492. lens shorts, which is used as a work area. type is the type of code
  84493. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84494. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84495. on return points to the next available entry's address. bits is the
  84496. requested root table index bits, and on return it is the actual root
  84497. table index bits. It will differ if the request is greater than the
  84498. longest code or if it is less than the shortest code.
  84499. */
  84500. int inflate_table (codetype type,
  84501. unsigned short FAR *lens,
  84502. unsigned codes,
  84503. code FAR * FAR *table,
  84504. unsigned FAR *bits,
  84505. unsigned short FAR *work)
  84506. {
  84507. unsigned len; /* a code's length in bits */
  84508. unsigned sym; /* index of code symbols */
  84509. unsigned min, max; /* minimum and maximum code lengths */
  84510. unsigned root; /* number of index bits for root table */
  84511. unsigned curr; /* number of index bits for current table */
  84512. unsigned drop; /* code bits to drop for sub-table */
  84513. int left; /* number of prefix codes available */
  84514. unsigned used; /* code entries in table used */
  84515. unsigned huff; /* Huffman code */
  84516. unsigned incr; /* for incrementing code, index */
  84517. unsigned fill; /* index for replicating entries */
  84518. unsigned low; /* low bits for current root entry */
  84519. unsigned mask; /* mask for low root bits */
  84520. code thisx; /* table entry for duplication */
  84521. code FAR *next; /* next available space in table */
  84522. const unsigned short FAR *base; /* base value table to use */
  84523. const unsigned short FAR *extra; /* extra bits table to use */
  84524. int end; /* use base and extra for symbol > end */
  84525. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84526. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84527. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84528. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84529. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84530. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84531. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84532. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84533. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84534. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84535. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84536. 8193, 12289, 16385, 24577, 0, 0};
  84537. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84538. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84539. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84540. 28, 28, 29, 29, 64, 64};
  84541. /*
  84542. Process a set of code lengths to create a canonical Huffman code. The
  84543. code lengths are lens[0..codes-1]. Each length corresponds to the
  84544. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84545. symbols by length from short to long, and retaining the symbol order
  84546. for codes with equal lengths. Then the code starts with all zero bits
  84547. for the first code of the shortest length, and the codes are integer
  84548. increments for the same length, and zeros are appended as the length
  84549. increases. For the deflate format, these bits are stored backwards
  84550. from their more natural integer increment ordering, and so when the
  84551. decoding tables are built in the large loop below, the integer codes
  84552. are incremented backwards.
  84553. This routine assumes, but does not check, that all of the entries in
  84554. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84555. 1..MAXBITS is interpreted as that code length. zero means that that
  84556. symbol does not occur in this code.
  84557. The codes are sorted by computing a count of codes for each length,
  84558. creating from that a table of starting indices for each length in the
  84559. sorted table, and then entering the symbols in order in the sorted
  84560. table. The sorted table is work[], with that space being provided by
  84561. the caller.
  84562. The length counts are used for other purposes as well, i.e. finding
  84563. the minimum and maximum length codes, determining if there are any
  84564. codes at all, checking for a valid set of lengths, and looking ahead
  84565. at length counts to determine sub-table sizes when building the
  84566. decoding tables.
  84567. */
  84568. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84569. for (len = 0; len <= MAXBITS; len++)
  84570. count[len] = 0;
  84571. for (sym = 0; sym < codes; sym++)
  84572. count[lens[sym]]++;
  84573. /* bound code lengths, force root to be within code lengths */
  84574. root = *bits;
  84575. for (max = MAXBITS; max >= 1; max--)
  84576. if (count[max] != 0) break;
  84577. if (root > max) root = max;
  84578. if (max == 0) { /* no symbols to code at all */
  84579. thisx.op = (unsigned char)64; /* invalid code marker */
  84580. thisx.bits = (unsigned char)1;
  84581. thisx.val = (unsigned short)0;
  84582. *(*table)++ = thisx; /* make a table to force an error */
  84583. *(*table)++ = thisx;
  84584. *bits = 1;
  84585. return 0; /* no symbols, but wait for decoding to report error */
  84586. }
  84587. for (min = 1; min <= MAXBITS; min++)
  84588. if (count[min] != 0) break;
  84589. if (root < min) root = min;
  84590. /* check for an over-subscribed or incomplete set of lengths */
  84591. left = 1;
  84592. for (len = 1; len <= MAXBITS; len++) {
  84593. left <<= 1;
  84594. left -= count[len];
  84595. if (left < 0) return -1; /* over-subscribed */
  84596. }
  84597. if (left > 0 && (type == CODES || max != 1))
  84598. return -1; /* incomplete set */
  84599. /* generate offsets into symbol table for each length for sorting */
  84600. offs[1] = 0;
  84601. for (len = 1; len < MAXBITS; len++)
  84602. offs[len + 1] = offs[len] + count[len];
  84603. /* sort symbols by length, by symbol order within each length */
  84604. for (sym = 0; sym < codes; sym++)
  84605. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84606. /*
  84607. Create and fill in decoding tables. In this loop, the table being
  84608. filled is at next and has curr index bits. The code being used is huff
  84609. with length len. That code is converted to an index by dropping drop
  84610. bits off of the bottom. For codes where len is less than drop + curr,
  84611. those top drop + curr - len bits are incremented through all values to
  84612. fill the table with replicated entries.
  84613. root is the number of index bits for the root table. When len exceeds
  84614. root, sub-tables are created pointed to by the root entry with an index
  84615. of the low root bits of huff. This is saved in low to check for when a
  84616. new sub-table should be started. drop is zero when the root table is
  84617. being filled, and drop is root when sub-tables are being filled.
  84618. When a new sub-table is needed, it is necessary to look ahead in the
  84619. code lengths to determine what size sub-table is needed. The length
  84620. counts are used for this, and so count[] is decremented as codes are
  84621. entered in the tables.
  84622. used keeps track of how many table entries have been allocated from the
  84623. provided *table space. It is checked when a LENS table is being made
  84624. against the space in *table, ENOUGH, minus the maximum space needed by
  84625. the worst case distance code, MAXD. This should never happen, but the
  84626. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84627. This assumes that when type == LENS, bits == 9.
  84628. sym increments through all symbols, and the loop terminates when
  84629. all codes of length max, i.e. all codes, have been processed. This
  84630. routine permits incomplete codes, so another loop after this one fills
  84631. in the rest of the decoding tables with invalid code markers.
  84632. */
  84633. /* set up for code type */
  84634. switch (type) {
  84635. case CODES:
  84636. base = extra = work; /* dummy value--not used */
  84637. end = 19;
  84638. break;
  84639. case LENS:
  84640. base = lbase;
  84641. base -= 257;
  84642. extra = lext;
  84643. extra -= 257;
  84644. end = 256;
  84645. break;
  84646. default: /* DISTS */
  84647. base = dbase;
  84648. extra = dext;
  84649. end = -1;
  84650. }
  84651. /* initialize state for loop */
  84652. huff = 0; /* starting code */
  84653. sym = 0; /* starting code symbol */
  84654. len = min; /* starting code length */
  84655. next = *table; /* current table to fill in */
  84656. curr = root; /* current table index bits */
  84657. drop = 0; /* current bits to drop from code for index */
  84658. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84659. used = 1U << root; /* use root table entries */
  84660. mask = used - 1; /* mask for comparing low */
  84661. /* check available table space */
  84662. if (type == LENS && used >= ENOUGH - MAXD)
  84663. return 1;
  84664. /* process all codes and make table entries */
  84665. for (;;) {
  84666. /* create table entry */
  84667. thisx.bits = (unsigned char)(len - drop);
  84668. if ((int)(work[sym]) < end) {
  84669. thisx.op = (unsigned char)0;
  84670. thisx.val = work[sym];
  84671. }
  84672. else if ((int)(work[sym]) > end) {
  84673. thisx.op = (unsigned char)(extra[work[sym]]);
  84674. thisx.val = base[work[sym]];
  84675. }
  84676. else {
  84677. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84678. thisx.val = 0;
  84679. }
  84680. /* replicate for those indices with low len bits equal to huff */
  84681. incr = 1U << (len - drop);
  84682. fill = 1U << curr;
  84683. min = fill; /* save offset to next table */
  84684. do {
  84685. fill -= incr;
  84686. next[(huff >> drop) + fill] = thisx;
  84687. } while (fill != 0);
  84688. /* backwards increment the len-bit code huff */
  84689. incr = 1U << (len - 1);
  84690. while (huff & incr)
  84691. incr >>= 1;
  84692. if (incr != 0) {
  84693. huff &= incr - 1;
  84694. huff += incr;
  84695. }
  84696. else
  84697. huff = 0;
  84698. /* go to next symbol, update count, len */
  84699. sym++;
  84700. if (--(count[len]) == 0) {
  84701. if (len == max) break;
  84702. len = lens[work[sym]];
  84703. }
  84704. /* create new sub-table if needed */
  84705. if (len > root && (huff & mask) != low) {
  84706. /* if first time, transition to sub-tables */
  84707. if (drop == 0)
  84708. drop = root;
  84709. /* increment past last table */
  84710. next += min; /* here min is 1 << curr */
  84711. /* determine length of next table */
  84712. curr = len - drop;
  84713. left = (int)(1 << curr);
  84714. while (curr + drop < max) {
  84715. left -= count[curr + drop];
  84716. if (left <= 0) break;
  84717. curr++;
  84718. left <<= 1;
  84719. }
  84720. /* check for enough space */
  84721. used += 1U << curr;
  84722. if (type == LENS && used >= ENOUGH - MAXD)
  84723. return 1;
  84724. /* point entry in root table to sub-table */
  84725. low = huff & mask;
  84726. (*table)[low].op = (unsigned char)curr;
  84727. (*table)[low].bits = (unsigned char)root;
  84728. (*table)[low].val = (unsigned short)(next - *table);
  84729. }
  84730. }
  84731. /*
  84732. Fill in rest of table for incomplete codes. This loop is similar to the
  84733. loop above in incrementing huff for table indices. It is assumed that
  84734. len is equal to curr + drop, so there is no loop needed to increment
  84735. through high index bits. When the current sub-table is filled, the loop
  84736. drops back to the root table to fill in any remaining entries there.
  84737. */
  84738. thisx.op = (unsigned char)64; /* invalid code marker */
  84739. thisx.bits = (unsigned char)(len - drop);
  84740. thisx.val = (unsigned short)0;
  84741. while (huff != 0) {
  84742. /* when done with sub-table, drop back to root table */
  84743. if (drop != 0 && (huff & mask) != low) {
  84744. drop = 0;
  84745. len = root;
  84746. next = *table;
  84747. thisx.bits = (unsigned char)len;
  84748. }
  84749. /* put invalid code marker in table */
  84750. next[huff >> drop] = thisx;
  84751. /* backwards increment the len-bit code huff */
  84752. incr = 1U << (len - 1);
  84753. while (huff & incr)
  84754. incr >>= 1;
  84755. if (incr != 0) {
  84756. huff &= incr - 1;
  84757. huff += incr;
  84758. }
  84759. else
  84760. huff = 0;
  84761. }
  84762. /* set return parameters */
  84763. *table += used;
  84764. *bits = root;
  84765. return 0;
  84766. }
  84767. /*** End of inlined file: inftrees.c ***/
  84768. /*** Start of inlined file: trees.c ***/
  84769. /*
  84770. * ALGORITHM
  84771. *
  84772. * The "deflation" process uses several Huffman trees. The more
  84773. * common source values are represented by shorter bit sequences.
  84774. *
  84775. * Each code tree is stored in a compressed form which is itself
  84776. * a Huffman encoding of the lengths of all the code strings (in
  84777. * ascending order by source values). The actual code strings are
  84778. * reconstructed from the lengths in the inflate process, as described
  84779. * in the deflate specification.
  84780. *
  84781. * REFERENCES
  84782. *
  84783. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84784. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84785. *
  84786. * Storer, James A.
  84787. * Data Compression: Methods and Theory, pp. 49-50.
  84788. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84789. *
  84790. * Sedgewick, R.
  84791. * Algorithms, p290.
  84792. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84793. */
  84794. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84795. /* #define GEN_TREES_H */
  84796. #ifdef DEBUG
  84797. # include <ctype.h>
  84798. #endif
  84799. /* ===========================================================================
  84800. * Constants
  84801. */
  84802. #define MAX_BL_BITS 7
  84803. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84804. #define END_BLOCK 256
  84805. /* end of block literal code */
  84806. #define REP_3_6 16
  84807. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84808. #define REPZ_3_10 17
  84809. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84810. #define REPZ_11_138 18
  84811. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84812. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84813. = {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};
  84814. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84815. = {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};
  84816. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84817. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84818. local const uch bl_order[BL_CODES]
  84819. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84820. /* The lengths of the bit length codes are sent in order of decreasing
  84821. * probability, to avoid transmitting the lengths for unused bit length codes.
  84822. */
  84823. #define Buf_size (8 * 2*sizeof(char))
  84824. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84825. * more than 16 bits on some systems.)
  84826. */
  84827. /* ===========================================================================
  84828. * Local data. These are initialized only once.
  84829. */
  84830. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84831. #if defined(GEN_TREES_H) || !defined(STDC)
  84832. /* non ANSI compilers may not accept trees.h */
  84833. local ct_data static_ltree[L_CODES+2];
  84834. /* The static literal tree. Since the bit lengths are imposed, there is no
  84835. * need for the L_CODES extra codes used during heap construction. However
  84836. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84837. * below).
  84838. */
  84839. local ct_data static_dtree[D_CODES];
  84840. /* The static distance tree. (Actually a trivial tree since all codes use
  84841. * 5 bits.)
  84842. */
  84843. uch _dist_code[DIST_CODE_LEN];
  84844. /* Distance codes. The first 256 values correspond to the distances
  84845. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84846. * the 15 bit distances.
  84847. */
  84848. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84849. /* length code for each normalized match length (0 == MIN_MATCH) */
  84850. local int base_length[LENGTH_CODES];
  84851. /* First normalized length for each code (0 = MIN_MATCH) */
  84852. local int base_dist[D_CODES];
  84853. /* First normalized distance for each code (0 = distance of 1) */
  84854. #else
  84855. /*** Start of inlined file: trees.h ***/
  84856. local const ct_data static_ltree[L_CODES+2] = {
  84857. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84858. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84859. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84860. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84861. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84862. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84863. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84864. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84865. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84866. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84867. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84868. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84869. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84870. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84871. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84872. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84873. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84874. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84875. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84876. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84877. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84878. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84879. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84880. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84881. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84882. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84883. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84884. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84885. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84886. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84887. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84888. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84889. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84890. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84891. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84892. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84893. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84894. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84895. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84896. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84897. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84898. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84899. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84900. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84901. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84902. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84903. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84904. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84905. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84906. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84907. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84908. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84909. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84910. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84911. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84912. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84913. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84914. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84915. };
  84916. local const ct_data static_dtree[D_CODES] = {
  84917. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84918. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84919. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84920. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84921. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84922. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84923. };
  84924. const uch _dist_code[DIST_CODE_LEN] = {
  84925. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84926. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84927. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84928. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84929. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84930. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84931. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84932. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84933. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84934. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84935. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84936. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84937. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84938. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84939. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84940. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84941. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84942. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84943. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84944. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84945. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84946. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84947. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84948. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84949. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84950. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84951. };
  84952. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84953. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84954. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84955. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84956. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84957. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84958. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84959. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84960. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84961. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84962. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84963. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84964. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84965. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84966. };
  84967. local const int base_length[LENGTH_CODES] = {
  84968. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84969. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84970. };
  84971. local const int base_dist[D_CODES] = {
  84972. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84973. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84974. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84975. };
  84976. /*** End of inlined file: trees.h ***/
  84977. #endif /* GEN_TREES_H */
  84978. struct static_tree_desc_s {
  84979. const ct_data *static_tree; /* static tree or NULL */
  84980. const intf *extra_bits; /* extra bits for each code or NULL */
  84981. int extra_base; /* base index for extra_bits */
  84982. int elems; /* max number of elements in the tree */
  84983. int max_length; /* max bit length for the codes */
  84984. };
  84985. local static_tree_desc static_l_desc =
  84986. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84987. local static_tree_desc static_d_desc =
  84988. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84989. local static_tree_desc static_bl_desc =
  84990. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84991. /* ===========================================================================
  84992. * Local (static) routines in this file.
  84993. */
  84994. local void tr_static_init OF((void));
  84995. local void init_block OF((deflate_state *s));
  84996. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84997. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84998. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84999. local void build_tree OF((deflate_state *s, tree_desc *desc));
  85000. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85001. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85002. local int build_bl_tree OF((deflate_state *s));
  85003. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  85004. int blcodes));
  85005. local void compress_block OF((deflate_state *s, ct_data *ltree,
  85006. ct_data *dtree));
  85007. local void set_data_type OF((deflate_state *s));
  85008. local unsigned bi_reverse OF((unsigned value, int length));
  85009. local void bi_windup OF((deflate_state *s));
  85010. local void bi_flush OF((deflate_state *s));
  85011. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  85012. int header));
  85013. #ifdef GEN_TREES_H
  85014. local void gen_trees_header OF((void));
  85015. #endif
  85016. #ifndef DEBUG
  85017. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  85018. /* Send a code of the given tree. c and tree must not have side effects */
  85019. #else /* DEBUG */
  85020. # define send_code(s, c, tree) \
  85021. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85022. send_bits(s, tree[c].Code, tree[c].Len); }
  85023. #endif
  85024. /* ===========================================================================
  85025. * Output a short LSB first on the stream.
  85026. * IN assertion: there is enough room in pendingBuf.
  85027. */
  85028. #define put_short(s, w) { \
  85029. put_byte(s, (uch)((w) & 0xff)); \
  85030. put_byte(s, (uch)((ush)(w) >> 8)); \
  85031. }
  85032. /* ===========================================================================
  85033. * Send a value on a given number of bits.
  85034. * IN assertion: length <= 16 and value fits in length bits.
  85035. */
  85036. #ifdef DEBUG
  85037. local void send_bits OF((deflate_state *s, int value, int length));
  85038. local void send_bits (deflate_state *s, int value, int length)
  85039. {
  85040. Tracevv((stderr," l %2d v %4x ", length, value));
  85041. Assert(length > 0 && length <= 15, "invalid length");
  85042. s->bits_sent += (ulg)length;
  85043. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85044. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85045. * unused bits in value.
  85046. */
  85047. if (s->bi_valid > (int)Buf_size - length) {
  85048. s->bi_buf |= (value << s->bi_valid);
  85049. put_short(s, s->bi_buf);
  85050. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85051. s->bi_valid += length - Buf_size;
  85052. } else {
  85053. s->bi_buf |= value << s->bi_valid;
  85054. s->bi_valid += length;
  85055. }
  85056. }
  85057. #else /* !DEBUG */
  85058. #define send_bits(s, value, length) \
  85059. { int len = length;\
  85060. if (s->bi_valid > (int)Buf_size - len) {\
  85061. int val = value;\
  85062. s->bi_buf |= (val << s->bi_valid);\
  85063. put_short(s, s->bi_buf);\
  85064. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85065. s->bi_valid += len - Buf_size;\
  85066. } else {\
  85067. s->bi_buf |= (value) << s->bi_valid;\
  85068. s->bi_valid += len;\
  85069. }\
  85070. }
  85071. #endif /* DEBUG */
  85072. /* the arguments must not have side effects */
  85073. /* ===========================================================================
  85074. * Initialize the various 'constant' tables.
  85075. */
  85076. local void tr_static_init()
  85077. {
  85078. #if defined(GEN_TREES_H) || !defined(STDC)
  85079. static int static_init_done = 0;
  85080. int n; /* iterates over tree elements */
  85081. int bits; /* bit counter */
  85082. int length; /* length value */
  85083. int code; /* code value */
  85084. int dist; /* distance index */
  85085. ush bl_count[MAX_BITS+1];
  85086. /* number of codes at each bit length for an optimal tree */
  85087. if (static_init_done) return;
  85088. /* For some embedded targets, global variables are not initialized: */
  85089. static_l_desc.static_tree = static_ltree;
  85090. static_l_desc.extra_bits = extra_lbits;
  85091. static_d_desc.static_tree = static_dtree;
  85092. static_d_desc.extra_bits = extra_dbits;
  85093. static_bl_desc.extra_bits = extra_blbits;
  85094. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85095. length = 0;
  85096. for (code = 0; code < LENGTH_CODES-1; code++) {
  85097. base_length[code] = length;
  85098. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85099. _length_code[length++] = (uch)code;
  85100. }
  85101. }
  85102. Assert (length == 256, "tr_static_init: length != 256");
  85103. /* Note that the length 255 (match length 258) can be represented
  85104. * in two different ways: code 284 + 5 bits or code 285, so we
  85105. * overwrite length_code[255] to use the best encoding:
  85106. */
  85107. _length_code[length-1] = (uch)code;
  85108. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85109. dist = 0;
  85110. for (code = 0 ; code < 16; code++) {
  85111. base_dist[code] = dist;
  85112. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85113. _dist_code[dist++] = (uch)code;
  85114. }
  85115. }
  85116. Assert (dist == 256, "tr_static_init: dist != 256");
  85117. dist >>= 7; /* from now on, all distances are divided by 128 */
  85118. for ( ; code < D_CODES; code++) {
  85119. base_dist[code] = dist << 7;
  85120. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85121. _dist_code[256 + dist++] = (uch)code;
  85122. }
  85123. }
  85124. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85125. /* Construct the codes of the static literal tree */
  85126. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85127. n = 0;
  85128. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85129. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85130. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85131. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85132. /* Codes 286 and 287 do not exist, but we must include them in the
  85133. * tree construction to get a canonical Huffman tree (longest code
  85134. * all ones)
  85135. */
  85136. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85137. /* The static distance tree is trivial: */
  85138. for (n = 0; n < D_CODES; n++) {
  85139. static_dtree[n].Len = 5;
  85140. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85141. }
  85142. static_init_done = 1;
  85143. # ifdef GEN_TREES_H
  85144. gen_trees_header();
  85145. # endif
  85146. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85147. }
  85148. /* ===========================================================================
  85149. * Genererate the file trees.h describing the static trees.
  85150. */
  85151. #ifdef GEN_TREES_H
  85152. # ifndef DEBUG
  85153. # include <stdio.h>
  85154. # endif
  85155. # define SEPARATOR(i, last, width) \
  85156. ((i) == (last)? "\n};\n\n" : \
  85157. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85158. void gen_trees_header()
  85159. {
  85160. FILE *header = fopen("trees.h", "w");
  85161. int i;
  85162. Assert (header != NULL, "Can't open trees.h");
  85163. fprintf(header,
  85164. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85165. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85166. for (i = 0; i < L_CODES+2; i++) {
  85167. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85168. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85169. }
  85170. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85171. for (i = 0; i < D_CODES; i++) {
  85172. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85173. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85174. }
  85175. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85176. for (i = 0; i < DIST_CODE_LEN; i++) {
  85177. fprintf(header, "%2u%s", _dist_code[i],
  85178. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85179. }
  85180. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85181. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85182. fprintf(header, "%2u%s", _length_code[i],
  85183. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85184. }
  85185. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85186. for (i = 0; i < LENGTH_CODES; i++) {
  85187. fprintf(header, "%1u%s", base_length[i],
  85188. SEPARATOR(i, LENGTH_CODES-1, 20));
  85189. }
  85190. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85191. for (i = 0; i < D_CODES; i++) {
  85192. fprintf(header, "%5u%s", base_dist[i],
  85193. SEPARATOR(i, D_CODES-1, 10));
  85194. }
  85195. fclose(header);
  85196. }
  85197. #endif /* GEN_TREES_H */
  85198. /* ===========================================================================
  85199. * Initialize the tree data structures for a new zlib stream.
  85200. */
  85201. void _tr_init(deflate_state *s)
  85202. {
  85203. tr_static_init();
  85204. s->l_desc.dyn_tree = s->dyn_ltree;
  85205. s->l_desc.stat_desc = &static_l_desc;
  85206. s->d_desc.dyn_tree = s->dyn_dtree;
  85207. s->d_desc.stat_desc = &static_d_desc;
  85208. s->bl_desc.dyn_tree = s->bl_tree;
  85209. s->bl_desc.stat_desc = &static_bl_desc;
  85210. s->bi_buf = 0;
  85211. s->bi_valid = 0;
  85212. s->last_eob_len = 8; /* enough lookahead for inflate */
  85213. #ifdef DEBUG
  85214. s->compressed_len = 0L;
  85215. s->bits_sent = 0L;
  85216. #endif
  85217. /* Initialize the first block of the first file: */
  85218. init_block(s);
  85219. }
  85220. /* ===========================================================================
  85221. * Initialize a new block.
  85222. */
  85223. local void init_block (deflate_state *s)
  85224. {
  85225. int n; /* iterates over tree elements */
  85226. /* Initialize the trees. */
  85227. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85228. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85229. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85230. s->dyn_ltree[END_BLOCK].Freq = 1;
  85231. s->opt_len = s->static_len = 0L;
  85232. s->last_lit = s->matches = 0;
  85233. }
  85234. #define SMALLEST 1
  85235. /* Index within the heap array of least frequent node in the Huffman tree */
  85236. /* ===========================================================================
  85237. * Remove the smallest element from the heap and recreate the heap with
  85238. * one less element. Updates heap and heap_len.
  85239. */
  85240. #define pqremove(s, tree, top) \
  85241. {\
  85242. top = s->heap[SMALLEST]; \
  85243. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85244. pqdownheap(s, tree, SMALLEST); \
  85245. }
  85246. /* ===========================================================================
  85247. * Compares to subtrees, using the tree depth as tie breaker when
  85248. * the subtrees have equal frequency. This minimizes the worst case length.
  85249. */
  85250. #define smaller(tree, n, m, depth) \
  85251. (tree[n].Freq < tree[m].Freq || \
  85252. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85253. /* ===========================================================================
  85254. * Restore the heap property by moving down the tree starting at node k,
  85255. * exchanging a node with the smallest of its two sons if necessary, stopping
  85256. * when the heap property is re-established (each father smaller than its
  85257. * two sons).
  85258. */
  85259. local void pqdownheap (deflate_state *s,
  85260. ct_data *tree, /* the tree to restore */
  85261. int k) /* node to move down */
  85262. {
  85263. int v = s->heap[k];
  85264. int j = k << 1; /* left son of k */
  85265. while (j <= s->heap_len) {
  85266. /* Set j to the smallest of the two sons: */
  85267. if (j < s->heap_len &&
  85268. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85269. j++;
  85270. }
  85271. /* Exit if v is smaller than both sons */
  85272. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85273. /* Exchange v with the smallest son */
  85274. s->heap[k] = s->heap[j]; k = j;
  85275. /* And continue down the tree, setting j to the left son of k */
  85276. j <<= 1;
  85277. }
  85278. s->heap[k] = v;
  85279. }
  85280. /* ===========================================================================
  85281. * Compute the optimal bit lengths for a tree and update the total bit length
  85282. * for the current block.
  85283. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85284. * above are the tree nodes sorted by increasing frequency.
  85285. * OUT assertions: the field len is set to the optimal bit length, the
  85286. * array bl_count contains the frequencies for each bit length.
  85287. * The length opt_len is updated; static_len is also updated if stree is
  85288. * not null.
  85289. */
  85290. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85291. {
  85292. ct_data *tree = desc->dyn_tree;
  85293. int max_code = desc->max_code;
  85294. const ct_data *stree = desc->stat_desc->static_tree;
  85295. const intf *extra = desc->stat_desc->extra_bits;
  85296. int base = desc->stat_desc->extra_base;
  85297. int max_length = desc->stat_desc->max_length;
  85298. int h; /* heap index */
  85299. int n, m; /* iterate over the tree elements */
  85300. int bits; /* bit length */
  85301. int xbits; /* extra bits */
  85302. ush f; /* frequency */
  85303. int overflow = 0; /* number of elements with bit length too large */
  85304. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85305. /* In a first pass, compute the optimal bit lengths (which may
  85306. * overflow in the case of the bit length tree).
  85307. */
  85308. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85309. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85310. n = s->heap[h];
  85311. bits = tree[tree[n].Dad].Len + 1;
  85312. if (bits > max_length) bits = max_length, overflow++;
  85313. tree[n].Len = (ush)bits;
  85314. /* We overwrite tree[n].Dad which is no longer needed */
  85315. if (n > max_code) continue; /* not a leaf node */
  85316. s->bl_count[bits]++;
  85317. xbits = 0;
  85318. if (n >= base) xbits = extra[n-base];
  85319. f = tree[n].Freq;
  85320. s->opt_len += (ulg)f * (bits + xbits);
  85321. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85322. }
  85323. if (overflow == 0) return;
  85324. Trace((stderr,"\nbit length overflow\n"));
  85325. /* This happens for example on obj2 and pic of the Calgary corpus */
  85326. /* Find the first bit length which could increase: */
  85327. do {
  85328. bits = max_length-1;
  85329. while (s->bl_count[bits] == 0) bits--;
  85330. s->bl_count[bits]--; /* move one leaf down the tree */
  85331. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85332. s->bl_count[max_length]--;
  85333. /* The brother of the overflow item also moves one step up,
  85334. * but this does not affect bl_count[max_length]
  85335. */
  85336. overflow -= 2;
  85337. } while (overflow > 0);
  85338. /* Now recompute all bit lengths, scanning in increasing frequency.
  85339. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85340. * lengths instead of fixing only the wrong ones. This idea is taken
  85341. * from 'ar' written by Haruhiko Okumura.)
  85342. */
  85343. for (bits = max_length; bits != 0; bits--) {
  85344. n = s->bl_count[bits];
  85345. while (n != 0) {
  85346. m = s->heap[--h];
  85347. if (m > max_code) continue;
  85348. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85349. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85350. s->opt_len += ((long)bits - (long)tree[m].Len)
  85351. *(long)tree[m].Freq;
  85352. tree[m].Len = (ush)bits;
  85353. }
  85354. n--;
  85355. }
  85356. }
  85357. }
  85358. /* ===========================================================================
  85359. * Generate the codes for a given tree and bit counts (which need not be
  85360. * optimal).
  85361. * IN assertion: the array bl_count contains the bit length statistics for
  85362. * the given tree and the field len is set for all tree elements.
  85363. * OUT assertion: the field code is set for all tree elements of non
  85364. * zero code length.
  85365. */
  85366. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85367. int max_code, /* largest code with non zero frequency */
  85368. ushf *bl_count) /* number of codes at each bit length */
  85369. {
  85370. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85371. ush code = 0; /* running code value */
  85372. int bits; /* bit index */
  85373. int n; /* code index */
  85374. /* The distribution counts are first used to generate the code values
  85375. * without bit reversal.
  85376. */
  85377. for (bits = 1; bits <= MAX_BITS; bits++) {
  85378. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85379. }
  85380. /* Check that the bit counts in bl_count are consistent. The last code
  85381. * must be all ones.
  85382. */
  85383. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85384. "inconsistent bit counts");
  85385. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85386. for (n = 0; n <= max_code; n++) {
  85387. int len = tree[n].Len;
  85388. if (len == 0) continue;
  85389. /* Now reverse the bits */
  85390. tree[n].Code = bi_reverse(next_code[len]++, len);
  85391. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85392. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85393. }
  85394. }
  85395. /* ===========================================================================
  85396. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85397. * Update the total bit length for the current block.
  85398. * IN assertion: the field freq is set for all tree elements.
  85399. * OUT assertions: the fields len and code are set to the optimal bit length
  85400. * and corresponding code. The length opt_len is updated; static_len is
  85401. * also updated if stree is not null. The field max_code is set.
  85402. */
  85403. local void build_tree (deflate_state *s,
  85404. tree_desc *desc) /* the tree descriptor */
  85405. {
  85406. ct_data *tree = desc->dyn_tree;
  85407. const ct_data *stree = desc->stat_desc->static_tree;
  85408. int elems = desc->stat_desc->elems;
  85409. int n, m; /* iterate over heap elements */
  85410. int max_code = -1; /* largest code with non zero frequency */
  85411. int node; /* new node being created */
  85412. /* Construct the initial heap, with least frequent element in
  85413. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85414. * heap[0] is not used.
  85415. */
  85416. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85417. for (n = 0; n < elems; n++) {
  85418. if (tree[n].Freq != 0) {
  85419. s->heap[++(s->heap_len)] = max_code = n;
  85420. s->depth[n] = 0;
  85421. } else {
  85422. tree[n].Len = 0;
  85423. }
  85424. }
  85425. /* The pkzip format requires that at least one distance code exists,
  85426. * and that at least one bit should be sent even if there is only one
  85427. * possible code. So to avoid special checks later on we force at least
  85428. * two codes of non zero frequency.
  85429. */
  85430. while (s->heap_len < 2) {
  85431. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85432. tree[node].Freq = 1;
  85433. s->depth[node] = 0;
  85434. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85435. /* node is 0 or 1 so it does not have extra bits */
  85436. }
  85437. desc->max_code = max_code;
  85438. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85439. * establish sub-heaps of increasing lengths:
  85440. */
  85441. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85442. /* Construct the Huffman tree by repeatedly combining the least two
  85443. * frequent nodes.
  85444. */
  85445. node = elems; /* next internal node of the tree */
  85446. do {
  85447. pqremove(s, tree, n); /* n = node of least frequency */
  85448. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85449. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85450. s->heap[--(s->heap_max)] = m;
  85451. /* Create a new node father of n and m */
  85452. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85453. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85454. s->depth[n] : s->depth[m]) + 1);
  85455. tree[n].Dad = tree[m].Dad = (ush)node;
  85456. #ifdef DUMP_BL_TREE
  85457. if (tree == s->bl_tree) {
  85458. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85459. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85460. }
  85461. #endif
  85462. /* and insert the new node in the heap */
  85463. s->heap[SMALLEST] = node++;
  85464. pqdownheap(s, tree, SMALLEST);
  85465. } while (s->heap_len >= 2);
  85466. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85467. /* At this point, the fields freq and dad are set. We can now
  85468. * generate the bit lengths.
  85469. */
  85470. gen_bitlen(s, (tree_desc *)desc);
  85471. /* The field len is now set, we can generate the bit codes */
  85472. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85473. }
  85474. /* ===========================================================================
  85475. * Scan a literal or distance tree to determine the frequencies of the codes
  85476. * in the bit length tree.
  85477. */
  85478. local void scan_tree (deflate_state *s,
  85479. ct_data *tree, /* the tree to be scanned */
  85480. int max_code) /* and its largest code of non zero frequency */
  85481. {
  85482. int n; /* iterates over all tree elements */
  85483. int prevlen = -1; /* last emitted length */
  85484. int curlen; /* length of current code */
  85485. int nextlen = tree[0].Len; /* length of next code */
  85486. int count = 0; /* repeat count of the current code */
  85487. int max_count = 7; /* max repeat count */
  85488. int min_count = 4; /* min repeat count */
  85489. if (nextlen == 0) max_count = 138, min_count = 3;
  85490. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85491. for (n = 0; n <= max_code; n++) {
  85492. curlen = nextlen; nextlen = tree[n+1].Len;
  85493. if (++count < max_count && curlen == nextlen) {
  85494. continue;
  85495. } else if (count < min_count) {
  85496. s->bl_tree[curlen].Freq += count;
  85497. } else if (curlen != 0) {
  85498. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85499. s->bl_tree[REP_3_6].Freq++;
  85500. } else if (count <= 10) {
  85501. s->bl_tree[REPZ_3_10].Freq++;
  85502. } else {
  85503. s->bl_tree[REPZ_11_138].Freq++;
  85504. }
  85505. count = 0; prevlen = curlen;
  85506. if (nextlen == 0) {
  85507. max_count = 138, min_count = 3;
  85508. } else if (curlen == nextlen) {
  85509. max_count = 6, min_count = 3;
  85510. } else {
  85511. max_count = 7, min_count = 4;
  85512. }
  85513. }
  85514. }
  85515. /* ===========================================================================
  85516. * Send a literal or distance tree in compressed form, using the codes in
  85517. * bl_tree.
  85518. */
  85519. local void send_tree (deflate_state *s,
  85520. ct_data *tree, /* the tree to be scanned */
  85521. int max_code) /* and its largest code of non zero frequency */
  85522. {
  85523. int n; /* iterates over all tree elements */
  85524. int prevlen = -1; /* last emitted length */
  85525. int curlen; /* length of current code */
  85526. int nextlen = tree[0].Len; /* length of next code */
  85527. int count = 0; /* repeat count of the current code */
  85528. int max_count = 7; /* max repeat count */
  85529. int min_count = 4; /* min repeat count */
  85530. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85531. if (nextlen == 0) max_count = 138, min_count = 3;
  85532. for (n = 0; n <= max_code; n++) {
  85533. curlen = nextlen; nextlen = tree[n+1].Len;
  85534. if (++count < max_count && curlen == nextlen) {
  85535. continue;
  85536. } else if (count < min_count) {
  85537. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85538. } else if (curlen != 0) {
  85539. if (curlen != prevlen) {
  85540. send_code(s, curlen, s->bl_tree); count--;
  85541. }
  85542. Assert(count >= 3 && count <= 6, " 3_6?");
  85543. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85544. } else if (count <= 10) {
  85545. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85546. } else {
  85547. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85548. }
  85549. count = 0; prevlen = curlen;
  85550. if (nextlen == 0) {
  85551. max_count = 138, min_count = 3;
  85552. } else if (curlen == nextlen) {
  85553. max_count = 6, min_count = 3;
  85554. } else {
  85555. max_count = 7, min_count = 4;
  85556. }
  85557. }
  85558. }
  85559. /* ===========================================================================
  85560. * Construct the Huffman tree for the bit lengths and return the index in
  85561. * bl_order of the last bit length code to send.
  85562. */
  85563. local int build_bl_tree (deflate_state *s)
  85564. {
  85565. int max_blindex; /* index of last bit length code of non zero freq */
  85566. /* Determine the bit length frequencies for literal and distance trees */
  85567. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85568. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85569. /* Build the bit length tree: */
  85570. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85571. /* opt_len now includes the length of the tree representations, except
  85572. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85573. */
  85574. /* Determine the number of bit length codes to send. The pkzip format
  85575. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85576. * 3 but the actual value used is 4.)
  85577. */
  85578. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85579. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85580. }
  85581. /* Update opt_len to include the bit length tree and counts */
  85582. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85583. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85584. s->opt_len, s->static_len));
  85585. return max_blindex;
  85586. }
  85587. /* ===========================================================================
  85588. * Send the header for a block using dynamic Huffman trees: the counts, the
  85589. * lengths of the bit length codes, the literal tree and the distance tree.
  85590. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85591. */
  85592. local void send_all_trees (deflate_state *s,
  85593. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85594. {
  85595. int rank; /* index in bl_order */
  85596. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85597. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85598. "too many codes");
  85599. Tracev((stderr, "\nbl counts: "));
  85600. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85601. send_bits(s, dcodes-1, 5);
  85602. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85603. for (rank = 0; rank < blcodes; rank++) {
  85604. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85605. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85606. }
  85607. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85608. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85609. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85610. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85611. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85612. }
  85613. /* ===========================================================================
  85614. * Send a stored block
  85615. */
  85616. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85617. {
  85618. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85619. #ifdef DEBUG
  85620. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85621. s->compressed_len += (stored_len + 4) << 3;
  85622. #endif
  85623. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85624. }
  85625. /* ===========================================================================
  85626. * Send one empty static block to give enough lookahead for inflate.
  85627. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85628. * The current inflate code requires 9 bits of lookahead. If the
  85629. * last two codes for the previous block (real code plus EOB) were coded
  85630. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85631. * the last real code. In this case we send two empty static blocks instead
  85632. * of one. (There are no problems if the previous block is stored or fixed.)
  85633. * To simplify the code, we assume the worst case of last real code encoded
  85634. * on one bit only.
  85635. */
  85636. void _tr_align (deflate_state *s)
  85637. {
  85638. send_bits(s, STATIC_TREES<<1, 3);
  85639. send_code(s, END_BLOCK, static_ltree);
  85640. #ifdef DEBUG
  85641. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85642. #endif
  85643. bi_flush(s);
  85644. /* Of the 10 bits for the empty block, we have already sent
  85645. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85646. * the EOB of the previous block) was thus at least one plus the length
  85647. * of the EOB plus what we have just sent of the empty static block.
  85648. */
  85649. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85650. send_bits(s, STATIC_TREES<<1, 3);
  85651. send_code(s, END_BLOCK, static_ltree);
  85652. #ifdef DEBUG
  85653. s->compressed_len += 10L;
  85654. #endif
  85655. bi_flush(s);
  85656. }
  85657. s->last_eob_len = 7;
  85658. }
  85659. /* ===========================================================================
  85660. * Determine the best encoding for the current block: dynamic trees, static
  85661. * trees or store, and output the encoded block to the zip file.
  85662. */
  85663. void _tr_flush_block (deflate_state *s,
  85664. charf *buf, /* input block, or NULL if too old */
  85665. ulg stored_len, /* length of input block */
  85666. int eof) /* true if this is the last block for a file */
  85667. {
  85668. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85669. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85670. /* Build the Huffman trees unless a stored block is forced */
  85671. if (s->level > 0) {
  85672. /* Check if the file is binary or text */
  85673. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85674. set_data_type(s);
  85675. /* Construct the literal and distance trees */
  85676. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85677. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85678. s->static_len));
  85679. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85680. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85681. s->static_len));
  85682. /* At this point, opt_len and static_len are the total bit lengths of
  85683. * the compressed block data, excluding the tree representations.
  85684. */
  85685. /* Build the bit length tree for the above two trees, and get the index
  85686. * in bl_order of the last bit length code to send.
  85687. */
  85688. max_blindex = build_bl_tree(s);
  85689. /* Determine the best encoding. Compute the block lengths in bytes. */
  85690. opt_lenb = (s->opt_len+3+7)>>3;
  85691. static_lenb = (s->static_len+3+7)>>3;
  85692. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85693. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85694. s->last_lit));
  85695. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85696. } else {
  85697. Assert(buf != (char*)0, "lost buf");
  85698. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85699. }
  85700. #ifdef FORCE_STORED
  85701. if (buf != (char*)0) { /* force stored block */
  85702. #else
  85703. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85704. /* 4: two words for the lengths */
  85705. #endif
  85706. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85707. * Otherwise we can't have processed more than WSIZE input bytes since
  85708. * the last block flush, because compression would have been
  85709. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85710. * transform a block into a stored block.
  85711. */
  85712. _tr_stored_block(s, buf, stored_len, eof);
  85713. #ifdef FORCE_STATIC
  85714. } else if (static_lenb >= 0) { /* force static trees */
  85715. #else
  85716. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85717. #endif
  85718. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85719. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85720. #ifdef DEBUG
  85721. s->compressed_len += 3 + s->static_len;
  85722. #endif
  85723. } else {
  85724. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85725. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85726. max_blindex+1);
  85727. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85728. #ifdef DEBUG
  85729. s->compressed_len += 3 + s->opt_len;
  85730. #endif
  85731. }
  85732. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85733. /* The above check is made mod 2^32, for files larger than 512 MB
  85734. * and uLong implemented on 32 bits.
  85735. */
  85736. init_block(s);
  85737. if (eof) {
  85738. bi_windup(s);
  85739. #ifdef DEBUG
  85740. s->compressed_len += 7; /* align on byte boundary */
  85741. #endif
  85742. }
  85743. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85744. s->compressed_len-7*eof));
  85745. }
  85746. /* ===========================================================================
  85747. * Save the match info and tally the frequency counts. Return true if
  85748. * the current block must be flushed.
  85749. */
  85750. int _tr_tally (deflate_state *s,
  85751. unsigned dist, /* distance of matched string */
  85752. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85753. {
  85754. s->d_buf[s->last_lit] = (ush)dist;
  85755. s->l_buf[s->last_lit++] = (uch)lc;
  85756. if (dist == 0) {
  85757. /* lc is the unmatched char */
  85758. s->dyn_ltree[lc].Freq++;
  85759. } else {
  85760. s->matches++;
  85761. /* Here, lc is the match length - MIN_MATCH */
  85762. dist--; /* dist = match distance - 1 */
  85763. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85764. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85765. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85766. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85767. s->dyn_dtree[d_code(dist)].Freq++;
  85768. }
  85769. #ifdef TRUNCATE_BLOCK
  85770. /* Try to guess if it is profitable to stop the current block here */
  85771. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85772. /* Compute an upper bound for the compressed length */
  85773. ulg out_length = (ulg)s->last_lit*8L;
  85774. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85775. int dcode;
  85776. for (dcode = 0; dcode < D_CODES; dcode++) {
  85777. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85778. (5L+extra_dbits[dcode]);
  85779. }
  85780. out_length >>= 3;
  85781. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85782. s->last_lit, in_length, out_length,
  85783. 100L - out_length*100L/in_length));
  85784. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85785. }
  85786. #endif
  85787. return (s->last_lit == s->lit_bufsize-1);
  85788. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85789. * on 16 bit machines and because stored blocks are restricted to
  85790. * 64K-1 bytes.
  85791. */
  85792. }
  85793. /* ===========================================================================
  85794. * Send the block data compressed using the given Huffman trees
  85795. */
  85796. local void compress_block (deflate_state *s,
  85797. ct_data *ltree, /* literal tree */
  85798. ct_data *dtree) /* distance tree */
  85799. {
  85800. unsigned dist; /* distance of matched string */
  85801. int lc; /* match length or unmatched char (if dist == 0) */
  85802. unsigned lx = 0; /* running index in l_buf */
  85803. unsigned code; /* the code to send */
  85804. int extra; /* number of extra bits to send */
  85805. if (s->last_lit != 0) do {
  85806. dist = s->d_buf[lx];
  85807. lc = s->l_buf[lx++];
  85808. if (dist == 0) {
  85809. send_code(s, lc, ltree); /* send a literal byte */
  85810. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85811. } else {
  85812. /* Here, lc is the match length - MIN_MATCH */
  85813. code = _length_code[lc];
  85814. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85815. extra = extra_lbits[code];
  85816. if (extra != 0) {
  85817. lc -= base_length[code];
  85818. send_bits(s, lc, extra); /* send the extra length bits */
  85819. }
  85820. dist--; /* dist is now the match distance - 1 */
  85821. code = d_code(dist);
  85822. Assert (code < D_CODES, "bad d_code");
  85823. send_code(s, code, dtree); /* send the distance code */
  85824. extra = extra_dbits[code];
  85825. if (extra != 0) {
  85826. dist -= base_dist[code];
  85827. send_bits(s, dist, extra); /* send the extra distance bits */
  85828. }
  85829. } /* literal or match pair ? */
  85830. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85831. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85832. "pendingBuf overflow");
  85833. } while (lx < s->last_lit);
  85834. send_code(s, END_BLOCK, ltree);
  85835. s->last_eob_len = ltree[END_BLOCK].Len;
  85836. }
  85837. /* ===========================================================================
  85838. * Set the data type to BINARY or TEXT, using a crude approximation:
  85839. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85840. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85841. * IN assertion: the fields Freq of dyn_ltree are set.
  85842. */
  85843. local void set_data_type (deflate_state *s)
  85844. {
  85845. int n;
  85846. for (n = 0; n < 9; n++)
  85847. if (s->dyn_ltree[n].Freq != 0)
  85848. break;
  85849. if (n == 9)
  85850. for (n = 14; n < 32; n++)
  85851. if (s->dyn_ltree[n].Freq != 0)
  85852. break;
  85853. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85854. }
  85855. /* ===========================================================================
  85856. * Reverse the first len bits of a code, using straightforward code (a faster
  85857. * method would use a table)
  85858. * IN assertion: 1 <= len <= 15
  85859. */
  85860. local unsigned bi_reverse (unsigned code, int len)
  85861. {
  85862. register unsigned res = 0;
  85863. do {
  85864. res |= code & 1;
  85865. code >>= 1, res <<= 1;
  85866. } while (--len > 0);
  85867. return res >> 1;
  85868. }
  85869. /* ===========================================================================
  85870. * Flush the bit buffer, keeping at most 7 bits in it.
  85871. */
  85872. local void bi_flush (deflate_state *s)
  85873. {
  85874. if (s->bi_valid == 16) {
  85875. put_short(s, s->bi_buf);
  85876. s->bi_buf = 0;
  85877. s->bi_valid = 0;
  85878. } else if (s->bi_valid >= 8) {
  85879. put_byte(s, (Byte)s->bi_buf);
  85880. s->bi_buf >>= 8;
  85881. s->bi_valid -= 8;
  85882. }
  85883. }
  85884. /* ===========================================================================
  85885. * Flush the bit buffer and align the output on a byte boundary
  85886. */
  85887. local void bi_windup (deflate_state *s)
  85888. {
  85889. if (s->bi_valid > 8) {
  85890. put_short(s, s->bi_buf);
  85891. } else if (s->bi_valid > 0) {
  85892. put_byte(s, (Byte)s->bi_buf);
  85893. }
  85894. s->bi_buf = 0;
  85895. s->bi_valid = 0;
  85896. #ifdef DEBUG
  85897. s->bits_sent = (s->bits_sent+7) & ~7;
  85898. #endif
  85899. }
  85900. /* ===========================================================================
  85901. * Copy a stored block, storing first the length and its
  85902. * one's complement if requested.
  85903. */
  85904. local void copy_block(deflate_state *s,
  85905. charf *buf, /* the input data */
  85906. unsigned len, /* its length */
  85907. int header) /* true if block header must be written */
  85908. {
  85909. bi_windup(s); /* align on byte boundary */
  85910. s->last_eob_len = 8; /* enough lookahead for inflate */
  85911. if (header) {
  85912. put_short(s, (ush)len);
  85913. put_short(s, (ush)~len);
  85914. #ifdef DEBUG
  85915. s->bits_sent += 2*16;
  85916. #endif
  85917. }
  85918. #ifdef DEBUG
  85919. s->bits_sent += (ulg)len<<3;
  85920. #endif
  85921. while (len--) {
  85922. put_byte(s, *buf++);
  85923. }
  85924. }
  85925. /*** End of inlined file: trees.c ***/
  85926. /*** Start of inlined file: zutil.c ***/
  85927. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85928. #ifndef NO_DUMMY_DECL
  85929. struct internal_state {int dummy;}; /* for buggy compilers */
  85930. #endif
  85931. const char * const z_errmsg[10] = {
  85932. "need dictionary", /* Z_NEED_DICT 2 */
  85933. "stream end", /* Z_STREAM_END 1 */
  85934. "", /* Z_OK 0 */
  85935. "file error", /* Z_ERRNO (-1) */
  85936. "stream error", /* Z_STREAM_ERROR (-2) */
  85937. "data error", /* Z_DATA_ERROR (-3) */
  85938. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85939. "buffer error", /* Z_BUF_ERROR (-5) */
  85940. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85941. ""};
  85942. /*const char * ZEXPORT zlibVersion()
  85943. {
  85944. return ZLIB_VERSION;
  85945. }
  85946. uLong ZEXPORT zlibCompileFlags()
  85947. {
  85948. uLong flags;
  85949. flags = 0;
  85950. switch (sizeof(uInt)) {
  85951. case 2: break;
  85952. case 4: flags += 1; break;
  85953. case 8: flags += 2; break;
  85954. default: flags += 3;
  85955. }
  85956. switch (sizeof(uLong)) {
  85957. case 2: break;
  85958. case 4: flags += 1 << 2; break;
  85959. case 8: flags += 2 << 2; break;
  85960. default: flags += 3 << 2;
  85961. }
  85962. switch (sizeof(voidpf)) {
  85963. case 2: break;
  85964. case 4: flags += 1 << 4; break;
  85965. case 8: flags += 2 << 4; break;
  85966. default: flags += 3 << 4;
  85967. }
  85968. switch (sizeof(z_off_t)) {
  85969. case 2: break;
  85970. case 4: flags += 1 << 6; break;
  85971. case 8: flags += 2 << 6; break;
  85972. default: flags += 3 << 6;
  85973. }
  85974. #ifdef DEBUG
  85975. flags += 1 << 8;
  85976. #endif
  85977. #if defined(ASMV) || defined(ASMINF)
  85978. flags += 1 << 9;
  85979. #endif
  85980. #ifdef ZLIB_WINAPI
  85981. flags += 1 << 10;
  85982. #endif
  85983. #ifdef BUILDFIXED
  85984. flags += 1 << 12;
  85985. #endif
  85986. #ifdef DYNAMIC_CRC_TABLE
  85987. flags += 1 << 13;
  85988. #endif
  85989. #ifdef NO_GZCOMPRESS
  85990. flags += 1L << 16;
  85991. #endif
  85992. #ifdef NO_GZIP
  85993. flags += 1L << 17;
  85994. #endif
  85995. #ifdef PKZIP_BUG_WORKAROUND
  85996. flags += 1L << 20;
  85997. #endif
  85998. #ifdef FASTEST
  85999. flags += 1L << 21;
  86000. #endif
  86001. #ifdef STDC
  86002. # ifdef NO_vsnprintf
  86003. flags += 1L << 25;
  86004. # ifdef HAS_vsprintf_void
  86005. flags += 1L << 26;
  86006. # endif
  86007. # else
  86008. # ifdef HAS_vsnprintf_void
  86009. flags += 1L << 26;
  86010. # endif
  86011. # endif
  86012. #else
  86013. flags += 1L << 24;
  86014. # ifdef NO_snprintf
  86015. flags += 1L << 25;
  86016. # ifdef HAS_sprintf_void
  86017. flags += 1L << 26;
  86018. # endif
  86019. # else
  86020. # ifdef HAS_snprintf_void
  86021. flags += 1L << 26;
  86022. # endif
  86023. # endif
  86024. #endif
  86025. return flags;
  86026. }*/
  86027. #ifdef DEBUG
  86028. # ifndef verbose
  86029. # define verbose 0
  86030. # endif
  86031. int z_verbose = verbose;
  86032. void z_error (const char *m)
  86033. {
  86034. fprintf(stderr, "%s\n", m);
  86035. exit(1);
  86036. }
  86037. #endif
  86038. /* exported to allow conversion of error code to string for compress() and
  86039. * uncompress()
  86040. */
  86041. const char * ZEXPORT zError(int err)
  86042. {
  86043. return ERR_MSG(err);
  86044. }
  86045. #if defined(_WIN32_WCE)
  86046. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86047. * errno. We define it as a global variable to simplify porting.
  86048. * Its value is always 0 and should not be used.
  86049. */
  86050. int errno = 0;
  86051. #endif
  86052. #ifndef HAVE_MEMCPY
  86053. void zmemcpy(dest, source, len)
  86054. Bytef* dest;
  86055. const Bytef* source;
  86056. uInt len;
  86057. {
  86058. if (len == 0) return;
  86059. do {
  86060. *dest++ = *source++; /* ??? to be unrolled */
  86061. } while (--len != 0);
  86062. }
  86063. int zmemcmp(s1, s2, len)
  86064. const Bytef* s1;
  86065. const Bytef* s2;
  86066. uInt len;
  86067. {
  86068. uInt j;
  86069. for (j = 0; j < len; j++) {
  86070. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86071. }
  86072. return 0;
  86073. }
  86074. void zmemzero(dest, len)
  86075. Bytef* dest;
  86076. uInt len;
  86077. {
  86078. if (len == 0) return;
  86079. do {
  86080. *dest++ = 0; /* ??? to be unrolled */
  86081. } while (--len != 0);
  86082. }
  86083. #endif
  86084. #ifdef SYS16BIT
  86085. #ifdef __TURBOC__
  86086. /* Turbo C in 16-bit mode */
  86087. # define MY_ZCALLOC
  86088. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86089. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86090. * must fix the pointer. Warning: the pointer must be put back to its
  86091. * original form in order to free it, use zcfree().
  86092. */
  86093. #define MAX_PTR 10
  86094. /* 10*64K = 640K */
  86095. local int next_ptr = 0;
  86096. typedef struct ptr_table_s {
  86097. voidpf org_ptr;
  86098. voidpf new_ptr;
  86099. } ptr_table;
  86100. local ptr_table table[MAX_PTR];
  86101. /* This table is used to remember the original form of pointers
  86102. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86103. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86104. * protected from concurrent access. This hack doesn't work anyway on
  86105. * a protected system like OS/2. Use Microsoft C instead.
  86106. */
  86107. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86108. {
  86109. voidpf buf = opaque; /* just to make some compilers happy */
  86110. ulg bsize = (ulg)items*size;
  86111. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86112. * will return a usable pointer which doesn't have to be normalized.
  86113. */
  86114. if (bsize < 65520L) {
  86115. buf = farmalloc(bsize);
  86116. if (*(ush*)&buf != 0) return buf;
  86117. } else {
  86118. buf = farmalloc(bsize + 16L);
  86119. }
  86120. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86121. table[next_ptr].org_ptr = buf;
  86122. /* Normalize the pointer to seg:0 */
  86123. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86124. *(ush*)&buf = 0;
  86125. table[next_ptr++].new_ptr = buf;
  86126. return buf;
  86127. }
  86128. void zcfree (voidpf opaque, voidpf ptr)
  86129. {
  86130. int n;
  86131. if (*(ush*)&ptr != 0) { /* object < 64K */
  86132. farfree(ptr);
  86133. return;
  86134. }
  86135. /* Find the original pointer */
  86136. for (n = 0; n < next_ptr; n++) {
  86137. if (ptr != table[n].new_ptr) continue;
  86138. farfree(table[n].org_ptr);
  86139. while (++n < next_ptr) {
  86140. table[n-1] = table[n];
  86141. }
  86142. next_ptr--;
  86143. return;
  86144. }
  86145. ptr = opaque; /* just to make some compilers happy */
  86146. Assert(0, "zcfree: ptr not found");
  86147. }
  86148. #endif /* __TURBOC__ */
  86149. #ifdef M_I86
  86150. /* Microsoft C in 16-bit mode */
  86151. # define MY_ZCALLOC
  86152. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86153. # define _halloc halloc
  86154. # define _hfree hfree
  86155. #endif
  86156. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86157. {
  86158. if (opaque) opaque = 0; /* to make compiler happy */
  86159. return _halloc((long)items, size);
  86160. }
  86161. void zcfree (voidpf opaque, voidpf ptr)
  86162. {
  86163. if (opaque) opaque = 0; /* to make compiler happy */
  86164. _hfree(ptr);
  86165. }
  86166. #endif /* M_I86 */
  86167. #endif /* SYS16BIT */
  86168. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86169. #ifndef STDC
  86170. extern voidp malloc OF((uInt size));
  86171. extern voidp calloc OF((uInt items, uInt size));
  86172. extern void free OF((voidpf ptr));
  86173. #endif
  86174. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86175. {
  86176. if (opaque) items += size - size; /* make compiler happy */
  86177. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86178. (voidpf)calloc(items, size);
  86179. }
  86180. void zcfree (voidpf opaque, voidpf ptr)
  86181. {
  86182. free(ptr);
  86183. if (opaque) return; /* make compiler happy */
  86184. }
  86185. #endif /* MY_ZCALLOC */
  86186. /*** End of inlined file: zutil.c ***/
  86187. #undef Byte
  86188. #else
  86189. #include <zlib.h>
  86190. #endif
  86191. }
  86192. #if JUCE_MSVC
  86193. #pragma warning (pop)
  86194. #endif
  86195. BEGIN_JUCE_NAMESPACE
  86196. // internal helper object that holds the zlib structures so they don't have to be
  86197. // included publicly.
  86198. class GZIPDecompressorInputStream::GZIPDecompressHelper
  86199. {
  86200. public:
  86201. GZIPDecompressHelper (const bool noWrap)
  86202. : finished (true),
  86203. needsDictionary (false),
  86204. error (true),
  86205. streamIsValid (false),
  86206. data (0),
  86207. dataSize (0)
  86208. {
  86209. using namespace zlibNamespace;
  86210. zerostruct (stream);
  86211. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86212. finished = error = ! streamIsValid;
  86213. }
  86214. ~GZIPDecompressHelper()
  86215. {
  86216. using namespace zlibNamespace;
  86217. if (streamIsValid)
  86218. inflateEnd (&stream);
  86219. }
  86220. bool needsInput() const throw() { return dataSize <= 0; }
  86221. void setInput (uint8* const data_, const int size) throw()
  86222. {
  86223. data = data_;
  86224. dataSize = size;
  86225. }
  86226. int doNextBlock (uint8* const dest, const int destSize)
  86227. {
  86228. using namespace zlibNamespace;
  86229. if (streamIsValid && data != 0 && ! finished)
  86230. {
  86231. stream.next_in = data;
  86232. stream.next_out = dest;
  86233. stream.avail_in = dataSize;
  86234. stream.avail_out = destSize;
  86235. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86236. {
  86237. case Z_STREAM_END:
  86238. finished = true;
  86239. // deliberate fall-through
  86240. case Z_OK:
  86241. data += dataSize - stream.avail_in;
  86242. dataSize = stream.avail_in;
  86243. return destSize - stream.avail_out;
  86244. case Z_NEED_DICT:
  86245. needsDictionary = true;
  86246. data += dataSize - stream.avail_in;
  86247. dataSize = stream.avail_in;
  86248. break;
  86249. case Z_DATA_ERROR:
  86250. case Z_MEM_ERROR:
  86251. error = true;
  86252. default:
  86253. break;
  86254. }
  86255. }
  86256. return 0;
  86257. }
  86258. bool finished, needsDictionary, error, streamIsValid;
  86259. enum { gzipDecompBufferSize = 32768 };
  86260. private:
  86261. zlibNamespace::z_stream stream;
  86262. uint8* data;
  86263. int dataSize;
  86264. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86265. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86266. };
  86267. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86268. const bool deleteSourceWhenDestroyed,
  86269. const bool noWrap_,
  86270. const int64 uncompressedStreamLength_)
  86271. : sourceStream (sourceStream_),
  86272. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86273. uncompressedStreamLength (uncompressedStreamLength_),
  86274. noWrap (noWrap_),
  86275. isEof (false),
  86276. activeBufferSize (0),
  86277. originalSourcePos (sourceStream_->getPosition()),
  86278. currentPos (0),
  86279. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86280. helper (new GZIPDecompressHelper (noWrap_))
  86281. {
  86282. }
  86283. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  86284. : sourceStream (&sourceStream_),
  86285. uncompressedStreamLength (-1),
  86286. noWrap (false),
  86287. isEof (false),
  86288. activeBufferSize (0),
  86289. originalSourcePos (sourceStream_.getPosition()),
  86290. currentPos (0),
  86291. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86292. helper (new GZIPDecompressHelper (false))
  86293. {
  86294. }
  86295. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86296. {
  86297. }
  86298. int64 GZIPDecompressorInputStream::getTotalLength()
  86299. {
  86300. return uncompressedStreamLength;
  86301. }
  86302. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86303. {
  86304. if ((howMany > 0) && ! isEof)
  86305. {
  86306. jassert (destBuffer != 0);
  86307. if (destBuffer != 0)
  86308. {
  86309. int numRead = 0;
  86310. uint8* d = static_cast <uint8*> (destBuffer);
  86311. while (! helper->error)
  86312. {
  86313. const int n = helper->doNextBlock (d, howMany);
  86314. currentPos += n;
  86315. if (n == 0)
  86316. {
  86317. if (helper->finished || helper->needsDictionary)
  86318. {
  86319. isEof = true;
  86320. return numRead;
  86321. }
  86322. if (helper->needsInput())
  86323. {
  86324. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  86325. if (activeBufferSize > 0)
  86326. {
  86327. helper->setInput (buffer, activeBufferSize);
  86328. }
  86329. else
  86330. {
  86331. isEof = true;
  86332. return numRead;
  86333. }
  86334. }
  86335. }
  86336. else
  86337. {
  86338. numRead += n;
  86339. howMany -= n;
  86340. d += n;
  86341. if (howMany <= 0)
  86342. return numRead;
  86343. }
  86344. }
  86345. }
  86346. }
  86347. return 0;
  86348. }
  86349. bool GZIPDecompressorInputStream::isExhausted()
  86350. {
  86351. return helper->error || isEof;
  86352. }
  86353. int64 GZIPDecompressorInputStream::getPosition()
  86354. {
  86355. return currentPos;
  86356. }
  86357. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86358. {
  86359. if (newPos < currentPos)
  86360. {
  86361. // to go backwards, reset the stream and start again..
  86362. isEof = false;
  86363. activeBufferSize = 0;
  86364. currentPos = 0;
  86365. helper = new GZIPDecompressHelper (noWrap);
  86366. sourceStream->setPosition (originalSourcePos);
  86367. }
  86368. skipNextBytes (newPos - currentPos);
  86369. return true;
  86370. }
  86371. END_JUCE_NAMESPACE
  86372. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86373. #endif
  86374. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86375. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86376. #if JUCE_USE_FLAC
  86377. #if JUCE_WINDOWS
  86378. #include <windows.h>
  86379. #endif
  86380. namespace FlacNamespace
  86381. {
  86382. #if JUCE_INCLUDE_FLAC_CODE
  86383. #if JUCE_MSVC
  86384. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86385. #endif
  86386. #define FLAC__NO_DLL 1
  86387. #if ! defined (SIZE_MAX)
  86388. #define SIZE_MAX 0xffffffff
  86389. #endif
  86390. #define __STDC_LIMIT_MACROS 1
  86391. /*** Start of inlined file: all.h ***/
  86392. #ifndef FLAC__ALL_H
  86393. #define FLAC__ALL_H
  86394. /*** Start of inlined file: export.h ***/
  86395. #ifndef FLAC__EXPORT_H
  86396. #define FLAC__EXPORT_H
  86397. /** \file include/FLAC/export.h
  86398. *
  86399. * \brief
  86400. * This module contains #defines and symbols for exporting function
  86401. * calls, and providing version information and compiled-in features.
  86402. *
  86403. * See the \link flac_export export \endlink module.
  86404. */
  86405. /** \defgroup flac_export FLAC/export.h: export symbols
  86406. * \ingroup flac
  86407. *
  86408. * \brief
  86409. * This module contains #defines and symbols for exporting function
  86410. * calls, and providing version information and compiled-in features.
  86411. *
  86412. * If you are compiling with MSVC and will link to the static library
  86413. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86414. * make sure the symbols are exported properly.
  86415. *
  86416. * \{
  86417. */
  86418. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86419. #define FLAC_API
  86420. #else
  86421. #ifdef FLAC_API_EXPORTS
  86422. #define FLAC_API _declspec(dllexport)
  86423. #else
  86424. #define FLAC_API _declspec(dllimport)
  86425. #endif
  86426. #endif
  86427. /** These #defines will mirror the libtool-based library version number, see
  86428. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86429. */
  86430. #define FLAC_API_VERSION_CURRENT 10
  86431. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86432. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86433. #ifdef __cplusplus
  86434. extern "C" {
  86435. #endif
  86436. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86437. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86438. #ifdef __cplusplus
  86439. }
  86440. #endif
  86441. /* \} */
  86442. #endif
  86443. /*** End of inlined file: export.h ***/
  86444. /*** Start of inlined file: assert.h ***/
  86445. #ifndef FLAC__ASSERT_H
  86446. #define FLAC__ASSERT_H
  86447. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86448. #ifdef DEBUG
  86449. #include <assert.h>
  86450. #define FLAC__ASSERT(x) assert(x)
  86451. #define FLAC__ASSERT_DECLARATION(x) x
  86452. #else
  86453. #define FLAC__ASSERT(x)
  86454. #define FLAC__ASSERT_DECLARATION(x)
  86455. #endif
  86456. #endif
  86457. /*** End of inlined file: assert.h ***/
  86458. /*** Start of inlined file: callback.h ***/
  86459. #ifndef FLAC__CALLBACK_H
  86460. #define FLAC__CALLBACK_H
  86461. /*** Start of inlined file: ordinals.h ***/
  86462. #ifndef FLAC__ORDINALS_H
  86463. #define FLAC__ORDINALS_H
  86464. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86465. #include <inttypes.h>
  86466. #endif
  86467. typedef signed char FLAC__int8;
  86468. typedef unsigned char FLAC__uint8;
  86469. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86470. typedef __int16 FLAC__int16;
  86471. typedef __int32 FLAC__int32;
  86472. typedef __int64 FLAC__int64;
  86473. typedef unsigned __int16 FLAC__uint16;
  86474. typedef unsigned __int32 FLAC__uint32;
  86475. typedef unsigned __int64 FLAC__uint64;
  86476. #elif defined(__EMX__)
  86477. typedef short FLAC__int16;
  86478. typedef long FLAC__int32;
  86479. typedef long long FLAC__int64;
  86480. typedef unsigned short FLAC__uint16;
  86481. typedef unsigned long FLAC__uint32;
  86482. typedef unsigned long long FLAC__uint64;
  86483. #else
  86484. typedef int16_t FLAC__int16;
  86485. typedef int32_t FLAC__int32;
  86486. typedef int64_t FLAC__int64;
  86487. typedef uint16_t FLAC__uint16;
  86488. typedef uint32_t FLAC__uint32;
  86489. typedef uint64_t FLAC__uint64;
  86490. #endif
  86491. typedef int FLAC__bool;
  86492. typedef FLAC__uint8 FLAC__byte;
  86493. #ifdef true
  86494. #undef true
  86495. #endif
  86496. #ifdef false
  86497. #undef false
  86498. #endif
  86499. #ifndef __cplusplus
  86500. #define true 1
  86501. #define false 0
  86502. #endif
  86503. #endif
  86504. /*** End of inlined file: ordinals.h ***/
  86505. #include <stdlib.h> /* for size_t */
  86506. /** \file include/FLAC/callback.h
  86507. *
  86508. * \brief
  86509. * This module defines the structures for describing I/O callbacks
  86510. * to the other FLAC interfaces.
  86511. *
  86512. * See the detailed documentation for callbacks in the
  86513. * \link flac_callbacks callbacks \endlink module.
  86514. */
  86515. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86516. * \ingroup flac
  86517. *
  86518. * \brief
  86519. * This module defines the structures for describing I/O callbacks
  86520. * to the other FLAC interfaces.
  86521. *
  86522. * The purpose of the I/O callback functions is to create a common way
  86523. * for the metadata interfaces to handle I/O.
  86524. *
  86525. * Originally the metadata interfaces required filenames as the way of
  86526. * specifying FLAC files to operate on. This is problematic in some
  86527. * environments so there is an additional option to specify a set of
  86528. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86529. *
  86530. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86531. * opaque structure for a data source.
  86532. *
  86533. * The callback function prototypes are similar (but not identical) to the
  86534. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86535. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86536. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86537. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86538. * is required. \warning You generally CANNOT directly use fseek or ftell
  86539. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86540. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86541. * large files. You will have to find an equivalent function (e.g. ftello),
  86542. * or write a wrapper. The same is true for feof() since this is usually
  86543. * implemented as a macro, not as a function whose address can be taken.
  86544. *
  86545. * \{
  86546. */
  86547. #ifdef __cplusplus
  86548. extern "C" {
  86549. #endif
  86550. /** This is the opaque handle type used by the callbacks. Typically
  86551. * this is a \c FILE* or address of a file descriptor.
  86552. */
  86553. typedef void* FLAC__IOHandle;
  86554. /** Signature for the read callback.
  86555. * The signature and semantics match POSIX fread() implementations
  86556. * and can generally be used interchangeably.
  86557. *
  86558. * \param ptr The address of the read buffer.
  86559. * \param size The size of the records to be read.
  86560. * \param nmemb The number of records to be read.
  86561. * \param handle The handle to the data source.
  86562. * \retval size_t
  86563. * The number of records read.
  86564. */
  86565. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86566. /** Signature for the write callback.
  86567. * The signature and semantics match POSIX fwrite() implementations
  86568. * and can generally be used interchangeably.
  86569. *
  86570. * \param ptr The address of the write buffer.
  86571. * \param size The size of the records to be written.
  86572. * \param nmemb The number of records to be written.
  86573. * \param handle The handle to the data source.
  86574. * \retval size_t
  86575. * The number of records written.
  86576. */
  86577. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86578. /** Signature for the seek callback.
  86579. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86580. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86581. * and 32-bits wide.
  86582. *
  86583. * \param handle The handle to the data source.
  86584. * \param offset The new position, relative to \a whence
  86585. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86586. * \retval int
  86587. * \c 0 on success, \c -1 on error.
  86588. */
  86589. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86590. /** Signature for the tell callback.
  86591. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86592. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86593. * and 32-bits wide.
  86594. *
  86595. * \param handle The handle to the data source.
  86596. * \retval FLAC__int64
  86597. * The current position on success, \c -1 on error.
  86598. */
  86599. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86600. /** Signature for the EOF callback.
  86601. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86602. * on many systems, feof() is a macro, so in this case a wrapper function
  86603. * must be provided instead.
  86604. *
  86605. * \param handle The handle to the data source.
  86606. * \retval int
  86607. * \c 0 if not at end of file, nonzero if at end of file.
  86608. */
  86609. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86610. /** Signature for the close callback.
  86611. * The signature and semantics match POSIX fclose() implementations
  86612. * and can generally be used interchangeably.
  86613. *
  86614. * \param handle The handle to the data source.
  86615. * \retval int
  86616. * \c 0 on success, \c EOF on error.
  86617. */
  86618. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86619. /** A structure for holding a set of callbacks.
  86620. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86621. * describe which of the callbacks are required. The ones that are not
  86622. * required may be set to NULL.
  86623. *
  86624. * If the seek requirement for an interface is optional, you can signify that
  86625. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86626. */
  86627. typedef struct {
  86628. FLAC__IOCallback_Read read;
  86629. FLAC__IOCallback_Write write;
  86630. FLAC__IOCallback_Seek seek;
  86631. FLAC__IOCallback_Tell tell;
  86632. FLAC__IOCallback_Eof eof;
  86633. FLAC__IOCallback_Close close;
  86634. } FLAC__IOCallbacks;
  86635. /* \} */
  86636. #ifdef __cplusplus
  86637. }
  86638. #endif
  86639. #endif
  86640. /*** End of inlined file: callback.h ***/
  86641. /*** Start of inlined file: format.h ***/
  86642. #ifndef FLAC__FORMAT_H
  86643. #define FLAC__FORMAT_H
  86644. #ifdef __cplusplus
  86645. extern "C" {
  86646. #endif
  86647. /** \file include/FLAC/format.h
  86648. *
  86649. * \brief
  86650. * This module contains structure definitions for the representation
  86651. * of FLAC format components in memory. These are the basic
  86652. * structures used by the rest of the interfaces.
  86653. *
  86654. * See the detailed documentation in the
  86655. * \link flac_format format \endlink module.
  86656. */
  86657. /** \defgroup flac_format FLAC/format.h: format components
  86658. * \ingroup flac
  86659. *
  86660. * \brief
  86661. * This module contains structure definitions for the representation
  86662. * of FLAC format components in memory. These are the basic
  86663. * structures used by the rest of the interfaces.
  86664. *
  86665. * First, you should be familiar with the
  86666. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86667. * follow directly from the specification. As a user of libFLAC, the
  86668. * interesting parts really are the structures that describe the frame
  86669. * header and metadata blocks.
  86670. *
  86671. * The format structures here are very primitive, designed to store
  86672. * information in an efficient way. Reading information from the
  86673. * structures is easy but creating or modifying them directly is
  86674. * more complex. For the most part, as a user of a library, editing
  86675. * is not necessary; however, for metadata blocks it is, so there are
  86676. * convenience functions provided in the \link flac_metadata metadata
  86677. * module \endlink to simplify the manipulation of metadata blocks.
  86678. *
  86679. * \note
  86680. * It's not the best convention, but symbols ending in _LEN are in bits
  86681. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86682. * global variables because they are usually used when declaring byte
  86683. * arrays and some compilers require compile-time knowledge of array
  86684. * sizes when declared on the stack.
  86685. *
  86686. * \{
  86687. */
  86688. /*
  86689. Most of the values described in this file are defined by the FLAC
  86690. format specification. There is nothing to tune here.
  86691. */
  86692. /** The largest legal metadata type code. */
  86693. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86694. /** The minimum block size, in samples, permitted by the format. */
  86695. #define FLAC__MIN_BLOCK_SIZE (16u)
  86696. /** The maximum block size, in samples, permitted by the format. */
  86697. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86698. /** The maximum block size, in samples, permitted by the FLAC subset for
  86699. * sample rates up to 48kHz. */
  86700. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86701. /** The maximum number of channels permitted by the format. */
  86702. #define FLAC__MAX_CHANNELS (8u)
  86703. /** The minimum sample resolution permitted by the format. */
  86704. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86705. /** The maximum sample resolution permitted by the format. */
  86706. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86707. /** The maximum sample resolution permitted by libFLAC.
  86708. *
  86709. * \warning
  86710. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86711. * the reference encoder/decoder is currently limited to 24 bits because
  86712. * of prevalent 32-bit math, so make sure and use this value when
  86713. * appropriate.
  86714. */
  86715. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86716. /** The maximum sample rate permitted by the format. The value is
  86717. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86718. * as to why.
  86719. */
  86720. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86721. /** The maximum LPC order permitted by the format. */
  86722. #define FLAC__MAX_LPC_ORDER (32u)
  86723. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86724. * up to 48kHz. */
  86725. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86726. /** The minimum quantized linear predictor coefficient precision
  86727. * permitted by the format.
  86728. */
  86729. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86730. /** The maximum quantized linear predictor coefficient precision
  86731. * permitted by the format.
  86732. */
  86733. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86734. /** The maximum order of the fixed predictors permitted by the format. */
  86735. #define FLAC__MAX_FIXED_ORDER (4u)
  86736. /** The maximum Rice partition order permitted by the format. */
  86737. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86738. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86739. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86740. /** The version string of the release, stamped onto the libraries and binaries.
  86741. *
  86742. * \note
  86743. * This does not correspond to the shared library version number, which
  86744. * is used to determine binary compatibility.
  86745. */
  86746. extern FLAC_API const char *FLAC__VERSION_STRING;
  86747. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86748. * This is a NUL-terminated ASCII string; when inserted into the
  86749. * VORBIS_COMMENT the trailing null is stripped.
  86750. */
  86751. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86752. /** The byte string representation of the beginning of a FLAC stream. */
  86753. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86754. /** The 32-bit integer big-endian representation of the beginning of
  86755. * a FLAC stream.
  86756. */
  86757. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86758. /** The length of the FLAC signature in bits. */
  86759. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86760. /** The length of the FLAC signature in bytes. */
  86761. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86762. /*****************************************************************************
  86763. *
  86764. * Subframe structures
  86765. *
  86766. *****************************************************************************/
  86767. /*****************************************************************************/
  86768. /** An enumeration of the available entropy coding methods. */
  86769. typedef enum {
  86770. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86771. /**< Residual is coded by partitioning into contexts, each with it's own
  86772. * 4-bit Rice parameter. */
  86773. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86774. /**< Residual is coded by partitioning into contexts, each with it's own
  86775. * 5-bit Rice parameter. */
  86776. } FLAC__EntropyCodingMethodType;
  86777. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86778. *
  86779. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86780. * give the string equivalent. The contents should not be modified.
  86781. */
  86782. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86783. /** Contents of a Rice partitioned residual
  86784. */
  86785. typedef struct {
  86786. unsigned *parameters;
  86787. /**< The Rice parameters for each context. */
  86788. unsigned *raw_bits;
  86789. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86790. * partitions and zero for unescaped partitions.
  86791. */
  86792. unsigned capacity_by_order;
  86793. /**< The capacity of the \a parameters and \a raw_bits arrays
  86794. * specified as an order, i.e. the number of array elements
  86795. * allocated is 2 ^ \a capacity_by_order.
  86796. */
  86797. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86798. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86799. */
  86800. typedef struct {
  86801. unsigned order;
  86802. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86803. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86804. /**< The context's Rice parameters and/or raw bits. */
  86805. } FLAC__EntropyCodingMethod_PartitionedRice;
  86806. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86807. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86808. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86809. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86810. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86811. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86812. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86813. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86814. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86815. */
  86816. typedef struct {
  86817. FLAC__EntropyCodingMethodType type;
  86818. union {
  86819. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86820. } data;
  86821. } FLAC__EntropyCodingMethod;
  86822. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86823. /*****************************************************************************/
  86824. /** An enumeration of the available subframe types. */
  86825. typedef enum {
  86826. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86827. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86828. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86829. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86830. } FLAC__SubframeType;
  86831. /** Maps a FLAC__SubframeType to a C string.
  86832. *
  86833. * Using a FLAC__SubframeType as the index to this array will
  86834. * give the string equivalent. The contents should not be modified.
  86835. */
  86836. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86837. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86838. */
  86839. typedef struct {
  86840. FLAC__int32 value; /**< The constant signal value. */
  86841. } FLAC__Subframe_Constant;
  86842. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86843. */
  86844. typedef struct {
  86845. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86846. } FLAC__Subframe_Verbatim;
  86847. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86848. */
  86849. typedef struct {
  86850. FLAC__EntropyCodingMethod entropy_coding_method;
  86851. /**< The residual coding method. */
  86852. unsigned order;
  86853. /**< The polynomial order. */
  86854. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86855. /**< Warmup samples to prime the predictor, length == order. */
  86856. const FLAC__int32 *residual;
  86857. /**< The residual signal, length == (blocksize minus order) samples. */
  86858. } FLAC__Subframe_Fixed;
  86859. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86860. */
  86861. typedef struct {
  86862. FLAC__EntropyCodingMethod entropy_coding_method;
  86863. /**< The residual coding method. */
  86864. unsigned order;
  86865. /**< The FIR order. */
  86866. unsigned qlp_coeff_precision;
  86867. /**< Quantized FIR filter coefficient precision in bits. */
  86868. int quantization_level;
  86869. /**< The qlp coeff shift needed. */
  86870. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86871. /**< FIR filter coefficients. */
  86872. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86873. /**< Warmup samples to prime the predictor, length == order. */
  86874. const FLAC__int32 *residual;
  86875. /**< The residual signal, length == (blocksize minus order) samples. */
  86876. } FLAC__Subframe_LPC;
  86877. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86878. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86879. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86880. */
  86881. typedef struct {
  86882. FLAC__SubframeType type;
  86883. union {
  86884. FLAC__Subframe_Constant constant;
  86885. FLAC__Subframe_Fixed fixed;
  86886. FLAC__Subframe_LPC lpc;
  86887. FLAC__Subframe_Verbatim verbatim;
  86888. } data;
  86889. unsigned wasted_bits;
  86890. } FLAC__Subframe;
  86891. /** == 1 (bit)
  86892. *
  86893. * This used to be a zero-padding bit (hence the name
  86894. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86895. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86896. * to mean something else.
  86897. */
  86898. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86899. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86900. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86901. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86902. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86903. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86904. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86905. /*****************************************************************************/
  86906. /*****************************************************************************
  86907. *
  86908. * Frame structures
  86909. *
  86910. *****************************************************************************/
  86911. /** An enumeration of the available channel assignments. */
  86912. typedef enum {
  86913. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86914. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86915. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86916. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86917. } FLAC__ChannelAssignment;
  86918. /** Maps a FLAC__ChannelAssignment to a C string.
  86919. *
  86920. * Using a FLAC__ChannelAssignment as the index to this array will
  86921. * give the string equivalent. The contents should not be modified.
  86922. */
  86923. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86924. /** An enumeration of the possible frame numbering methods. */
  86925. typedef enum {
  86926. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86927. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86928. } FLAC__FrameNumberType;
  86929. /** Maps a FLAC__FrameNumberType to a C string.
  86930. *
  86931. * Using a FLAC__FrameNumberType as the index to this array will
  86932. * give the string equivalent. The contents should not be modified.
  86933. */
  86934. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86935. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86936. */
  86937. typedef struct {
  86938. unsigned blocksize;
  86939. /**< The number of samples per subframe. */
  86940. unsigned sample_rate;
  86941. /**< The sample rate in Hz. */
  86942. unsigned channels;
  86943. /**< The number of channels (== number of subframes). */
  86944. FLAC__ChannelAssignment channel_assignment;
  86945. /**< The channel assignment for the frame. */
  86946. unsigned bits_per_sample;
  86947. /**< The sample resolution. */
  86948. FLAC__FrameNumberType number_type;
  86949. /**< The numbering scheme used for the frame. As a convenience, the
  86950. * decoder will always convert a frame number to a sample number because
  86951. * the rules are complex. */
  86952. union {
  86953. FLAC__uint32 frame_number;
  86954. FLAC__uint64 sample_number;
  86955. } number;
  86956. /**< The frame number or sample number of first sample in frame;
  86957. * use the \a number_type value to determine which to use. */
  86958. FLAC__uint8 crc;
  86959. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86960. * of the raw frame header bytes, meaning everything before the CRC byte
  86961. * including the sync code.
  86962. */
  86963. } FLAC__FrameHeader;
  86964. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86965. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86966. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86967. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86968. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86969. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86970. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86971. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86972. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86973. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86974. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86975. */
  86976. typedef struct {
  86977. FLAC__uint16 crc;
  86978. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86979. * 0) of the bytes before the crc, back to and including the frame header
  86980. * sync code.
  86981. */
  86982. } FLAC__FrameFooter;
  86983. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86984. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86985. */
  86986. typedef struct {
  86987. FLAC__FrameHeader header;
  86988. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86989. FLAC__FrameFooter footer;
  86990. } FLAC__Frame;
  86991. /*****************************************************************************/
  86992. /*****************************************************************************
  86993. *
  86994. * Meta-data structures
  86995. *
  86996. *****************************************************************************/
  86997. /** An enumeration of the available metadata block types. */
  86998. typedef enum {
  86999. FLAC__METADATA_TYPE_STREAMINFO = 0,
  87000. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  87001. FLAC__METADATA_TYPE_PADDING = 1,
  87002. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  87003. FLAC__METADATA_TYPE_APPLICATION = 2,
  87004. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  87005. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  87006. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  87007. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  87008. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  87009. FLAC__METADATA_TYPE_CUESHEET = 5,
  87010. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  87011. FLAC__METADATA_TYPE_PICTURE = 6,
  87012. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  87013. FLAC__METADATA_TYPE_UNDEFINED = 7
  87014. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  87015. } FLAC__MetadataType;
  87016. /** Maps a FLAC__MetadataType to a C string.
  87017. *
  87018. * Using a FLAC__MetadataType as the index to this array will
  87019. * give the string equivalent. The contents should not be modified.
  87020. */
  87021. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  87022. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  87023. */
  87024. typedef struct {
  87025. unsigned min_blocksize, max_blocksize;
  87026. unsigned min_framesize, max_framesize;
  87027. unsigned sample_rate;
  87028. unsigned channels;
  87029. unsigned bits_per_sample;
  87030. FLAC__uint64 total_samples;
  87031. FLAC__byte md5sum[16];
  87032. } FLAC__StreamMetadata_StreamInfo;
  87033. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87034. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87035. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87036. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87037. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87038. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87039. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87040. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87041. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87042. /** The total stream length of the STREAMINFO block in bytes. */
  87043. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87044. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87045. */
  87046. typedef struct {
  87047. int dummy;
  87048. /**< Conceptually this is an empty struct since we don't store the
  87049. * padding bytes. Empty structs are not allowed by some C compilers,
  87050. * hence the dummy.
  87051. */
  87052. } FLAC__StreamMetadata_Padding;
  87053. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87054. */
  87055. typedef struct {
  87056. FLAC__byte id[4];
  87057. FLAC__byte *data;
  87058. } FLAC__StreamMetadata_Application;
  87059. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87060. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87061. */
  87062. typedef struct {
  87063. FLAC__uint64 sample_number;
  87064. /**< The sample number of the target frame. */
  87065. FLAC__uint64 stream_offset;
  87066. /**< The offset, in bytes, of the target frame with respect to
  87067. * beginning of the first frame. */
  87068. unsigned frame_samples;
  87069. /**< The number of samples in the target frame. */
  87070. } FLAC__StreamMetadata_SeekPoint;
  87071. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87072. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87073. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87074. /** The total stream length of a seek point in bytes. */
  87075. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87076. /** The value used in the \a sample_number field of
  87077. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87078. * point (== 0xffffffffffffffff).
  87079. */
  87080. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87081. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87082. *
  87083. * \note From the format specification:
  87084. * - The seek points must be sorted by ascending sample number.
  87085. * - Each seek point's sample number must be the first sample of the
  87086. * target frame.
  87087. * - Each seek point's sample number must be unique within the table.
  87088. * - Existence of a SEEKTABLE block implies a correct setting of
  87089. * total_samples in the stream_info block.
  87090. * - Behavior is undefined when more than one SEEKTABLE block is
  87091. * present in a stream.
  87092. */
  87093. typedef struct {
  87094. unsigned num_points;
  87095. FLAC__StreamMetadata_SeekPoint *points;
  87096. } FLAC__StreamMetadata_SeekTable;
  87097. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87098. *
  87099. * For convenience, the APIs maintain a trailing NUL character at the end of
  87100. * \a entry which is not counted toward \a length, i.e.
  87101. * \code strlen(entry) == length \endcode
  87102. */
  87103. typedef struct {
  87104. FLAC__uint32 length;
  87105. FLAC__byte *entry;
  87106. } FLAC__StreamMetadata_VorbisComment_Entry;
  87107. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87108. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87109. */
  87110. typedef struct {
  87111. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87112. FLAC__uint32 num_comments;
  87113. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87114. } FLAC__StreamMetadata_VorbisComment;
  87115. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87116. /** FLAC CUESHEET track index structure. (See the
  87117. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87118. * the full description of each field.)
  87119. */
  87120. typedef struct {
  87121. FLAC__uint64 offset;
  87122. /**< Offset in samples, relative to the track offset, of the index
  87123. * point.
  87124. */
  87125. FLAC__byte number;
  87126. /**< The index point number. */
  87127. } FLAC__StreamMetadata_CueSheet_Index;
  87128. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87129. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87130. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87131. /** FLAC CUESHEET track structure. (See the
  87132. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87133. * the full description of each field.)
  87134. */
  87135. typedef struct {
  87136. FLAC__uint64 offset;
  87137. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87138. FLAC__byte number;
  87139. /**< The track number. */
  87140. char isrc[13];
  87141. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87142. unsigned type:1;
  87143. /**< The track type: 0 for audio, 1 for non-audio. */
  87144. unsigned pre_emphasis:1;
  87145. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87146. FLAC__byte num_indices;
  87147. /**< The number of track index points. */
  87148. FLAC__StreamMetadata_CueSheet_Index *indices;
  87149. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87150. } FLAC__StreamMetadata_CueSheet_Track;
  87151. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87152. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87153. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87154. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87155. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87156. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87157. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87158. /** FLAC CUESHEET structure. (See the
  87159. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87160. * for the full description of each field.)
  87161. */
  87162. typedef struct {
  87163. char media_catalog_number[129];
  87164. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87165. * general, the media catalog number may be 0 to 128 bytes long; any
  87166. * unused characters should be right-padded with NUL characters.
  87167. */
  87168. FLAC__uint64 lead_in;
  87169. /**< The number of lead-in samples. */
  87170. FLAC__bool is_cd;
  87171. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87172. unsigned num_tracks;
  87173. /**< The number of tracks. */
  87174. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87175. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87176. } FLAC__StreamMetadata_CueSheet;
  87177. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87178. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87179. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87180. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87181. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87182. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87183. typedef enum {
  87184. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87185. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87186. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87187. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87188. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87189. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87190. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87191. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87192. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87193. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87194. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87195. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87196. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87197. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87198. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87199. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87200. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87201. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87202. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87203. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87204. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87205. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87206. } FLAC__StreamMetadata_Picture_Type;
  87207. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87208. *
  87209. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87210. * will give the string equivalent. The contents should not be
  87211. * modified.
  87212. */
  87213. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87214. /** FLAC PICTURE structure. (See the
  87215. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87216. * for the full description of each field.)
  87217. */
  87218. typedef struct {
  87219. FLAC__StreamMetadata_Picture_Type type;
  87220. /**< The kind of picture stored. */
  87221. char *mime_type;
  87222. /**< Picture data's MIME type, in ASCII printable characters
  87223. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87224. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87225. * MIME type of '-->' is also allowed, in which case the picture
  87226. * data should be a complete URL. In file storage, the MIME type is
  87227. * stored as a 32-bit length followed by the ASCII string with no NUL
  87228. * terminator, but is converted to a plain C string in this structure
  87229. * for convenience.
  87230. */
  87231. FLAC__byte *description;
  87232. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87233. * the description is stored as a 32-bit length followed by the UTF-8
  87234. * string with no NUL terminator, but is converted to a plain C string
  87235. * in this structure for convenience.
  87236. */
  87237. FLAC__uint32 width;
  87238. /**< Picture's width in pixels. */
  87239. FLAC__uint32 height;
  87240. /**< Picture's height in pixels. */
  87241. FLAC__uint32 depth;
  87242. /**< Picture's color depth in bits-per-pixel. */
  87243. FLAC__uint32 colors;
  87244. /**< For indexed palettes (like GIF), picture's number of colors (the
  87245. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87246. */
  87247. FLAC__uint32 data_length;
  87248. /**< Length of binary picture data in bytes. */
  87249. FLAC__byte *data;
  87250. /**< Binary picture data. */
  87251. } FLAC__StreamMetadata_Picture;
  87252. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87253. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87254. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87255. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87256. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87257. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87258. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87259. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87260. /** Structure that is used when a metadata block of unknown type is loaded.
  87261. * The contents are opaque. The structure is used only internally to
  87262. * correctly handle unknown metadata.
  87263. */
  87264. typedef struct {
  87265. FLAC__byte *data;
  87266. } FLAC__StreamMetadata_Unknown;
  87267. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87268. */
  87269. typedef struct {
  87270. FLAC__MetadataType type;
  87271. /**< The type of the metadata block; used determine which member of the
  87272. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87273. * then \a data.unknown must be used. */
  87274. FLAC__bool is_last;
  87275. /**< \c true if this metadata block is the last, else \a false */
  87276. unsigned length;
  87277. /**< Length, in bytes, of the block data as it appears in the stream. */
  87278. union {
  87279. FLAC__StreamMetadata_StreamInfo stream_info;
  87280. FLAC__StreamMetadata_Padding padding;
  87281. FLAC__StreamMetadata_Application application;
  87282. FLAC__StreamMetadata_SeekTable seek_table;
  87283. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87284. FLAC__StreamMetadata_CueSheet cue_sheet;
  87285. FLAC__StreamMetadata_Picture picture;
  87286. FLAC__StreamMetadata_Unknown unknown;
  87287. } data;
  87288. /**< Polymorphic block data; use the \a type value to determine which
  87289. * to use. */
  87290. } FLAC__StreamMetadata;
  87291. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87292. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87293. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87294. /** The total stream length of a metadata block header in bytes. */
  87295. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87296. /*****************************************************************************/
  87297. /*****************************************************************************
  87298. *
  87299. * Utility functions
  87300. *
  87301. *****************************************************************************/
  87302. /** Tests that a sample rate is valid for FLAC.
  87303. *
  87304. * \param sample_rate The sample rate to test for compliance.
  87305. * \retval FLAC__bool
  87306. * \c true if the given sample rate conforms to the specification, else
  87307. * \c false.
  87308. */
  87309. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87310. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87311. * for valid sample rates are slightly more complex since the rate has to
  87312. * be expressible completely in the frame header.
  87313. *
  87314. * \param sample_rate The sample rate to test for compliance.
  87315. * \retval FLAC__bool
  87316. * \c true if the given sample rate conforms to the specification for the
  87317. * subset, else \c false.
  87318. */
  87319. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87320. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87321. * comment specification.
  87322. *
  87323. * Vorbis comment names must be composed only of characters from
  87324. * [0x20-0x3C,0x3E-0x7D].
  87325. *
  87326. * \param name A NUL-terminated string to be checked.
  87327. * \assert
  87328. * \code name != NULL \endcode
  87329. * \retval FLAC__bool
  87330. * \c false if entry name is illegal, else \c true.
  87331. */
  87332. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87333. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87334. * comment specification.
  87335. *
  87336. * Vorbis comment values must be valid UTF-8 sequences.
  87337. *
  87338. * \param value A string to be checked.
  87339. * \param length A the length of \a value in bytes. May be
  87340. * \c (unsigned)(-1) to indicate that \a value is a plain
  87341. * UTF-8 NUL-terminated string.
  87342. * \assert
  87343. * \code value != NULL \endcode
  87344. * \retval FLAC__bool
  87345. * \c false if entry name is illegal, else \c true.
  87346. */
  87347. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87348. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87349. * comment specification.
  87350. *
  87351. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87352. * 'value' must be legal according to
  87353. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87354. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87355. *
  87356. * \param entry An entry to be checked.
  87357. * \param length The length of \a entry in bytes.
  87358. * \assert
  87359. * \code value != NULL \endcode
  87360. * \retval FLAC__bool
  87361. * \c false if entry name is illegal, else \c true.
  87362. */
  87363. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87364. /** Check a seek table to see if it conforms to the FLAC specification.
  87365. * See the format specification for limits on the contents of the
  87366. * seek table.
  87367. *
  87368. * \param seek_table A pointer to a seek table to be checked.
  87369. * \assert
  87370. * \code seek_table != NULL \endcode
  87371. * \retval FLAC__bool
  87372. * \c false if seek table is illegal, else \c true.
  87373. */
  87374. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87375. /** Sort a seek table's seek points according to the format specification.
  87376. * This includes a "unique-ification" step to remove duplicates, i.e.
  87377. * seek points with identical \a sample_number values. Duplicate seek
  87378. * points are converted into placeholder points and sorted to the end of
  87379. * the table.
  87380. *
  87381. * \param seek_table A pointer to a seek table to be sorted.
  87382. * \assert
  87383. * \code seek_table != NULL \endcode
  87384. * \retval unsigned
  87385. * The number of duplicate seek points converted into placeholders.
  87386. */
  87387. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87388. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87389. * See the format specification for limits on the contents of the
  87390. * cue sheet.
  87391. *
  87392. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87393. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87394. * stringent requirements for a CD-DA (audio) disc.
  87395. * \param violation Address of a pointer to a string. If there is a
  87396. * violation, a pointer to a string explanation of the
  87397. * violation will be returned here. \a violation may be
  87398. * \c NULL if you don't need the returned string. Do not
  87399. * free the returned string; it will always point to static
  87400. * data.
  87401. * \assert
  87402. * \code cue_sheet != NULL \endcode
  87403. * \retval FLAC__bool
  87404. * \c false if cue sheet is illegal, else \c true.
  87405. */
  87406. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87407. /** Check picture data to see if it conforms to the FLAC specification.
  87408. * See the format specification for limits on the contents of the
  87409. * PICTURE block.
  87410. *
  87411. * \param picture A pointer to existing picture data to be checked.
  87412. * \param violation Address of a pointer to a string. If there is a
  87413. * violation, a pointer to a string explanation of the
  87414. * violation will be returned here. \a violation may be
  87415. * \c NULL if you don't need the returned string. Do not
  87416. * free the returned string; it will always point to static
  87417. * data.
  87418. * \assert
  87419. * \code picture != NULL \endcode
  87420. * \retval FLAC__bool
  87421. * \c false if picture data is illegal, else \c true.
  87422. */
  87423. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87424. /* \} */
  87425. #ifdef __cplusplus
  87426. }
  87427. #endif
  87428. #endif
  87429. /*** End of inlined file: format.h ***/
  87430. /*** Start of inlined file: metadata.h ***/
  87431. #ifndef FLAC__METADATA_H
  87432. #define FLAC__METADATA_H
  87433. #include <sys/types.h> /* for off_t */
  87434. /* --------------------------------------------------------------------
  87435. (For an example of how all these routines are used, see the source
  87436. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87437. metaflac in src/metaflac/)
  87438. ------------------------------------------------------------------*/
  87439. /** \file include/FLAC/metadata.h
  87440. *
  87441. * \brief
  87442. * This module provides functions for creating and manipulating FLAC
  87443. * metadata blocks in memory, and three progressively more powerful
  87444. * interfaces for traversing and editing metadata in FLAC files.
  87445. *
  87446. * See the detailed documentation for each interface in the
  87447. * \link flac_metadata metadata \endlink module.
  87448. */
  87449. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87450. * \ingroup flac
  87451. *
  87452. * \brief
  87453. * This module provides functions for creating and manipulating FLAC
  87454. * metadata blocks in memory, and three progressively more powerful
  87455. * interfaces for traversing and editing metadata in native FLAC files.
  87456. * Note that currently only the Chain interface (level 2) supports Ogg
  87457. * FLAC files, and it is read-only i.e. no writing back changed
  87458. * metadata to file.
  87459. *
  87460. * There are three metadata interfaces of increasing complexity:
  87461. *
  87462. * Level 0:
  87463. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87464. * PICTURE blocks.
  87465. *
  87466. * Level 1:
  87467. * Read-write access to all metadata blocks. This level is write-
  87468. * efficient in most cases (more on this below), and uses less memory
  87469. * than level 2.
  87470. *
  87471. * Level 2:
  87472. * Read-write access to all metadata blocks. This level is write-
  87473. * efficient in all cases, but uses more memory since all metadata for
  87474. * the whole file is read into memory and manipulated before writing
  87475. * out again.
  87476. *
  87477. * What do we mean by efficient? Since FLAC metadata appears at the
  87478. * beginning of the file, when writing metadata back to a FLAC file
  87479. * it is possible to grow or shrink the metadata such that the entire
  87480. * file must be rewritten. However, if the size remains the same during
  87481. * changes or PADDING blocks are utilized, only the metadata needs to be
  87482. * overwritten, which is much faster.
  87483. *
  87484. * Efficient means the whole file is rewritten at most one time, and only
  87485. * when necessary. Level 1 is not efficient only in the case that you
  87486. * cause more than one metadata block to grow or shrink beyond what can
  87487. * be accomodated by padding. In this case you should probably use level
  87488. * 2, which allows you to edit all the metadata for a file in memory and
  87489. * write it out all at once.
  87490. *
  87491. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87492. * front of the file.
  87493. *
  87494. * All levels access files via their filenames. In addition, level 2
  87495. * has additional alternative read and write functions that take an I/O
  87496. * handle and callbacks, for situations where access by filename is not
  87497. * possible.
  87498. *
  87499. * In addition to the three interfaces, this module defines functions for
  87500. * creating and manipulating various metadata objects in memory. As we see
  87501. * from the Format module, FLAC metadata blocks in memory are very primitive
  87502. * structures for storing information in an efficient way. Reading
  87503. * information from the structures is easy but creating or modifying them
  87504. * directly is more complex. The metadata object routines here facilitate
  87505. * this by taking care of the consistency and memory management drudgery.
  87506. *
  87507. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87508. * metadata however, you will not probably not need these.
  87509. *
  87510. * From a dependency standpoint, none of the encoders or decoders require
  87511. * the metadata module. This is so that embedded users can strip out the
  87512. * metadata module from libFLAC to reduce the size and complexity.
  87513. */
  87514. #ifdef __cplusplus
  87515. extern "C" {
  87516. #endif
  87517. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87518. * \ingroup flac_metadata
  87519. *
  87520. * \brief
  87521. * The level 0 interface consists of individual routines to read the
  87522. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87523. * only a filename.
  87524. *
  87525. * They try to skip any ID3v2 tag at the head of the file.
  87526. *
  87527. * \{
  87528. */
  87529. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87530. * will try to skip any ID3v2 tag at the head of the file.
  87531. *
  87532. * \param filename The path to the FLAC file to read.
  87533. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87534. * FLAC__StreamMetadata is a simple structure with no
  87535. * memory allocation involved, you pass the address of
  87536. * an existing structure. It need not be initialized.
  87537. * \assert
  87538. * \code filename != NULL \endcode
  87539. * \code streaminfo != NULL \endcode
  87540. * \retval FLAC__bool
  87541. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87542. * \c false if there was a memory allocation error, a file decoder error,
  87543. * or the file contained no STREAMINFO block. (A memory allocation error
  87544. * is possible because this function must set up a file decoder.)
  87545. */
  87546. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87547. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87548. * function will try to skip any ID3v2 tag at the head of the file.
  87549. *
  87550. * \param filename The path to the FLAC file to read.
  87551. * \param tags The address where the returned pointer will be
  87552. * stored. The \a tags object must be deleted by
  87553. * the caller using FLAC__metadata_object_delete().
  87554. * \assert
  87555. * \code filename != NULL \endcode
  87556. * \code tags != NULL \endcode
  87557. * \retval FLAC__bool
  87558. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87559. * and \a *tags will be set to the address of the metadata structure.
  87560. * Returns \c false if there was a memory allocation error, a file
  87561. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87562. * \a *tags will be set to \c NULL.
  87563. */
  87564. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87565. /** Read the CUESHEET metadata block of the given FLAC file. This
  87566. * function will try to skip any ID3v2 tag at the head of the file.
  87567. *
  87568. * \param filename The path to the FLAC file to read.
  87569. * \param cuesheet The address where the returned pointer will be
  87570. * stored. The \a cuesheet object must be deleted by
  87571. * the caller using FLAC__metadata_object_delete().
  87572. * \assert
  87573. * \code filename != NULL \endcode
  87574. * \code cuesheet != NULL \endcode
  87575. * \retval FLAC__bool
  87576. * \c true if a valid CUESHEET block was read from \a filename,
  87577. * and \a *cuesheet will be set to the address of the metadata
  87578. * structure. Returns \c false if there was a memory allocation
  87579. * error, a file decoder error, or the file contained no CUESHEET
  87580. * block, and \a *cuesheet will be set to \c NULL.
  87581. */
  87582. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87583. /** Read a PICTURE metadata block of the given FLAC file. This
  87584. * function will try to skip any ID3v2 tag at the head of the file.
  87585. * Since there can be more than one PICTURE block in a file, this
  87586. * function takes a number of parameters that act as constraints to
  87587. * the search. The PICTURE block with the largest area matching all
  87588. * the constraints will be returned, or \a *picture will be set to
  87589. * \c NULL if there was no such block.
  87590. *
  87591. * \param filename The path to the FLAC file to read.
  87592. * \param picture The address where the returned pointer will be
  87593. * stored. The \a picture object must be deleted by
  87594. * the caller using FLAC__metadata_object_delete().
  87595. * \param type The desired picture type. Use \c -1 to mean
  87596. * "any type".
  87597. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87598. * string will be matched exactly. Use \c NULL to
  87599. * mean "any MIME type".
  87600. * \param description The desired description. The string will be
  87601. * matched exactly. Use \c NULL to mean "any
  87602. * description".
  87603. * \param max_width The maximum width in pixels desired. Use
  87604. * \c (unsigned)(-1) to mean "any width".
  87605. * \param max_height The maximum height in pixels desired. Use
  87606. * \c (unsigned)(-1) to mean "any height".
  87607. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87608. * Use \c (unsigned)(-1) to mean "any depth".
  87609. * \param max_colors The maximum number of colors desired. Use
  87610. * \c (unsigned)(-1) to mean "any number of colors".
  87611. * \assert
  87612. * \code filename != NULL \endcode
  87613. * \code picture != NULL \endcode
  87614. * \retval FLAC__bool
  87615. * \c true if a valid PICTURE block was read from \a filename,
  87616. * and \a *picture will be set to the address of the metadata
  87617. * structure. Returns \c false if there was a memory allocation
  87618. * error, a file decoder error, or the file contained no PICTURE
  87619. * block, and \a *picture will be set to \c NULL.
  87620. */
  87621. 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);
  87622. /* \} */
  87623. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87624. * \ingroup flac_metadata
  87625. *
  87626. * \brief
  87627. * The level 1 interface provides read-write access to FLAC file metadata and
  87628. * operates directly on the FLAC file.
  87629. *
  87630. * The general usage of this interface is:
  87631. *
  87632. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87633. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87634. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87635. * see if the file is writable, or only read access is allowed.
  87636. * - Use FLAC__metadata_simple_iterator_next() and
  87637. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87638. * This is does not read the actual blocks themselves.
  87639. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87640. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87641. * forward from the front of the file.
  87642. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87643. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87644. * the current iterator position. The returned object is yours to modify
  87645. * and free.
  87646. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87647. * back. You must have write permission to the original file. Make sure to
  87648. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87649. * below.
  87650. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87651. * Use the object creation functions from
  87652. * \link flac_metadata_object here \endlink to generate new objects.
  87653. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87654. * currently referred to by the iterator, or replace it with padding.
  87655. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87656. * finished.
  87657. *
  87658. * \note
  87659. * The FLAC file remains open the whole time between
  87660. * FLAC__metadata_simple_iterator_init() and
  87661. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87662. * the file during this time.
  87663. *
  87664. * \note
  87665. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87666. * FLAC__StreamMetadata objects. These are managed automatically.
  87667. *
  87668. * \note
  87669. * If any of the modification functions
  87670. * (FLAC__metadata_simple_iterator_set_block(),
  87671. * FLAC__metadata_simple_iterator_delete_block(),
  87672. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87673. * you should delete the iterator as it may no longer be valid.
  87674. *
  87675. * \{
  87676. */
  87677. struct FLAC__Metadata_SimpleIterator;
  87678. /** The opaque structure definition for the level 1 iterator type.
  87679. * See the
  87680. * \link flac_metadata_level1 metadata level 1 module \endlink
  87681. * for a detailed description.
  87682. */
  87683. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87684. /** Status type for FLAC__Metadata_SimpleIterator.
  87685. *
  87686. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87687. */
  87688. typedef enum {
  87689. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87690. /**< The iterator is in the normal OK state */
  87691. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87692. /**< The data passed into a function violated the function's usage criteria */
  87693. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87694. /**< The iterator could not open the target file */
  87695. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87696. /**< The iterator could not find the FLAC signature at the start of the file */
  87697. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87698. /**< The iterator tried to write to a file that was not writable */
  87699. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87700. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87701. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87702. /**< The iterator encountered an error while reading the FLAC file */
  87703. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87704. /**< The iterator encountered an error while seeking in the FLAC file */
  87705. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87706. /**< The iterator encountered an error while writing the FLAC file */
  87707. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87708. /**< The iterator encountered an error renaming the FLAC file */
  87709. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87710. /**< The iterator encountered an error removing the temporary file */
  87711. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87712. /**< Memory allocation failed */
  87713. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87714. /**< The caller violated an assertion or an unexpected error occurred */
  87715. } FLAC__Metadata_SimpleIteratorStatus;
  87716. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87717. *
  87718. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87719. * will give the string equivalent. The contents should not be modified.
  87720. */
  87721. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87722. /** Create a new iterator instance.
  87723. *
  87724. * \retval FLAC__Metadata_SimpleIterator*
  87725. * \c NULL if there was an error allocating memory, else the new instance.
  87726. */
  87727. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87728. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87729. *
  87730. * \param iterator A pointer to an existing iterator.
  87731. * \assert
  87732. * \code iterator != NULL \endcode
  87733. */
  87734. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87735. /** Get the current status of the iterator. Call this after a function
  87736. * returns \c false to get the reason for the error. Also resets the status
  87737. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87738. *
  87739. * \param iterator A pointer to an existing iterator.
  87740. * \assert
  87741. * \code iterator != NULL \endcode
  87742. * \retval FLAC__Metadata_SimpleIteratorStatus
  87743. * The current status of the iterator.
  87744. */
  87745. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87746. /** Initialize the iterator to point to the first metadata block in the
  87747. * given FLAC file.
  87748. *
  87749. * \param iterator A pointer to an existing iterator.
  87750. * \param filename The path to the FLAC file.
  87751. * \param read_only If \c true, the FLAC file will be opened
  87752. * in read-only mode; if \c false, the FLAC
  87753. * file will be opened for edit even if no
  87754. * edits are performed.
  87755. * \param preserve_file_stats If \c true, the owner and modification
  87756. * time will be preserved even if the FLAC
  87757. * file is written to.
  87758. * \assert
  87759. * \code iterator != NULL \endcode
  87760. * \code filename != NULL \endcode
  87761. * \retval FLAC__bool
  87762. * \c false if a memory allocation error occurs, the file can't be
  87763. * opened, or another error occurs, else \c true.
  87764. */
  87765. 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);
  87766. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87767. * FLAC__metadata_simple_iterator_set_block() and
  87768. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87769. *
  87770. * \param iterator A pointer to an existing iterator.
  87771. * \assert
  87772. * \code iterator != NULL \endcode
  87773. * \retval FLAC__bool
  87774. * See above.
  87775. */
  87776. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87777. /** Moves the iterator forward one metadata block, returning \c false if
  87778. * already at the end.
  87779. *
  87780. * \param iterator A pointer to an existing initialized iterator.
  87781. * \assert
  87782. * \code iterator != NULL \endcode
  87783. * \a iterator has been successfully initialized with
  87784. * FLAC__metadata_simple_iterator_init()
  87785. * \retval FLAC__bool
  87786. * \c false if already at the last metadata block of the chain, else
  87787. * \c true.
  87788. */
  87789. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87790. /** Moves the iterator backward one metadata block, returning \c false if
  87791. * already at the beginning.
  87792. *
  87793. * \param iterator A pointer to an existing initialized iterator.
  87794. * \assert
  87795. * \code iterator != NULL \endcode
  87796. * \a iterator has been successfully initialized with
  87797. * FLAC__metadata_simple_iterator_init()
  87798. * \retval FLAC__bool
  87799. * \c false if already at the first metadata block of the chain, else
  87800. * \c true.
  87801. */
  87802. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87803. /** Returns a flag telling if the current metadata block is the last.
  87804. *
  87805. * \param iterator A pointer to an existing initialized iterator.
  87806. * \assert
  87807. * \code iterator != NULL \endcode
  87808. * \a iterator has been successfully initialized with
  87809. * FLAC__metadata_simple_iterator_init()
  87810. * \retval FLAC__bool
  87811. * \c true if the current metadata block is the last in the file,
  87812. * else \c false.
  87813. */
  87814. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87815. /** Get the offset of the metadata block at the current position. This
  87816. * avoids reading the actual block data which can save time for large
  87817. * blocks.
  87818. *
  87819. * \param iterator A pointer to an existing initialized iterator.
  87820. * \assert
  87821. * \code iterator != NULL \endcode
  87822. * \a iterator has been successfully initialized with
  87823. * FLAC__metadata_simple_iterator_init()
  87824. * \retval off_t
  87825. * The offset of the metadata block at the current iterator position.
  87826. * This is the byte offset relative to the beginning of the file of
  87827. * the current metadata block's header.
  87828. */
  87829. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87830. /** Get the type of the metadata block at the current position. This
  87831. * avoids reading the actual block data which can save time for large
  87832. * blocks.
  87833. *
  87834. * \param iterator A pointer to an existing initialized iterator.
  87835. * \assert
  87836. * \code iterator != NULL \endcode
  87837. * \a iterator has been successfully initialized with
  87838. * FLAC__metadata_simple_iterator_init()
  87839. * \retval FLAC__MetadataType
  87840. * The type of the metadata block at the current iterator position.
  87841. */
  87842. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87843. /** Get the length of the metadata block at the current position. This
  87844. * avoids reading the actual block data which can save time for large
  87845. * blocks.
  87846. *
  87847. * \param iterator A pointer to an existing initialized iterator.
  87848. * \assert
  87849. * \code iterator != NULL \endcode
  87850. * \a iterator has been successfully initialized with
  87851. * FLAC__metadata_simple_iterator_init()
  87852. * \retval unsigned
  87853. * The length of the metadata block at the current iterator position.
  87854. * The is same length as that in the
  87855. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87856. * i.e. the length of the metadata body that follows the header.
  87857. */
  87858. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87859. /** Get the application ID of the \c APPLICATION block at the current
  87860. * position. This avoids reading the actual block data which can save
  87861. * time for large blocks.
  87862. *
  87863. * \param iterator A pointer to an existing initialized iterator.
  87864. * \param id A pointer to a buffer of at least \c 4 bytes where
  87865. * the ID will be stored.
  87866. * \assert
  87867. * \code iterator != NULL \endcode
  87868. * \code id != NULL \endcode
  87869. * \a iterator has been successfully initialized with
  87870. * FLAC__metadata_simple_iterator_init()
  87871. * \retval FLAC__bool
  87872. * \c true if the ID was successfully read, else \c false, in which
  87873. * case you should check FLAC__metadata_simple_iterator_status() to
  87874. * find out why. If the status is
  87875. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87876. * current metadata block is not an \c APPLICATION block. Otherwise
  87877. * if the status is
  87878. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87879. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87880. * occurred and the iterator can no longer be used.
  87881. */
  87882. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87883. /** Get the metadata block at the current position. You can modify the
  87884. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87885. * write it back to the FLAC file.
  87886. *
  87887. * You must call FLAC__metadata_object_delete() on the returned object
  87888. * when you are finished with it.
  87889. *
  87890. * \param iterator A pointer to an existing initialized iterator.
  87891. * \assert
  87892. * \code iterator != NULL \endcode
  87893. * \a iterator has been successfully initialized with
  87894. * FLAC__metadata_simple_iterator_init()
  87895. * \retval FLAC__StreamMetadata*
  87896. * The current metadata block, or \c NULL if there was a memory
  87897. * allocation error.
  87898. */
  87899. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87900. /** Write a block back to the FLAC file. This function tries to be
  87901. * as efficient as possible; how the block is actually written is
  87902. * shown by the following:
  87903. *
  87904. * Existing block is a STREAMINFO block and the new block is a
  87905. * STREAMINFO block: the new block is written in place. Make sure
  87906. * you know what you're doing when changing the values of a
  87907. * STREAMINFO block.
  87908. *
  87909. * Existing block is a STREAMINFO block and the new block is a
  87910. * not a STREAMINFO block: this is an error since the first block
  87911. * must be a STREAMINFO block. Returns \c false without altering the
  87912. * file.
  87913. *
  87914. * Existing block is not a STREAMINFO block and the new block is a
  87915. * STREAMINFO block: this is an error since there may be only one
  87916. * STREAMINFO block. Returns \c false without altering the file.
  87917. *
  87918. * Existing block and new block are the same length: the existing
  87919. * block will be replaced by the new block, written in place.
  87920. *
  87921. * Existing block is longer than new block: if use_padding is \c true,
  87922. * the existing block will be overwritten in place with the new
  87923. * block followed by a PADDING block, if possible, to make the total
  87924. * size the same as the existing block. Remember that a padding
  87925. * block requires at least four bytes so if the difference in size
  87926. * between the new block and existing block is less than that, the
  87927. * entire file will have to be rewritten, using the new block's
  87928. * exact size. If use_padding is \c false, the entire file will be
  87929. * rewritten, replacing the existing block by the new block.
  87930. *
  87931. * Existing block is shorter than new block: if use_padding is \c true,
  87932. * the function will try and expand the new block into the following
  87933. * PADDING block, if it exists and doing so won't shrink the PADDING
  87934. * block to less than 4 bytes. If there is no following PADDING
  87935. * block, or it will shrink to less than 4 bytes, or use_padding is
  87936. * \c false, the entire file is rewritten, replacing the existing block
  87937. * with the new block. Note that in this case any following PADDING
  87938. * block is preserved as is.
  87939. *
  87940. * After writing the block, the iterator will remain in the same
  87941. * place, i.e. pointing to the new block.
  87942. *
  87943. * \param iterator A pointer to an existing initialized iterator.
  87944. * \param block The block to set.
  87945. * \param use_padding See above.
  87946. * \assert
  87947. * \code iterator != NULL \endcode
  87948. * \a iterator has been successfully initialized with
  87949. * FLAC__metadata_simple_iterator_init()
  87950. * \code block != NULL \endcode
  87951. * \retval FLAC__bool
  87952. * \c true if successful, else \c false.
  87953. */
  87954. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87955. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87956. * except that instead of writing over an existing block, it appends
  87957. * a block after the existing block. \a use_padding is again used to
  87958. * tell the function to try an expand into following padding in an
  87959. * attempt to avoid rewriting the entire file.
  87960. *
  87961. * This function will fail and return \c false if given a STREAMINFO
  87962. * block.
  87963. *
  87964. * After writing the block, the iterator will be pointing to the
  87965. * new block.
  87966. *
  87967. * \param iterator A pointer to an existing initialized iterator.
  87968. * \param block The block to set.
  87969. * \param use_padding See above.
  87970. * \assert
  87971. * \code iterator != NULL \endcode
  87972. * \a iterator has been successfully initialized with
  87973. * FLAC__metadata_simple_iterator_init()
  87974. * \code block != NULL \endcode
  87975. * \retval FLAC__bool
  87976. * \c true if successful, else \c false.
  87977. */
  87978. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87979. /** Deletes the block at the current position. This will cause the
  87980. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87981. * in which case the block will be replaced by an equal-sized PADDING
  87982. * block. The iterator will be left pointing to the block before the
  87983. * one just deleted.
  87984. *
  87985. * You may not delete the STREAMINFO block.
  87986. *
  87987. * \param iterator A pointer to an existing initialized iterator.
  87988. * \param use_padding See above.
  87989. * \assert
  87990. * \code iterator != NULL \endcode
  87991. * \a iterator has been successfully initialized with
  87992. * FLAC__metadata_simple_iterator_init()
  87993. * \retval FLAC__bool
  87994. * \c true if successful, else \c false.
  87995. */
  87996. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87997. /* \} */
  87998. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87999. * \ingroup flac_metadata
  88000. *
  88001. * \brief
  88002. * The level 2 interface provides read-write access to FLAC file metadata;
  88003. * all metadata is read into memory, operated on in memory, and then written
  88004. * to file, which is more efficient than level 1 when editing multiple blocks.
  88005. *
  88006. * Currently Ogg FLAC is supported for read only, via
  88007. * FLAC__metadata_chain_read_ogg() but a subsequent
  88008. * FLAC__metadata_chain_write() will fail.
  88009. *
  88010. * The general usage of this interface is:
  88011. *
  88012. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  88013. * linked list of FLAC metadata blocks.
  88014. * - Read all metadata into the the chain from a FLAC file using
  88015. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  88016. * check the status.
  88017. * - Optionally, consolidate the padding using
  88018. * FLAC__metadata_chain_merge_padding() or
  88019. * FLAC__metadata_chain_sort_padding().
  88020. * - Create a new iterator using FLAC__metadata_iterator_new()
  88021. * - Initialize the iterator to point to the first element in the chain
  88022. * using FLAC__metadata_iterator_init()
  88023. * - Traverse the chain using FLAC__metadata_iterator_next and
  88024. * FLAC__metadata_iterator_prev().
  88025. * - Get a block for reading or modification using
  88026. * FLAC__metadata_iterator_get_block(). The pointer to the object
  88027. * inside the chain is returned, so the block is yours to modify.
  88028. * Changes will be reflected in the FLAC file when you write the
  88029. * chain. You can also add and delete blocks (see functions below).
  88030. * - When done, write out the chain using FLAC__metadata_chain_write().
  88031. * Make sure to read the whole comment to the function below.
  88032. * - Delete the chain using FLAC__metadata_chain_delete().
  88033. *
  88034. * \note
  88035. * Even though the FLAC file is not open while the chain is being
  88036. * manipulated, you must not alter the file externally during
  88037. * this time. The chain assumes the FLAC file will not change
  88038. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88039. * and FLAC__metadata_chain_write().
  88040. *
  88041. * \note
  88042. * Do not modify the is_last, length, or type fields of returned
  88043. * FLAC__StreamMetadata objects. These are managed automatically.
  88044. *
  88045. * \note
  88046. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88047. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88048. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88049. * become owned by the chain and they will be deleted when the chain is
  88050. * deleted.
  88051. *
  88052. * \{
  88053. */
  88054. struct FLAC__Metadata_Chain;
  88055. /** The opaque structure definition for the level 2 chain type.
  88056. */
  88057. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88058. struct FLAC__Metadata_Iterator;
  88059. /** The opaque structure definition for the level 2 iterator type.
  88060. */
  88061. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88062. typedef enum {
  88063. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88064. /**< The chain is in the normal OK state */
  88065. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88066. /**< The data passed into a function violated the function's usage criteria */
  88067. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88068. /**< The chain could not open the target file */
  88069. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88070. /**< The chain could not find the FLAC signature at the start of the file */
  88071. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88072. /**< The chain tried to write to a file that was not writable */
  88073. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88074. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88075. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88076. /**< The chain encountered an error while reading the FLAC file */
  88077. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88078. /**< The chain encountered an error while seeking in the FLAC file */
  88079. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88080. /**< The chain encountered an error while writing the FLAC file */
  88081. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88082. /**< The chain encountered an error renaming the FLAC file */
  88083. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88084. /**< The chain encountered an error removing the temporary file */
  88085. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88086. /**< Memory allocation failed */
  88087. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88088. /**< The caller violated an assertion or an unexpected error occurred */
  88089. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88090. /**< One or more of the required callbacks was NULL */
  88091. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88092. /**< FLAC__metadata_chain_write() was called on a chain read by
  88093. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88094. * or
  88095. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88096. * was called on a chain read by
  88097. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88098. * Matching read/write methods must always be used. */
  88099. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88100. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88101. * chain write requires a tempfile; use
  88102. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88103. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88104. * called when the chain write does not require a tempfile; use
  88105. * FLAC__metadata_chain_write_with_callbacks() instead.
  88106. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88107. * before writing via callbacks. */
  88108. } FLAC__Metadata_ChainStatus;
  88109. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88110. *
  88111. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88112. * will give the string equivalent. The contents should not be modified.
  88113. */
  88114. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88115. /*********** FLAC__Metadata_Chain ***********/
  88116. /** Create a new chain instance.
  88117. *
  88118. * \retval FLAC__Metadata_Chain*
  88119. * \c NULL if there was an error allocating memory, else the new instance.
  88120. */
  88121. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88122. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88123. *
  88124. * \param chain A pointer to an existing chain.
  88125. * \assert
  88126. * \code chain != NULL \endcode
  88127. */
  88128. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88129. /** Get the current status of the chain. Call this after a function
  88130. * returns \c false to get the reason for the error. Also resets the
  88131. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88132. *
  88133. * \param chain A pointer to an existing chain.
  88134. * \assert
  88135. * \code chain != NULL \endcode
  88136. * \retval FLAC__Metadata_ChainStatus
  88137. * The current status of the chain.
  88138. */
  88139. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88140. /** Read all metadata from a FLAC file into the chain.
  88141. *
  88142. * \param chain A pointer to an existing chain.
  88143. * \param filename The path to the FLAC file to read.
  88144. * \assert
  88145. * \code chain != NULL \endcode
  88146. * \code filename != NULL \endcode
  88147. * \retval FLAC__bool
  88148. * \c true if a valid list of metadata blocks was read from
  88149. * \a filename, else \c false. On failure, check the status with
  88150. * FLAC__metadata_chain_status().
  88151. */
  88152. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88153. /** Read all metadata from an Ogg FLAC file into the chain.
  88154. *
  88155. * \note Ogg FLAC metadata data writing is not supported yet and
  88156. * FLAC__metadata_chain_write() will fail.
  88157. *
  88158. * \param chain A pointer to an existing chain.
  88159. * \param filename The path to the Ogg FLAC file to read.
  88160. * \assert
  88161. * \code chain != NULL \endcode
  88162. * \code filename != NULL \endcode
  88163. * \retval FLAC__bool
  88164. * \c true if a valid list of metadata blocks was read from
  88165. * \a filename, else \c false. On failure, check the status with
  88166. * FLAC__metadata_chain_status().
  88167. */
  88168. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88169. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88170. *
  88171. * The \a handle need only be open for reading, but must be seekable.
  88172. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88173. * for Windows).
  88174. *
  88175. * \param chain A pointer to an existing chain.
  88176. * \param handle The I/O handle of the FLAC stream to read. The
  88177. * handle will NOT be closed after the metadata is read;
  88178. * that is the duty of the caller.
  88179. * \param callbacks
  88180. * A set of callbacks to use for I/O. The mandatory
  88181. * callbacks are \a read, \a seek, and \a tell.
  88182. * \assert
  88183. * \code chain != NULL \endcode
  88184. * \retval FLAC__bool
  88185. * \c true if a valid list of metadata blocks was read from
  88186. * \a handle, else \c false. On failure, check the status with
  88187. * FLAC__metadata_chain_status().
  88188. */
  88189. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88190. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88191. *
  88192. * The \a handle need only be open for reading, but must be seekable.
  88193. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88194. * for Windows).
  88195. *
  88196. * \note Ogg FLAC metadata data writing is not supported yet and
  88197. * FLAC__metadata_chain_write() will fail.
  88198. *
  88199. * \param chain A pointer to an existing chain.
  88200. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88201. * handle will NOT be closed after the metadata is read;
  88202. * that is the duty of the caller.
  88203. * \param callbacks
  88204. * A set of callbacks to use for I/O. The mandatory
  88205. * callbacks are \a read, \a seek, and \a tell.
  88206. * \assert
  88207. * \code chain != NULL \endcode
  88208. * \retval FLAC__bool
  88209. * \c true if a valid list of metadata blocks was read from
  88210. * \a handle, else \c false. On failure, check the status with
  88211. * FLAC__metadata_chain_status().
  88212. */
  88213. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88214. /** Checks if writing the given chain would require the use of a
  88215. * temporary file, or if it could be written in place.
  88216. *
  88217. * Under certain conditions, padding can be utilized so that writing
  88218. * edited metadata back to the FLAC file does not require rewriting the
  88219. * entire file. If rewriting is required, then a temporary workfile is
  88220. * required. When writing metadata using callbacks, you must check
  88221. * this function to know whether to call
  88222. * FLAC__metadata_chain_write_with_callbacks() or
  88223. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88224. * writing with FLAC__metadata_chain_write(), the temporary file is
  88225. * handled internally.
  88226. *
  88227. * \param chain A pointer to an existing chain.
  88228. * \param use_padding
  88229. * Whether or not padding will be allowed to be used
  88230. * during the write. The value of \a use_padding given
  88231. * here must match the value later passed to
  88232. * FLAC__metadata_chain_write_with_callbacks() or
  88233. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88234. * \assert
  88235. * \code chain != NULL \endcode
  88236. * \retval FLAC__bool
  88237. * \c true if writing the current chain would require a tempfile, or
  88238. * \c false if metadata can be written in place.
  88239. */
  88240. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88241. /** Write all metadata out to the FLAC file. This function tries to be as
  88242. * efficient as possible; how the metadata is actually written is shown by
  88243. * the following:
  88244. *
  88245. * If the current chain is the same size as the existing metadata, the new
  88246. * data is written in place.
  88247. *
  88248. * If the current chain is longer than the existing metadata, and
  88249. * \a use_padding is \c true, and the last block is a PADDING block of
  88250. * sufficient length, the function will truncate the final padding block
  88251. * so that the overall size of the metadata is the same as the existing
  88252. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88253. * the above conditions are met, the entire FLAC file must be rewritten.
  88254. * If you want to use padding this way it is a good idea to call
  88255. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88256. * amount of padding to work with, unless you need to preserve ordering
  88257. * of the PADDING blocks for some reason.
  88258. *
  88259. * If the current chain is shorter than the existing metadata, and
  88260. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88261. * is extended to make the overall size the same as the existing data. If
  88262. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88263. * PADDING block is added to the end of the new data to make it the same
  88264. * size as the existing data (if possible, see the note to
  88265. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88266. * and the new data is written in place. If none of the above apply or
  88267. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88268. *
  88269. * If \a preserve_file_stats is \c true, the owner and modification time will
  88270. * be preserved even if the FLAC file is written.
  88271. *
  88272. * For this write function to be used, the chain must have been read with
  88273. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88274. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88275. *
  88276. * \param chain A pointer to an existing chain.
  88277. * \param use_padding See above.
  88278. * \param preserve_file_stats See above.
  88279. * \assert
  88280. * \code chain != NULL \endcode
  88281. * \retval FLAC__bool
  88282. * \c true if the write succeeded, else \c false. On failure,
  88283. * check the status with FLAC__metadata_chain_status().
  88284. */
  88285. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88286. /** Write all metadata out to a FLAC stream via callbacks.
  88287. *
  88288. * (See FLAC__metadata_chain_write() for the details on how padding is
  88289. * used to write metadata in place if possible.)
  88290. *
  88291. * The \a handle must be open for updating and be seekable. The
  88292. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88293. * for Windows).
  88294. *
  88295. * For this write function to be used, the chain must have been read with
  88296. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88297. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88298. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88299. * \c false.
  88300. *
  88301. * \param chain A pointer to an existing chain.
  88302. * \param use_padding See FLAC__metadata_chain_write()
  88303. * \param handle The I/O handle of the FLAC stream to write. The
  88304. * handle will NOT be closed after the metadata is
  88305. * written; that is the duty of the caller.
  88306. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88307. * callbacks are \a write and \a seek.
  88308. * \assert
  88309. * \code chain != NULL \endcode
  88310. * \retval FLAC__bool
  88311. * \c true if the write succeeded, else \c false. On failure,
  88312. * check the status with FLAC__metadata_chain_status().
  88313. */
  88314. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88315. /** Write all metadata out to a FLAC stream via callbacks.
  88316. *
  88317. * (See FLAC__metadata_chain_write() for the details on how padding is
  88318. * used to write metadata in place if possible.)
  88319. *
  88320. * This version of the write-with-callbacks function must be used when
  88321. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88322. * this function, you must supply an I/O handle corresponding to the
  88323. * FLAC file to edit, and a temporary handle to which the new FLAC
  88324. * file will be written. It is the caller's job to move this temporary
  88325. * FLAC file on top of the original FLAC file to complete the metadata
  88326. * edit.
  88327. *
  88328. * The \a handle must be open for reading and be seekable. The
  88329. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88330. * for Windows).
  88331. *
  88332. * The \a temp_handle must be open for writing. The
  88333. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88334. * for Windows). It should be an empty stream, or at least positioned
  88335. * at the start-of-file (in which case it is the caller's duty to
  88336. * truncate it on return).
  88337. *
  88338. * For this write function to be used, the chain must have been read with
  88339. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88340. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88341. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88342. * \c true.
  88343. *
  88344. * \param chain A pointer to an existing chain.
  88345. * \param use_padding See FLAC__metadata_chain_write()
  88346. * \param handle The I/O handle of the original FLAC stream to read.
  88347. * The handle will NOT be closed after the metadata is
  88348. * written; that is the duty of the caller.
  88349. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88350. * The mandatory callbacks are \a read, \a seek, and
  88351. * \a eof.
  88352. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88353. * handle will NOT be closed after the metadata is
  88354. * written; that is the duty of the caller.
  88355. * \param temp_callbacks
  88356. * A set of callbacks to use for I/O on temp_handle.
  88357. * The only mandatory callback is \a write.
  88358. * \assert
  88359. * \code chain != NULL \endcode
  88360. * \retval FLAC__bool
  88361. * \c true if the write succeeded, else \c false. On failure,
  88362. * check the status with FLAC__metadata_chain_status().
  88363. */
  88364. 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);
  88365. /** Merge adjacent PADDING blocks into a single block.
  88366. *
  88367. * \note This function does not write to the FLAC file, it only
  88368. * modifies the chain.
  88369. *
  88370. * \warning Any iterator on the current chain will become invalid after this
  88371. * call. You should delete the iterator and get a new one.
  88372. *
  88373. * \param chain A pointer to an existing chain.
  88374. * \assert
  88375. * \code chain != NULL \endcode
  88376. */
  88377. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88378. /** This function will move all PADDING blocks to the end on the metadata,
  88379. * then merge them into a single block.
  88380. *
  88381. * \note This function does not write to the FLAC file, it only
  88382. * modifies the chain.
  88383. *
  88384. * \warning Any iterator on the current chain will become invalid after this
  88385. * call. You should delete the iterator and get a new one.
  88386. *
  88387. * \param chain A pointer to an existing chain.
  88388. * \assert
  88389. * \code chain != NULL \endcode
  88390. */
  88391. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88392. /*********** FLAC__Metadata_Iterator ***********/
  88393. /** Create a new iterator instance.
  88394. *
  88395. * \retval FLAC__Metadata_Iterator*
  88396. * \c NULL if there was an error allocating memory, else the new instance.
  88397. */
  88398. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88399. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88400. *
  88401. * \param iterator A pointer to an existing iterator.
  88402. * \assert
  88403. * \code iterator != NULL \endcode
  88404. */
  88405. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88406. /** Initialize the iterator to point to the first metadata block in the
  88407. * given chain.
  88408. *
  88409. * \param iterator A pointer to an existing iterator.
  88410. * \param chain A pointer to an existing and initialized (read) chain.
  88411. * \assert
  88412. * \code iterator != NULL \endcode
  88413. * \code chain != NULL \endcode
  88414. */
  88415. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88416. /** Moves the iterator forward one metadata block, returning \c false if
  88417. * already at the end.
  88418. *
  88419. * \param iterator A pointer to an existing initialized iterator.
  88420. * \assert
  88421. * \code iterator != NULL \endcode
  88422. * \a iterator has been successfully initialized with
  88423. * FLAC__metadata_iterator_init()
  88424. * \retval FLAC__bool
  88425. * \c false if already at the last metadata block of the chain, else
  88426. * \c true.
  88427. */
  88428. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88429. /** Moves the iterator backward one metadata block, returning \c false if
  88430. * already at the beginning.
  88431. *
  88432. * \param iterator A pointer to an existing initialized iterator.
  88433. * \assert
  88434. * \code iterator != NULL \endcode
  88435. * \a iterator has been successfully initialized with
  88436. * FLAC__metadata_iterator_init()
  88437. * \retval FLAC__bool
  88438. * \c false if already at the first metadata block of the chain, else
  88439. * \c true.
  88440. */
  88441. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88442. /** Get the type of the metadata block at the current position.
  88443. *
  88444. * \param iterator A pointer to an existing initialized iterator.
  88445. * \assert
  88446. * \code iterator != NULL \endcode
  88447. * \a iterator has been successfully initialized with
  88448. * FLAC__metadata_iterator_init()
  88449. * \retval FLAC__MetadataType
  88450. * The type of the metadata block at the current iterator position.
  88451. */
  88452. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88453. /** Get the metadata block at the current position. You can modify
  88454. * the block in place but must write the chain before the changes
  88455. * are reflected to the FLAC file. You do not need to call
  88456. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88457. * the pointer returned by FLAC__metadata_iterator_get_block()
  88458. * points directly into the chain.
  88459. *
  88460. * \warning
  88461. * Do not call FLAC__metadata_object_delete() on the returned object;
  88462. * to delete a block use FLAC__metadata_iterator_delete_block().
  88463. *
  88464. * \param iterator A pointer to an existing initialized iterator.
  88465. * \assert
  88466. * \code iterator != NULL \endcode
  88467. * \a iterator has been successfully initialized with
  88468. * FLAC__metadata_iterator_init()
  88469. * \retval FLAC__StreamMetadata*
  88470. * The current metadata block.
  88471. */
  88472. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88473. /** Set the metadata block at the current position, replacing the existing
  88474. * block. The new block passed in becomes owned by the chain and it will be
  88475. * deleted when the chain is deleted.
  88476. *
  88477. * \param iterator A pointer to an existing initialized iterator.
  88478. * \param block A pointer to a metadata block.
  88479. * \assert
  88480. * \code iterator != NULL \endcode
  88481. * \a iterator has been successfully initialized with
  88482. * FLAC__metadata_iterator_init()
  88483. * \code block != NULL \endcode
  88484. * \retval FLAC__bool
  88485. * \c false if the conditions in the above description are not met, or
  88486. * a memory allocation error occurs, otherwise \c true.
  88487. */
  88488. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88489. /** Removes the current block from the chain. If \a replace_with_padding is
  88490. * \c true, the block will instead be replaced with a padding block of equal
  88491. * size. You can not delete the STREAMINFO block. The iterator will be
  88492. * left pointing to the block before the one just "deleted", even if
  88493. * \a replace_with_padding is \c true.
  88494. *
  88495. * \param iterator A pointer to an existing initialized iterator.
  88496. * \param replace_with_padding See above.
  88497. * \assert
  88498. * \code iterator != NULL \endcode
  88499. * \a iterator has been successfully initialized with
  88500. * FLAC__metadata_iterator_init()
  88501. * \retval FLAC__bool
  88502. * \c false if the conditions in the above description are not met,
  88503. * otherwise \c true.
  88504. */
  88505. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88506. /** Insert a new block before the current block. You cannot insert a block
  88507. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88508. * as there can be only one, the one that already exists at the head when you
  88509. * read in a chain. The chain takes ownership of the new block and it will be
  88510. * deleted when the chain is deleted. The iterator will be left pointing to
  88511. * the new block.
  88512. *
  88513. * \param iterator A pointer to an existing initialized iterator.
  88514. * \param block A pointer to a metadata block to insert.
  88515. * \assert
  88516. * \code iterator != NULL \endcode
  88517. * \a iterator has been successfully initialized with
  88518. * FLAC__metadata_iterator_init()
  88519. * \retval FLAC__bool
  88520. * \c false if the conditions in the above description are not met, or
  88521. * a memory allocation error occurs, otherwise \c true.
  88522. */
  88523. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88524. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88525. * block as there can be only one, the one that already exists at the head when
  88526. * you read in a chain. The chain takes ownership of the new block and it will
  88527. * be deleted when the chain is deleted. The iterator will be left pointing to
  88528. * the new block.
  88529. *
  88530. * \param iterator A pointer to an existing initialized iterator.
  88531. * \param block A pointer to a metadata block to insert.
  88532. * \assert
  88533. * \code iterator != NULL \endcode
  88534. * \a iterator has been successfully initialized with
  88535. * FLAC__metadata_iterator_init()
  88536. * \retval FLAC__bool
  88537. * \c false if the conditions in the above description are not met, or
  88538. * a memory allocation error occurs, otherwise \c true.
  88539. */
  88540. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88541. /* \} */
  88542. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88543. * \ingroup flac_metadata
  88544. *
  88545. * \brief
  88546. * This module contains methods for manipulating FLAC metadata objects.
  88547. *
  88548. * Since many are variable length we have to be careful about the memory
  88549. * management. We decree that all pointers to data in the object are
  88550. * owned by the object and memory-managed by the object.
  88551. *
  88552. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88553. * functions to create all instances. When using the
  88554. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88555. * \a copy to \c true to have the function make it's own copy of the data, or
  88556. * to \c false to give the object ownership of your data. In the latter case
  88557. * your pointer must be freeable by free() and will be free()d when the object
  88558. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88559. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88560. * the length argument is 0 and the \a copy argument is \c false.
  88561. *
  88562. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88563. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88564. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88565. * case of a memory allocation error.
  88566. *
  88567. * We don't have the convenience of C++ here, so note that the library relies
  88568. * on you to keep the types straight. In other words, if you pass, for
  88569. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88570. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88571. * failure.
  88572. *
  88573. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88574. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88575. * toward the length or stored in the stream, but it can make working with plain
  88576. * comments (those that don't contain embedded-NULs in the value) easier.
  88577. * Entries passed into these functions have trailing NULs added if missing, and
  88578. * returned entries are guaranteed to have a trailing NUL.
  88579. *
  88580. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88581. * comment entry/name/value will first validate that it complies with the Vorbis
  88582. * comment specification and return false if it does not.
  88583. *
  88584. * There is no need to recalculate the length field on metadata blocks you
  88585. * have modified. They will be calculated automatically before they are
  88586. * written back to a file.
  88587. *
  88588. * \{
  88589. */
  88590. /** Create a new metadata object instance of the given type.
  88591. *
  88592. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88593. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88594. * the vendor string set (but zero comments).
  88595. *
  88596. * Do not pass in a value greater than or equal to
  88597. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88598. * doing.
  88599. *
  88600. * \param type Type of object to create
  88601. * \retval FLAC__StreamMetadata*
  88602. * \c NULL if there was an error allocating memory or the type code is
  88603. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88604. */
  88605. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88606. /** Create a copy of an existing metadata object.
  88607. *
  88608. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88609. * object is also copied. The caller takes ownership of the new block and
  88610. * is responsible for freeing it with FLAC__metadata_object_delete().
  88611. *
  88612. * \param object Pointer to object to copy.
  88613. * \assert
  88614. * \code object != NULL \endcode
  88615. * \retval FLAC__StreamMetadata*
  88616. * \c NULL if there was an error allocating memory, else the new instance.
  88617. */
  88618. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88619. /** Free a metadata object. Deletes the object pointed to by \a object.
  88620. *
  88621. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88622. * object is also deleted.
  88623. *
  88624. * \param object A pointer to an existing object.
  88625. * \assert
  88626. * \code object != NULL \endcode
  88627. */
  88628. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88629. /** Compares two metadata objects.
  88630. *
  88631. * The compare is "deep", i.e. dynamically allocated data within the
  88632. * object is also compared.
  88633. *
  88634. * \param block1 A pointer to an existing object.
  88635. * \param block2 A pointer to an existing object.
  88636. * \assert
  88637. * \code block1 != NULL \endcode
  88638. * \code block2 != NULL \endcode
  88639. * \retval FLAC__bool
  88640. * \c true if objects are identical, else \c false.
  88641. */
  88642. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88643. /** Sets the application data of an APPLICATION block.
  88644. *
  88645. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88646. * takes ownership of the pointer. The existing data will be freed if this
  88647. * function is successful, otherwise the original data will remain if \a copy
  88648. * is \c true and malloc() fails.
  88649. *
  88650. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88651. *
  88652. * \param object A pointer to an existing APPLICATION object.
  88653. * \param data A pointer to the data to set.
  88654. * \param length The length of \a data in bytes.
  88655. * \param copy See above.
  88656. * \assert
  88657. * \code object != NULL \endcode
  88658. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88659. * \code (data != NULL && length > 0) ||
  88660. * (data == NULL && length == 0 && copy == false) \endcode
  88661. * \retval FLAC__bool
  88662. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88663. */
  88664. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88665. /** Resize the seekpoint array.
  88666. *
  88667. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88668. * points will be added to the end.
  88669. *
  88670. * \param object A pointer to an existing SEEKTABLE object.
  88671. * \param new_num_points The desired length of the array; may be \c 0.
  88672. * \assert
  88673. * \code object != NULL \endcode
  88674. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88675. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88676. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88677. * \retval FLAC__bool
  88678. * \c false if memory allocation error, else \c true.
  88679. */
  88680. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88681. /** Set a seekpoint in a seektable.
  88682. *
  88683. * \param object A pointer to an existing SEEKTABLE object.
  88684. * \param point_num Index into seekpoint array to set.
  88685. * \param point The point to set.
  88686. * \assert
  88687. * \code object != NULL \endcode
  88688. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88689. * \code object->data.seek_table.num_points > point_num \endcode
  88690. */
  88691. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88692. /** Insert a seekpoint into a seektable.
  88693. *
  88694. * \param object A pointer to an existing SEEKTABLE object.
  88695. * \param point_num Index into seekpoint array to set.
  88696. * \param point The point to set.
  88697. * \assert
  88698. * \code object != NULL \endcode
  88699. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88700. * \code object->data.seek_table.num_points >= point_num \endcode
  88701. * \retval FLAC__bool
  88702. * \c false if memory allocation error, else \c true.
  88703. */
  88704. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88705. /** Delete a seekpoint from a seektable.
  88706. *
  88707. * \param object A pointer to an existing SEEKTABLE object.
  88708. * \param point_num Index into seekpoint array to set.
  88709. * \assert
  88710. * \code object != NULL \endcode
  88711. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88712. * \code object->data.seek_table.num_points > point_num \endcode
  88713. * \retval FLAC__bool
  88714. * \c false if memory allocation error, else \c true.
  88715. */
  88716. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88717. /** Check a seektable to see if it conforms to the FLAC specification.
  88718. * See the format specification for limits on the contents of the
  88719. * seektable.
  88720. *
  88721. * \param object A pointer to an existing SEEKTABLE object.
  88722. * \assert
  88723. * \code object != NULL \endcode
  88724. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88725. * \retval FLAC__bool
  88726. * \c false if seek table is illegal, else \c true.
  88727. */
  88728. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88729. /** Append a number of placeholder points to the end of a seek table.
  88730. *
  88731. * \note
  88732. * As with the other ..._seektable_template_... functions, you should
  88733. * call FLAC__metadata_object_seektable_template_sort() when finished
  88734. * to make the seek table legal.
  88735. *
  88736. * \param object A pointer to an existing SEEKTABLE object.
  88737. * \param num The number of placeholder points to append.
  88738. * \assert
  88739. * \code object != NULL \endcode
  88740. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88741. * \retval FLAC__bool
  88742. * \c false if memory allocation fails, else \c true.
  88743. */
  88744. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88745. /** Append a specific seek point template to the end of a seek table.
  88746. *
  88747. * \note
  88748. * As with the other ..._seektable_template_... functions, you should
  88749. * call FLAC__metadata_object_seektable_template_sort() when finished
  88750. * to make the seek table legal.
  88751. *
  88752. * \param object A pointer to an existing SEEKTABLE object.
  88753. * \param sample_number The sample number of the seek point template.
  88754. * \assert
  88755. * \code object != NULL \endcode
  88756. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88757. * \retval FLAC__bool
  88758. * \c false if memory allocation fails, else \c true.
  88759. */
  88760. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88761. /** Append specific seek point templates to the end of a seek table.
  88762. *
  88763. * \note
  88764. * As with the other ..._seektable_template_... functions, you should
  88765. * call FLAC__metadata_object_seektable_template_sort() when finished
  88766. * to make the seek table legal.
  88767. *
  88768. * \param object A pointer to an existing SEEKTABLE object.
  88769. * \param sample_numbers An array of sample numbers for the seek points.
  88770. * \param num The number of seek point templates to append.
  88771. * \assert
  88772. * \code object != NULL \endcode
  88773. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88774. * \retval FLAC__bool
  88775. * \c false if memory allocation fails, else \c true.
  88776. */
  88777. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88778. /** Append a set of evenly-spaced seek point templates to the end of a
  88779. * seek table.
  88780. *
  88781. * \note
  88782. * As with the other ..._seektable_template_... functions, you should
  88783. * call FLAC__metadata_object_seektable_template_sort() when finished
  88784. * to make the seek table legal.
  88785. *
  88786. * \param object A pointer to an existing SEEKTABLE object.
  88787. * \param num The number of placeholder points to append.
  88788. * \param total_samples The total number of samples to be encoded;
  88789. * the seekpoints will be spaced approximately
  88790. * \a total_samples / \a num samples apart.
  88791. * \assert
  88792. * \code object != NULL \endcode
  88793. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88794. * \code total_samples > 0 \endcode
  88795. * \retval FLAC__bool
  88796. * \c false if memory allocation fails, else \c true.
  88797. */
  88798. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88799. /** Append a set of evenly-spaced seek point templates to the end of a
  88800. * seek table.
  88801. *
  88802. * \note
  88803. * As with the other ..._seektable_template_... functions, you should
  88804. * call FLAC__metadata_object_seektable_template_sort() when finished
  88805. * to make the seek table legal.
  88806. *
  88807. * \param object A pointer to an existing SEEKTABLE object.
  88808. * \param samples The number of samples apart to space the placeholder
  88809. * points. The first point will be at sample \c 0, the
  88810. * second at sample \a samples, then 2*\a samples, and
  88811. * so on. As long as \a samples and \a total_samples
  88812. * are greater than \c 0, there will always be at least
  88813. * one seekpoint at sample \c 0.
  88814. * \param total_samples The total number of samples to be encoded;
  88815. * the seekpoints will be spaced
  88816. * \a samples samples apart.
  88817. * \assert
  88818. * \code object != NULL \endcode
  88819. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88820. * \code samples > 0 \endcode
  88821. * \code total_samples > 0 \endcode
  88822. * \retval FLAC__bool
  88823. * \c false if memory allocation fails, else \c true.
  88824. */
  88825. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88826. /** Sort a seek table's seek points according to the format specification,
  88827. * removing duplicates.
  88828. *
  88829. * \param object A pointer to a seek table to be sorted.
  88830. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88831. * If \c true, duplicates are deleted and the seek table is
  88832. * shrunk appropriately; the number of placeholder points
  88833. * present in the seek table will be the same after the call
  88834. * as before.
  88835. * \assert
  88836. * \code object != NULL \endcode
  88837. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88838. * \retval FLAC__bool
  88839. * \c false if realloc() fails, else \c true.
  88840. */
  88841. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88842. /** Sets the vendor string in a VORBIS_COMMENT block.
  88843. *
  88844. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88845. * one already.
  88846. *
  88847. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88848. * takes ownership of the \c entry.entry pointer.
  88849. *
  88850. * \note If this function returns \c false, the caller still owns the
  88851. * pointer.
  88852. *
  88853. * \param object A pointer to an existing VORBIS_COMMENT object.
  88854. * \param entry The entry to set the vendor string to.
  88855. * \param copy See above.
  88856. * \assert
  88857. * \code object != NULL \endcode
  88858. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88859. * \code (entry.entry != NULL && entry.length > 0) ||
  88860. * (entry.entry == NULL && entry.length == 0) \endcode
  88861. * \retval FLAC__bool
  88862. * \c false if memory allocation fails or \a entry does not comply with the
  88863. * Vorbis comment specification, else \c true.
  88864. */
  88865. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88866. /** Resize the comment array.
  88867. *
  88868. * If the size shrinks, elements will truncated; if it grows, new empty
  88869. * fields will be added to the end.
  88870. *
  88871. * \param object A pointer to an existing VORBIS_COMMENT object.
  88872. * \param new_num_comments The desired length of the array; may be \c 0.
  88873. * \assert
  88874. * \code object != NULL \endcode
  88875. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88876. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88877. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88878. * \retval FLAC__bool
  88879. * \c false if memory allocation fails, else \c true.
  88880. */
  88881. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88882. /** Sets a comment in a VORBIS_COMMENT block.
  88883. *
  88884. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88885. * one already.
  88886. *
  88887. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88888. * takes ownership of the \c entry.entry pointer.
  88889. *
  88890. * \note If this function returns \c false, the caller still owns the
  88891. * pointer.
  88892. *
  88893. * \param object A pointer to an existing VORBIS_COMMENT object.
  88894. * \param comment_num Index into comment array to set.
  88895. * \param entry The entry to set the comment to.
  88896. * \param copy See above.
  88897. * \assert
  88898. * \code object != NULL \endcode
  88899. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88900. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88901. * \code (entry.entry != NULL && entry.length > 0) ||
  88902. * (entry.entry == NULL && entry.length == 0) \endcode
  88903. * \retval FLAC__bool
  88904. * \c false if memory allocation fails or \a entry does not comply with the
  88905. * Vorbis comment specification, else \c true.
  88906. */
  88907. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88908. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88909. *
  88910. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88911. * one already.
  88912. *
  88913. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88914. * takes ownership of the \c entry.entry pointer.
  88915. *
  88916. * \note If this function returns \c false, the caller still owns the
  88917. * pointer.
  88918. *
  88919. * \param object A pointer to an existing VORBIS_COMMENT object.
  88920. * \param comment_num The index at which to insert the comment. The comments
  88921. * at and after \a comment_num move right one position.
  88922. * To append a comment to the end, set \a comment_num to
  88923. * \c object->data.vorbis_comment.num_comments .
  88924. * \param entry The comment to insert.
  88925. * \param copy See above.
  88926. * \assert
  88927. * \code object != NULL \endcode
  88928. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88929. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88930. * \code (entry.entry != NULL && entry.length > 0) ||
  88931. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88932. * \retval FLAC__bool
  88933. * \c false if memory allocation fails or \a entry does not comply with the
  88934. * Vorbis comment specification, else \c true.
  88935. */
  88936. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88937. /** Appends a comment to a VORBIS_COMMENT block.
  88938. *
  88939. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88940. * one already.
  88941. *
  88942. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88943. * takes ownership of the \c entry.entry pointer.
  88944. *
  88945. * \note If this function returns \c false, the caller still owns the
  88946. * pointer.
  88947. *
  88948. * \param object A pointer to an existing VORBIS_COMMENT object.
  88949. * \param entry The comment to insert.
  88950. * \param copy See above.
  88951. * \assert
  88952. * \code object != NULL \endcode
  88953. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88954. * \code (entry.entry != NULL && entry.length > 0) ||
  88955. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88956. * \retval FLAC__bool
  88957. * \c false if memory allocation fails or \a entry does not comply with the
  88958. * Vorbis comment specification, else \c true.
  88959. */
  88960. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88961. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88962. *
  88963. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88964. * one already.
  88965. *
  88966. * Depending on the the value of \a all, either all or just the first comment
  88967. * whose field name(s) match the given entry's name will be replaced by the
  88968. * given entry. If no comments match, \a entry will simply be appended.
  88969. *
  88970. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88971. * takes ownership of the \c entry.entry pointer.
  88972. *
  88973. * \note If this function returns \c false, the caller still owns the
  88974. * pointer.
  88975. *
  88976. * \param object A pointer to an existing VORBIS_COMMENT object.
  88977. * \param entry The comment to insert.
  88978. * \param all If \c true, all comments whose field name matches
  88979. * \a entry's field name will be removed, and \a entry will
  88980. * be inserted at the position of the first matching
  88981. * comment. If \c false, only the first comment whose
  88982. * field name matches \a entry's field name will be
  88983. * replaced with \a entry.
  88984. * \param copy See above.
  88985. * \assert
  88986. * \code object != NULL \endcode
  88987. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88988. * \code (entry.entry != NULL && entry.length > 0) ||
  88989. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88990. * \retval FLAC__bool
  88991. * \c false if memory allocation fails or \a entry does not comply with the
  88992. * Vorbis comment specification, else \c true.
  88993. */
  88994. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88995. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88996. *
  88997. * \param object A pointer to an existing VORBIS_COMMENT object.
  88998. * \param comment_num The index of the comment to delete.
  88999. * \assert
  89000. * \code object != NULL \endcode
  89001. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89002. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  89003. * \retval FLAC__bool
  89004. * \c false if realloc() fails, else \c true.
  89005. */
  89006. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  89007. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  89008. *
  89009. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  89010. * memory and shall be owned by the caller. For convenience the entry will
  89011. * have a terminating NUL.
  89012. *
  89013. * \param entry A pointer to a Vorbis comment entry. The entry's
  89014. * \c entry pointer should not point to allocated
  89015. * memory as it will be overwritten.
  89016. * \param field_name The field name in ASCII, \c NUL terminated.
  89017. * \param field_value The field value in UTF-8, \c NUL terminated.
  89018. * \assert
  89019. * \code entry != NULL \endcode
  89020. * \code field_name != NULL \endcode
  89021. * \code field_value != NULL \endcode
  89022. * \retval FLAC__bool
  89023. * \c false if malloc() fails, or if \a field_name or \a field_value does
  89024. * not comply with the Vorbis comment specification, else \c true.
  89025. */
  89026. 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);
  89027. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  89028. *
  89029. * The returned pointers to name and value will be allocated by malloc()
  89030. * and shall be owned by the caller.
  89031. *
  89032. * \param entry An existing Vorbis comment entry.
  89033. * \param field_name The address of where the returned pointer to the
  89034. * field name will be stored.
  89035. * \param field_value The address of where the returned pointer to the
  89036. * field value will be stored.
  89037. * \assert
  89038. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89039. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89040. * \code field_name != NULL \endcode
  89041. * \code field_value != NULL \endcode
  89042. * \retval FLAC__bool
  89043. * \c false if memory allocation fails or \a entry does not comply with the
  89044. * Vorbis comment specification, else \c true.
  89045. */
  89046. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_to_name_value_pair(const FLAC__StreamMetadata_VorbisComment_Entry entry, char **field_name, char **field_value);
  89047. /** Check if the given Vorbis comment entry's field name matches the given
  89048. * field name.
  89049. *
  89050. * \param entry An existing Vorbis comment entry.
  89051. * \param field_name The field name to check.
  89052. * \param field_name_length The length of \a field_name, not including the
  89053. * terminating \c NUL.
  89054. * \assert
  89055. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89056. * \retval FLAC__bool
  89057. * \c true if the field names match, else \c false
  89058. */
  89059. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89060. /** Find a Vorbis comment with the given field name.
  89061. *
  89062. * The search begins at entry number \a offset; use an offset of 0 to
  89063. * search from the beginning of the comment array.
  89064. *
  89065. * \param object A pointer to an existing VORBIS_COMMENT object.
  89066. * \param offset The offset into the comment array from where to start
  89067. * the search.
  89068. * \param field_name The field name of the comment to find.
  89069. * \assert
  89070. * \code object != NULL \endcode
  89071. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89072. * \code field_name != NULL \endcode
  89073. * \retval int
  89074. * The offset in the comment array of the first comment whose field
  89075. * name matches \a field_name, or \c -1 if no match was found.
  89076. */
  89077. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89078. /** Remove first Vorbis comment matching the given field name.
  89079. *
  89080. * \param object A pointer to an existing VORBIS_COMMENT object.
  89081. * \param field_name The field name of comment to delete.
  89082. * \assert
  89083. * \code object != NULL \endcode
  89084. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89085. * \retval int
  89086. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89087. * \c 1 for one matching entry deleted.
  89088. */
  89089. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89090. /** Remove all Vorbis comments matching the given field name.
  89091. *
  89092. * \param object A pointer to an existing VORBIS_COMMENT object.
  89093. * \param field_name The field name of comments to delete.
  89094. * \assert
  89095. * \code object != NULL \endcode
  89096. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89097. * \retval int
  89098. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89099. * else the number of matching entries deleted.
  89100. */
  89101. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89102. /** Create a new CUESHEET track instance.
  89103. *
  89104. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89105. *
  89106. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89107. * \c NULL if there was an error allocating memory, else the new instance.
  89108. */
  89109. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89110. /** Create a copy of an existing CUESHEET track object.
  89111. *
  89112. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89113. * object is also copied. The caller takes ownership of the new object and
  89114. * is responsible for freeing it with
  89115. * FLAC__metadata_object_cuesheet_track_delete().
  89116. *
  89117. * \param object Pointer to object to copy.
  89118. * \assert
  89119. * \code object != NULL \endcode
  89120. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89121. * \c NULL if there was an error allocating memory, else the new instance.
  89122. */
  89123. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89124. /** Delete a CUESHEET track object
  89125. *
  89126. * \param object A pointer to an existing CUESHEET track object.
  89127. * \assert
  89128. * \code object != NULL \endcode
  89129. */
  89130. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89131. /** Resize a track's index point array.
  89132. *
  89133. * If the size shrinks, elements will truncated; if it grows, new blank
  89134. * indices will be added to the end.
  89135. *
  89136. * \param object A pointer to an existing CUESHEET object.
  89137. * \param track_num The index of the track to modify. NOTE: this is not
  89138. * necessarily the same as the track's \a number field.
  89139. * \param new_num_indices The desired length of the array; may be \c 0.
  89140. * \assert
  89141. * \code object != NULL \endcode
  89142. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89143. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89144. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89145. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89146. * \retval FLAC__bool
  89147. * \c false if memory allocation error, else \c true.
  89148. */
  89149. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89150. /** Insert an index point in a CUESHEET track at the given index.
  89151. *
  89152. * \param object A pointer to an existing CUESHEET object.
  89153. * \param track_num The index of the track to modify. NOTE: this is not
  89154. * necessarily the same as the track's \a number field.
  89155. * \param index_num The index into the track's index array at which to
  89156. * insert the index point. NOTE: this is not necessarily
  89157. * the same as the index point's \a number field. The
  89158. * indices at and after \a index_num move right one
  89159. * position. To append an index point to the end, set
  89160. * \a index_num to
  89161. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89162. * \param index The index point to insert.
  89163. * \assert
  89164. * \code object != NULL \endcode
  89165. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89166. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89167. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89168. * \retval FLAC__bool
  89169. * \c false if realloc() fails, else \c true.
  89170. */
  89171. 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);
  89172. /** Insert a blank index point in a CUESHEET track at the given index.
  89173. *
  89174. * A blank index point is one in which all field values are zero.
  89175. *
  89176. * \param object A pointer to an existing CUESHEET object.
  89177. * \param track_num The index of the track to modify. NOTE: this is not
  89178. * necessarily the same as the track's \a number field.
  89179. * \param index_num The index into the track's index array at which to
  89180. * insert the index point. NOTE: this is not necessarily
  89181. * the same as the index point's \a number field. The
  89182. * indices at and after \a index_num move right one
  89183. * position. To append an index point to the end, set
  89184. * \a index_num to
  89185. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89186. * \assert
  89187. * \code object != NULL \endcode
  89188. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89189. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89190. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89191. * \retval FLAC__bool
  89192. * \c false if realloc() fails, else \c true.
  89193. */
  89194. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89195. /** Delete an index point in a CUESHEET track at the given index.
  89196. *
  89197. * \param object A pointer to an existing CUESHEET object.
  89198. * \param track_num The index into the track array of the track to
  89199. * modify. NOTE: this is not necessarily the same
  89200. * as the track's \a number field.
  89201. * \param index_num The index into the track's index array of the index
  89202. * to delete. NOTE: this is not necessarily the same
  89203. * as the index's \a number field.
  89204. * \assert
  89205. * \code object != NULL \endcode
  89206. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89207. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89208. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89209. * \retval FLAC__bool
  89210. * \c false if realloc() fails, else \c true.
  89211. */
  89212. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89213. /** Resize the track array.
  89214. *
  89215. * If the size shrinks, elements will truncated; if it grows, new blank
  89216. * tracks will be added to the end.
  89217. *
  89218. * \param object A pointer to an existing CUESHEET object.
  89219. * \param new_num_tracks The desired length of the array; may be \c 0.
  89220. * \assert
  89221. * \code object != NULL \endcode
  89222. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89223. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89224. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89225. * \retval FLAC__bool
  89226. * \c false if memory allocation error, else \c true.
  89227. */
  89228. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89229. /** Sets a track in a CUESHEET block.
  89230. *
  89231. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89232. * takes ownership of the \a track pointer.
  89233. *
  89234. * \param object A pointer to an existing CUESHEET object.
  89235. * \param track_num Index into track array to set. NOTE: this is not
  89236. * necessarily the same as the track's \a number field.
  89237. * \param track The track to set the track to. You may safely pass in
  89238. * a const pointer if \a copy is \c true.
  89239. * \param copy See above.
  89240. * \assert
  89241. * \code object != NULL \endcode
  89242. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89243. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89244. * \code (track->indices != NULL && track->num_indices > 0) ||
  89245. * (track->indices == NULL && track->num_indices == 0)
  89246. * \retval FLAC__bool
  89247. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89248. */
  89249. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89250. /** Insert a track in a CUESHEET block at the given index.
  89251. *
  89252. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89253. * takes ownership of the \a track pointer.
  89254. *
  89255. * \param object A pointer to an existing CUESHEET object.
  89256. * \param track_num The index at which to insert the track. NOTE: this
  89257. * is not necessarily the same as the track's \a number
  89258. * field. The tracks at and after \a track_num move right
  89259. * one position. To append a track to the end, set
  89260. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89261. * \param track The track to insert. You may safely pass in a const
  89262. * pointer if \a copy is \c true.
  89263. * \param copy See above.
  89264. * \assert
  89265. * \code object != NULL \endcode
  89266. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89267. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89268. * \retval FLAC__bool
  89269. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89270. */
  89271. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89272. /** Insert a blank track in a CUESHEET block at the given index.
  89273. *
  89274. * A blank track is one in which all field values are zero.
  89275. *
  89276. * \param object A pointer to an existing CUESHEET object.
  89277. * \param track_num The index at which to insert the track. NOTE: this
  89278. * is not necessarily the same as the track's \a number
  89279. * field. The tracks at and after \a track_num move right
  89280. * one position. To append a track to the end, set
  89281. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89282. * \assert
  89283. * \code object != NULL \endcode
  89284. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89285. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89286. * \retval FLAC__bool
  89287. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89288. */
  89289. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89290. /** Delete a track in a CUESHEET block at the given index.
  89291. *
  89292. * \param object A pointer to an existing CUESHEET object.
  89293. * \param track_num The index into the track array of the track to
  89294. * delete. NOTE: this is not necessarily the same
  89295. * as the track's \a number field.
  89296. * \assert
  89297. * \code object != NULL \endcode
  89298. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89299. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89300. * \retval FLAC__bool
  89301. * \c false if realloc() fails, else \c true.
  89302. */
  89303. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89304. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89305. * See the format specification for limits on the contents of the
  89306. * cue sheet.
  89307. *
  89308. * \param object A pointer to an existing CUESHEET object.
  89309. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89310. * stringent requirements for a CD-DA (audio) disc.
  89311. * \param violation Address of a pointer to a string. If there is a
  89312. * violation, a pointer to a string explanation of the
  89313. * violation will be returned here. \a violation may be
  89314. * \c NULL if you don't need the returned string. Do not
  89315. * free the returned string; it will always point to static
  89316. * data.
  89317. * \assert
  89318. * \code object != NULL \endcode
  89319. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89320. * \retval FLAC__bool
  89321. * \c false if cue sheet is illegal, else \c true.
  89322. */
  89323. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89324. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89325. * assumes the cue sheet corresponds to a CD; the result is undefined
  89326. * if the cuesheet's is_cd bit is not set.
  89327. *
  89328. * \param object A pointer to an existing CUESHEET object.
  89329. * \assert
  89330. * \code object != NULL \endcode
  89331. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89332. * \retval FLAC__uint32
  89333. * The unsigned integer representation of the CDDB/freedb ID
  89334. */
  89335. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89336. /** Sets the MIME type of a PICTURE block.
  89337. *
  89338. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89339. * takes ownership of the pointer. The existing string will be freed if this
  89340. * function is successful, otherwise the original string will remain if \a copy
  89341. * is \c true and malloc() fails.
  89342. *
  89343. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89344. *
  89345. * \param object A pointer to an existing PICTURE object.
  89346. * \param mime_type A pointer to the MIME type string. The string must be
  89347. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89348. * is done.
  89349. * \param copy See above.
  89350. * \assert
  89351. * \code object != NULL \endcode
  89352. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89353. * \code (mime_type != NULL) \endcode
  89354. * \retval FLAC__bool
  89355. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89356. */
  89357. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89358. /** Sets the description of a PICTURE block.
  89359. *
  89360. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89361. * takes ownership of the pointer. The existing string will be freed if this
  89362. * function is successful, otherwise the original string will remain if \a copy
  89363. * is \c true and malloc() fails.
  89364. *
  89365. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89366. *
  89367. * \param object A pointer to an existing PICTURE object.
  89368. * \param description A pointer to the description string. The string must be
  89369. * valid UTF-8, NUL-terminated. No validation is done.
  89370. * \param copy See above.
  89371. * \assert
  89372. * \code object != NULL \endcode
  89373. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89374. * \code (description != NULL) \endcode
  89375. * \retval FLAC__bool
  89376. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89377. */
  89378. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89379. /** Sets the picture data of a PICTURE block.
  89380. *
  89381. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89382. * takes ownership of the pointer. Also sets the \a data_length field of the
  89383. * metadata object to what is passed in as the \a length parameter. The
  89384. * existing data will be freed if this function is successful, otherwise the
  89385. * original data and data_length will remain if \a copy is \c true and
  89386. * malloc() fails.
  89387. *
  89388. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89389. *
  89390. * \param object A pointer to an existing PICTURE object.
  89391. * \param data A pointer to the data to set.
  89392. * \param length The length of \a data in bytes.
  89393. * \param copy See above.
  89394. * \assert
  89395. * \code object != NULL \endcode
  89396. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89397. * \code (data != NULL && length > 0) ||
  89398. * (data == NULL && length == 0 && copy == false) \endcode
  89399. * \retval FLAC__bool
  89400. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89401. */
  89402. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89403. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89404. * See the format specification for limits on the contents of the
  89405. * PICTURE block.
  89406. *
  89407. * \param object A pointer to existing PICTURE block to be checked.
  89408. * \param violation Address of a pointer to a string. If there is a
  89409. * violation, a pointer to a string explanation of the
  89410. * violation will be returned here. \a violation may be
  89411. * \c NULL if you don't need the returned string. Do not
  89412. * free the returned string; it will always point to static
  89413. * data.
  89414. * \assert
  89415. * \code object != NULL \endcode
  89416. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89417. * \retval FLAC__bool
  89418. * \c false if PICTURE block is illegal, else \c true.
  89419. */
  89420. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89421. /* \} */
  89422. #ifdef __cplusplus
  89423. }
  89424. #endif
  89425. #endif
  89426. /*** End of inlined file: metadata.h ***/
  89427. /*** Start of inlined file: stream_decoder.h ***/
  89428. #ifndef FLAC__STREAM_DECODER_H
  89429. #define FLAC__STREAM_DECODER_H
  89430. #include <stdio.h> /* for FILE */
  89431. #ifdef __cplusplus
  89432. extern "C" {
  89433. #endif
  89434. /** \file include/FLAC/stream_decoder.h
  89435. *
  89436. * \brief
  89437. * This module contains the functions which implement the stream
  89438. * decoder.
  89439. *
  89440. * See the detailed documentation in the
  89441. * \link flac_stream_decoder stream decoder \endlink module.
  89442. */
  89443. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89444. * \ingroup flac
  89445. *
  89446. * \brief
  89447. * This module describes the decoder layers provided by libFLAC.
  89448. *
  89449. * The stream decoder can be used to decode complete streams either from
  89450. * the client via callbacks, or directly from a file, depending on how
  89451. * it is initialized. When decoding via callbacks, the client provides
  89452. * callbacks for reading FLAC data and writing decoded samples, and
  89453. * handling metadata and errors. If the client also supplies seek-related
  89454. * callback, the decoder function for sample-accurate seeking within the
  89455. * FLAC input is also available. When decoding from a file, the client
  89456. * needs only supply a filename or open \c FILE* and write/metadata/error
  89457. * callbacks; the rest of the callbacks are supplied internally. For more
  89458. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89459. */
  89460. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89461. * \ingroup flac_decoder
  89462. *
  89463. * \brief
  89464. * This module contains the functions which implement the stream
  89465. * decoder.
  89466. *
  89467. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89468. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89469. *
  89470. * The basic usage of this decoder is as follows:
  89471. * - The program creates an instance of a decoder using
  89472. * FLAC__stream_decoder_new().
  89473. * - The program overrides the default settings using
  89474. * FLAC__stream_decoder_set_*() functions.
  89475. * - The program initializes the instance to validate the settings and
  89476. * prepare for decoding using
  89477. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89478. * or FLAC__stream_decoder_init_file() for native FLAC,
  89479. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89480. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89481. * - The program calls the FLAC__stream_decoder_process_*() functions
  89482. * to decode data, which subsequently calls the callbacks.
  89483. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89484. * which flushes the input and output and resets the decoder to the
  89485. * uninitialized state.
  89486. * - The instance may be used again or deleted with
  89487. * FLAC__stream_decoder_delete().
  89488. *
  89489. * In more detail, the program will create a new instance by calling
  89490. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89491. * functions to override the default decoder options, and call
  89492. * one of the FLAC__stream_decoder_init_*() functions.
  89493. *
  89494. * There are three initialization functions for native FLAC, one for
  89495. * setting up the decoder to decode FLAC data from the client via
  89496. * callbacks, and two for decoding directly from a FLAC file.
  89497. *
  89498. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89499. * You must also supply several callbacks for handling I/O. Some (like
  89500. * seeking) are optional, depending on the capabilities of the input.
  89501. *
  89502. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89503. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89504. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89505. * the other callbacks internally.
  89506. *
  89507. * There are three similarly-named init functions for decoding from Ogg
  89508. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89509. * library has been built with Ogg support.
  89510. *
  89511. * Once the decoder is initialized, your program will call one of several
  89512. * functions to start the decoding process:
  89513. *
  89514. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89515. * most one metadata block or audio frame and return, calling either the
  89516. * metadata callback or write callback, respectively, once. If the decoder
  89517. * loses sync it will return with only the error callback being called.
  89518. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89519. * to process the stream from the current location and stop upon reaching
  89520. * the first audio frame. The client will get one metadata, write, or error
  89521. * callback per metadata block, audio frame, or sync error, respectively.
  89522. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89523. * to process the stream from the current location until the read callback
  89524. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89525. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89526. * write, or error callback per metadata block, audio frame, or sync error,
  89527. * respectively.
  89528. *
  89529. * When the decoder has finished decoding (normally or through an abort),
  89530. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89531. * ensures the decoder is in the correct state and frees memory. Then the
  89532. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89533. * again to decode another stream.
  89534. *
  89535. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89536. * At any point after the stream decoder has been initialized, the client can
  89537. * call this function to seek to an exact sample within the stream.
  89538. * Subsequently, the first time the write callback is called it will be
  89539. * passed a (possibly partial) block starting at that sample.
  89540. *
  89541. * If the client cannot seek via the callback interface provided, but still
  89542. * has another way of seeking, it can flush the decoder using
  89543. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89544. * through the read callback.
  89545. *
  89546. * The stream decoder also provides MD5 signature checking. If this is
  89547. * turned on before initialization, FLAC__stream_decoder_finish() will
  89548. * report when the decoded MD5 signature does not match the one stored
  89549. * in the STREAMINFO block. MD5 checking is automatically turned off
  89550. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89551. * in the STREAMINFO block or when a seek is attempted.
  89552. *
  89553. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89554. * attention. By default, the decoder only calls the metadata_callback for
  89555. * the STREAMINFO block. These functions allow you to tell the decoder
  89556. * explicitly which blocks to parse and return via the metadata_callback
  89557. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89558. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89559. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89560. * which blocks to return. Remember that metadata blocks can potentially
  89561. * be big (for example, cover art) so filtering out the ones you don't
  89562. * use can reduce the memory requirements of the decoder. Also note the
  89563. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89564. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89565. * filtering APPLICATION blocks based on the application ID.
  89566. *
  89567. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89568. * they still can legally be filtered from the metadata_callback.
  89569. *
  89570. * \note
  89571. * The "set" functions may only be called when the decoder is in the
  89572. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89573. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89574. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89575. * return \c true, otherwise \c false.
  89576. *
  89577. * \note
  89578. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89579. * defaults, including the callbacks.
  89580. *
  89581. * \{
  89582. */
  89583. /** State values for a FLAC__StreamDecoder
  89584. *
  89585. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89586. */
  89587. typedef enum {
  89588. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89589. /**< The decoder is ready to search for metadata. */
  89590. FLAC__STREAM_DECODER_READ_METADATA,
  89591. /**< The decoder is ready to or is in the process of reading metadata. */
  89592. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89593. /**< The decoder is ready to or is in the process of searching for the
  89594. * frame sync code.
  89595. */
  89596. FLAC__STREAM_DECODER_READ_FRAME,
  89597. /**< The decoder is ready to or is in the process of reading a frame. */
  89598. FLAC__STREAM_DECODER_END_OF_STREAM,
  89599. /**< The decoder has reached the end of the stream. */
  89600. FLAC__STREAM_DECODER_OGG_ERROR,
  89601. /**< An error occurred in the underlying Ogg layer. */
  89602. FLAC__STREAM_DECODER_SEEK_ERROR,
  89603. /**< An error occurred while seeking. The decoder must be flushed
  89604. * with FLAC__stream_decoder_flush() or reset with
  89605. * FLAC__stream_decoder_reset() before decoding can continue.
  89606. */
  89607. FLAC__STREAM_DECODER_ABORTED,
  89608. /**< The decoder was aborted by the read callback. */
  89609. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89610. /**< An error occurred allocating memory. The decoder is in an invalid
  89611. * state and can no longer be used.
  89612. */
  89613. FLAC__STREAM_DECODER_UNINITIALIZED
  89614. /**< The decoder is in the uninitialized state; one of the
  89615. * FLAC__stream_decoder_init_*() functions must be called before samples
  89616. * can be processed.
  89617. */
  89618. } FLAC__StreamDecoderState;
  89619. /** Maps a FLAC__StreamDecoderState to a C string.
  89620. *
  89621. * Using a FLAC__StreamDecoderState as the index to this array
  89622. * will give the string equivalent. The contents should not be modified.
  89623. */
  89624. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89625. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89626. */
  89627. typedef enum {
  89628. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89629. /**< Initialization was successful. */
  89630. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89631. /**< The library was not compiled with support for the given container
  89632. * format.
  89633. */
  89634. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89635. /**< A required callback was not supplied. */
  89636. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89637. /**< An error occurred allocating memory. */
  89638. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89639. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89640. * FLAC__stream_decoder_init_ogg_file(). */
  89641. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89642. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89643. * already initialized, usually because
  89644. * FLAC__stream_decoder_finish() was not called.
  89645. */
  89646. } FLAC__StreamDecoderInitStatus;
  89647. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89648. *
  89649. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89650. * will give the string equivalent. The contents should not be modified.
  89651. */
  89652. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89653. /** Return values for the FLAC__StreamDecoder read callback.
  89654. */
  89655. typedef enum {
  89656. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89657. /**< The read was OK and decoding can continue. */
  89658. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89659. /**< The read was attempted while at the end of the stream. Note that
  89660. * the client must only return this value when the read callback was
  89661. * called when already at the end of the stream. Otherwise, if the read
  89662. * itself moves to the end of the stream, the client should still return
  89663. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89664. * the next read callback it should return
  89665. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89666. * of \c 0.
  89667. */
  89668. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89669. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89670. } FLAC__StreamDecoderReadStatus;
  89671. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89672. *
  89673. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89674. * will give the string equivalent. The contents should not be modified.
  89675. */
  89676. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89677. /** Return values for the FLAC__StreamDecoder seek callback.
  89678. */
  89679. typedef enum {
  89680. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89681. /**< The seek was OK and decoding can continue. */
  89682. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89683. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89684. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89685. /**< Client does not support seeking. */
  89686. } FLAC__StreamDecoderSeekStatus;
  89687. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89688. *
  89689. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89690. * will give the string equivalent. The contents should not be modified.
  89691. */
  89692. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89693. /** Return values for the FLAC__StreamDecoder tell callback.
  89694. */
  89695. typedef enum {
  89696. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89697. /**< The tell was OK and decoding can continue. */
  89698. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89699. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89700. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89701. /**< Client does not support telling the position. */
  89702. } FLAC__StreamDecoderTellStatus;
  89703. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89704. *
  89705. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89706. * will give the string equivalent. The contents should not be modified.
  89707. */
  89708. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89709. /** Return values for the FLAC__StreamDecoder length callback.
  89710. */
  89711. typedef enum {
  89712. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89713. /**< The length call was OK and decoding can continue. */
  89714. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89715. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89716. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89717. /**< Client does not support reporting the length. */
  89718. } FLAC__StreamDecoderLengthStatus;
  89719. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89720. *
  89721. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89722. * will give the string equivalent. The contents should not be modified.
  89723. */
  89724. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89725. /** Return values for the FLAC__StreamDecoder write callback.
  89726. */
  89727. typedef enum {
  89728. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89729. /**< The write was OK and decoding can continue. */
  89730. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89731. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89732. } FLAC__StreamDecoderWriteStatus;
  89733. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89734. *
  89735. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89736. * will give the string equivalent. The contents should not be modified.
  89737. */
  89738. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89739. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89740. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89741. * all. The rest could be caused by bad sync (false synchronization on
  89742. * data that is not the start of a frame) or corrupted data. The error
  89743. * itself is the decoder's best guess at what happened assuming a correct
  89744. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89745. * could be caused by a correct sync on the start of a frame, but some
  89746. * data in the frame header was corrupted. Or it could be the result of
  89747. * syncing on a point the stream that looked like the starting of a frame
  89748. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89749. * could be because the decoder encountered a valid frame made by a future
  89750. * version of the encoder which it cannot parse, or because of a false
  89751. * sync making it appear as though an encountered frame was generated by
  89752. * a future encoder.
  89753. */
  89754. typedef enum {
  89755. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89756. /**< An error in the stream caused the decoder to lose synchronization. */
  89757. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89758. /**< The decoder encountered a corrupted frame header. */
  89759. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89760. /**< The frame's data did not match the CRC in the footer. */
  89761. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89762. /**< The decoder encountered reserved fields in use in the stream. */
  89763. } FLAC__StreamDecoderErrorStatus;
  89764. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89765. *
  89766. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89767. * will give the string equivalent. The contents should not be modified.
  89768. */
  89769. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89770. /***********************************************************************
  89771. *
  89772. * class FLAC__StreamDecoder
  89773. *
  89774. ***********************************************************************/
  89775. struct FLAC__StreamDecoderProtected;
  89776. struct FLAC__StreamDecoderPrivate;
  89777. /** The opaque structure definition for the stream decoder type.
  89778. * See the \link flac_stream_decoder stream decoder module \endlink
  89779. * for a detailed description.
  89780. */
  89781. typedef struct {
  89782. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89783. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89784. } FLAC__StreamDecoder;
  89785. /** Signature for the read callback.
  89786. *
  89787. * A function pointer matching this signature must be passed to
  89788. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89789. * called when the decoder needs more input data. The address of the
  89790. * buffer to be filled is supplied, along with the number of bytes the
  89791. * buffer can hold. The callback may choose to supply less data and
  89792. * modify the byte count but must be careful not to overflow the buffer.
  89793. * The callback then returns a status code chosen from
  89794. * FLAC__StreamDecoderReadStatus.
  89795. *
  89796. * Here is an example of a read callback for stdio streams:
  89797. * \code
  89798. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89799. * {
  89800. * FILE *file = ((MyClientData*)client_data)->file;
  89801. * if(*bytes > 0) {
  89802. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89803. * if(ferror(file))
  89804. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89805. * else if(*bytes == 0)
  89806. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89807. * else
  89808. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89809. * }
  89810. * else
  89811. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89812. * }
  89813. * \endcode
  89814. *
  89815. * \note In general, FLAC__StreamDecoder functions which change the
  89816. * state should not be called on the \a decoder while in the callback.
  89817. *
  89818. * \param decoder The decoder instance calling the callback.
  89819. * \param buffer A pointer to a location for the callee to store
  89820. * data to be decoded.
  89821. * \param bytes A pointer to the size of the buffer. On entry
  89822. * to the callback, it contains the maximum number
  89823. * of bytes that may be stored in \a buffer. The
  89824. * callee must set it to the actual number of bytes
  89825. * stored (0 in case of error or end-of-stream) before
  89826. * returning.
  89827. * \param client_data The callee's client data set through
  89828. * FLAC__stream_decoder_init_*().
  89829. * \retval FLAC__StreamDecoderReadStatus
  89830. * The callee's return status. Note that the callback should return
  89831. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89832. * zero bytes were read and there is no more data to be read.
  89833. */
  89834. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89835. /** Signature for the seek callback.
  89836. *
  89837. * A function pointer matching this signature may be passed to
  89838. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89839. * called when the decoder needs to seek the input stream. The decoder
  89840. * will pass the absolute byte offset to seek to, 0 meaning the
  89841. * beginning of the stream.
  89842. *
  89843. * Here is an example of a seek callback for stdio streams:
  89844. * \code
  89845. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89846. * {
  89847. * FILE *file = ((MyClientData*)client_data)->file;
  89848. * if(file == stdin)
  89849. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89850. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89851. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89852. * else
  89853. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89854. * }
  89855. * \endcode
  89856. *
  89857. * \note In general, FLAC__StreamDecoder functions which change the
  89858. * state should not be called on the \a decoder while in the callback.
  89859. *
  89860. * \param decoder The decoder instance calling the callback.
  89861. * \param absolute_byte_offset The offset from the beginning of the stream
  89862. * to seek to.
  89863. * \param client_data The callee's client data set through
  89864. * FLAC__stream_decoder_init_*().
  89865. * \retval FLAC__StreamDecoderSeekStatus
  89866. * The callee's return status.
  89867. */
  89868. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89869. /** Signature for the tell callback.
  89870. *
  89871. * A function pointer matching this signature may be passed to
  89872. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89873. * called when the decoder wants to know the current position of the
  89874. * stream. The callback should return the byte offset from the
  89875. * beginning of the stream.
  89876. *
  89877. * Here is an example of a tell callback for stdio streams:
  89878. * \code
  89879. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89880. * {
  89881. * FILE *file = ((MyClientData*)client_data)->file;
  89882. * off_t pos;
  89883. * if(file == stdin)
  89884. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89885. * else if((pos = ftello(file)) < 0)
  89886. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89887. * else {
  89888. * *absolute_byte_offset = (FLAC__uint64)pos;
  89889. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89890. * }
  89891. * }
  89892. * \endcode
  89893. *
  89894. * \note In general, FLAC__StreamDecoder functions which change the
  89895. * state should not be called on the \a decoder while in the callback.
  89896. *
  89897. * \param decoder The decoder instance calling the callback.
  89898. * \param absolute_byte_offset A pointer to storage for the current offset
  89899. * from the beginning of the stream.
  89900. * \param client_data The callee's client data set through
  89901. * FLAC__stream_decoder_init_*().
  89902. * \retval FLAC__StreamDecoderTellStatus
  89903. * The callee's return status.
  89904. */
  89905. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89906. /** Signature for the length callback.
  89907. *
  89908. * A function pointer matching this signature may be passed to
  89909. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89910. * called when the decoder wants to know the total length of the stream
  89911. * in bytes.
  89912. *
  89913. * Here is an example of a length callback for stdio streams:
  89914. * \code
  89915. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89916. * {
  89917. * FILE *file = ((MyClientData*)client_data)->file;
  89918. * struct stat filestats;
  89919. *
  89920. * if(file == stdin)
  89921. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89922. * else if(fstat(fileno(file), &filestats) != 0)
  89923. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89924. * else {
  89925. * *stream_length = (FLAC__uint64)filestats.st_size;
  89926. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89927. * }
  89928. * }
  89929. * \endcode
  89930. *
  89931. * \note In general, FLAC__StreamDecoder functions which change the
  89932. * state should not be called on the \a decoder while in the callback.
  89933. *
  89934. * \param decoder The decoder instance calling the callback.
  89935. * \param stream_length A pointer to storage for the length of the stream
  89936. * in bytes.
  89937. * \param client_data The callee's client data set through
  89938. * FLAC__stream_decoder_init_*().
  89939. * \retval FLAC__StreamDecoderLengthStatus
  89940. * The callee's return status.
  89941. */
  89942. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89943. /** Signature for the EOF callback.
  89944. *
  89945. * A function pointer matching this signature may be passed to
  89946. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89947. * called when the decoder needs to know if the end of the stream has
  89948. * been reached.
  89949. *
  89950. * Here is an example of a EOF callback for stdio streams:
  89951. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89952. * \code
  89953. * {
  89954. * FILE *file = ((MyClientData*)client_data)->file;
  89955. * return feof(file)? true : false;
  89956. * }
  89957. * \endcode
  89958. *
  89959. * \note In general, FLAC__StreamDecoder functions which change the
  89960. * state should not be called on the \a decoder while in the callback.
  89961. *
  89962. * \param decoder The decoder instance calling the callback.
  89963. * \param client_data The callee's client data set through
  89964. * FLAC__stream_decoder_init_*().
  89965. * \retval FLAC__bool
  89966. * \c true if the currently at the end of the stream, else \c false.
  89967. */
  89968. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89969. /** Signature for the write callback.
  89970. *
  89971. * A function pointer matching this signature must be passed to one of
  89972. * the FLAC__stream_decoder_init_*() functions.
  89973. * The supplied function will be called when the decoder has decoded a
  89974. * single audio frame. The decoder will pass the frame metadata as well
  89975. * as an array of pointers (one for each channel) pointing to the
  89976. * decoded audio.
  89977. *
  89978. * \note In general, FLAC__StreamDecoder functions which change the
  89979. * state should not be called on the \a decoder while in the callback.
  89980. *
  89981. * \param decoder The decoder instance calling the callback.
  89982. * \param frame The description of the decoded frame. See
  89983. * FLAC__Frame.
  89984. * \param buffer An array of pointers to decoded channels of data.
  89985. * Each pointer will point to an array of signed
  89986. * samples of length \a frame->header.blocksize.
  89987. * Channels will be ordered according to the FLAC
  89988. * specification; see the documentation for the
  89989. * <A HREF="../format.html#frame_header">frame header</A>.
  89990. * \param client_data The callee's client data set through
  89991. * FLAC__stream_decoder_init_*().
  89992. * \retval FLAC__StreamDecoderWriteStatus
  89993. * The callee's return status.
  89994. */
  89995. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89996. /** Signature for the metadata callback.
  89997. *
  89998. * A function pointer matching this signature must be passed to one of
  89999. * the FLAC__stream_decoder_init_*() functions.
  90000. * The supplied function will be called when the decoder has decoded a
  90001. * metadata block. In a valid FLAC file there will always be one
  90002. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  90003. * These will be supplied by the decoder in the same order as they
  90004. * appear in the stream and always before the first audio frame (i.e.
  90005. * write callback). The metadata block that is passed in must not be
  90006. * modified, and it doesn't live beyond the callback, so you should make
  90007. * a copy of it with FLAC__metadata_object_clone() if you will need it
  90008. * elsewhere. Since metadata blocks can potentially be large, by
  90009. * default the decoder only calls the metadata callback for the
  90010. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  90011. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  90012. *
  90013. * \note In general, FLAC__StreamDecoder functions which change the
  90014. * state should not be called on the \a decoder while in the callback.
  90015. *
  90016. * \param decoder The decoder instance calling the callback.
  90017. * \param metadata The decoded metadata block.
  90018. * \param client_data The callee's client data set through
  90019. * FLAC__stream_decoder_init_*().
  90020. */
  90021. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90022. /** Signature for the error callback.
  90023. *
  90024. * A function pointer matching this signature must be passed to one of
  90025. * the FLAC__stream_decoder_init_*() functions.
  90026. * The supplied function will be called whenever an error occurs during
  90027. * decoding.
  90028. *
  90029. * \note In general, FLAC__StreamDecoder functions which change the
  90030. * state should not be called on the \a decoder while in the callback.
  90031. *
  90032. * \param decoder The decoder instance calling the callback.
  90033. * \param status The error encountered by the decoder.
  90034. * \param client_data The callee's client data set through
  90035. * FLAC__stream_decoder_init_*().
  90036. */
  90037. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90038. /***********************************************************************
  90039. *
  90040. * Class constructor/destructor
  90041. *
  90042. ***********************************************************************/
  90043. /** Create a new stream decoder instance. The instance is created with
  90044. * default settings; see the individual FLAC__stream_decoder_set_*()
  90045. * functions for each setting's default.
  90046. *
  90047. * \retval FLAC__StreamDecoder*
  90048. * \c NULL if there was an error allocating memory, else the new instance.
  90049. */
  90050. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90051. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90052. *
  90053. * \param decoder A pointer to an existing decoder.
  90054. * \assert
  90055. * \code decoder != NULL \endcode
  90056. */
  90057. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90058. /***********************************************************************
  90059. *
  90060. * Public class method prototypes
  90061. *
  90062. ***********************************************************************/
  90063. /** Set the serial number for the FLAC stream within the Ogg container.
  90064. * The default behavior is to use the serial number of the first Ogg
  90065. * page. Setting a serial number here will explicitly specify which
  90066. * stream is to be decoded.
  90067. *
  90068. * \note
  90069. * This does not need to be set for native FLAC decoding.
  90070. *
  90071. * \default \c use serial number of first page
  90072. * \param decoder A decoder instance to set.
  90073. * \param serial_number See above.
  90074. * \assert
  90075. * \code decoder != NULL \endcode
  90076. * \retval FLAC__bool
  90077. * \c false if the decoder is already initialized, else \c true.
  90078. */
  90079. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90080. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90081. * compute the MD5 signature of the unencoded audio data while decoding
  90082. * and compare it to the signature from the STREAMINFO block, if it
  90083. * exists, during FLAC__stream_decoder_finish().
  90084. *
  90085. * MD5 signature checking will be turned off (until the next
  90086. * FLAC__stream_decoder_reset()) if there is no signature in the
  90087. * STREAMINFO block or when a seek is attempted.
  90088. *
  90089. * Clients that do not use the MD5 check should leave this off to speed
  90090. * up decoding.
  90091. *
  90092. * \default \c false
  90093. * \param decoder A decoder instance to set.
  90094. * \param value Flag value (see above).
  90095. * \assert
  90096. * \code decoder != NULL \endcode
  90097. * \retval FLAC__bool
  90098. * \c false if the decoder is already initialized, else \c true.
  90099. */
  90100. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90101. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90102. *
  90103. * \default By default, only the \c STREAMINFO block is returned via the
  90104. * metadata callback.
  90105. * \param decoder A decoder instance to set.
  90106. * \param type See above.
  90107. * \assert
  90108. * \code decoder != NULL \endcode
  90109. * \a type is valid
  90110. * \retval FLAC__bool
  90111. * \c false if the decoder is already initialized, else \c true.
  90112. */
  90113. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90114. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90115. * given \a id.
  90116. *
  90117. * \default By default, only the \c STREAMINFO block is returned via the
  90118. * metadata callback.
  90119. * \param decoder A decoder instance to set.
  90120. * \param id See above.
  90121. * \assert
  90122. * \code decoder != NULL \endcode
  90123. * \code id != NULL \endcode
  90124. * \retval FLAC__bool
  90125. * \c false if the decoder is already initialized, else \c true.
  90126. */
  90127. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90128. /** Direct the decoder to pass on all metadata blocks of any type.
  90129. *
  90130. * \default By default, only the \c STREAMINFO block is returned via the
  90131. * metadata callback.
  90132. * \param decoder A decoder instance to set.
  90133. * \assert
  90134. * \code decoder != NULL \endcode
  90135. * \retval FLAC__bool
  90136. * \c false if the decoder is already initialized, else \c true.
  90137. */
  90138. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90139. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90140. *
  90141. * \default By default, only the \c STREAMINFO block is returned via the
  90142. * metadata callback.
  90143. * \param decoder A decoder instance to set.
  90144. * \param type See above.
  90145. * \assert
  90146. * \code decoder != NULL \endcode
  90147. * \a type is valid
  90148. * \retval FLAC__bool
  90149. * \c false if the decoder is already initialized, else \c true.
  90150. */
  90151. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90152. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90153. * the given \a id.
  90154. *
  90155. * \default By default, only the \c STREAMINFO block is returned via the
  90156. * metadata callback.
  90157. * \param decoder A decoder instance to set.
  90158. * \param id See above.
  90159. * \assert
  90160. * \code decoder != NULL \endcode
  90161. * \code id != NULL \endcode
  90162. * \retval FLAC__bool
  90163. * \c false if the decoder is already initialized, else \c true.
  90164. */
  90165. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90166. /** Direct the decoder to filter out all metadata blocks of any type.
  90167. *
  90168. * \default By default, only the \c STREAMINFO block is returned via the
  90169. * metadata callback.
  90170. * \param decoder A decoder instance to set.
  90171. * \assert
  90172. * \code decoder != NULL \endcode
  90173. * \retval FLAC__bool
  90174. * \c false if the decoder is already initialized, else \c true.
  90175. */
  90176. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90177. /** Get the current decoder state.
  90178. *
  90179. * \param decoder A decoder instance to query.
  90180. * \assert
  90181. * \code decoder != NULL \endcode
  90182. * \retval FLAC__StreamDecoderState
  90183. * The current decoder state.
  90184. */
  90185. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90186. /** Get the current decoder state as a C string.
  90187. *
  90188. * \param decoder A decoder instance to query.
  90189. * \assert
  90190. * \code decoder != NULL \endcode
  90191. * \retval const char *
  90192. * The decoder state as a C string. Do not modify the contents.
  90193. */
  90194. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90195. /** Get the "MD5 signature checking" flag.
  90196. * This is the value of the setting, not whether or not the decoder is
  90197. * currently checking the MD5 (remember, it can be turned off automatically
  90198. * by a seek). When the decoder is reset the flag will be restored to the
  90199. * value returned by this function.
  90200. *
  90201. * \param decoder A decoder instance to query.
  90202. * \assert
  90203. * \code decoder != NULL \endcode
  90204. * \retval FLAC__bool
  90205. * See above.
  90206. */
  90207. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90208. /** Get the total number of samples in the stream being decoded.
  90209. * Will only be valid after decoding has started and will contain the
  90210. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90211. *
  90212. * \param decoder A decoder instance to query.
  90213. * \assert
  90214. * \code decoder != NULL \endcode
  90215. * \retval unsigned
  90216. * See above.
  90217. */
  90218. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90219. /** Get the current number of channels in the stream being decoded.
  90220. * Will only be valid after decoding has started and will contain the
  90221. * value from the most recently decoded frame header.
  90222. *
  90223. * \param decoder A decoder instance to query.
  90224. * \assert
  90225. * \code decoder != NULL \endcode
  90226. * \retval unsigned
  90227. * See above.
  90228. */
  90229. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90230. /** Get the current channel assignment in the stream being decoded.
  90231. * Will only be valid after decoding has started and will contain the
  90232. * value from the most recently decoded frame header.
  90233. *
  90234. * \param decoder A decoder instance to query.
  90235. * \assert
  90236. * \code decoder != NULL \endcode
  90237. * \retval FLAC__ChannelAssignment
  90238. * See above.
  90239. */
  90240. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90241. /** Get the current sample resolution in the stream being decoded.
  90242. * Will only be valid after decoding has started and will contain the
  90243. * value from the most recently decoded frame header.
  90244. *
  90245. * \param decoder A decoder instance to query.
  90246. * \assert
  90247. * \code decoder != NULL \endcode
  90248. * \retval unsigned
  90249. * See above.
  90250. */
  90251. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90252. /** Get the current sample rate in Hz of the stream being decoded.
  90253. * Will only be valid after decoding has started and will contain the
  90254. * value from the most recently decoded frame header.
  90255. *
  90256. * \param decoder A decoder instance to query.
  90257. * \assert
  90258. * \code decoder != NULL \endcode
  90259. * \retval unsigned
  90260. * See above.
  90261. */
  90262. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90263. /** Get the current blocksize of the stream being decoded.
  90264. * Will only be valid after decoding has started and will contain the
  90265. * value from the most recently decoded frame header.
  90266. *
  90267. * \param decoder A decoder instance to query.
  90268. * \assert
  90269. * \code decoder != NULL \endcode
  90270. * \retval unsigned
  90271. * See above.
  90272. */
  90273. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90274. /** Returns the decoder's current read position within the stream.
  90275. * The position is the byte offset from the start of the stream.
  90276. * Bytes before this position have been fully decoded. Note that
  90277. * there may still be undecoded bytes in the decoder's read FIFO.
  90278. * The returned position is correct even after a seek.
  90279. *
  90280. * \warning This function currently only works for native FLAC,
  90281. * not Ogg FLAC streams.
  90282. *
  90283. * \param decoder A decoder instance to query.
  90284. * \param position Address at which to return the desired position.
  90285. * \assert
  90286. * \code decoder != NULL \endcode
  90287. * \code position != NULL \endcode
  90288. * \retval FLAC__bool
  90289. * \c true if successful, \c false if the stream is not native FLAC,
  90290. * or there was an error from the 'tell' callback or it returned
  90291. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90292. */
  90293. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90294. /** Initialize the decoder instance to decode native FLAC streams.
  90295. *
  90296. * This flavor of initialization sets up the decoder to decode from a
  90297. * native FLAC stream. I/O is performed via callbacks to the client.
  90298. * For decoding from a plain file via filename or open FILE*,
  90299. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90300. * provide a simpler interface.
  90301. *
  90302. * This function should be called after FLAC__stream_decoder_new() and
  90303. * FLAC__stream_decoder_set_*() but before any of the
  90304. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90305. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90306. * if initialization succeeded.
  90307. *
  90308. * \param decoder An uninitialized decoder instance.
  90309. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90310. * pointer must not be \c NULL.
  90311. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90312. * pointer may be \c NULL if seeking is not
  90313. * supported. If \a seek_callback is not \c NULL then a
  90314. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90315. * Alternatively, a dummy seek callback that just
  90316. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90317. * may also be supplied, all though this is slightly
  90318. * less efficient for the decoder.
  90319. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90320. * pointer may be \c NULL if not supported by the client. If
  90321. * \a seek_callback is not \c NULL then a
  90322. * \a tell_callback must also be supplied.
  90323. * Alternatively, a dummy tell callback that just
  90324. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90325. * may also be supplied, all though this is slightly
  90326. * less efficient for the decoder.
  90327. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90328. * pointer may be \c NULL if not supported by the client. If
  90329. * \a seek_callback is not \c NULL then a
  90330. * \a length_callback must also be supplied.
  90331. * Alternatively, a dummy length callback that just
  90332. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90333. * may also be supplied, all though this is slightly
  90334. * less efficient for the decoder.
  90335. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90336. * pointer may be \c NULL if not supported by the client. If
  90337. * \a seek_callback is not \c NULL then a
  90338. * \a eof_callback must also be supplied.
  90339. * Alternatively, a dummy length callback that just
  90340. * returns \c false
  90341. * may also be supplied, all though this is slightly
  90342. * less efficient for the decoder.
  90343. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90344. * pointer must not be \c NULL.
  90345. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90346. * pointer may be \c NULL if the callback is not
  90347. * desired.
  90348. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90349. * pointer must not be \c NULL.
  90350. * \param client_data This value will be supplied to callbacks in their
  90351. * \a client_data argument.
  90352. * \assert
  90353. * \code decoder != NULL \endcode
  90354. * \retval FLAC__StreamDecoderInitStatus
  90355. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90356. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90357. */
  90358. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90359. FLAC__StreamDecoder *decoder,
  90360. FLAC__StreamDecoderReadCallback read_callback,
  90361. FLAC__StreamDecoderSeekCallback seek_callback,
  90362. FLAC__StreamDecoderTellCallback tell_callback,
  90363. FLAC__StreamDecoderLengthCallback length_callback,
  90364. FLAC__StreamDecoderEofCallback eof_callback,
  90365. FLAC__StreamDecoderWriteCallback write_callback,
  90366. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90367. FLAC__StreamDecoderErrorCallback error_callback,
  90368. void *client_data
  90369. );
  90370. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90371. *
  90372. * This flavor of initialization sets up the decoder to decode from a
  90373. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90374. * client. For decoding from a plain file via filename or open FILE*,
  90375. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90376. * provide a simpler interface.
  90377. *
  90378. * This function should be called after FLAC__stream_decoder_new() and
  90379. * FLAC__stream_decoder_set_*() but before any of the
  90380. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90381. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90382. * if initialization succeeded.
  90383. *
  90384. * \note Support for Ogg FLAC in the library is optional. If this
  90385. * library has been built without support for Ogg FLAC, this function
  90386. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90387. *
  90388. * \param decoder An uninitialized decoder instance.
  90389. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90390. * pointer must not be \c NULL.
  90391. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90392. * pointer may be \c NULL if seeking is not
  90393. * supported. If \a seek_callback is not \c NULL then a
  90394. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90395. * Alternatively, a dummy seek callback that just
  90396. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90397. * may also be supplied, all though this is slightly
  90398. * less efficient for the decoder.
  90399. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90400. * pointer may be \c NULL if not supported by the client. If
  90401. * \a seek_callback is not \c NULL then a
  90402. * \a tell_callback must also be supplied.
  90403. * Alternatively, a dummy tell callback that just
  90404. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90405. * may also be supplied, all though this is slightly
  90406. * less efficient for the decoder.
  90407. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90408. * pointer may be \c NULL if not supported by the client. If
  90409. * \a seek_callback is not \c NULL then a
  90410. * \a length_callback must also be supplied.
  90411. * Alternatively, a dummy length callback that just
  90412. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90413. * may also be supplied, all though this is slightly
  90414. * less efficient for the decoder.
  90415. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90416. * pointer may be \c NULL if not supported by the client. If
  90417. * \a seek_callback is not \c NULL then a
  90418. * \a eof_callback must also be supplied.
  90419. * Alternatively, a dummy length callback that just
  90420. * returns \c false
  90421. * may also be supplied, all though this is slightly
  90422. * less efficient for the decoder.
  90423. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90424. * pointer must not be \c NULL.
  90425. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90426. * pointer may be \c NULL if the callback is not
  90427. * desired.
  90428. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90429. * pointer must not be \c NULL.
  90430. * \param client_data This value will be supplied to callbacks in their
  90431. * \a client_data argument.
  90432. * \assert
  90433. * \code decoder != NULL \endcode
  90434. * \retval FLAC__StreamDecoderInitStatus
  90435. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90436. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90437. */
  90438. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90439. FLAC__StreamDecoder *decoder,
  90440. FLAC__StreamDecoderReadCallback read_callback,
  90441. FLAC__StreamDecoderSeekCallback seek_callback,
  90442. FLAC__StreamDecoderTellCallback tell_callback,
  90443. FLAC__StreamDecoderLengthCallback length_callback,
  90444. FLAC__StreamDecoderEofCallback eof_callback,
  90445. FLAC__StreamDecoderWriteCallback write_callback,
  90446. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90447. FLAC__StreamDecoderErrorCallback error_callback,
  90448. void *client_data
  90449. );
  90450. /** Initialize the decoder instance to decode native FLAC files.
  90451. *
  90452. * This flavor of initialization sets up the decoder to decode from a
  90453. * plain native FLAC file. For non-stdio streams, you must use
  90454. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90455. *
  90456. * This function should be called after FLAC__stream_decoder_new() and
  90457. * FLAC__stream_decoder_set_*() but before any of the
  90458. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90459. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90460. * if initialization succeeded.
  90461. *
  90462. * \param decoder An uninitialized decoder instance.
  90463. * \param file An open FLAC file. The file should have been
  90464. * opened with mode \c "rb" and rewound. The file
  90465. * becomes owned by the decoder and should not be
  90466. * manipulated by the client while decoding.
  90467. * Unless \a file is \c stdin, it will be closed
  90468. * when FLAC__stream_decoder_finish() is called.
  90469. * Note however that seeking will not work when
  90470. * decoding from \c stdout since it is not seekable.
  90471. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90472. * pointer must not be \c NULL.
  90473. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90474. * pointer may be \c NULL if the callback is not
  90475. * desired.
  90476. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90477. * pointer must not be \c NULL.
  90478. * \param client_data This value will be supplied to callbacks in their
  90479. * \a client_data argument.
  90480. * \assert
  90481. * \code decoder != NULL \endcode
  90482. * \code file != NULL \endcode
  90483. * \retval FLAC__StreamDecoderInitStatus
  90484. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90485. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90486. */
  90487. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90488. FLAC__StreamDecoder *decoder,
  90489. FILE *file,
  90490. FLAC__StreamDecoderWriteCallback write_callback,
  90491. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90492. FLAC__StreamDecoderErrorCallback error_callback,
  90493. void *client_data
  90494. );
  90495. /** Initialize the decoder instance to decode Ogg FLAC files.
  90496. *
  90497. * This flavor of initialization sets up the decoder to decode from a
  90498. * plain Ogg FLAC file. For non-stdio streams, you must use
  90499. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90500. *
  90501. * This function should be called after FLAC__stream_decoder_new() and
  90502. * FLAC__stream_decoder_set_*() but before any of the
  90503. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90504. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90505. * if initialization succeeded.
  90506. *
  90507. * \note Support for Ogg FLAC in the library is optional. If this
  90508. * library has been built without support for Ogg FLAC, this function
  90509. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90510. *
  90511. * \param decoder An uninitialized decoder instance.
  90512. * \param file An open FLAC file. The file should have been
  90513. * opened with mode \c "rb" and rewound. The file
  90514. * becomes owned by the decoder and should not be
  90515. * manipulated by the client while decoding.
  90516. * Unless \a file is \c stdin, it will be closed
  90517. * when FLAC__stream_decoder_finish() is called.
  90518. * Note however that seeking will not work when
  90519. * decoding from \c stdout since it is not seekable.
  90520. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90521. * pointer must not be \c NULL.
  90522. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90523. * pointer may be \c NULL if the callback is not
  90524. * desired.
  90525. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90526. * pointer must not be \c NULL.
  90527. * \param client_data This value will be supplied to callbacks in their
  90528. * \a client_data argument.
  90529. * \assert
  90530. * \code decoder != NULL \endcode
  90531. * \code file != NULL \endcode
  90532. * \retval FLAC__StreamDecoderInitStatus
  90533. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90534. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90535. */
  90536. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90537. FLAC__StreamDecoder *decoder,
  90538. FILE *file,
  90539. FLAC__StreamDecoderWriteCallback write_callback,
  90540. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90541. FLAC__StreamDecoderErrorCallback error_callback,
  90542. void *client_data
  90543. );
  90544. /** Initialize the decoder instance to decode native FLAC files.
  90545. *
  90546. * This flavor of initialization sets up the decoder to decode from a plain
  90547. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90548. * example, with Unicode filenames on Windows), you must use
  90549. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90550. * and provide callbacks for the I/O.
  90551. *
  90552. * This function should be called after FLAC__stream_decoder_new() and
  90553. * FLAC__stream_decoder_set_*() but before any of the
  90554. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90555. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90556. * if initialization succeeded.
  90557. *
  90558. * \param decoder An uninitialized decoder instance.
  90559. * \param filename The name of the file to decode from. The file will
  90560. * be opened with fopen(). Use \c NULL to decode from
  90561. * \c stdin. Note that \c stdin is not seekable.
  90562. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90563. * pointer must not be \c NULL.
  90564. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90565. * pointer may be \c NULL if the callback is not
  90566. * desired.
  90567. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90568. * pointer must not be \c NULL.
  90569. * \param client_data This value will be supplied to callbacks in their
  90570. * \a client_data argument.
  90571. * \assert
  90572. * \code decoder != NULL \endcode
  90573. * \retval FLAC__StreamDecoderInitStatus
  90574. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90575. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90576. */
  90577. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90578. FLAC__StreamDecoder *decoder,
  90579. const char *filename,
  90580. FLAC__StreamDecoderWriteCallback write_callback,
  90581. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90582. FLAC__StreamDecoderErrorCallback error_callback,
  90583. void *client_data
  90584. );
  90585. /** Initialize the decoder instance to decode Ogg FLAC files.
  90586. *
  90587. * This flavor of initialization sets up the decoder to decode from a plain
  90588. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90589. * example, with Unicode filenames on Windows), you must use
  90590. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90591. * and provide callbacks for the I/O.
  90592. *
  90593. * This function should be called after FLAC__stream_decoder_new() and
  90594. * FLAC__stream_decoder_set_*() but before any of the
  90595. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90596. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90597. * if initialization succeeded.
  90598. *
  90599. * \note Support for Ogg FLAC in the library is optional. If this
  90600. * library has been built without support for Ogg FLAC, this function
  90601. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90602. *
  90603. * \param decoder An uninitialized decoder instance.
  90604. * \param filename The name of the file to decode from. The file will
  90605. * be opened with fopen(). Use \c NULL to decode from
  90606. * \c stdin. Note that \c stdin is not seekable.
  90607. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90608. * pointer must not be \c NULL.
  90609. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90610. * pointer may be \c NULL if the callback is not
  90611. * desired.
  90612. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90613. * pointer must not be \c NULL.
  90614. * \param client_data This value will be supplied to callbacks in their
  90615. * \a client_data argument.
  90616. * \assert
  90617. * \code decoder != NULL \endcode
  90618. * \retval FLAC__StreamDecoderInitStatus
  90619. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90620. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90621. */
  90622. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90623. FLAC__StreamDecoder *decoder,
  90624. const char *filename,
  90625. FLAC__StreamDecoderWriteCallback write_callback,
  90626. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90627. FLAC__StreamDecoderErrorCallback error_callback,
  90628. void *client_data
  90629. );
  90630. /** Finish the decoding process.
  90631. * Flushes the decoding buffer, releases resources, resets the decoder
  90632. * settings to their defaults, and returns the decoder state to
  90633. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90634. *
  90635. * In the event of a prematurely-terminated decode, it is not strictly
  90636. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90637. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90638. * with a FLAC__stream_decoder_finish().
  90639. *
  90640. * \param decoder An uninitialized decoder instance.
  90641. * \assert
  90642. * \code decoder != NULL \endcode
  90643. * \retval FLAC__bool
  90644. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90645. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90646. * signature does not match the one computed by the decoder; else
  90647. * \c true.
  90648. */
  90649. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90650. /** Flush the stream input.
  90651. * The decoder's input buffer will be cleared and the state set to
  90652. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90653. * off MD5 checking.
  90654. *
  90655. * \param decoder A decoder instance.
  90656. * \assert
  90657. * \code decoder != NULL \endcode
  90658. * \retval FLAC__bool
  90659. * \c true if successful, else \c false if a memory allocation
  90660. * error occurs (in which case the state will be set to
  90661. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90662. */
  90663. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90664. /** Reset the decoding process.
  90665. * The decoder's input buffer will be cleared and the state set to
  90666. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90667. * FLAC__stream_decoder_finish() except that the settings are
  90668. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90669. * before decoding again. MD5 checking will be restored to its original
  90670. * setting.
  90671. *
  90672. * If the decoder is seekable, or was initialized with
  90673. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90674. * the decoder will also attempt to seek to the beginning of the file.
  90675. * If this rewind fails, this function will return \c false. It follows
  90676. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90677. * \c stdin.
  90678. *
  90679. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90680. * and is not seekable (i.e. no seek callback was provided or the seek
  90681. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90682. * is the duty of the client to start feeding data from the beginning of
  90683. * the stream on the next FLAC__stream_decoder_process() or
  90684. * FLAC__stream_decoder_process_interleaved() call.
  90685. *
  90686. * \param decoder A decoder instance.
  90687. * \assert
  90688. * \code decoder != NULL \endcode
  90689. * \retval FLAC__bool
  90690. * \c true if successful, else \c false if a memory allocation occurs
  90691. * (in which case the state will be set to
  90692. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90693. * occurs (the state will be unchanged).
  90694. */
  90695. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90696. /** Decode one metadata block or audio frame.
  90697. * This version instructs the decoder to decode a either a single metadata
  90698. * block or a single frame and stop, unless the callbacks return a fatal
  90699. * error or the read callback returns
  90700. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90701. *
  90702. * As the decoder needs more input it will call the read callback.
  90703. * Depending on what was decoded, the metadata or write callback will be
  90704. * called with the decoded metadata block or audio frame.
  90705. *
  90706. * Unless there is a fatal read error or end of stream, this function
  90707. * will return once one whole frame is decoded. In other words, if the
  90708. * stream is not synchronized or points to a corrupt frame header, the
  90709. * decoder will continue to try and resync until it gets to a valid
  90710. * frame, then decode one frame, then return. If the decoder points to
  90711. * a frame whose frame CRC in the frame footer does not match the
  90712. * computed frame CRC, this function will issue a
  90713. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90714. * error callback, and return, having decoded one complete, although
  90715. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90716. * correct length to the write callback.)
  90717. *
  90718. * \param decoder An initialized decoder instance.
  90719. * \assert
  90720. * \code decoder != NULL \endcode
  90721. * \retval FLAC__bool
  90722. * \c false if any fatal read, write, or memory allocation error
  90723. * occurred (meaning decoding must stop), else \c true; for more
  90724. * information about the decoder, check the decoder state with
  90725. * FLAC__stream_decoder_get_state().
  90726. */
  90727. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90728. /** Decode until the end of the metadata.
  90729. * This version instructs the decoder to decode from the current position
  90730. * and continue until all the metadata has been read, or until the
  90731. * callbacks return a fatal error or the read callback returns
  90732. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90733. *
  90734. * As the decoder needs more input it will call the read callback.
  90735. * As each metadata block is decoded, the metadata callback will be called
  90736. * with the decoded metadata.
  90737. *
  90738. * \param decoder An initialized decoder instance.
  90739. * \assert
  90740. * \code decoder != NULL \endcode
  90741. * \retval FLAC__bool
  90742. * \c false if any fatal read, write, or memory allocation error
  90743. * occurred (meaning decoding must stop), else \c true; for more
  90744. * information about the decoder, check the decoder state with
  90745. * FLAC__stream_decoder_get_state().
  90746. */
  90747. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90748. /** Decode until the end of the stream.
  90749. * This version instructs the decoder to decode from the current position
  90750. * and continue until the end of stream (the read callback returns
  90751. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90752. * callbacks return a fatal error.
  90753. *
  90754. * As the decoder needs more input it will call the read callback.
  90755. * As each metadata block and frame is decoded, the metadata or write
  90756. * callback will be called with the decoded metadata or frame.
  90757. *
  90758. * \param decoder An initialized decoder instance.
  90759. * \assert
  90760. * \code decoder != NULL \endcode
  90761. * \retval FLAC__bool
  90762. * \c false if any fatal read, write, or memory allocation error
  90763. * occurred (meaning decoding must stop), else \c true; for more
  90764. * information about the decoder, check the decoder state with
  90765. * FLAC__stream_decoder_get_state().
  90766. */
  90767. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90768. /** Skip one audio frame.
  90769. * This version instructs the decoder to 'skip' a single frame and stop,
  90770. * unless the callbacks return a fatal error or the read callback returns
  90771. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90772. *
  90773. * The decoding flow is the same as what occurs when
  90774. * FLAC__stream_decoder_process_single() is called to process an audio
  90775. * frame, except that this function does not decode the parsed data into
  90776. * PCM or call the write callback. The integrity of the frame is still
  90777. * checked the same way as in the other process functions.
  90778. *
  90779. * This function will return once one whole frame is skipped, in the
  90780. * same way that FLAC__stream_decoder_process_single() will return once
  90781. * one whole frame is decoded.
  90782. *
  90783. * This function can be used in more quickly determining FLAC frame
  90784. * boundaries when decoding of the actual data is not needed, for
  90785. * example when an application is separating a FLAC stream into frames
  90786. * for editing or storing in a container. To do this, the application
  90787. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90788. * to the next frame, then use
  90789. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90790. * boundary.
  90791. *
  90792. * This function should only be called when the stream has advanced
  90793. * past all the metadata, otherwise it will return \c false.
  90794. *
  90795. * \param decoder An initialized decoder instance not in a metadata
  90796. * state.
  90797. * \assert
  90798. * \code decoder != NULL \endcode
  90799. * \retval FLAC__bool
  90800. * \c false if any fatal read, write, or memory allocation error
  90801. * occurred (meaning decoding must stop), or if the decoder
  90802. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90803. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90804. * information about the decoder, check the decoder state with
  90805. * FLAC__stream_decoder_get_state().
  90806. */
  90807. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90808. /** Flush the input and seek to an absolute sample.
  90809. * Decoding will resume at the given sample. Note that because of
  90810. * this, the next write callback may contain a partial block. The
  90811. * client must support seeking the input or this function will fail
  90812. * and return \c false. Furthermore, if the decoder state is
  90813. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90814. * with FLAC__stream_decoder_flush() or reset with
  90815. * FLAC__stream_decoder_reset() before decoding can continue.
  90816. *
  90817. * \param decoder A decoder instance.
  90818. * \param sample The target sample number to seek to.
  90819. * \assert
  90820. * \code decoder != NULL \endcode
  90821. * \retval FLAC__bool
  90822. * \c true if successful, else \c false.
  90823. */
  90824. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90825. /* \} */
  90826. #ifdef __cplusplus
  90827. }
  90828. #endif
  90829. #endif
  90830. /*** End of inlined file: stream_decoder.h ***/
  90831. /*** Start of inlined file: stream_encoder.h ***/
  90832. #ifndef FLAC__STREAM_ENCODER_H
  90833. #define FLAC__STREAM_ENCODER_H
  90834. #include <stdio.h> /* for FILE */
  90835. #ifdef __cplusplus
  90836. extern "C" {
  90837. #endif
  90838. /** \file include/FLAC/stream_encoder.h
  90839. *
  90840. * \brief
  90841. * This module contains the functions which implement the stream
  90842. * encoder.
  90843. *
  90844. * See the detailed documentation in the
  90845. * \link flac_stream_encoder stream encoder \endlink module.
  90846. */
  90847. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90848. * \ingroup flac
  90849. *
  90850. * \brief
  90851. * This module describes the encoder layers provided by libFLAC.
  90852. *
  90853. * The stream encoder can be used to encode complete streams either to the
  90854. * client via callbacks, or directly to a file, depending on how it is
  90855. * initialized. When encoding via callbacks, the client provides a write
  90856. * callback which will be called whenever FLAC data is ready to be written.
  90857. * If the client also supplies a seek callback, the encoder will also
  90858. * automatically handle the writing back of metadata discovered while
  90859. * encoding, like stream info, seek points offsets, etc. When encoding to
  90860. * a file, the client needs only supply a filename or open \c FILE* and an
  90861. * optional progress callback for periodic notification of progress; the
  90862. * write and seek callbacks are supplied internally. For more info see the
  90863. * \link flac_stream_encoder stream encoder \endlink module.
  90864. */
  90865. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90866. * \ingroup flac_encoder
  90867. *
  90868. * \brief
  90869. * This module contains the functions which implement the stream
  90870. * encoder.
  90871. *
  90872. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90873. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90874. *
  90875. * The basic usage of this encoder is as follows:
  90876. * - The program creates an instance of an encoder using
  90877. * FLAC__stream_encoder_new().
  90878. * - The program overrides the default settings using
  90879. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90880. * functions should be called:
  90881. * - FLAC__stream_encoder_set_channels()
  90882. * - FLAC__stream_encoder_set_bits_per_sample()
  90883. * - FLAC__stream_encoder_set_sample_rate()
  90884. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90885. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90886. * - If the application wants to control the compression level or set its own
  90887. * metadata, then the following should also be called:
  90888. * - FLAC__stream_encoder_set_compression_level()
  90889. * - FLAC__stream_encoder_set_verify()
  90890. * - FLAC__stream_encoder_set_metadata()
  90891. * - The rest of the set functions should only be called if the client needs
  90892. * exact control over how the audio is compressed; thorough understanding
  90893. * of the FLAC format is necessary to achieve good results.
  90894. * - The program initializes the instance to validate the settings and
  90895. * prepare for encoding using
  90896. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90897. * or FLAC__stream_encoder_init_file() for native FLAC
  90898. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90899. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90900. * - The program calls FLAC__stream_encoder_process() or
  90901. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90902. * subsequently calls the callbacks when there is encoder data ready
  90903. * to be written.
  90904. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90905. * which causes the encoder to encode any data still in its input pipe,
  90906. * update the metadata with the final encoding statistics if output
  90907. * seeking is possible, and finally reset the encoder to the
  90908. * uninitialized state.
  90909. * - The instance may be used again or deleted with
  90910. * FLAC__stream_encoder_delete().
  90911. *
  90912. * In more detail, the stream encoder functions similarly to the
  90913. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90914. * callbacks and more options. Typically the client will create a new
  90915. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90916. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90917. * calling one of the FLAC__stream_encoder_init_*() functions.
  90918. *
  90919. * Unlike the decoders, the stream encoder has many options that can
  90920. * affect the speed and compression ratio. When setting these parameters
  90921. * you should have some basic knowledge of the format (see the
  90922. * <A HREF="../documentation.html#format">user-level documentation</A>
  90923. * or the <A HREF="../format.html">formal description</A>). The
  90924. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90925. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90926. * functions will do this, so make sure to pay attention to the state
  90927. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90928. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90929. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90930. * the constructor.
  90931. *
  90932. * There are three initialization functions for native FLAC, one for
  90933. * setting up the encoder to encode FLAC data to the client via
  90934. * callbacks, and two for encoding directly to a file.
  90935. *
  90936. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90937. * You must also supply a write callback which will be called anytime
  90938. * there is raw encoded data to write. If the client can seek the output
  90939. * it is best to also supply seek and tell callbacks, as this allows the
  90940. * encoder to go back after encoding is finished to write back
  90941. * information that was collected while encoding, like seek point offsets,
  90942. * frame sizes, etc.
  90943. *
  90944. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90945. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90946. * filename or open \c FILE*; the encoder will handle all the callbacks
  90947. * internally. You may also supply a progress callback for periodic
  90948. * notification of the encoding progress.
  90949. *
  90950. * There are three similarly-named init functions for encoding to Ogg
  90951. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90952. * library has been built with Ogg support.
  90953. *
  90954. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90955. * call the write callback several times, once with the \c fLaC signature,
  90956. * and once for each encoded metadata block. Note that for Ogg FLAC
  90957. * encoding you will usually get at least twice the number of callbacks than
  90958. * with native FLAC, one for the Ogg page header and one for the page body.
  90959. *
  90960. * After initializing the instance, the client may feed audio data to the
  90961. * encoder in one of two ways:
  90962. *
  90963. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90964. * will pass an array of pointers to buffers, one for each channel, to
  90965. * the encoder, each of the same length. The samples need not be
  90966. * block-aligned, but each channel should have the same number of samples.
  90967. * - Channel interleaved, through
  90968. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90969. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90970. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90971. * Again, the samples need not be block-aligned but they must be
  90972. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90973. * the last value channelN_sampleM.
  90974. *
  90975. * Note that for either process call, each sample in the buffers should be a
  90976. * signed integer, right-justified to the resolution set by
  90977. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90978. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90979. *
  90980. * When the client is finished encoding data, it calls
  90981. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90982. * data still in its input pipe, and call the metadata callback with the
  90983. * final encoding statistics. Then the instance may be deleted with
  90984. * FLAC__stream_encoder_delete() or initialized again to encode another
  90985. * stream.
  90986. *
  90987. * For programs that write their own metadata, but that do not know the
  90988. * actual metadata until after encoding, it is advantageous to instruct
  90989. * the encoder to write a PADDING block of the correct size, so that
  90990. * instead of rewriting the whole stream after encoding, the program can
  90991. * just overwrite the PADDING block. If only the maximum size of the
  90992. * metadata is known, the program can write a slightly larger padding
  90993. * block, then split it after encoding.
  90994. *
  90995. * Make sure you understand how lengths are calculated. All FLAC metadata
  90996. * blocks have a 4 byte header which contains the type and length. This
  90997. * length does not include the 4 bytes of the header. See the format page
  90998. * for the specification of metadata blocks and their lengths.
  90999. *
  91000. * \note
  91001. * If you are writing the FLAC data to a file via callbacks, make sure it
  91002. * is open for update (e.g. mode "w+" for stdio streams). This is because
  91003. * after the first encoding pass, the encoder will try to seek back to the
  91004. * beginning of the stream, to the STREAMINFO block, to write some data
  91005. * there. (If using FLAC__stream_encoder_init*_file() or
  91006. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  91007. *
  91008. * \note
  91009. * The "set" functions may only be called when the encoder is in the
  91010. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  91011. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  91012. * before FLAC__stream_encoder_init_*(). If this is the case they will
  91013. * return \c true, otherwise \c false.
  91014. *
  91015. * \note
  91016. * FLAC__stream_encoder_finish() resets all settings to the constructor
  91017. * defaults.
  91018. *
  91019. * \{
  91020. */
  91021. /** State values for a FLAC__StreamEncoder.
  91022. *
  91023. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  91024. *
  91025. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  91026. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  91027. * must be deleted with FLAC__stream_encoder_delete().
  91028. */
  91029. typedef enum {
  91030. FLAC__STREAM_ENCODER_OK = 0,
  91031. /**< The encoder is in the normal OK state and samples can be processed. */
  91032. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91033. /**< The encoder is in the uninitialized state; one of the
  91034. * FLAC__stream_encoder_init_*() functions must be called before samples
  91035. * can be processed.
  91036. */
  91037. FLAC__STREAM_ENCODER_OGG_ERROR,
  91038. /**< An error occurred in the underlying Ogg layer. */
  91039. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91040. /**< An error occurred in the underlying verify stream decoder;
  91041. * check FLAC__stream_encoder_get_verify_decoder_state().
  91042. */
  91043. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91044. /**< The verify decoder detected a mismatch between the original
  91045. * audio signal and the decoded audio signal.
  91046. */
  91047. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91048. /**< One of the callbacks returned a fatal error. */
  91049. FLAC__STREAM_ENCODER_IO_ERROR,
  91050. /**< An I/O error occurred while opening/reading/writing a file.
  91051. * Check \c errno.
  91052. */
  91053. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91054. /**< An error occurred while writing the stream; usually, the
  91055. * write_callback returned an error.
  91056. */
  91057. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91058. /**< Memory allocation failed. */
  91059. } FLAC__StreamEncoderState;
  91060. /** Maps a FLAC__StreamEncoderState to a C string.
  91061. *
  91062. * Using a FLAC__StreamEncoderState as the index to this array
  91063. * will give the string equivalent. The contents should not be modified.
  91064. */
  91065. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91066. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91067. */
  91068. typedef enum {
  91069. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91070. /**< Initialization was successful. */
  91071. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91072. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91073. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91074. /**< The library was not compiled with support for the given container
  91075. * format.
  91076. */
  91077. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91078. /**< A required callback was not supplied. */
  91079. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91080. /**< The encoder has an invalid setting for number of channels. */
  91081. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91082. /**< The encoder has an invalid setting for bits-per-sample.
  91083. * FLAC supports 4-32 bps but the reference encoder currently supports
  91084. * only up to 24 bps.
  91085. */
  91086. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91087. /**< The encoder has an invalid setting for the input sample rate. */
  91088. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91089. /**< The encoder has an invalid setting for the block size. */
  91090. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91091. /**< The encoder has an invalid setting for the maximum LPC order. */
  91092. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91093. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91094. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91095. /**< The specified block size is less than the maximum LPC order. */
  91096. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91097. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91098. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91099. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91100. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91101. * - One of the metadata blocks contains an undefined type
  91102. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91103. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91104. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91105. */
  91106. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91107. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91108. * already initialized, usually because
  91109. * FLAC__stream_encoder_finish() was not called.
  91110. */
  91111. } FLAC__StreamEncoderInitStatus;
  91112. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91113. *
  91114. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91115. * will give the string equivalent. The contents should not be modified.
  91116. */
  91117. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91118. /** Return values for the FLAC__StreamEncoder read callback.
  91119. */
  91120. typedef enum {
  91121. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91122. /**< The read was OK and decoding can continue. */
  91123. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91124. /**< The read was attempted at the end of the stream. */
  91125. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91126. /**< An unrecoverable error occurred. */
  91127. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91128. /**< Client does not support reading back from the output. */
  91129. } FLAC__StreamEncoderReadStatus;
  91130. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91131. *
  91132. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91133. * will give the string equivalent. The contents should not be modified.
  91134. */
  91135. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91136. /** Return values for the FLAC__StreamEncoder write callback.
  91137. */
  91138. typedef enum {
  91139. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91140. /**< The write was OK and encoding can continue. */
  91141. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91142. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91143. } FLAC__StreamEncoderWriteStatus;
  91144. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91145. *
  91146. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91147. * will give the string equivalent. The contents should not be modified.
  91148. */
  91149. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91150. /** Return values for the FLAC__StreamEncoder seek callback.
  91151. */
  91152. typedef enum {
  91153. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91154. /**< The seek was OK and encoding can continue. */
  91155. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91156. /**< An unrecoverable error occurred. */
  91157. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91158. /**< Client does not support seeking. */
  91159. } FLAC__StreamEncoderSeekStatus;
  91160. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91161. *
  91162. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91163. * will give the string equivalent. The contents should not be modified.
  91164. */
  91165. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91166. /** Return values for the FLAC__StreamEncoder tell callback.
  91167. */
  91168. typedef enum {
  91169. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91170. /**< The tell was OK and encoding can continue. */
  91171. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91172. /**< An unrecoverable error occurred. */
  91173. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91174. /**< Client does not support seeking. */
  91175. } FLAC__StreamEncoderTellStatus;
  91176. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91177. *
  91178. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91179. * will give the string equivalent. The contents should not be modified.
  91180. */
  91181. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91182. /***********************************************************************
  91183. *
  91184. * class FLAC__StreamEncoder
  91185. *
  91186. ***********************************************************************/
  91187. struct FLAC__StreamEncoderProtected;
  91188. struct FLAC__StreamEncoderPrivate;
  91189. /** The opaque structure definition for the stream encoder type.
  91190. * See the \link flac_stream_encoder stream encoder module \endlink
  91191. * for a detailed description.
  91192. */
  91193. typedef struct {
  91194. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91195. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91196. } FLAC__StreamEncoder;
  91197. /** Signature for the read callback.
  91198. *
  91199. * A function pointer matching this signature must be passed to
  91200. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91201. * The supplied function will be called when the encoder needs to read back
  91202. * encoded data. This happens during the metadata callback, when the encoder
  91203. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91204. * while encoding. The address of the buffer to be filled is supplied, along
  91205. * with the number of bytes the buffer can hold. The callback may choose to
  91206. * supply less data and modify the byte count but must be careful not to
  91207. * overflow the buffer. The callback then returns a status code chosen from
  91208. * FLAC__StreamEncoderReadStatus.
  91209. *
  91210. * Here is an example of a read callback for stdio streams:
  91211. * \code
  91212. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91213. * {
  91214. * FILE *file = ((MyClientData*)client_data)->file;
  91215. * if(*bytes > 0) {
  91216. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91217. * if(ferror(file))
  91218. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91219. * else if(*bytes == 0)
  91220. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91221. * else
  91222. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91223. * }
  91224. * else
  91225. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91226. * }
  91227. * \endcode
  91228. *
  91229. * \note In general, FLAC__StreamEncoder functions which change the
  91230. * state should not be called on the \a encoder while in the callback.
  91231. *
  91232. * \param encoder The encoder instance calling the callback.
  91233. * \param buffer A pointer to a location for the callee to store
  91234. * data to be encoded.
  91235. * \param bytes A pointer to the size of the buffer. On entry
  91236. * to the callback, it contains the maximum number
  91237. * of bytes that may be stored in \a buffer. The
  91238. * callee must set it to the actual number of bytes
  91239. * stored (0 in case of error or end-of-stream) before
  91240. * returning.
  91241. * \param client_data The callee's client data set through
  91242. * FLAC__stream_encoder_set_client_data().
  91243. * \retval FLAC__StreamEncoderReadStatus
  91244. * The callee's return status.
  91245. */
  91246. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91247. /** Signature for the write callback.
  91248. *
  91249. * A function pointer matching this signature must be passed to
  91250. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91251. * by the encoder anytime there is raw encoded data ready to write. It may
  91252. * include metadata mixed with encoded audio frames and the data is not
  91253. * guaranteed to be aligned on frame or metadata block boundaries.
  91254. *
  91255. * The only duty of the callback is to write out the \a bytes worth of data
  91256. * in \a buffer to the current position in the output stream. The arguments
  91257. * \a samples and \a current_frame are purely informational. If \a samples
  91258. * is greater than \c 0, then \a current_frame will hold the current frame
  91259. * number that is being written; otherwise it indicates that the write
  91260. * callback is being called to write metadata.
  91261. *
  91262. * \note
  91263. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91264. * write callback will be called twice when writing each audio
  91265. * frame; once for the page header, and once for the page body.
  91266. * When writing the page header, the \a samples argument to the
  91267. * write callback will be \c 0.
  91268. *
  91269. * \note In general, FLAC__StreamEncoder functions which change the
  91270. * state should not be called on the \a encoder while in the callback.
  91271. *
  91272. * \param encoder The encoder instance calling the callback.
  91273. * \param buffer An array of encoded data of length \a bytes.
  91274. * \param bytes The byte length of \a buffer.
  91275. * \param samples The number of samples encoded by \a buffer.
  91276. * \c 0 has a special meaning; see above.
  91277. * \param current_frame The number of the current frame being encoded.
  91278. * \param client_data The callee's client data set through
  91279. * FLAC__stream_encoder_init_*().
  91280. * \retval FLAC__StreamEncoderWriteStatus
  91281. * The callee's return status.
  91282. */
  91283. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91284. /** Signature for the seek callback.
  91285. *
  91286. * A function pointer matching this signature may be passed to
  91287. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91288. * when the encoder needs to seek the output stream. The encoder will pass
  91289. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91290. *
  91291. * Here is an example of a seek callback for stdio streams:
  91292. * \code
  91293. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91294. * {
  91295. * FILE *file = ((MyClientData*)client_data)->file;
  91296. * if(file == stdin)
  91297. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91298. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91299. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91300. * else
  91301. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91302. * }
  91303. * \endcode
  91304. *
  91305. * \note In general, FLAC__StreamEncoder functions which change the
  91306. * state should not be called on the \a encoder while in the callback.
  91307. *
  91308. * \param encoder The encoder instance calling the callback.
  91309. * \param absolute_byte_offset The offset from the beginning of the stream
  91310. * to seek to.
  91311. * \param client_data The callee's client data set through
  91312. * FLAC__stream_encoder_init_*().
  91313. * \retval FLAC__StreamEncoderSeekStatus
  91314. * The callee's return status.
  91315. */
  91316. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91317. /** Signature for the tell callback.
  91318. *
  91319. * A function pointer matching this signature may be passed to
  91320. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91321. * when the encoder needs to know the current position of the output stream.
  91322. *
  91323. * \warning
  91324. * The callback must return the true current byte offset of the output to
  91325. * which the encoder is writing. If you are buffering the output, make
  91326. * sure and take this into account. If you are writing directly to a
  91327. * FILE* from your write callback, ftell() is sufficient. If you are
  91328. * writing directly to a file descriptor from your write callback, you
  91329. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91330. * these points to rewrite metadata after encoding.
  91331. *
  91332. * Here is an example of a tell callback for stdio streams:
  91333. * \code
  91334. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91335. * {
  91336. * FILE *file = ((MyClientData*)client_data)->file;
  91337. * off_t pos;
  91338. * if(file == stdin)
  91339. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91340. * else if((pos = ftello(file)) < 0)
  91341. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91342. * else {
  91343. * *absolute_byte_offset = (FLAC__uint64)pos;
  91344. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91345. * }
  91346. * }
  91347. * \endcode
  91348. *
  91349. * \note In general, FLAC__StreamEncoder functions which change the
  91350. * state should not be called on the \a encoder while in the callback.
  91351. *
  91352. * \param encoder The encoder instance calling the callback.
  91353. * \param absolute_byte_offset The address at which to store the current
  91354. * position of the output.
  91355. * \param client_data The callee's client data set through
  91356. * FLAC__stream_encoder_init_*().
  91357. * \retval FLAC__StreamEncoderTellStatus
  91358. * The callee's return status.
  91359. */
  91360. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91361. /** Signature for the metadata callback.
  91362. *
  91363. * A function pointer matching this signature may be passed to
  91364. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91365. * once at the end of encoding with the populated STREAMINFO structure. This
  91366. * is so the client can seek back to the beginning of the file and write the
  91367. * STREAMINFO block with the correct statistics after encoding (like
  91368. * minimum/maximum frame size and total samples).
  91369. *
  91370. * \note In general, FLAC__StreamEncoder functions which change the
  91371. * state should not be called on the \a encoder while in the callback.
  91372. *
  91373. * \param encoder The encoder instance calling the callback.
  91374. * \param metadata The final populated STREAMINFO block.
  91375. * \param client_data The callee's client data set through
  91376. * FLAC__stream_encoder_init_*().
  91377. */
  91378. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91379. /** Signature for the progress callback.
  91380. *
  91381. * A function pointer matching this signature may be passed to
  91382. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91383. * The supplied function will be called when the encoder has finished
  91384. * writing a frame. The \c total_frames_estimate argument to the
  91385. * callback will be based on the value from
  91386. * FLAC__stream_encoder_set_total_samples_estimate().
  91387. *
  91388. * \note In general, FLAC__StreamEncoder functions which change the
  91389. * state should not be called on the \a encoder while in the callback.
  91390. *
  91391. * \param encoder The encoder instance calling the callback.
  91392. * \param bytes_written Bytes written so far.
  91393. * \param samples_written Samples written so far.
  91394. * \param frames_written Frames written so far.
  91395. * \param total_frames_estimate The estimate of the total number of
  91396. * frames to be written.
  91397. * \param client_data The callee's client data set through
  91398. * FLAC__stream_encoder_init_*().
  91399. */
  91400. 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);
  91401. /***********************************************************************
  91402. *
  91403. * Class constructor/destructor
  91404. *
  91405. ***********************************************************************/
  91406. /** Create a new stream encoder instance. The instance is created with
  91407. * default settings; see the individual FLAC__stream_encoder_set_*()
  91408. * functions for each setting's default.
  91409. *
  91410. * \retval FLAC__StreamEncoder*
  91411. * \c NULL if there was an error allocating memory, else the new instance.
  91412. */
  91413. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91414. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91415. *
  91416. * \param encoder A pointer to an existing encoder.
  91417. * \assert
  91418. * \code encoder != NULL \endcode
  91419. */
  91420. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91421. /***********************************************************************
  91422. *
  91423. * Public class method prototypes
  91424. *
  91425. ***********************************************************************/
  91426. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91427. *
  91428. * \note
  91429. * This does not need to be set for native FLAC encoding.
  91430. *
  91431. * \note
  91432. * It is recommended to set a serial number explicitly as the default of '0'
  91433. * may collide with other streams.
  91434. *
  91435. * \default \c 0
  91436. * \param encoder An encoder instance to set.
  91437. * \param serial_number See above.
  91438. * \assert
  91439. * \code encoder != NULL \endcode
  91440. * \retval FLAC__bool
  91441. * \c false if the encoder is already initialized, else \c true.
  91442. */
  91443. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91444. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91445. * encoded output by feeding it through an internal decoder and comparing
  91446. * the original signal against the decoded signal. If a mismatch occurs,
  91447. * the process call will return \c false. Note that this will slow the
  91448. * encoding process by the extra time required for decoding and comparison.
  91449. *
  91450. * \default \c false
  91451. * \param encoder An encoder instance to set.
  91452. * \param value Flag value (see above).
  91453. * \assert
  91454. * \code encoder != NULL \endcode
  91455. * \retval FLAC__bool
  91456. * \c false if the encoder is already initialized, else \c true.
  91457. */
  91458. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91459. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91460. * the encoder will comply with the Subset and will check the
  91461. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91462. * comply. If \c false, the settings may take advantage of the full
  91463. * range that the format allows.
  91464. *
  91465. * Make sure you know what it entails before setting this to \c false.
  91466. *
  91467. * \default \c true
  91468. * \param encoder An encoder instance to set.
  91469. * \param value Flag value (see above).
  91470. * \assert
  91471. * \code encoder != NULL \endcode
  91472. * \retval FLAC__bool
  91473. * \c false if the encoder is already initialized, else \c true.
  91474. */
  91475. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91476. /** Set the number of channels to be encoded.
  91477. *
  91478. * \default \c 2
  91479. * \param encoder An encoder instance to set.
  91480. * \param value See above.
  91481. * \assert
  91482. * \code encoder != NULL \endcode
  91483. * \retval FLAC__bool
  91484. * \c false if the encoder is already initialized, else \c true.
  91485. */
  91486. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91487. /** Set the sample resolution of the input to be encoded.
  91488. *
  91489. * \warning
  91490. * Do not feed the encoder data that is wider than the value you
  91491. * set here or you will generate an invalid stream.
  91492. *
  91493. * \default \c 16
  91494. * \param encoder An encoder instance to set.
  91495. * \param value See above.
  91496. * \assert
  91497. * \code encoder != NULL \endcode
  91498. * \retval FLAC__bool
  91499. * \c false if the encoder is already initialized, else \c true.
  91500. */
  91501. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91502. /** Set the sample rate (in Hz) of the input to be encoded.
  91503. *
  91504. * \default \c 44100
  91505. * \param encoder An encoder instance to set.
  91506. * \param value See above.
  91507. * \assert
  91508. * \code encoder != NULL \endcode
  91509. * \retval FLAC__bool
  91510. * \c false if the encoder is already initialized, else \c true.
  91511. */
  91512. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91513. /** Set the compression level
  91514. *
  91515. * The compression level is roughly proportional to the amount of effort
  91516. * the encoder expends to compress the file. A higher level usually
  91517. * means more computation but higher compression. The default level is
  91518. * suitable for most applications.
  91519. *
  91520. * Currently the levels range from \c 0 (fastest, least compression) to
  91521. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91522. * treated as \c 8.
  91523. *
  91524. * This function automatically calls the following other \c _set_
  91525. * functions with appropriate values, so the client does not need to
  91526. * unless it specifically wants to override them:
  91527. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91528. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91529. * - FLAC__stream_encoder_set_apodization()
  91530. * - FLAC__stream_encoder_set_max_lpc_order()
  91531. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91532. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91533. * - FLAC__stream_encoder_set_do_escape_coding()
  91534. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91535. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91536. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91537. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91538. *
  91539. * The actual values set for each level are:
  91540. * <table>
  91541. * <tr>
  91542. * <td><b>level</b><td>
  91543. * <td>do mid-side stereo<td>
  91544. * <td>loose mid-side stereo<td>
  91545. * <td>apodization<td>
  91546. * <td>max lpc order<td>
  91547. * <td>qlp coeff precision<td>
  91548. * <td>qlp coeff prec search<td>
  91549. * <td>escape coding<td>
  91550. * <td>exhaustive model search<td>
  91551. * <td>min residual partition order<td>
  91552. * <td>max residual partition order<td>
  91553. * <td>rice parameter search dist<td>
  91554. * </tr>
  91555. * <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>
  91556. * <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>
  91557. * <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>
  91558. * <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>
  91559. * <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>
  91560. * <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>
  91561. * <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>
  91562. * <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>
  91563. * <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>
  91564. * </table>
  91565. *
  91566. * \default \c 5
  91567. * \param encoder An encoder instance to set.
  91568. * \param value See above.
  91569. * \assert
  91570. * \code encoder != NULL \endcode
  91571. * \retval FLAC__bool
  91572. * \c false if the encoder is already initialized, else \c true.
  91573. */
  91574. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91575. /** Set the blocksize to use while encoding.
  91576. *
  91577. * The number of samples to use per frame. Use \c 0 to let the encoder
  91578. * estimate a blocksize; this is usually best.
  91579. *
  91580. * \default \c 0
  91581. * \param encoder An encoder instance to set.
  91582. * \param value See above.
  91583. * \assert
  91584. * \code encoder != NULL \endcode
  91585. * \retval FLAC__bool
  91586. * \c false if the encoder is already initialized, else \c true.
  91587. */
  91588. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91589. /** Set to \c true to enable mid-side encoding on stereo input. The
  91590. * number of channels must be 2 for this to have any effect. Set to
  91591. * \c false to use only independent channel coding.
  91592. *
  91593. * \default \c false
  91594. * \param encoder An encoder instance to set.
  91595. * \param value Flag value (see above).
  91596. * \assert
  91597. * \code encoder != NULL \endcode
  91598. * \retval FLAC__bool
  91599. * \c false if the encoder is already initialized, else \c true.
  91600. */
  91601. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91602. /** Set to \c true to enable adaptive switching between mid-side and
  91603. * left-right encoding on stereo input. Set to \c false to use
  91604. * exhaustive searching. Setting this to \c true requires
  91605. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91606. * \c true in order to have any effect.
  91607. *
  91608. * \default \c false
  91609. * \param encoder An encoder instance to set.
  91610. * \param value Flag value (see above).
  91611. * \assert
  91612. * \code encoder != NULL \endcode
  91613. * \retval FLAC__bool
  91614. * \c false if the encoder is already initialized, else \c true.
  91615. */
  91616. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91617. /** Sets the apodization function(s) the encoder will use when windowing
  91618. * audio data for LPC analysis.
  91619. *
  91620. * The \a specification is a plain ASCII string which specifies exactly
  91621. * which functions to use. There may be more than one (up to 32),
  91622. * separated by \c ';' characters. Some functions take one or more
  91623. * comma-separated arguments in parentheses.
  91624. *
  91625. * The available functions are \c bartlett, \c bartlett_hann,
  91626. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91627. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91628. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91629. *
  91630. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91631. * (0<STDDEV<=0.5).
  91632. *
  91633. * For \c tukey(P), P specifies the fraction of the window that is
  91634. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91635. * corresponds to \c hann.
  91636. *
  91637. * Example specifications are \c "blackman" or
  91638. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91639. *
  91640. * Any function that is specified erroneously is silently dropped. Up
  91641. * to 32 functions are kept, the rest are dropped. If the specification
  91642. * is empty the encoder defaults to \c "tukey(0.5)".
  91643. *
  91644. * When more than one function is specified, then for every subframe the
  91645. * encoder will try each of them separately and choose the window that
  91646. * results in the smallest compressed subframe.
  91647. *
  91648. * Note that each function specified causes the encoder to occupy a
  91649. * floating point array in which to store the window.
  91650. *
  91651. * \default \c "tukey(0.5)"
  91652. * \param encoder An encoder instance to set.
  91653. * \param specification See above.
  91654. * \assert
  91655. * \code encoder != NULL \endcode
  91656. * \code specification != NULL \endcode
  91657. * \retval FLAC__bool
  91658. * \c false if the encoder is already initialized, else \c true.
  91659. */
  91660. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91661. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91662. *
  91663. * \default \c 0
  91664. * \param encoder An encoder instance to set.
  91665. * \param 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_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91672. /** Set the precision, in bits, of the quantized linear predictor
  91673. * coefficients, or \c 0 to let the encoder select it based on the
  91674. * blocksize.
  91675. *
  91676. * \note
  91677. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91678. * be less than 32.
  91679. *
  91680. * \default \c 0
  91681. * \param encoder An encoder instance to set.
  91682. * \param value See above.
  91683. * \assert
  91684. * \code encoder != NULL \endcode
  91685. * \retval FLAC__bool
  91686. * \c false if the encoder is already initialized, else \c true.
  91687. */
  91688. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91689. /** Set to \c false to use only the specified quantized linear predictor
  91690. * coefficient precision, or \c true to search neighboring precision
  91691. * values and use the best one.
  91692. *
  91693. * \default \c false
  91694. * \param encoder An encoder instance to set.
  91695. * \param value See above.
  91696. * \assert
  91697. * \code encoder != NULL \endcode
  91698. * \retval FLAC__bool
  91699. * \c false if the encoder is already initialized, else \c true.
  91700. */
  91701. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91702. /** Deprecated. Setting this value has no effect.
  91703. *
  91704. * \default \c false
  91705. * \param encoder An encoder instance to set.
  91706. * \param value See above.
  91707. * \assert
  91708. * \code encoder != NULL \endcode
  91709. * \retval FLAC__bool
  91710. * \c false if the encoder is already initialized, else \c true.
  91711. */
  91712. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91713. /** Set to \c false to let the encoder estimate the best model order
  91714. * based on the residual signal energy, or \c true to force the
  91715. * encoder to evaluate all order models and select the best.
  91716. *
  91717. * \default \c false
  91718. * \param encoder An encoder instance to set.
  91719. * \param value See above.
  91720. * \assert
  91721. * \code encoder != NULL \endcode
  91722. * \retval FLAC__bool
  91723. * \c false if the encoder is already initialized, else \c true.
  91724. */
  91725. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91726. /** Set the minimum partition order to search when coding the residual.
  91727. * This is used in tandem with
  91728. * FLAC__stream_encoder_set_max_residual_partition_order().
  91729. *
  91730. * The partition order determines the context size in the residual.
  91731. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91732. *
  91733. * Set both min and max values to \c 0 to force a single context,
  91734. * whose Rice parameter is based on the residual signal variance.
  91735. * Otherwise, set a min and max order, and the encoder will search
  91736. * all orders, using the mean of each context for its Rice parameter,
  91737. * and use the best.
  91738. *
  91739. * \default \c 0
  91740. * \param encoder An encoder instance to set.
  91741. * \param value See above.
  91742. * \assert
  91743. * \code encoder != NULL \endcode
  91744. * \retval FLAC__bool
  91745. * \c false if the encoder is already initialized, else \c true.
  91746. */
  91747. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91748. /** Set the maximum partition order to search when coding the residual.
  91749. * This is used in tandem with
  91750. * FLAC__stream_encoder_set_min_residual_partition_order().
  91751. *
  91752. * The partition order determines the context size in the residual.
  91753. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91754. *
  91755. * Set both min and max values to \c 0 to force a single context,
  91756. * whose Rice parameter is based on the residual signal variance.
  91757. * Otherwise, set a min and max order, and the encoder will search
  91758. * all orders, using the mean of each context for its Rice parameter,
  91759. * and use the best.
  91760. *
  91761. * \default \c 0
  91762. * \param encoder An encoder instance to set.
  91763. * \param value See above.
  91764. * \assert
  91765. * \code encoder != NULL \endcode
  91766. * \retval FLAC__bool
  91767. * \c false if the encoder is already initialized, else \c true.
  91768. */
  91769. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91770. /** Deprecated. Setting this value has no effect.
  91771. *
  91772. * \default \c 0
  91773. * \param encoder An encoder instance to set.
  91774. * \param value See above.
  91775. * \assert
  91776. * \code encoder != NULL \endcode
  91777. * \retval FLAC__bool
  91778. * \c false if the encoder is already initialized, else \c true.
  91779. */
  91780. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91781. /** Set an estimate of the total samples that will be encoded.
  91782. * This is merely an estimate and may be set to \c 0 if unknown.
  91783. * This value will be written to the STREAMINFO block before encoding,
  91784. * and can remove the need for the caller to rewrite the value later
  91785. * if the value is known before encoding.
  91786. *
  91787. * \default \c 0
  91788. * \param encoder An encoder instance to set.
  91789. * \param value See above.
  91790. * \assert
  91791. * \code encoder != NULL \endcode
  91792. * \retval FLAC__bool
  91793. * \c false if the encoder is already initialized, else \c true.
  91794. */
  91795. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91796. /** Set the metadata blocks to be emitted to the stream before encoding.
  91797. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91798. * array of pointers to metadata blocks. The array is non-const since
  91799. * the encoder may need to change the \a is_last flag inside them, and
  91800. * in some cases update seek point offsets. Otherwise, the encoder will
  91801. * not modify or free the blocks. It is up to the caller to free the
  91802. * metadata blocks after encoding finishes.
  91803. *
  91804. * \note
  91805. * The encoder stores only copies of the pointers in the \a metadata array;
  91806. * the metadata blocks themselves must survive at least until after
  91807. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91808. *
  91809. * \note
  91810. * The STREAMINFO block is always written and no STREAMINFO block may
  91811. * occur in the supplied array.
  91812. *
  91813. * \note
  91814. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91815. * in the \a metadata array, but the client has specified that it does not
  91816. * support seeking, then the SEEKTABLE will be written verbatim. However
  91817. * by itself this is not very useful as the client will not know the stream
  91818. * offsets for the seekpoints ahead of time. In order to get a proper
  91819. * seektable the client must support seeking. See next note.
  91820. *
  91821. * \note
  91822. * SEEKTABLE blocks are handled specially. Since you will not know
  91823. * the values for the seek point stream offsets, you should pass in
  91824. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91825. * required sample numbers (or placeholder points), with \c 0 for the
  91826. * \a frame_samples and \a stream_offset fields for each point. If the
  91827. * client has specified that it supports seeking by providing a seek
  91828. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91829. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91830. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91831. * then while it is encoding the encoder will fill the stream offsets in
  91832. * for you and when encoding is finished, it will seek back and write the
  91833. * real values into the SEEKTABLE block in the stream. There are helper
  91834. * routines for manipulating seektable template blocks; see metadata.h:
  91835. * FLAC__metadata_object_seektable_template_*(). If the client does
  91836. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91837. * will slow down or remove the ability to seek in the FLAC stream.
  91838. *
  91839. * \note
  91840. * The encoder instance \b will modify the first \c SEEKTABLE block
  91841. * as it transforms the template to a valid seektable while encoding,
  91842. * but it is still up to the caller to free all metadata blocks after
  91843. * encoding.
  91844. *
  91845. * \note
  91846. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91847. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91848. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91849. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91850. * block is present in the \a metadata array, libFLAC will write an
  91851. * empty one, containing only the vendor string.
  91852. *
  91853. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91854. * the second metadata block of the stream. The encoder already supplies
  91855. * the STREAMINFO block automatically. If \a metadata does not contain a
  91856. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91857. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91858. * first, the init function will reorder \a metadata by moving the
  91859. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91860. * blocks will remain as they were.
  91861. *
  91862. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91863. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91864. * return \c false.
  91865. *
  91866. * \default \c NULL, 0
  91867. * \param encoder An encoder instance to set.
  91868. * \param metadata See above.
  91869. * \param num_blocks See above.
  91870. * \assert
  91871. * \code encoder != NULL \endcode
  91872. * \retval FLAC__bool
  91873. * \c false if the encoder is already initialized, else \c true.
  91874. * \c false if the encoder is already initialized, or if
  91875. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91876. */
  91877. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91878. /** Get the current encoder state.
  91879. *
  91880. * \param encoder An encoder instance to query.
  91881. * \assert
  91882. * \code encoder != NULL \endcode
  91883. * \retval FLAC__StreamEncoderState
  91884. * The current encoder state.
  91885. */
  91886. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91887. /** Get the state of the verify stream decoder.
  91888. * Useful when the stream encoder state is
  91889. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91890. *
  91891. * \param encoder An encoder instance to query.
  91892. * \assert
  91893. * \code encoder != NULL \endcode
  91894. * \retval FLAC__StreamDecoderState
  91895. * The verify stream decoder state.
  91896. */
  91897. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91898. /** Get the current encoder state as a C string.
  91899. * This version automatically resolves
  91900. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91901. * verify decoder's state.
  91902. *
  91903. * \param encoder A encoder instance to query.
  91904. * \assert
  91905. * \code encoder != NULL \endcode
  91906. * \retval const char *
  91907. * The encoder state as a C string. Do not modify the contents.
  91908. */
  91909. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91910. /** Get relevant values about the nature of a verify decoder error.
  91911. * Useful when the stream encoder state is
  91912. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91913. * be addresses in which the stats will be returned, or NULL if value
  91914. * is not desired.
  91915. *
  91916. * \param encoder An encoder instance to query.
  91917. * \param absolute_sample The absolute sample number of the mismatch.
  91918. * \param frame_number The number of the frame in which the mismatch occurred.
  91919. * \param channel The channel in which the mismatch occurred.
  91920. * \param sample The number of the sample (relative to the frame) in
  91921. * which the mismatch occurred.
  91922. * \param expected The expected value for the sample in question.
  91923. * \param got The actual value returned by the decoder.
  91924. * \assert
  91925. * \code encoder != NULL \endcode
  91926. */
  91927. 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);
  91928. /** Get the "verify" flag.
  91929. *
  91930. * \param encoder An encoder instance to query.
  91931. * \assert
  91932. * \code encoder != NULL \endcode
  91933. * \retval FLAC__bool
  91934. * See FLAC__stream_encoder_set_verify().
  91935. */
  91936. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91937. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91938. *
  91939. * \param encoder An encoder instance to query.
  91940. * \assert
  91941. * \code encoder != NULL \endcode
  91942. * \retval FLAC__bool
  91943. * See FLAC__stream_encoder_set_streamable_subset().
  91944. */
  91945. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91946. /** Get the number of input channels being processed.
  91947. *
  91948. * \param encoder An encoder instance to query.
  91949. * \assert
  91950. * \code encoder != NULL \endcode
  91951. * \retval unsigned
  91952. * See FLAC__stream_encoder_set_channels().
  91953. */
  91954. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91955. /** Get the input sample resolution setting.
  91956. *
  91957. * \param encoder An encoder instance to query.
  91958. * \assert
  91959. * \code encoder != NULL \endcode
  91960. * \retval unsigned
  91961. * See FLAC__stream_encoder_set_bits_per_sample().
  91962. */
  91963. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91964. /** Get the input sample rate setting.
  91965. *
  91966. * \param encoder An encoder instance to query.
  91967. * \assert
  91968. * \code encoder != NULL \endcode
  91969. * \retval unsigned
  91970. * See FLAC__stream_encoder_set_sample_rate().
  91971. */
  91972. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91973. /** Get the blocksize setting.
  91974. *
  91975. * \param encoder An encoder instance to query.
  91976. * \assert
  91977. * \code encoder != NULL \endcode
  91978. * \retval unsigned
  91979. * See FLAC__stream_encoder_set_blocksize().
  91980. */
  91981. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91982. /** Get the "mid/side stereo coding" flag.
  91983. *
  91984. * \param encoder An encoder instance to query.
  91985. * \assert
  91986. * \code encoder != NULL \endcode
  91987. * \retval FLAC__bool
  91988. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91989. */
  91990. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91991. /** Get the "adaptive mid/side switching" flag.
  91992. *
  91993. * \param encoder An encoder instance to query.
  91994. * \assert
  91995. * \code encoder != NULL \endcode
  91996. * \retval FLAC__bool
  91997. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91998. */
  91999. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92000. /** Get the maximum LPC order setting.
  92001. *
  92002. * \param encoder An encoder instance to query.
  92003. * \assert
  92004. * \code encoder != NULL \endcode
  92005. * \retval unsigned
  92006. * See FLAC__stream_encoder_set_max_lpc_order().
  92007. */
  92008. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  92009. /** Get the quantized linear predictor coefficient precision setting.
  92010. *
  92011. * \param encoder An encoder instance to query.
  92012. * \assert
  92013. * \code encoder != NULL \endcode
  92014. * \retval unsigned
  92015. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  92016. */
  92017. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  92018. /** Get the qlp coefficient precision search flag.
  92019. *
  92020. * \param encoder An encoder instance to query.
  92021. * \assert
  92022. * \code encoder != NULL \endcode
  92023. * \retval FLAC__bool
  92024. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  92025. */
  92026. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  92027. /** Get the "escape coding" flag.
  92028. *
  92029. * \param encoder An encoder instance to query.
  92030. * \assert
  92031. * \code encoder != NULL \endcode
  92032. * \retval FLAC__bool
  92033. * See FLAC__stream_encoder_set_do_escape_coding().
  92034. */
  92035. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92036. /** Get the exhaustive model search flag.
  92037. *
  92038. * \param encoder An encoder instance to query.
  92039. * \assert
  92040. * \code encoder != NULL \endcode
  92041. * \retval FLAC__bool
  92042. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92043. */
  92044. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92045. /** Get the minimum residual partition order setting.
  92046. *
  92047. * \param encoder An encoder instance to query.
  92048. * \assert
  92049. * \code encoder != NULL \endcode
  92050. * \retval unsigned
  92051. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92052. */
  92053. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92054. /** Get maximum residual partition order setting.
  92055. *
  92056. * \param encoder An encoder instance to query.
  92057. * \assert
  92058. * \code encoder != NULL \endcode
  92059. * \retval unsigned
  92060. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92061. */
  92062. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92063. /** Get the Rice parameter search distance setting.
  92064. *
  92065. * \param encoder An encoder instance to query.
  92066. * \assert
  92067. * \code encoder != NULL \endcode
  92068. * \retval unsigned
  92069. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92070. */
  92071. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92072. /** Get the previously set estimate of the total samples to be encoded.
  92073. * The encoder merely mimics back the value given to
  92074. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92075. * other way of knowing how many samples the client will encode.
  92076. *
  92077. * \param encoder An encoder instance to set.
  92078. * \assert
  92079. * \code encoder != NULL \endcode
  92080. * \retval FLAC__uint64
  92081. * See FLAC__stream_encoder_get_total_samples_estimate().
  92082. */
  92083. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92084. /** Initialize the encoder instance to encode native FLAC streams.
  92085. *
  92086. * This flavor of initialization sets up the encoder to encode to a
  92087. * native FLAC stream. I/O is performed via callbacks to the client.
  92088. * For encoding to a plain file via filename or open \c FILE*,
  92089. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92090. * provide a simpler interface.
  92091. *
  92092. * This function should be called after FLAC__stream_encoder_new() and
  92093. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92094. * or FLAC__stream_encoder_process_interleaved().
  92095. * initialization succeeded.
  92096. *
  92097. * The call to FLAC__stream_encoder_init_stream() currently will also
  92098. * immediately call the write callback several times, once with the \c fLaC
  92099. * signature, and once for each encoded metadata block.
  92100. *
  92101. * \param encoder An uninitialized encoder instance.
  92102. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92103. * pointer must not be \c NULL.
  92104. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92105. * pointer may be \c NULL if seeking is not
  92106. * supported. The encoder uses seeking to go back
  92107. * and write some some stream statistics to the
  92108. * STREAMINFO block; this is recommended but not
  92109. * necessary to create a valid FLAC stream. If
  92110. * \a seek_callback is not \c NULL then a
  92111. * \a tell_callback must also be supplied.
  92112. * Alternatively, a dummy seek callback that just
  92113. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92114. * may also be supplied, all though this is slightly
  92115. * less efficient for the encoder.
  92116. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92117. * pointer may be \c NULL if seeking is not
  92118. * supported. If \a seek_callback is \c NULL then
  92119. * this argument will be ignored. If
  92120. * \a seek_callback is not \c NULL then a
  92121. * \a tell_callback must also be supplied.
  92122. * Alternatively, a dummy tell callback that just
  92123. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92124. * may also be supplied, all though this is slightly
  92125. * less efficient for the encoder.
  92126. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92127. * pointer may be \c NULL if the callback is not
  92128. * desired. If the client provides a seek callback,
  92129. * this function is not necessary as the encoder
  92130. * will automatically seek back and update the
  92131. * STREAMINFO block. It may also be \c NULL if the
  92132. * client does not support seeking, since it will
  92133. * have no way of going back to update the
  92134. * STREAMINFO. However the client can still supply
  92135. * a callback if it would like to know the details
  92136. * from the STREAMINFO.
  92137. * \param client_data This value will be supplied to callbacks in their
  92138. * \a client_data argument.
  92139. * \assert
  92140. * \code encoder != NULL \endcode
  92141. * \retval FLAC__StreamEncoderInitStatus
  92142. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92143. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92144. */
  92145. 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);
  92146. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92147. *
  92148. * This flavor of initialization sets up the encoder to encode to a FLAC
  92149. * stream in an Ogg container. I/O is performed via callbacks to the
  92150. * client. For encoding to a plain file via filename or open \c FILE*,
  92151. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92152. * provide a simpler interface.
  92153. *
  92154. * This function should be called after FLAC__stream_encoder_new() and
  92155. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92156. * or FLAC__stream_encoder_process_interleaved().
  92157. * initialization succeeded.
  92158. *
  92159. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92160. * immediately call the write callback several times to write the metadata
  92161. * packets.
  92162. *
  92163. * \param encoder An uninitialized encoder instance.
  92164. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92165. * pointer must not be \c NULL if \a seek_callback
  92166. * is non-NULL since they are both needed to be
  92167. * able to write data back to the Ogg FLAC stream
  92168. * in the post-encode phase.
  92169. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92170. * pointer must not be \c NULL.
  92171. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92172. * pointer may be \c NULL if seeking is not
  92173. * supported. The encoder uses seeking to go back
  92174. * and write some some stream statistics to the
  92175. * STREAMINFO block; this is recommended but not
  92176. * necessary to create a valid FLAC stream. If
  92177. * \a seek_callback is not \c NULL then a
  92178. * \a tell_callback must also be supplied.
  92179. * Alternatively, a dummy seek callback that just
  92180. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92181. * may also be supplied, all though this is slightly
  92182. * less efficient for the encoder.
  92183. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92184. * pointer may be \c NULL if seeking is not
  92185. * supported. If \a seek_callback is \c NULL then
  92186. * this argument will be ignored. If
  92187. * \a seek_callback is not \c NULL then a
  92188. * \a tell_callback must also be supplied.
  92189. * Alternatively, a dummy tell callback that just
  92190. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92191. * may also be supplied, all though this is slightly
  92192. * less efficient for the encoder.
  92193. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92194. * pointer may be \c NULL if the callback is not
  92195. * desired. If the client provides a seek callback,
  92196. * this function is not necessary as the encoder
  92197. * will automatically seek back and update the
  92198. * STREAMINFO block. It may also be \c NULL if the
  92199. * client does not support seeking, since it will
  92200. * have no way of going back to update the
  92201. * STREAMINFO. However the client can still supply
  92202. * a callback if it would like to know the details
  92203. * from the STREAMINFO.
  92204. * \param client_data This value will be supplied to callbacks in their
  92205. * \a client_data argument.
  92206. * \assert
  92207. * \code encoder != NULL \endcode
  92208. * \retval FLAC__StreamEncoderInitStatus
  92209. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92210. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92211. */
  92212. 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);
  92213. /** Initialize the encoder instance to encode native FLAC files.
  92214. *
  92215. * This flavor of initialization sets up the encoder to encode to a
  92216. * plain native FLAC file. For non-stdio streams, you must use
  92217. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92218. *
  92219. * This function should be called after FLAC__stream_encoder_new() and
  92220. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92221. * or FLAC__stream_encoder_process_interleaved().
  92222. * initialization succeeded.
  92223. *
  92224. * \param encoder An uninitialized encoder instance.
  92225. * \param file An open file. The file should have been opened
  92226. * with mode \c "w+b" and rewound. The file
  92227. * becomes owned by the encoder and should not be
  92228. * manipulated by the client while encoding.
  92229. * Unless \a file is \c stdout, it will be closed
  92230. * when FLAC__stream_encoder_finish() is called.
  92231. * Note however that a proper SEEKTABLE cannot be
  92232. * created when encoding to \c stdout since it is
  92233. * not seekable.
  92234. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92235. * pointer may be \c NULL if the callback is not
  92236. * desired.
  92237. * \param client_data This value will be supplied to callbacks in their
  92238. * \a client_data argument.
  92239. * \assert
  92240. * \code encoder != NULL \endcode
  92241. * \code file != NULL \endcode
  92242. * \retval FLAC__StreamEncoderInitStatus
  92243. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92244. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92245. */
  92246. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92247. /** Initialize the encoder instance to encode Ogg FLAC files.
  92248. *
  92249. * This flavor of initialization sets up the encoder to encode to a
  92250. * plain Ogg FLAC file. For non-stdio streams, you must use
  92251. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92252. *
  92253. * This function should be called after FLAC__stream_encoder_new() and
  92254. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92255. * or FLAC__stream_encoder_process_interleaved().
  92256. * initialization succeeded.
  92257. *
  92258. * \param encoder An uninitialized encoder instance.
  92259. * \param file An open file. The file should have been opened
  92260. * with mode \c "w+b" and rewound. The file
  92261. * becomes owned by the encoder and should not be
  92262. * manipulated by the client while encoding.
  92263. * Unless \a file is \c stdout, it will be closed
  92264. * when FLAC__stream_encoder_finish() is called.
  92265. * Note however that a proper SEEKTABLE cannot be
  92266. * created when encoding to \c stdout since it is
  92267. * not seekable.
  92268. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92269. * pointer may be \c NULL if the callback is not
  92270. * desired.
  92271. * \param client_data This value will be supplied to callbacks in their
  92272. * \a client_data argument.
  92273. * \assert
  92274. * \code encoder != NULL \endcode
  92275. * \code file != NULL \endcode
  92276. * \retval FLAC__StreamEncoderInitStatus
  92277. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92278. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92279. */
  92280. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92281. /** Initialize the encoder instance to encode native FLAC files.
  92282. *
  92283. * This flavor of initialization sets up the encoder to encode to a plain
  92284. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92285. * with Unicode filenames on Windows), you must use
  92286. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92287. * and provide callbacks for the I/O.
  92288. *
  92289. * This function should be called after FLAC__stream_encoder_new() and
  92290. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92291. * or FLAC__stream_encoder_process_interleaved().
  92292. * initialization succeeded.
  92293. *
  92294. * \param encoder An uninitialized encoder instance.
  92295. * \param filename The name of the file to encode to. The file will
  92296. * be opened with fopen(). Use \c NULL to encode to
  92297. * \c stdout. Note however that a proper SEEKTABLE
  92298. * cannot be created when encoding to \c stdout since
  92299. * it is not seekable.
  92300. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92301. * pointer may be \c NULL if the callback is not
  92302. * desired.
  92303. * \param client_data This value will be supplied to callbacks in their
  92304. * \a client_data argument.
  92305. * \assert
  92306. * \code encoder != NULL \endcode
  92307. * \retval FLAC__StreamEncoderInitStatus
  92308. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92309. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92310. */
  92311. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92312. /** Initialize the encoder instance to encode Ogg FLAC files.
  92313. *
  92314. * This flavor of initialization sets up the encoder to encode to a plain
  92315. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92316. * with Unicode filenames on Windows), you must use
  92317. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92318. * and provide callbacks for the I/O.
  92319. *
  92320. * This function should be called after FLAC__stream_encoder_new() and
  92321. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92322. * or FLAC__stream_encoder_process_interleaved().
  92323. * initialization succeeded.
  92324. *
  92325. * \param encoder An uninitialized encoder instance.
  92326. * \param filename The name of the file to encode to. The file will
  92327. * be opened with fopen(). Use \c NULL to encode to
  92328. * \c stdout. Note however that a proper SEEKTABLE
  92329. * cannot be created when encoding to \c stdout since
  92330. * it is not seekable.
  92331. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92332. * pointer may be \c NULL if the callback is not
  92333. * desired.
  92334. * \param client_data This value will be supplied to callbacks in their
  92335. * \a client_data argument.
  92336. * \assert
  92337. * \code encoder != NULL \endcode
  92338. * \retval FLAC__StreamEncoderInitStatus
  92339. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92340. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92341. */
  92342. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92343. /** Finish the encoding process.
  92344. * Flushes the encoding buffer, releases resources, resets the encoder
  92345. * settings to their defaults, and returns the encoder state to
  92346. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92347. * one or more write callbacks before returning, and will generate
  92348. * a metadata callback.
  92349. *
  92350. * Note that in the course of processing the last frame, errors can
  92351. * occur, so the caller should be sure to check the return value to
  92352. * ensure the file was encoded properly.
  92353. *
  92354. * In the event of a prematurely-terminated encode, it is not strictly
  92355. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92356. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92357. * with a FLAC__stream_encoder_finish().
  92358. *
  92359. * \param encoder An uninitialized encoder instance.
  92360. * \assert
  92361. * \code encoder != NULL \endcode
  92362. * \retval FLAC__bool
  92363. * \c false if an error occurred processing the last frame; or if verify
  92364. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92365. * verify mismatch; else \c true. If \c false, caller should check the
  92366. * state with FLAC__stream_encoder_get_state() for more information
  92367. * about the error.
  92368. */
  92369. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92370. /** Submit data for encoding.
  92371. * This version allows you to supply the input data via an array of
  92372. * pointers, each pointer pointing to an array of \a samples samples
  92373. * representing one channel. The samples need not be block-aligned,
  92374. * but each channel should have the same number of samples. Each sample
  92375. * should be a signed integer, right-justified to the resolution set by
  92376. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92377. * resolution is 16 bits per sample, the samples should all be in the
  92378. * range [-32768,32767].
  92379. *
  92380. * For applications where channel order is important, channels must
  92381. * follow the order as described in the
  92382. * <A HREF="../format.html#frame_header">frame header</A>.
  92383. *
  92384. * \param encoder An initialized encoder instance in the OK state.
  92385. * \param buffer An array of pointers to each channel's signal.
  92386. * \param samples The number of samples in one channel.
  92387. * \assert
  92388. * \code encoder != NULL \endcode
  92389. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92390. * \retval FLAC__bool
  92391. * \c true if successful, else \c false; in this case, check the
  92392. * encoder state with FLAC__stream_encoder_get_state() to see what
  92393. * went wrong.
  92394. */
  92395. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92396. /** Submit data for encoding.
  92397. * This version allows you to supply the input data where the channels
  92398. * are interleaved into a single array (i.e. channel0_sample0,
  92399. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92400. * The samples need not be block-aligned but they must be
  92401. * sample-aligned, i.e. the first value should be channel0_sample0
  92402. * and the last value channelN_sampleM. Each sample should be a signed
  92403. * integer, right-justified to the resolution set by
  92404. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92405. * resolution is 16 bits per sample, the samples should all be in the
  92406. * range [-32768,32767].
  92407. *
  92408. * For applications where channel order is important, channels must
  92409. * follow the order as described in the
  92410. * <A HREF="../format.html#frame_header">frame header</A>.
  92411. *
  92412. * \param encoder An initialized encoder instance in the OK state.
  92413. * \param buffer An array of channel-interleaved data (see above).
  92414. * \param samples The number of samples in one channel, the same as for
  92415. * FLAC__stream_encoder_process(). For example, if
  92416. * encoding two channels, \c 1000 \a samples corresponds
  92417. * to a \a buffer of 2000 values.
  92418. * \assert
  92419. * \code encoder != NULL \endcode
  92420. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92421. * \retval FLAC__bool
  92422. * \c true if successful, else \c false; in this case, check the
  92423. * encoder state with FLAC__stream_encoder_get_state() to see what
  92424. * went wrong.
  92425. */
  92426. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92427. /* \} */
  92428. #ifdef __cplusplus
  92429. }
  92430. #endif
  92431. #endif
  92432. /*** End of inlined file: stream_encoder.h ***/
  92433. #ifdef _MSC_VER
  92434. /* OPT: an MSVC built-in would be better */
  92435. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92436. {
  92437. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92438. return (x>>16) | (x<<16);
  92439. }
  92440. #endif
  92441. #if defined(_MSC_VER) && defined(_X86_)
  92442. /* OPT: an MSVC built-in would be better */
  92443. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92444. {
  92445. __asm {
  92446. mov edx, start
  92447. mov ecx, len
  92448. test ecx, ecx
  92449. loop1:
  92450. jz done1
  92451. mov eax, [edx]
  92452. bswap eax
  92453. mov [edx], eax
  92454. add edx, 4
  92455. dec ecx
  92456. jmp short loop1
  92457. done1:
  92458. }
  92459. }
  92460. #endif
  92461. /** \mainpage
  92462. *
  92463. * \section intro Introduction
  92464. *
  92465. * This is the documentation for the FLAC C and C++ APIs. It is
  92466. * highly interconnected; this introduction should give you a top
  92467. * level idea of the structure and how to find the information you
  92468. * need. As a prerequisite you should have at least a basic
  92469. * knowledge of the FLAC format, documented
  92470. * <A HREF="../format.html">here</A>.
  92471. *
  92472. * \section c_api FLAC C API
  92473. *
  92474. * The FLAC C API is the interface to libFLAC, a set of structures
  92475. * describing the components of FLAC streams, and functions for
  92476. * encoding and decoding streams, as well as manipulating FLAC
  92477. * metadata in files. The public include files will be installed
  92478. * in your include area (for example /usr/include/FLAC/...).
  92479. *
  92480. * By writing a little code and linking against libFLAC, it is
  92481. * relatively easy to add FLAC support to another program. The
  92482. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92483. * Complete source code of libFLAC as well as the command-line
  92484. * encoder and plugins is available and is a useful source of
  92485. * examples.
  92486. *
  92487. * Aside from encoders and decoders, libFLAC provides a powerful
  92488. * metadata interface for manipulating metadata in FLAC files. It
  92489. * allows the user to add, delete, and modify FLAC metadata blocks
  92490. * and it can automatically take advantage of PADDING blocks to avoid
  92491. * rewriting the entire FLAC file when changing the size of the
  92492. * metadata.
  92493. *
  92494. * libFLAC usually only requires the standard C library and C math
  92495. * library. In particular, threading is not used so there is no
  92496. * dependency on a thread library. However, libFLAC does not use
  92497. * global variables and should be thread-safe.
  92498. *
  92499. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92500. * However the metadata editing interfaces currently have limited
  92501. * read-only support for Ogg FLAC files.
  92502. *
  92503. * \section cpp_api FLAC C++ API
  92504. *
  92505. * The FLAC C++ API is a set of classes that encapsulate the
  92506. * structures and functions in libFLAC. They provide slightly more
  92507. * functionality with respect to metadata but are otherwise
  92508. * equivalent. For the most part, they share the same usage as
  92509. * their counterparts in libFLAC, and the FLAC C API documentation
  92510. * can be used as a supplement. The public include files
  92511. * for the C++ API will be installed in your include area (for
  92512. * example /usr/include/FLAC++/...).
  92513. *
  92514. * libFLAC++ is also licensed under
  92515. * <A HREF="../license.html">Xiph's BSD license</A>.
  92516. *
  92517. * \section getting_started Getting Started
  92518. *
  92519. * A good starting point for learning the API is to browse through
  92520. * the <A HREF="modules.html">modules</A>. Modules are logical
  92521. * groupings of related functions or classes, which correspond roughly
  92522. * to header files or sections of header files. Each module includes a
  92523. * detailed description of the general usage of its functions or
  92524. * classes.
  92525. *
  92526. * From there you can go on to look at the documentation of
  92527. * individual functions. You can see different views of the individual
  92528. * functions through the links in top bar across this page.
  92529. *
  92530. * If you prefer a more hands-on approach, you can jump right to some
  92531. * <A HREF="../documentation_example_code.html">example code</A>.
  92532. *
  92533. * \section porting_guide Porting Guide
  92534. *
  92535. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92536. * has been introduced which gives detailed instructions on how to
  92537. * port your code to newer versions of FLAC.
  92538. *
  92539. * \section embedded_developers Embedded Developers
  92540. *
  92541. * libFLAC has grown larger over time as more functionality has been
  92542. * included, but much of it may be unnecessary for a particular embedded
  92543. * implementation. Unused parts may be pruned by some simple editing of
  92544. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92545. * metadata interface are all independent from each other.
  92546. *
  92547. * It is easiest to just describe the dependencies:
  92548. *
  92549. * - All modules depend on the \link flac_format Format \endlink module.
  92550. * - The decoders and encoders depend on the bitbuffer.
  92551. * - The decoder is independent of the encoder. The encoder uses the
  92552. * decoder because of the verify feature, but this can be removed if
  92553. * not needed.
  92554. * - Parts of the metadata interface require the stream decoder (but not
  92555. * the encoder).
  92556. * - Ogg support is selectable through the compile time macro
  92557. * \c FLAC__HAS_OGG.
  92558. *
  92559. * For example, if your application only requires the stream decoder, no
  92560. * encoder, and no metadata interface, you can remove the stream encoder
  92561. * and the metadata interface, which will greatly reduce the size of the
  92562. * library.
  92563. *
  92564. * Also, there are several places in the libFLAC code with comments marked
  92565. * with "OPT:" where a #define can be changed to enable code that might be
  92566. * faster on a specific platform. Experimenting with these can yield faster
  92567. * binaries.
  92568. */
  92569. /** \defgroup porting Porting Guide for New Versions
  92570. *
  92571. * This module describes differences in the library interfaces from
  92572. * version to version. It assists in the porting of code that uses
  92573. * the libraries to newer versions of FLAC.
  92574. *
  92575. * One simple facility for making porting easier that has been added
  92576. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92577. * library's includes (e.g. \c include/FLAC/export.h). The
  92578. * \c #defines mirror the libraries'
  92579. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92580. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92581. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92582. * These can be used to support multiple versions of an API during the
  92583. * transition phase, e.g.
  92584. *
  92585. * \code
  92586. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92587. * legacy code
  92588. * #else
  92589. * new code
  92590. * #endif
  92591. * \endcode
  92592. *
  92593. * The the source will work for multiple versions and the legacy code can
  92594. * easily be removed when the transition is complete.
  92595. *
  92596. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92597. * include/FLAC/export.h), which can be used to determine whether or not
  92598. * the library has been compiled with support for Ogg FLAC. This is
  92599. * simpler than trying to call an Ogg init function and catching the
  92600. * error.
  92601. */
  92602. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92603. * \ingroup porting
  92604. *
  92605. * \brief
  92606. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92607. *
  92608. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92609. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92610. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92611. * decoding layers and three encoding layers have been merged into a
  92612. * single stream decoder and stream encoder. That is, the functionality
  92613. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92614. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92615. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92616. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92617. * is there is now a single API that can be used to encode or decode
  92618. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92619. * on both seekable and non-seekable streams.
  92620. *
  92621. * Instead of creating an encoder or decoder of a certain layer, now the
  92622. * client will always create a FLAC__StreamEncoder or
  92623. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92624. * initialization function. For example, for the decoder,
  92625. * FLAC__stream_decoder_init() has been replaced by
  92626. * FLAC__stream_decoder_init_stream(). This init function takes
  92627. * callbacks for the I/O, and the seeking callbacks are optional. This
  92628. * allows the client to use the same object for seekable and
  92629. * non-seekable streams. For decoding a FLAC file directly, the client
  92630. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92631. * and fewer callbacks; most of the other callbacks are supplied
  92632. * internally. For situations where fopen()ing by filename is not
  92633. * possible (e.g. Unicode filenames on Windows) the client can instead
  92634. * open the file itself and supply the FILE* to
  92635. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92636. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92637. * Since the callbacks and client data are now passed to the init
  92638. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92639. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92640. * rest of the calls to the decoder are the same as before.
  92641. *
  92642. * There are counterpart init functions for Ogg FLAC, e.g.
  92643. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92644. * and callbacks are the same as for native FLAC.
  92645. *
  92646. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92647. * been set up like so:
  92648. *
  92649. * \code
  92650. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92651. * if(decoder == NULL) do_something;
  92652. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92653. * [... other settings ...]
  92654. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92655. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92656. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92657. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92658. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92659. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92660. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92661. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92662. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92663. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92664. * \endcode
  92665. *
  92666. * In FLAC 1.1.3 it is like this:
  92667. *
  92668. * \code
  92669. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92670. * if(decoder == NULL) do_something;
  92671. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92672. * [... other settings ...]
  92673. * if(FLAC__stream_decoder_init_stream(
  92674. * decoder,
  92675. * my_read_callback,
  92676. * my_seek_callback, // or NULL
  92677. * my_tell_callback, // or NULL
  92678. * my_length_callback, // or NULL
  92679. * my_eof_callback, // or NULL
  92680. * my_write_callback,
  92681. * my_metadata_callback, // or NULL
  92682. * my_error_callback,
  92683. * my_client_data
  92684. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92685. * \endcode
  92686. *
  92687. * or you could do;
  92688. *
  92689. * \code
  92690. * [...]
  92691. * FILE *file = fopen("somefile.flac","rb");
  92692. * if(file == NULL) do_somthing;
  92693. * if(FLAC__stream_decoder_init_FILE(
  92694. * decoder,
  92695. * file,
  92696. * my_write_callback,
  92697. * my_metadata_callback, // or NULL
  92698. * my_error_callback,
  92699. * my_client_data
  92700. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92701. * \endcode
  92702. *
  92703. * or just:
  92704. *
  92705. * \code
  92706. * [...]
  92707. * if(FLAC__stream_decoder_init_file(
  92708. * decoder,
  92709. * "somefile.flac",
  92710. * my_write_callback,
  92711. * my_metadata_callback, // or NULL
  92712. * my_error_callback,
  92713. * my_client_data
  92714. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92715. * \endcode
  92716. *
  92717. * Another small change to the decoder is in how it handles unparseable
  92718. * streams. Before, when the decoder found an unparseable stream
  92719. * (reserved for when the decoder encounters a stream from a future
  92720. * encoder that it can't parse), it changed the state to
  92721. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92722. * drops sync and calls the error callback with a new error code
  92723. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92724. * more robust. If your error callback does not discriminate on the the
  92725. * error state, your code does not need to be changed.
  92726. *
  92727. * The encoder now has a new setting:
  92728. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92729. * method used to window the data before LPC analysis. You only need to
  92730. * add a call to this function if the default is not suitable. There
  92731. * are also two new convenience functions that may be useful:
  92732. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92733. * FLAC__metadata_get_cuesheet().
  92734. *
  92735. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92736. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92737. * is now \c size_t instead of \c unsigned.
  92738. */
  92739. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92740. * \ingroup porting
  92741. *
  92742. * \brief
  92743. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92744. *
  92745. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92746. * There was a slight change in the implementation of
  92747. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92748. * of the \a metadata array of pointers so the client no longer needs
  92749. * to maintain it after the call. The objects themselves that are
  92750. * pointed to by the array are still not copied though and must be
  92751. * maintained until the call to FLAC__stream_encoder_finish().
  92752. */
  92753. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92754. * \ingroup porting
  92755. *
  92756. * \brief
  92757. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92758. *
  92759. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92760. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92761. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92762. *
  92763. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92764. * has changed to reflect the conversion of one of the reserved bits
  92765. * into active use. It used to be \c 2 and now is \c 1. However the
  92766. * FLAC frame header length has not changed, so to skip the proper
  92767. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92768. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92769. */
  92770. /** \defgroup flac FLAC C API
  92771. *
  92772. * The FLAC C API is the interface to libFLAC, a set of structures
  92773. * describing the components of FLAC streams, and functions for
  92774. * encoding and decoding streams, as well as manipulating FLAC
  92775. * metadata in files.
  92776. *
  92777. * You should start with the format components as all other modules
  92778. * are dependent on it.
  92779. */
  92780. #endif
  92781. /*** End of inlined file: all.h ***/
  92782. /*** Start of inlined file: bitmath.c ***/
  92783. /*** Start of inlined file: juce_FlacHeader.h ***/
  92784. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92785. // tasks..
  92786. #define VERSION "1.2.1"
  92787. #define FLAC__NO_DLL 1
  92788. #if JUCE_MSVC
  92789. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92790. #endif
  92791. #if JUCE_MAC
  92792. #define FLAC__SYS_DARWIN 1
  92793. #endif
  92794. /*** End of inlined file: juce_FlacHeader.h ***/
  92795. #if JUCE_USE_FLAC
  92796. #if HAVE_CONFIG_H
  92797. # include <config.h>
  92798. #endif
  92799. /*** Start of inlined file: bitmath.h ***/
  92800. #ifndef FLAC__PRIVATE__BITMATH_H
  92801. #define FLAC__PRIVATE__BITMATH_H
  92802. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92803. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92804. unsigned FLAC__bitmath_silog2(int v);
  92805. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92806. #endif
  92807. /*** End of inlined file: bitmath.h ***/
  92808. /* An example of what FLAC__bitmath_ilog2() computes:
  92809. *
  92810. * ilog2( 0) = assertion failure
  92811. * ilog2( 1) = 0
  92812. * ilog2( 2) = 1
  92813. * ilog2( 3) = 1
  92814. * ilog2( 4) = 2
  92815. * ilog2( 5) = 2
  92816. * ilog2( 6) = 2
  92817. * ilog2( 7) = 2
  92818. * ilog2( 8) = 3
  92819. * ilog2( 9) = 3
  92820. * ilog2(10) = 3
  92821. * ilog2(11) = 3
  92822. * ilog2(12) = 3
  92823. * ilog2(13) = 3
  92824. * ilog2(14) = 3
  92825. * ilog2(15) = 3
  92826. * ilog2(16) = 4
  92827. * ilog2(17) = 4
  92828. * ilog2(18) = 4
  92829. */
  92830. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92831. {
  92832. unsigned l = 0;
  92833. FLAC__ASSERT(v > 0);
  92834. while(v >>= 1)
  92835. l++;
  92836. return l;
  92837. }
  92838. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92839. {
  92840. unsigned l = 0;
  92841. FLAC__ASSERT(v > 0);
  92842. while(v >>= 1)
  92843. l++;
  92844. return l;
  92845. }
  92846. /* An example of what FLAC__bitmath_silog2() computes:
  92847. *
  92848. * silog2(-10) = 5
  92849. * silog2(- 9) = 5
  92850. * silog2(- 8) = 4
  92851. * silog2(- 7) = 4
  92852. * silog2(- 6) = 4
  92853. * silog2(- 5) = 4
  92854. * silog2(- 4) = 3
  92855. * silog2(- 3) = 3
  92856. * silog2(- 2) = 2
  92857. * silog2(- 1) = 2
  92858. * silog2( 0) = 0
  92859. * silog2( 1) = 2
  92860. * silog2( 2) = 3
  92861. * silog2( 3) = 3
  92862. * silog2( 4) = 4
  92863. * silog2( 5) = 4
  92864. * silog2( 6) = 4
  92865. * silog2( 7) = 4
  92866. * silog2( 8) = 5
  92867. * silog2( 9) = 5
  92868. * silog2( 10) = 5
  92869. */
  92870. unsigned FLAC__bitmath_silog2(int v)
  92871. {
  92872. while(1) {
  92873. if(v == 0) {
  92874. return 0;
  92875. }
  92876. else if(v > 0) {
  92877. unsigned l = 0;
  92878. while(v) {
  92879. l++;
  92880. v >>= 1;
  92881. }
  92882. return l+1;
  92883. }
  92884. else if(v == -1) {
  92885. return 2;
  92886. }
  92887. else {
  92888. v++;
  92889. v = -v;
  92890. }
  92891. }
  92892. }
  92893. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92894. {
  92895. while(1) {
  92896. if(v == 0) {
  92897. return 0;
  92898. }
  92899. else if(v > 0) {
  92900. unsigned l = 0;
  92901. while(v) {
  92902. l++;
  92903. v >>= 1;
  92904. }
  92905. return l+1;
  92906. }
  92907. else if(v == -1) {
  92908. return 2;
  92909. }
  92910. else {
  92911. v++;
  92912. v = -v;
  92913. }
  92914. }
  92915. }
  92916. #endif
  92917. /*** End of inlined file: bitmath.c ***/
  92918. /*** Start of inlined file: bitreader.c ***/
  92919. /*** Start of inlined file: juce_FlacHeader.h ***/
  92920. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92921. // tasks..
  92922. #define VERSION "1.2.1"
  92923. #define FLAC__NO_DLL 1
  92924. #if JUCE_MSVC
  92925. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92926. #endif
  92927. #if JUCE_MAC
  92928. #define FLAC__SYS_DARWIN 1
  92929. #endif
  92930. /*** End of inlined file: juce_FlacHeader.h ***/
  92931. #if JUCE_USE_FLAC
  92932. #if HAVE_CONFIG_H
  92933. # include <config.h>
  92934. #endif
  92935. #include <stdlib.h> /* for malloc() */
  92936. #include <string.h> /* for memcpy(), memset() */
  92937. #ifdef _MSC_VER
  92938. #include <winsock.h> /* for ntohl() */
  92939. #elif defined FLAC__SYS_DARWIN
  92940. #include <machine/endian.h> /* for ntohl() */
  92941. #elif defined __MINGW32__
  92942. #include <winsock.h> /* for ntohl() */
  92943. #else
  92944. #include <netinet/in.h> /* for ntohl() */
  92945. #endif
  92946. /*** Start of inlined file: bitreader.h ***/
  92947. #ifndef FLAC__PRIVATE__BITREADER_H
  92948. #define FLAC__PRIVATE__BITREADER_H
  92949. #include <stdio.h> /* for FILE */
  92950. /*** Start of inlined file: cpu.h ***/
  92951. #ifndef FLAC__PRIVATE__CPU_H
  92952. #define FLAC__PRIVATE__CPU_H
  92953. #ifdef HAVE_CONFIG_H
  92954. #include <config.h>
  92955. #endif
  92956. typedef enum {
  92957. FLAC__CPUINFO_TYPE_IA32,
  92958. FLAC__CPUINFO_TYPE_PPC,
  92959. FLAC__CPUINFO_TYPE_UNKNOWN
  92960. } FLAC__CPUInfo_Type;
  92961. typedef struct {
  92962. FLAC__bool cpuid;
  92963. FLAC__bool bswap;
  92964. FLAC__bool cmov;
  92965. FLAC__bool mmx;
  92966. FLAC__bool fxsr;
  92967. FLAC__bool sse;
  92968. FLAC__bool sse2;
  92969. FLAC__bool sse3;
  92970. FLAC__bool ssse3;
  92971. FLAC__bool _3dnow;
  92972. FLAC__bool ext3dnow;
  92973. FLAC__bool extmmx;
  92974. } FLAC__CPUInfo_IA32;
  92975. typedef struct {
  92976. FLAC__bool altivec;
  92977. FLAC__bool ppc64;
  92978. } FLAC__CPUInfo_PPC;
  92979. typedef struct {
  92980. FLAC__bool use_asm;
  92981. FLAC__CPUInfo_Type type;
  92982. union {
  92983. FLAC__CPUInfo_IA32 ia32;
  92984. FLAC__CPUInfo_PPC ppc;
  92985. } data;
  92986. } FLAC__CPUInfo;
  92987. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92988. #ifndef FLAC__NO_ASM
  92989. #ifdef FLAC__CPU_IA32
  92990. #ifdef FLAC__HAS_NASM
  92991. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92992. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92993. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92994. #endif
  92995. #endif
  92996. #endif
  92997. #endif
  92998. /*** End of inlined file: cpu.h ***/
  92999. /*
  93000. * opaque structure definition
  93001. */
  93002. struct FLAC__BitReader;
  93003. typedef struct FLAC__BitReader FLAC__BitReader;
  93004. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93005. /*
  93006. * construction, deletion, initialization, etc functions
  93007. */
  93008. FLAC__BitReader *FLAC__bitreader_new(void);
  93009. void FLAC__bitreader_delete(FLAC__BitReader *br);
  93010. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  93011. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  93012. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  93013. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  93014. /*
  93015. * CRC functions
  93016. */
  93017. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  93018. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  93019. /*
  93020. * info functions
  93021. */
  93022. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  93023. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  93024. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  93025. /*
  93026. * read functions
  93027. */
  93028. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  93029. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  93030. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93031. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93032. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93033. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93034. 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! */
  93035. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93036. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93037. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93038. #ifndef FLAC__NO_ASM
  93039. # ifdef FLAC__CPU_IA32
  93040. # ifdef FLAC__HAS_NASM
  93041. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93042. # endif
  93043. # endif
  93044. #endif
  93045. #if 0 /* UNUSED */
  93046. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93047. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93048. #endif
  93049. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93050. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93051. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93052. #endif
  93053. /*** End of inlined file: bitreader.h ***/
  93054. /*** Start of inlined file: crc.h ***/
  93055. #ifndef FLAC__PRIVATE__CRC_H
  93056. #define FLAC__PRIVATE__CRC_H
  93057. /* 8 bit CRC generator, MSB shifted first
  93058. ** polynomial = x^8 + x^2 + x^1 + x^0
  93059. ** init = 0
  93060. */
  93061. extern FLAC__byte const FLAC__crc8_table[256];
  93062. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93063. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93064. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93065. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93066. /* 16 bit CRC generator, MSB shifted first
  93067. ** polynomial = x^16 + x^15 + x^2 + x^0
  93068. ** init = 0
  93069. */
  93070. extern unsigned FLAC__crc16_table[256];
  93071. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93072. /* this alternate may be faster on some systems/compilers */
  93073. #if 0
  93074. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93075. #endif
  93076. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93077. #endif
  93078. /*** End of inlined file: crc.h ***/
  93079. /* Things should be fastest when this matches the machine word size */
  93080. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93081. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93082. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93083. typedef FLAC__uint32 brword;
  93084. #define FLAC__BYTES_PER_WORD 4
  93085. #define FLAC__BITS_PER_WORD 32
  93086. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93087. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93088. #if WORDS_BIGENDIAN
  93089. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93090. #else
  93091. #if defined (_MSC_VER) && defined (_X86_)
  93092. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93093. #else
  93094. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93095. #endif
  93096. #endif
  93097. /* counts the # of zero MSBs in a word */
  93098. #define COUNT_ZERO_MSBS(word) ( \
  93099. (word) <= 0xffff ? \
  93100. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93101. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93102. )
  93103. /* this alternate might be slightly faster on some systems/compilers: */
  93104. #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])) )
  93105. /*
  93106. * This should be at least twice as large as the largest number of words
  93107. * required to represent any 'number' (in any encoding) you are going to
  93108. * read. With FLAC this is on the order of maybe a few hundred bits.
  93109. * If the buffer is smaller than that, the decoder won't be able to read
  93110. * in a whole number that is in a variable length encoding (e.g. Rice).
  93111. * But to be practical it should be at least 1K bytes.
  93112. *
  93113. * Increase this number to decrease the number of read callbacks, at the
  93114. * expense of using more memory. Or decrease for the reverse effect,
  93115. * keeping in mind the limit from the first paragraph. The optimal size
  93116. * also depends on the CPU cache size and other factors; some twiddling
  93117. * may be necessary to squeeze out the best performance.
  93118. */
  93119. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93120. static const unsigned char byte_to_unary_table[] = {
  93121. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93122. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93123. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93124. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93125. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93126. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93127. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93128. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93137. };
  93138. #ifdef min
  93139. #undef min
  93140. #endif
  93141. #define min(x,y) ((x)<(y)?(x):(y))
  93142. #ifdef max
  93143. #undef max
  93144. #endif
  93145. #define max(x,y) ((x)>(y)?(x):(y))
  93146. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93147. #ifdef _MSC_VER
  93148. #define FLAC__U64L(x) x
  93149. #else
  93150. #define FLAC__U64L(x) x##LLU
  93151. #endif
  93152. #ifndef FLaC__INLINE
  93153. #define FLaC__INLINE
  93154. #endif
  93155. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93156. struct FLAC__BitReader {
  93157. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93158. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93159. brword *buffer;
  93160. unsigned capacity; /* in words */
  93161. unsigned words; /* # of completed words in buffer */
  93162. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93163. unsigned consumed_words; /* #words ... */
  93164. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93165. unsigned read_crc16; /* the running frame CRC */
  93166. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93167. FLAC__BitReaderReadCallback read_callback;
  93168. void *client_data;
  93169. FLAC__CPUInfo cpu_info;
  93170. };
  93171. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93172. {
  93173. register unsigned crc = br->read_crc16;
  93174. #if FLAC__BYTES_PER_WORD == 4
  93175. switch(br->crc16_align) {
  93176. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93177. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93178. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93179. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93180. }
  93181. #elif FLAC__BYTES_PER_WORD == 8
  93182. switch(br->crc16_align) {
  93183. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93184. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93185. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93186. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93187. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93188. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93189. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93190. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93191. }
  93192. #else
  93193. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93194. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93195. br->read_crc16 = crc;
  93196. #endif
  93197. br->crc16_align = 0;
  93198. }
  93199. /* would be static except it needs to be called by asm routines */
  93200. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93201. {
  93202. unsigned start, end;
  93203. size_t bytes;
  93204. FLAC__byte *target;
  93205. /* first shift the unconsumed buffer data toward the front as much as possible */
  93206. if(br->consumed_words > 0) {
  93207. start = br->consumed_words;
  93208. end = br->words + (br->bytes? 1:0);
  93209. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93210. br->words -= start;
  93211. br->consumed_words = 0;
  93212. }
  93213. /*
  93214. * set the target for reading, taking into account word alignment and endianness
  93215. */
  93216. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93217. if(bytes == 0)
  93218. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93219. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93220. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93221. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93222. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93223. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93224. * ^^-------target, bytes=3
  93225. * on LE machines, have to byteswap the odd tail word so nothing is
  93226. * overwritten:
  93227. */
  93228. #if WORDS_BIGENDIAN
  93229. #else
  93230. if(br->bytes)
  93231. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93232. #endif
  93233. /* now it looks like:
  93234. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93235. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93236. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93237. * ^^-------target, bytes=3
  93238. */
  93239. /* read in the data; note that the callback may return a smaller number of bytes */
  93240. if(!br->read_callback(target, &bytes, br->client_data))
  93241. return false;
  93242. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93243. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93244. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93245. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93246. * now have to byteswap on LE machines:
  93247. */
  93248. #if WORDS_BIGENDIAN
  93249. #else
  93250. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93251. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93252. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93253. start = br->words;
  93254. local_swap32_block_(br->buffer + start, end - start);
  93255. }
  93256. else
  93257. # endif
  93258. for(start = br->words; start < end; start++)
  93259. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93260. #endif
  93261. /* now it looks like:
  93262. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93263. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93264. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93265. * finally we'll update the reader values:
  93266. */
  93267. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93268. br->words = end / FLAC__BYTES_PER_WORD;
  93269. br->bytes = end % FLAC__BYTES_PER_WORD;
  93270. return true;
  93271. }
  93272. /***********************************************************************
  93273. *
  93274. * Class constructor/destructor
  93275. *
  93276. ***********************************************************************/
  93277. FLAC__BitReader *FLAC__bitreader_new(void)
  93278. {
  93279. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93280. /* calloc() implies:
  93281. memset(br, 0, sizeof(FLAC__BitReader));
  93282. br->buffer = 0;
  93283. br->capacity = 0;
  93284. br->words = br->bytes = 0;
  93285. br->consumed_words = br->consumed_bits = 0;
  93286. br->read_callback = 0;
  93287. br->client_data = 0;
  93288. */
  93289. return br;
  93290. }
  93291. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93292. {
  93293. FLAC__ASSERT(0 != br);
  93294. FLAC__bitreader_free(br);
  93295. free(br);
  93296. }
  93297. /***********************************************************************
  93298. *
  93299. * Public class methods
  93300. *
  93301. ***********************************************************************/
  93302. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93303. {
  93304. FLAC__ASSERT(0 != br);
  93305. br->words = br->bytes = 0;
  93306. br->consumed_words = br->consumed_bits = 0;
  93307. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93308. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93309. if(br->buffer == 0)
  93310. return false;
  93311. br->read_callback = rcb;
  93312. br->client_data = cd;
  93313. br->cpu_info = cpu;
  93314. return true;
  93315. }
  93316. void FLAC__bitreader_free(FLAC__BitReader *br)
  93317. {
  93318. FLAC__ASSERT(0 != br);
  93319. if(0 != br->buffer)
  93320. free(br->buffer);
  93321. br->buffer = 0;
  93322. br->capacity = 0;
  93323. br->words = br->bytes = 0;
  93324. br->consumed_words = br->consumed_bits = 0;
  93325. br->read_callback = 0;
  93326. br->client_data = 0;
  93327. }
  93328. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93329. {
  93330. br->words = br->bytes = 0;
  93331. br->consumed_words = br->consumed_bits = 0;
  93332. return true;
  93333. }
  93334. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93335. {
  93336. unsigned i, j;
  93337. if(br == 0) {
  93338. fprintf(out, "bitreader is NULL\n");
  93339. }
  93340. else {
  93341. 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);
  93342. for(i = 0; i < br->words; i++) {
  93343. fprintf(out, "%08X: ", i);
  93344. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93345. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93346. fprintf(out, ".");
  93347. else
  93348. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93349. fprintf(out, "\n");
  93350. }
  93351. if(br->bytes > 0) {
  93352. fprintf(out, "%08X: ", i);
  93353. for(j = 0; j < br->bytes*8; j++)
  93354. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93355. fprintf(out, ".");
  93356. else
  93357. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93358. fprintf(out, "\n");
  93359. }
  93360. }
  93361. }
  93362. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93363. {
  93364. FLAC__ASSERT(0 != br);
  93365. FLAC__ASSERT(0 != br->buffer);
  93366. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93367. br->read_crc16 = (unsigned)seed;
  93368. br->crc16_align = br->consumed_bits;
  93369. }
  93370. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93371. {
  93372. FLAC__ASSERT(0 != br);
  93373. FLAC__ASSERT(0 != br->buffer);
  93374. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93375. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93376. /* CRC any tail bytes in a partially-consumed word */
  93377. if(br->consumed_bits) {
  93378. const brword tail = br->buffer[br->consumed_words];
  93379. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93380. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93381. }
  93382. return br->read_crc16;
  93383. }
  93384. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93385. {
  93386. return ((br->consumed_bits & 7) == 0);
  93387. }
  93388. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93389. {
  93390. return 8 - (br->consumed_bits & 7);
  93391. }
  93392. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93393. {
  93394. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93395. }
  93396. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93397. {
  93398. FLAC__ASSERT(0 != br);
  93399. FLAC__ASSERT(0 != br->buffer);
  93400. FLAC__ASSERT(bits <= 32);
  93401. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93402. FLAC__ASSERT(br->consumed_words <= br->words);
  93403. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93404. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93405. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93406. *val = 0;
  93407. return true;
  93408. }
  93409. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93410. if(!bitreader_read_from_client_(br))
  93411. return false;
  93412. }
  93413. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93414. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93415. if(br->consumed_bits) {
  93416. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93417. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93418. const brword word = br->buffer[br->consumed_words];
  93419. if(bits < n) {
  93420. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93421. br->consumed_bits += bits;
  93422. return true;
  93423. }
  93424. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93425. bits -= n;
  93426. crc16_update_word_(br, word);
  93427. br->consumed_words++;
  93428. br->consumed_bits = 0;
  93429. 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 */
  93430. *val <<= bits;
  93431. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93432. br->consumed_bits = bits;
  93433. }
  93434. return true;
  93435. }
  93436. else {
  93437. const brword word = br->buffer[br->consumed_words];
  93438. if(bits < FLAC__BITS_PER_WORD) {
  93439. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93440. br->consumed_bits = bits;
  93441. return true;
  93442. }
  93443. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93444. *val = word;
  93445. crc16_update_word_(br, word);
  93446. br->consumed_words++;
  93447. return true;
  93448. }
  93449. }
  93450. else {
  93451. /* in this case we're starting our read at a partial tail word;
  93452. * the reader has guaranteed that we have at least 'bits' bits
  93453. * available to read, which makes this case simpler.
  93454. */
  93455. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93456. if(br->consumed_bits) {
  93457. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93458. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93459. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93460. br->consumed_bits += bits;
  93461. return true;
  93462. }
  93463. else {
  93464. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93465. br->consumed_bits += bits;
  93466. return true;
  93467. }
  93468. }
  93469. }
  93470. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93471. {
  93472. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93473. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93474. return false;
  93475. /* sign-extend: */
  93476. *val <<= (32-bits);
  93477. *val >>= (32-bits);
  93478. return true;
  93479. }
  93480. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93481. {
  93482. FLAC__uint32 hi, lo;
  93483. if(bits > 32) {
  93484. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93485. return false;
  93486. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93487. return false;
  93488. *val = hi;
  93489. *val <<= 32;
  93490. *val |= lo;
  93491. }
  93492. else {
  93493. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93494. return false;
  93495. *val = lo;
  93496. }
  93497. return true;
  93498. }
  93499. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93500. {
  93501. FLAC__uint32 x8, x32 = 0;
  93502. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93503. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93504. return false;
  93505. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93506. return false;
  93507. x32 |= (x8 << 8);
  93508. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93509. return false;
  93510. x32 |= (x8 << 16);
  93511. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93512. return false;
  93513. x32 |= (x8 << 24);
  93514. *val = x32;
  93515. return true;
  93516. }
  93517. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93518. {
  93519. /*
  93520. * OPT: a faster implementation is possible but probably not that useful
  93521. * since this is only called a couple of times in the metadata readers.
  93522. */
  93523. FLAC__ASSERT(0 != br);
  93524. FLAC__ASSERT(0 != br->buffer);
  93525. if(bits > 0) {
  93526. const unsigned n = br->consumed_bits & 7;
  93527. unsigned m;
  93528. FLAC__uint32 x;
  93529. if(n != 0) {
  93530. m = min(8-n, bits);
  93531. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93532. return false;
  93533. bits -= m;
  93534. }
  93535. m = bits / 8;
  93536. if(m > 0) {
  93537. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93538. return false;
  93539. bits %= 8;
  93540. }
  93541. if(bits > 0) {
  93542. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93543. return false;
  93544. }
  93545. }
  93546. return true;
  93547. }
  93548. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93549. {
  93550. FLAC__uint32 x;
  93551. FLAC__ASSERT(0 != br);
  93552. FLAC__ASSERT(0 != br->buffer);
  93553. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93554. /* step 1: skip over partial head word to get word aligned */
  93555. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93556. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93557. return false;
  93558. nvals--;
  93559. }
  93560. if(0 == nvals)
  93561. return true;
  93562. /* step 2: skip whole words in chunks */
  93563. while(nvals >= FLAC__BYTES_PER_WORD) {
  93564. if(br->consumed_words < br->words) {
  93565. br->consumed_words++;
  93566. nvals -= FLAC__BYTES_PER_WORD;
  93567. }
  93568. else if(!bitreader_read_from_client_(br))
  93569. return false;
  93570. }
  93571. /* step 3: skip any remainder from partial tail bytes */
  93572. while(nvals) {
  93573. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93574. return false;
  93575. nvals--;
  93576. }
  93577. return true;
  93578. }
  93579. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93580. {
  93581. FLAC__uint32 x;
  93582. FLAC__ASSERT(0 != br);
  93583. FLAC__ASSERT(0 != br->buffer);
  93584. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93585. /* step 1: read from partial head word to get word aligned */
  93586. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93587. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93588. return false;
  93589. *val++ = (FLAC__byte)x;
  93590. nvals--;
  93591. }
  93592. if(0 == nvals)
  93593. return true;
  93594. /* step 2: read whole words in chunks */
  93595. while(nvals >= FLAC__BYTES_PER_WORD) {
  93596. if(br->consumed_words < br->words) {
  93597. const brword word = br->buffer[br->consumed_words++];
  93598. #if FLAC__BYTES_PER_WORD == 4
  93599. val[0] = (FLAC__byte)(word >> 24);
  93600. val[1] = (FLAC__byte)(word >> 16);
  93601. val[2] = (FLAC__byte)(word >> 8);
  93602. val[3] = (FLAC__byte)word;
  93603. #elif FLAC__BYTES_PER_WORD == 8
  93604. val[0] = (FLAC__byte)(word >> 56);
  93605. val[1] = (FLAC__byte)(word >> 48);
  93606. val[2] = (FLAC__byte)(word >> 40);
  93607. val[3] = (FLAC__byte)(word >> 32);
  93608. val[4] = (FLAC__byte)(word >> 24);
  93609. val[5] = (FLAC__byte)(word >> 16);
  93610. val[6] = (FLAC__byte)(word >> 8);
  93611. val[7] = (FLAC__byte)word;
  93612. #else
  93613. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93614. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93615. #endif
  93616. val += FLAC__BYTES_PER_WORD;
  93617. nvals -= FLAC__BYTES_PER_WORD;
  93618. }
  93619. else if(!bitreader_read_from_client_(br))
  93620. return false;
  93621. }
  93622. /* step 3: read any remainder from partial tail bytes */
  93623. while(nvals) {
  93624. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93625. return false;
  93626. *val++ = (FLAC__byte)x;
  93627. nvals--;
  93628. }
  93629. return true;
  93630. }
  93631. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93632. #if 0 /* slow but readable version */
  93633. {
  93634. unsigned bit;
  93635. FLAC__ASSERT(0 != br);
  93636. FLAC__ASSERT(0 != br->buffer);
  93637. *val = 0;
  93638. while(1) {
  93639. if(!FLAC__bitreader_read_bit(br, &bit))
  93640. return false;
  93641. if(bit)
  93642. break;
  93643. else
  93644. *val++;
  93645. }
  93646. return true;
  93647. }
  93648. #else
  93649. {
  93650. unsigned i;
  93651. FLAC__ASSERT(0 != br);
  93652. FLAC__ASSERT(0 != br->buffer);
  93653. *val = 0;
  93654. while(1) {
  93655. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93656. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93657. if(b) {
  93658. i = COUNT_ZERO_MSBS(b);
  93659. *val += i;
  93660. i++;
  93661. br->consumed_bits += i;
  93662. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93663. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93664. br->consumed_words++;
  93665. br->consumed_bits = 0;
  93666. }
  93667. return true;
  93668. }
  93669. else {
  93670. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93671. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93672. br->consumed_words++;
  93673. br->consumed_bits = 0;
  93674. /* didn't find stop bit yet, have to keep going... */
  93675. }
  93676. }
  93677. /* at this point we've eaten up all the whole words; have to try
  93678. * reading through any tail bytes before calling the read callback.
  93679. * this is a repeat of the above logic adjusted for the fact we
  93680. * don't have a whole word. note though if the client is feeding
  93681. * us data a byte at a time (unlikely), br->consumed_bits may not
  93682. * be zero.
  93683. */
  93684. if(br->bytes) {
  93685. const unsigned end = br->bytes * 8;
  93686. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93687. if(b) {
  93688. i = COUNT_ZERO_MSBS(b);
  93689. *val += i;
  93690. i++;
  93691. br->consumed_bits += i;
  93692. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93693. return true;
  93694. }
  93695. else {
  93696. *val += end - br->consumed_bits;
  93697. br->consumed_bits += end;
  93698. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93699. /* didn't find stop bit yet, have to keep going... */
  93700. }
  93701. }
  93702. if(!bitreader_read_from_client_(br))
  93703. return false;
  93704. }
  93705. }
  93706. #endif
  93707. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93708. {
  93709. FLAC__uint32 lsbs = 0, msbs = 0;
  93710. unsigned uval;
  93711. FLAC__ASSERT(0 != br);
  93712. FLAC__ASSERT(0 != br->buffer);
  93713. FLAC__ASSERT(parameter <= 31);
  93714. /* read the unary MSBs and end bit */
  93715. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93716. return false;
  93717. /* read the binary LSBs */
  93718. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93719. return false;
  93720. /* compose the value */
  93721. uval = (msbs << parameter) | lsbs;
  93722. if(uval & 1)
  93723. *val = -((int)(uval >> 1)) - 1;
  93724. else
  93725. *val = (int)(uval >> 1);
  93726. return true;
  93727. }
  93728. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93729. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93730. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93731. /* OPT: possibly faster version for use with MSVC */
  93732. #ifdef _MSC_VER
  93733. {
  93734. unsigned i;
  93735. unsigned uval = 0;
  93736. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93737. /* try and get br->consumed_words and br->consumed_bits into register;
  93738. * must remember to flush them back to *br before calling other
  93739. * bitwriter functions that use them, and before returning */
  93740. register unsigned cwords;
  93741. register unsigned cbits;
  93742. FLAC__ASSERT(0 != br);
  93743. FLAC__ASSERT(0 != br->buffer);
  93744. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93745. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93746. FLAC__ASSERT(parameter < 32);
  93747. /* 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 */
  93748. if(nvals == 0)
  93749. return true;
  93750. cbits = br->consumed_bits;
  93751. cwords = br->consumed_words;
  93752. while(1) {
  93753. /* read unary part */
  93754. while(1) {
  93755. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93756. brword b = br->buffer[cwords] << cbits;
  93757. if(b) {
  93758. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93759. __asm {
  93760. bsr eax, b
  93761. not eax
  93762. and eax, 31
  93763. mov i, eax
  93764. }
  93765. #else
  93766. i = COUNT_ZERO_MSBS(b);
  93767. #endif
  93768. uval += i;
  93769. bits = parameter;
  93770. i++;
  93771. cbits += i;
  93772. if(cbits == FLAC__BITS_PER_WORD) {
  93773. crc16_update_word_(br, br->buffer[cwords]);
  93774. cwords++;
  93775. cbits = 0;
  93776. }
  93777. goto break1;
  93778. }
  93779. else {
  93780. uval += FLAC__BITS_PER_WORD - cbits;
  93781. crc16_update_word_(br, br->buffer[cwords]);
  93782. cwords++;
  93783. cbits = 0;
  93784. /* didn't find stop bit yet, have to keep going... */
  93785. }
  93786. }
  93787. /* at this point we've eaten up all the whole words; have to try
  93788. * reading through any tail bytes before calling the read callback.
  93789. * this is a repeat of the above logic adjusted for the fact we
  93790. * don't have a whole word. note though if the client is feeding
  93791. * us data a byte at a time (unlikely), br->consumed_bits may not
  93792. * be zero.
  93793. */
  93794. if(br->bytes) {
  93795. const unsigned end = br->bytes * 8;
  93796. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93797. if(b) {
  93798. i = COUNT_ZERO_MSBS(b);
  93799. uval += i;
  93800. bits = parameter;
  93801. i++;
  93802. cbits += i;
  93803. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93804. goto break1;
  93805. }
  93806. else {
  93807. uval += end - cbits;
  93808. cbits += end;
  93809. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93810. /* didn't find stop bit yet, have to keep going... */
  93811. }
  93812. }
  93813. /* flush registers and read; bitreader_read_from_client_() does
  93814. * not touch br->consumed_bits at all but we still need to set
  93815. * it in case it fails and we have to return false.
  93816. */
  93817. br->consumed_bits = cbits;
  93818. br->consumed_words = cwords;
  93819. if(!bitreader_read_from_client_(br))
  93820. return false;
  93821. cwords = br->consumed_words;
  93822. }
  93823. break1:
  93824. /* read binary part */
  93825. FLAC__ASSERT(cwords <= br->words);
  93826. if(bits) {
  93827. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93828. /* flush registers and read; bitreader_read_from_client_() does
  93829. * not touch br->consumed_bits at all but we still need to set
  93830. * it in case it fails and we have to return false.
  93831. */
  93832. br->consumed_bits = cbits;
  93833. br->consumed_words = cwords;
  93834. if(!bitreader_read_from_client_(br))
  93835. return false;
  93836. cwords = br->consumed_words;
  93837. }
  93838. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93839. if(cbits) {
  93840. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93841. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93842. const brword word = br->buffer[cwords];
  93843. if(bits < n) {
  93844. uval <<= bits;
  93845. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93846. cbits += bits;
  93847. goto break2;
  93848. }
  93849. uval <<= n;
  93850. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93851. bits -= n;
  93852. crc16_update_word_(br, word);
  93853. cwords++;
  93854. cbits = 0;
  93855. 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 */
  93856. uval <<= bits;
  93857. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93858. cbits = bits;
  93859. }
  93860. goto break2;
  93861. }
  93862. else {
  93863. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93864. uval <<= bits;
  93865. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93866. cbits = bits;
  93867. goto break2;
  93868. }
  93869. }
  93870. else {
  93871. /* in this case we're starting our read at a partial tail word;
  93872. * the reader has guaranteed that we have at least 'bits' bits
  93873. * available to read, which makes this case simpler.
  93874. */
  93875. uval <<= bits;
  93876. if(cbits) {
  93877. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93878. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93879. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93880. cbits += bits;
  93881. goto break2;
  93882. }
  93883. else {
  93884. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93885. cbits += bits;
  93886. goto break2;
  93887. }
  93888. }
  93889. }
  93890. break2:
  93891. /* compose the value */
  93892. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93893. /* are we done? */
  93894. --nvals;
  93895. if(nvals == 0) {
  93896. br->consumed_bits = cbits;
  93897. br->consumed_words = cwords;
  93898. return true;
  93899. }
  93900. uval = 0;
  93901. ++vals;
  93902. }
  93903. }
  93904. #else
  93905. {
  93906. unsigned i;
  93907. unsigned uval = 0;
  93908. /* try and get br->consumed_words and br->consumed_bits into register;
  93909. * must remember to flush them back to *br before calling other
  93910. * bitwriter functions that use them, and before returning */
  93911. register unsigned cwords;
  93912. register unsigned cbits;
  93913. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93914. FLAC__ASSERT(0 != br);
  93915. FLAC__ASSERT(0 != br->buffer);
  93916. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93917. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93918. FLAC__ASSERT(parameter < 32);
  93919. /* 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 */
  93920. if(nvals == 0)
  93921. return true;
  93922. cbits = br->consumed_bits;
  93923. cwords = br->consumed_words;
  93924. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93925. while(1) {
  93926. /* read unary part */
  93927. while(1) {
  93928. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93929. brword b = br->buffer[cwords] << cbits;
  93930. if(b) {
  93931. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93932. asm volatile (
  93933. "bsrl %1, %0;"
  93934. "notl %0;"
  93935. "andl $31, %0;"
  93936. : "=r"(i)
  93937. : "r"(b)
  93938. );
  93939. #else
  93940. i = COUNT_ZERO_MSBS(b);
  93941. #endif
  93942. uval += i;
  93943. cbits += i;
  93944. cbits++; /* skip over stop bit */
  93945. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93946. crc16_update_word_(br, br->buffer[cwords]);
  93947. cwords++;
  93948. cbits = 0;
  93949. }
  93950. goto break1;
  93951. }
  93952. else {
  93953. uval += FLAC__BITS_PER_WORD - cbits;
  93954. crc16_update_word_(br, br->buffer[cwords]);
  93955. cwords++;
  93956. cbits = 0;
  93957. /* didn't find stop bit yet, have to keep going... */
  93958. }
  93959. }
  93960. /* at this point we've eaten up all the whole words; have to try
  93961. * reading through any tail bytes before calling the read callback.
  93962. * this is a repeat of the above logic adjusted for the fact we
  93963. * don't have a whole word. note though if the client is feeding
  93964. * us data a byte at a time (unlikely), br->consumed_bits may not
  93965. * be zero.
  93966. */
  93967. if(br->bytes) {
  93968. const unsigned end = br->bytes * 8;
  93969. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93970. if(b) {
  93971. i = COUNT_ZERO_MSBS(b);
  93972. uval += i;
  93973. cbits += i;
  93974. cbits++; /* skip over stop bit */
  93975. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93976. goto break1;
  93977. }
  93978. else {
  93979. uval += end - cbits;
  93980. cbits += end;
  93981. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93982. /* didn't find stop bit yet, have to keep going... */
  93983. }
  93984. }
  93985. /* flush registers and read; bitreader_read_from_client_() does
  93986. * not touch br->consumed_bits at all but we still need to set
  93987. * it in case it fails and we have to return false.
  93988. */
  93989. br->consumed_bits = cbits;
  93990. br->consumed_words = cwords;
  93991. if(!bitreader_read_from_client_(br))
  93992. return false;
  93993. cwords = br->consumed_words;
  93994. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93995. /* + uval to offset our count by the # of unary bits already
  93996. * consumed before the read, because we will add these back
  93997. * in all at once at break1
  93998. */
  93999. }
  94000. break1:
  94001. ucbits -= uval;
  94002. ucbits--; /* account for stop bit */
  94003. /* read binary part */
  94004. FLAC__ASSERT(cwords <= br->words);
  94005. if(parameter) {
  94006. while(ucbits < parameter) {
  94007. /* flush registers and read; bitreader_read_from_client_() does
  94008. * not touch br->consumed_bits at all but we still need to set
  94009. * it in case it fails and we have to return false.
  94010. */
  94011. br->consumed_bits = cbits;
  94012. br->consumed_words = cwords;
  94013. if(!bitreader_read_from_client_(br))
  94014. return false;
  94015. cwords = br->consumed_words;
  94016. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94017. }
  94018. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94019. if(cbits) {
  94020. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  94021. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94022. const brword word = br->buffer[cwords];
  94023. if(parameter < n) {
  94024. uval <<= parameter;
  94025. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  94026. cbits += parameter;
  94027. }
  94028. else {
  94029. uval <<= n;
  94030. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94031. crc16_update_word_(br, word);
  94032. cwords++;
  94033. cbits = parameter - n;
  94034. 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 */
  94035. uval <<= cbits;
  94036. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94037. }
  94038. }
  94039. }
  94040. else {
  94041. cbits = parameter;
  94042. uval <<= parameter;
  94043. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94044. }
  94045. }
  94046. else {
  94047. /* in this case we're starting our read at a partial tail word;
  94048. * the reader has guaranteed that we have at least 'parameter'
  94049. * bits available to read, which makes this case simpler.
  94050. */
  94051. uval <<= parameter;
  94052. if(cbits) {
  94053. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94054. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94055. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94056. cbits += parameter;
  94057. }
  94058. else {
  94059. cbits = parameter;
  94060. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94061. }
  94062. }
  94063. }
  94064. ucbits -= parameter;
  94065. /* compose the value */
  94066. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94067. /* are we done? */
  94068. --nvals;
  94069. if(nvals == 0) {
  94070. br->consumed_bits = cbits;
  94071. br->consumed_words = cwords;
  94072. return true;
  94073. }
  94074. uval = 0;
  94075. ++vals;
  94076. }
  94077. }
  94078. #endif
  94079. #if 0 /* UNUSED */
  94080. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94081. {
  94082. FLAC__uint32 lsbs = 0, msbs = 0;
  94083. unsigned bit, uval, k;
  94084. FLAC__ASSERT(0 != br);
  94085. FLAC__ASSERT(0 != br->buffer);
  94086. k = FLAC__bitmath_ilog2(parameter);
  94087. /* read the unary MSBs and end bit */
  94088. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94089. return false;
  94090. /* read the binary LSBs */
  94091. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94092. return false;
  94093. if(parameter == 1u<<k) {
  94094. /* compose the value */
  94095. uval = (msbs << k) | lsbs;
  94096. }
  94097. else {
  94098. unsigned d = (1 << (k+1)) - parameter;
  94099. if(lsbs >= d) {
  94100. if(!FLAC__bitreader_read_bit(br, &bit))
  94101. return false;
  94102. lsbs <<= 1;
  94103. lsbs |= bit;
  94104. lsbs -= d;
  94105. }
  94106. /* compose the value */
  94107. uval = msbs * parameter + lsbs;
  94108. }
  94109. /* unfold unsigned to signed */
  94110. if(uval & 1)
  94111. *val = -((int)(uval >> 1)) - 1;
  94112. else
  94113. *val = (int)(uval >> 1);
  94114. return true;
  94115. }
  94116. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94117. {
  94118. FLAC__uint32 lsbs, msbs = 0;
  94119. unsigned bit, k;
  94120. FLAC__ASSERT(0 != br);
  94121. FLAC__ASSERT(0 != br->buffer);
  94122. k = FLAC__bitmath_ilog2(parameter);
  94123. /* read the unary MSBs and end bit */
  94124. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94125. return false;
  94126. /* read the binary LSBs */
  94127. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94128. return false;
  94129. if(parameter == 1u<<k) {
  94130. /* compose the value */
  94131. *val = (msbs << k) | lsbs;
  94132. }
  94133. else {
  94134. unsigned d = (1 << (k+1)) - parameter;
  94135. if(lsbs >= d) {
  94136. if(!FLAC__bitreader_read_bit(br, &bit))
  94137. return false;
  94138. lsbs <<= 1;
  94139. lsbs |= bit;
  94140. lsbs -= d;
  94141. }
  94142. /* compose the value */
  94143. *val = msbs * parameter + lsbs;
  94144. }
  94145. return true;
  94146. }
  94147. #endif /* UNUSED */
  94148. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94149. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94150. {
  94151. FLAC__uint32 v = 0;
  94152. FLAC__uint32 x;
  94153. unsigned i;
  94154. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94155. return false;
  94156. if(raw)
  94157. raw[(*rawlen)++] = (FLAC__byte)x;
  94158. if(!(x & 0x80)) { /* 0xxxxxxx */
  94159. v = x;
  94160. i = 0;
  94161. }
  94162. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94163. v = x & 0x1F;
  94164. i = 1;
  94165. }
  94166. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94167. v = x & 0x0F;
  94168. i = 2;
  94169. }
  94170. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94171. v = x & 0x07;
  94172. i = 3;
  94173. }
  94174. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94175. v = x & 0x03;
  94176. i = 4;
  94177. }
  94178. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94179. v = x & 0x01;
  94180. i = 5;
  94181. }
  94182. else {
  94183. *val = 0xffffffff;
  94184. return true;
  94185. }
  94186. for( ; i; i--) {
  94187. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94188. return false;
  94189. if(raw)
  94190. raw[(*rawlen)++] = (FLAC__byte)x;
  94191. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94192. *val = 0xffffffff;
  94193. return true;
  94194. }
  94195. v <<= 6;
  94196. v |= (x & 0x3F);
  94197. }
  94198. *val = v;
  94199. return true;
  94200. }
  94201. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94202. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94203. {
  94204. FLAC__uint64 v = 0;
  94205. FLAC__uint32 x;
  94206. unsigned i;
  94207. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94208. return false;
  94209. if(raw)
  94210. raw[(*rawlen)++] = (FLAC__byte)x;
  94211. if(!(x & 0x80)) { /* 0xxxxxxx */
  94212. v = x;
  94213. i = 0;
  94214. }
  94215. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94216. v = x & 0x1F;
  94217. i = 1;
  94218. }
  94219. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94220. v = x & 0x0F;
  94221. i = 2;
  94222. }
  94223. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94224. v = x & 0x07;
  94225. i = 3;
  94226. }
  94227. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94228. v = x & 0x03;
  94229. i = 4;
  94230. }
  94231. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94232. v = x & 0x01;
  94233. i = 5;
  94234. }
  94235. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94236. v = 0;
  94237. i = 6;
  94238. }
  94239. else {
  94240. *val = FLAC__U64L(0xffffffffffffffff);
  94241. return true;
  94242. }
  94243. for( ; i; i--) {
  94244. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94245. return false;
  94246. if(raw)
  94247. raw[(*rawlen)++] = (FLAC__byte)x;
  94248. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94249. *val = FLAC__U64L(0xffffffffffffffff);
  94250. return true;
  94251. }
  94252. v <<= 6;
  94253. v |= (x & 0x3F);
  94254. }
  94255. *val = v;
  94256. return true;
  94257. }
  94258. #endif
  94259. /*** End of inlined file: bitreader.c ***/
  94260. /*** Start of inlined file: bitwriter.c ***/
  94261. /*** Start of inlined file: juce_FlacHeader.h ***/
  94262. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94263. // tasks..
  94264. #define VERSION "1.2.1"
  94265. #define FLAC__NO_DLL 1
  94266. #if JUCE_MSVC
  94267. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94268. #endif
  94269. #if JUCE_MAC
  94270. #define FLAC__SYS_DARWIN 1
  94271. #endif
  94272. /*** End of inlined file: juce_FlacHeader.h ***/
  94273. #if JUCE_USE_FLAC
  94274. #if HAVE_CONFIG_H
  94275. # include <config.h>
  94276. #endif
  94277. #include <stdlib.h> /* for malloc() */
  94278. #include <string.h> /* for memcpy(), memset() */
  94279. #ifdef _MSC_VER
  94280. #include <winsock.h> /* for ntohl() */
  94281. #elif defined FLAC__SYS_DARWIN
  94282. #include <machine/endian.h> /* for ntohl() */
  94283. #elif defined __MINGW32__
  94284. #include <winsock.h> /* for ntohl() */
  94285. #else
  94286. #include <netinet/in.h> /* for ntohl() */
  94287. #endif
  94288. #if 0 /* UNUSED */
  94289. #endif
  94290. /*** Start of inlined file: bitwriter.h ***/
  94291. #ifndef FLAC__PRIVATE__BITWRITER_H
  94292. #define FLAC__PRIVATE__BITWRITER_H
  94293. #include <stdio.h> /* for FILE */
  94294. /*
  94295. * opaque structure definition
  94296. */
  94297. struct FLAC__BitWriter;
  94298. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94299. /*
  94300. * construction, deletion, initialization, etc functions
  94301. */
  94302. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94303. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94304. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94305. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94306. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94307. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94308. /*
  94309. * CRC functions
  94310. *
  94311. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94312. */
  94313. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94314. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94315. /*
  94316. * info functions
  94317. */
  94318. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94319. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94320. /*
  94321. * direct buffer access
  94322. *
  94323. * there may be no calls on the bitwriter between get and release.
  94324. * the bitwriter continues to own the returned buffer.
  94325. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94326. */
  94327. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94328. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94329. /*
  94330. * write functions
  94331. */
  94332. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94333. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94334. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94335. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94336. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94337. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94338. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94339. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94340. #if 0 /* UNUSED */
  94341. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94342. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94343. #endif
  94344. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94345. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94346. #if 0 /* UNUSED */
  94347. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94348. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94349. #endif
  94350. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94351. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94352. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94353. #endif
  94354. /*** End of inlined file: bitwriter.h ***/
  94355. /*** Start of inlined file: alloc.h ***/
  94356. #ifndef FLAC__SHARE__ALLOC_H
  94357. #define FLAC__SHARE__ALLOC_H
  94358. #if HAVE_CONFIG_H
  94359. # include <config.h>
  94360. #endif
  94361. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94362. * before #including this file, otherwise SIZE_MAX might not be defined
  94363. */
  94364. #include <limits.h> /* for SIZE_MAX */
  94365. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94366. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94367. #endif
  94368. #include <stdlib.h> /* for size_t, malloc(), etc */
  94369. #ifndef SIZE_MAX
  94370. # ifndef SIZE_T_MAX
  94371. # ifdef _MSC_VER
  94372. # define SIZE_T_MAX UINT_MAX
  94373. # else
  94374. # error
  94375. # endif
  94376. # endif
  94377. # define SIZE_MAX SIZE_T_MAX
  94378. #endif
  94379. #ifndef FLaC__INLINE
  94380. #define FLaC__INLINE
  94381. #endif
  94382. /* avoid malloc()ing 0 bytes, see:
  94383. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94384. */
  94385. static FLaC__INLINE void *safe_malloc_(size_t size)
  94386. {
  94387. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94388. if(!size)
  94389. size++;
  94390. return malloc(size);
  94391. }
  94392. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94393. {
  94394. if(!nmemb || !size)
  94395. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94396. return calloc(nmemb, size);
  94397. }
  94398. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94399. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94400. {
  94401. size2 += size1;
  94402. if(size2 < size1)
  94403. return 0;
  94404. return safe_malloc_(size2);
  94405. }
  94406. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94407. {
  94408. size2 += size1;
  94409. if(size2 < size1)
  94410. return 0;
  94411. size3 += size2;
  94412. if(size3 < size2)
  94413. return 0;
  94414. return safe_malloc_(size3);
  94415. }
  94416. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94417. {
  94418. size2 += size1;
  94419. if(size2 < size1)
  94420. return 0;
  94421. size3 += size2;
  94422. if(size3 < size2)
  94423. return 0;
  94424. size4 += size3;
  94425. if(size4 < size3)
  94426. return 0;
  94427. return safe_malloc_(size4);
  94428. }
  94429. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94430. #if 0
  94431. needs support for cases where sizeof(size_t) != 4
  94432. {
  94433. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94434. if(sizeof(size_t) == 4) {
  94435. if ((double)size1 * (double)size2 < 4294967296.0)
  94436. return malloc(size1*size2);
  94437. }
  94438. return 0;
  94439. }
  94440. #else
  94441. /* better? */
  94442. {
  94443. if(!size1 || !size2)
  94444. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94445. if(size1 > SIZE_MAX / size2)
  94446. return 0;
  94447. return malloc(size1*size2);
  94448. }
  94449. #endif
  94450. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94451. {
  94452. if(!size1 || !size2 || !size3)
  94453. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94454. if(size1 > SIZE_MAX / size2)
  94455. return 0;
  94456. size1 *= size2;
  94457. if(size1 > SIZE_MAX / size3)
  94458. return 0;
  94459. return malloc(size1*size3);
  94460. }
  94461. /* size1*size2 + size3 */
  94462. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94463. {
  94464. if(!size1 || !size2)
  94465. return safe_malloc_(size3);
  94466. if(size1 > SIZE_MAX / size2)
  94467. return 0;
  94468. return safe_malloc_add_2op_(size1*size2, size3);
  94469. }
  94470. /* size1 * (size2 + size3) */
  94471. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94472. {
  94473. if(!size1 || (!size2 && !size3))
  94474. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94475. size2 += size3;
  94476. if(size2 < size3)
  94477. return 0;
  94478. return safe_malloc_mul_2op_(size1, size2);
  94479. }
  94480. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94481. {
  94482. size2 += size1;
  94483. if(size2 < size1)
  94484. return 0;
  94485. return realloc(ptr, size2);
  94486. }
  94487. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94488. {
  94489. size2 += size1;
  94490. if(size2 < size1)
  94491. return 0;
  94492. size3 += size2;
  94493. if(size3 < size2)
  94494. return 0;
  94495. return realloc(ptr, size3);
  94496. }
  94497. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94498. {
  94499. size2 += size1;
  94500. if(size2 < size1)
  94501. return 0;
  94502. size3 += size2;
  94503. if(size3 < size2)
  94504. return 0;
  94505. size4 += size3;
  94506. if(size4 < size3)
  94507. return 0;
  94508. return realloc(ptr, size4);
  94509. }
  94510. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94511. {
  94512. if(!size1 || !size2)
  94513. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94514. if(size1 > SIZE_MAX / size2)
  94515. return 0;
  94516. return realloc(ptr, size1*size2);
  94517. }
  94518. /* size1 * (size2 + size3) */
  94519. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94520. {
  94521. if(!size1 || (!size2 && !size3))
  94522. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94523. size2 += size3;
  94524. if(size2 < size3)
  94525. return 0;
  94526. return safe_realloc_mul_2op_(ptr, size1, size2);
  94527. }
  94528. #endif
  94529. /*** End of inlined file: alloc.h ***/
  94530. /* Things should be fastest when this matches the machine word size */
  94531. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94532. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94533. typedef FLAC__uint32 bwword;
  94534. #define FLAC__BYTES_PER_WORD 4
  94535. #define FLAC__BITS_PER_WORD 32
  94536. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94537. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94538. #if WORDS_BIGENDIAN
  94539. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94540. #else
  94541. #ifdef _MSC_VER
  94542. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94543. #else
  94544. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94545. #endif
  94546. #endif
  94547. /*
  94548. * The default capacity here doesn't matter too much. The buffer always grows
  94549. * to hold whatever is written to it. Usually the encoder will stop adding at
  94550. * a frame or metadata block, then write that out and clear the buffer for the
  94551. * next one.
  94552. */
  94553. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94554. /* When growing, increment 4K at a time */
  94555. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94556. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94557. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94558. #ifdef min
  94559. #undef min
  94560. #endif
  94561. #define min(x,y) ((x)<(y)?(x):(y))
  94562. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94563. #ifdef _MSC_VER
  94564. #define FLAC__U64L(x) x
  94565. #else
  94566. #define FLAC__U64L(x) x##LLU
  94567. #endif
  94568. #ifndef FLaC__INLINE
  94569. #define FLaC__INLINE
  94570. #endif
  94571. struct FLAC__BitWriter {
  94572. bwword *buffer;
  94573. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94574. unsigned capacity; /* capacity of buffer in words */
  94575. unsigned words; /* # of complete words in buffer */
  94576. unsigned bits; /* # of used bits in accum */
  94577. };
  94578. /* * WATCHOUT: The current implementation only grows the buffer. */
  94579. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94580. {
  94581. unsigned new_capacity;
  94582. bwword *new_buffer;
  94583. FLAC__ASSERT(0 != bw);
  94584. FLAC__ASSERT(0 != bw->buffer);
  94585. /* calculate total words needed to store 'bits_to_add' additional bits */
  94586. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94587. /* it's possible (due to pessimism in the growth estimation that
  94588. * leads to this call) that we don't actually need to grow
  94589. */
  94590. if(bw->capacity >= new_capacity)
  94591. return true;
  94592. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94593. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94594. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94595. /* make sure we got everything right */
  94596. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94597. FLAC__ASSERT(new_capacity > bw->capacity);
  94598. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94599. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94600. if(new_buffer == 0)
  94601. return false;
  94602. bw->buffer = new_buffer;
  94603. bw->capacity = new_capacity;
  94604. return true;
  94605. }
  94606. /***********************************************************************
  94607. *
  94608. * Class constructor/destructor
  94609. *
  94610. ***********************************************************************/
  94611. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94612. {
  94613. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94614. /* note that calloc() sets all members to 0 for us */
  94615. return bw;
  94616. }
  94617. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94618. {
  94619. FLAC__ASSERT(0 != bw);
  94620. FLAC__bitwriter_free(bw);
  94621. free(bw);
  94622. }
  94623. /***********************************************************************
  94624. *
  94625. * Public class methods
  94626. *
  94627. ***********************************************************************/
  94628. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94629. {
  94630. FLAC__ASSERT(0 != bw);
  94631. bw->words = bw->bits = 0;
  94632. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94633. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94634. if(bw->buffer == 0)
  94635. return false;
  94636. return true;
  94637. }
  94638. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94639. {
  94640. FLAC__ASSERT(0 != bw);
  94641. if(0 != bw->buffer)
  94642. free(bw->buffer);
  94643. bw->buffer = 0;
  94644. bw->capacity = 0;
  94645. bw->words = bw->bits = 0;
  94646. }
  94647. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94648. {
  94649. bw->words = bw->bits = 0;
  94650. }
  94651. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94652. {
  94653. unsigned i, j;
  94654. if(bw == 0) {
  94655. fprintf(out, "bitwriter is NULL\n");
  94656. }
  94657. else {
  94658. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94659. for(i = 0; i < bw->words; i++) {
  94660. fprintf(out, "%08X: ", i);
  94661. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94662. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94663. fprintf(out, "\n");
  94664. }
  94665. if(bw->bits > 0) {
  94666. fprintf(out, "%08X: ", i);
  94667. for(j = 0; j < bw->bits; j++)
  94668. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94669. fprintf(out, "\n");
  94670. }
  94671. }
  94672. }
  94673. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94674. {
  94675. const FLAC__byte *buffer;
  94676. size_t bytes;
  94677. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94678. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94679. return false;
  94680. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94681. FLAC__bitwriter_release_buffer(bw);
  94682. return true;
  94683. }
  94684. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94685. {
  94686. const FLAC__byte *buffer;
  94687. size_t bytes;
  94688. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94689. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94690. return false;
  94691. *crc = FLAC__crc8(buffer, bytes);
  94692. FLAC__bitwriter_release_buffer(bw);
  94693. return true;
  94694. }
  94695. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94696. {
  94697. return ((bw->bits & 7) == 0);
  94698. }
  94699. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94700. {
  94701. return FLAC__TOTAL_BITS(bw);
  94702. }
  94703. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94704. {
  94705. FLAC__ASSERT((bw->bits & 7) == 0);
  94706. /* double protection */
  94707. if(bw->bits & 7)
  94708. return false;
  94709. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94710. if(bw->bits) {
  94711. FLAC__ASSERT(bw->words <= bw->capacity);
  94712. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94713. return false;
  94714. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94715. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94716. }
  94717. /* now we can just return what we have */
  94718. *buffer = (FLAC__byte*)bw->buffer;
  94719. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94720. return true;
  94721. }
  94722. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94723. {
  94724. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94725. * get-mode' flag could be added everywhere and then cleared here
  94726. */
  94727. (void)bw;
  94728. }
  94729. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94730. {
  94731. unsigned n;
  94732. FLAC__ASSERT(0 != bw);
  94733. FLAC__ASSERT(0 != bw->buffer);
  94734. if(bits == 0)
  94735. return true;
  94736. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94737. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94738. return false;
  94739. /* first part gets to word alignment */
  94740. if(bw->bits) {
  94741. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94742. bw->accum <<= n;
  94743. bits -= n;
  94744. bw->bits += n;
  94745. if(bw->bits == FLAC__BITS_PER_WORD) {
  94746. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94747. bw->bits = 0;
  94748. }
  94749. else
  94750. return true;
  94751. }
  94752. /* do whole words */
  94753. while(bits >= FLAC__BITS_PER_WORD) {
  94754. bw->buffer[bw->words++] = 0;
  94755. bits -= FLAC__BITS_PER_WORD;
  94756. }
  94757. /* do any leftovers */
  94758. if(bits > 0) {
  94759. bw->accum = 0;
  94760. bw->bits = bits;
  94761. }
  94762. return true;
  94763. }
  94764. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94765. {
  94766. register unsigned left;
  94767. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94768. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94769. FLAC__ASSERT(0 != bw);
  94770. FLAC__ASSERT(0 != bw->buffer);
  94771. FLAC__ASSERT(bits <= 32);
  94772. if(bits == 0)
  94773. return true;
  94774. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94775. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94776. return false;
  94777. left = FLAC__BITS_PER_WORD - bw->bits;
  94778. if(bits < left) {
  94779. bw->accum <<= bits;
  94780. bw->accum |= val;
  94781. bw->bits += bits;
  94782. }
  94783. 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 */
  94784. bw->accum <<= left;
  94785. bw->accum |= val >> (bw->bits = bits - left);
  94786. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94787. bw->accum = val;
  94788. }
  94789. else {
  94790. bw->accum = val;
  94791. bw->bits = 0;
  94792. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94793. }
  94794. return true;
  94795. }
  94796. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94797. {
  94798. /* zero-out unused bits */
  94799. if(bits < 32)
  94800. val &= (~(0xffffffff << bits));
  94801. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94802. }
  94803. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94804. {
  94805. /* this could be a little faster but it's not used for much */
  94806. if(bits > 32) {
  94807. return
  94808. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94809. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94810. }
  94811. else
  94812. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94813. }
  94814. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94815. {
  94816. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94817. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94818. return false;
  94819. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94820. return false;
  94821. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94822. return false;
  94823. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94824. return false;
  94825. return true;
  94826. }
  94827. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94828. {
  94829. unsigned i;
  94830. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94831. for(i = 0; i < nvals; i++) {
  94832. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94833. return false;
  94834. }
  94835. return true;
  94836. }
  94837. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94838. {
  94839. if(val < 32)
  94840. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94841. else
  94842. return
  94843. FLAC__bitwriter_write_zeroes(bw, val) &&
  94844. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94845. }
  94846. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94847. {
  94848. FLAC__uint32 uval;
  94849. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94850. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94851. uval = (val<<1) ^ (val>>31);
  94852. return 1 + parameter + (uval >> parameter);
  94853. }
  94854. #if 0 /* UNUSED */
  94855. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94856. {
  94857. unsigned bits, msbs, uval;
  94858. unsigned k;
  94859. FLAC__ASSERT(parameter > 0);
  94860. /* fold signed to unsigned */
  94861. if(val < 0)
  94862. uval = (unsigned)(((-(++val)) << 1) + 1);
  94863. else
  94864. uval = (unsigned)(val << 1);
  94865. k = FLAC__bitmath_ilog2(parameter);
  94866. if(parameter == 1u<<k) {
  94867. FLAC__ASSERT(k <= 30);
  94868. msbs = uval >> k;
  94869. bits = 1 + k + msbs;
  94870. }
  94871. else {
  94872. unsigned q, r, d;
  94873. d = (1 << (k+1)) - parameter;
  94874. q = uval / parameter;
  94875. r = uval - (q * parameter);
  94876. bits = 1 + q + k;
  94877. if(r >= d)
  94878. bits++;
  94879. }
  94880. return bits;
  94881. }
  94882. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94883. {
  94884. unsigned bits, msbs;
  94885. unsigned k;
  94886. FLAC__ASSERT(parameter > 0);
  94887. k = FLAC__bitmath_ilog2(parameter);
  94888. if(parameter == 1u<<k) {
  94889. FLAC__ASSERT(k <= 30);
  94890. msbs = uval >> k;
  94891. bits = 1 + k + msbs;
  94892. }
  94893. else {
  94894. unsigned q, r, d;
  94895. d = (1 << (k+1)) - parameter;
  94896. q = uval / parameter;
  94897. r = uval - (q * parameter);
  94898. bits = 1 + q + k;
  94899. if(r >= d)
  94900. bits++;
  94901. }
  94902. return bits;
  94903. }
  94904. #endif /* UNUSED */
  94905. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94906. {
  94907. unsigned total_bits, interesting_bits, msbs;
  94908. FLAC__uint32 uval, pattern;
  94909. FLAC__ASSERT(0 != bw);
  94910. FLAC__ASSERT(0 != bw->buffer);
  94911. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94912. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94913. uval = (val<<1) ^ (val>>31);
  94914. msbs = uval >> parameter;
  94915. interesting_bits = 1 + parameter;
  94916. total_bits = interesting_bits + msbs;
  94917. pattern = 1 << parameter; /* the unary end bit */
  94918. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94919. if(total_bits <= 32)
  94920. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94921. else
  94922. return
  94923. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94924. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94925. }
  94926. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94927. {
  94928. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94929. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94930. FLAC__uint32 uval;
  94931. unsigned left;
  94932. const unsigned lsbits = 1 + parameter;
  94933. unsigned msbits;
  94934. FLAC__ASSERT(0 != bw);
  94935. FLAC__ASSERT(0 != bw->buffer);
  94936. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94937. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94938. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94939. while(nvals) {
  94940. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94941. uval = (*vals<<1) ^ (*vals>>31);
  94942. msbits = uval >> parameter;
  94943. #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) */
  94944. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94945. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94946. bw->bits = bw->bits + msbits + lsbits;
  94947. uval |= mask1; /* set stop bit */
  94948. uval &= mask2; /* mask off unused top bits */
  94949. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94950. bw->accum <<= msbits;
  94951. bw->accum <<= lsbits;
  94952. bw->accum |= uval;
  94953. if(bw->bits == FLAC__BITS_PER_WORD) {
  94954. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94955. bw->bits = 0;
  94956. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94957. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94958. FLAC__ASSERT(bw->capacity == bw->words);
  94959. return false;
  94960. }
  94961. }
  94962. }
  94963. else {
  94964. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94965. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94966. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94967. bw->bits = bw->bits + msbits + lsbits;
  94968. uval |= mask1; /* set stop bit */
  94969. uval &= mask2; /* mask off unused top bits */
  94970. bw->accum <<= msbits + lsbits;
  94971. bw->accum |= uval;
  94972. }
  94973. else {
  94974. #endif
  94975. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94976. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94977. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94978. return false;
  94979. if(msbits) {
  94980. /* first part gets to word alignment */
  94981. if(bw->bits) {
  94982. left = FLAC__BITS_PER_WORD - bw->bits;
  94983. if(msbits < left) {
  94984. bw->accum <<= msbits;
  94985. bw->bits += msbits;
  94986. goto break1;
  94987. }
  94988. else {
  94989. bw->accum <<= left;
  94990. msbits -= left;
  94991. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94992. bw->bits = 0;
  94993. }
  94994. }
  94995. /* do whole words */
  94996. while(msbits >= FLAC__BITS_PER_WORD) {
  94997. bw->buffer[bw->words++] = 0;
  94998. msbits -= FLAC__BITS_PER_WORD;
  94999. }
  95000. /* do any leftovers */
  95001. if(msbits > 0) {
  95002. bw->accum = 0;
  95003. bw->bits = msbits;
  95004. }
  95005. }
  95006. break1:
  95007. uval |= mask1; /* set stop bit */
  95008. uval &= mask2; /* mask off unused top bits */
  95009. left = FLAC__BITS_PER_WORD - bw->bits;
  95010. if(lsbits < left) {
  95011. bw->accum <<= lsbits;
  95012. bw->accum |= uval;
  95013. bw->bits += lsbits;
  95014. }
  95015. else {
  95016. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  95017. * be > lsbits (because of previous assertions) so it would have
  95018. * triggered the (lsbits<left) case above.
  95019. */
  95020. FLAC__ASSERT(bw->bits);
  95021. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  95022. bw->accum <<= left;
  95023. bw->accum |= uval >> (bw->bits = lsbits - left);
  95024. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95025. bw->accum = uval;
  95026. }
  95027. #if 1
  95028. }
  95029. #endif
  95030. vals++;
  95031. nvals--;
  95032. }
  95033. return true;
  95034. }
  95035. #if 0 /* UNUSED */
  95036. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95037. {
  95038. unsigned total_bits, msbs, uval;
  95039. unsigned k;
  95040. FLAC__ASSERT(0 != bw);
  95041. FLAC__ASSERT(0 != bw->buffer);
  95042. FLAC__ASSERT(parameter > 0);
  95043. /* fold signed to unsigned */
  95044. if(val < 0)
  95045. uval = (unsigned)(((-(++val)) << 1) + 1);
  95046. else
  95047. uval = (unsigned)(val << 1);
  95048. k = FLAC__bitmath_ilog2(parameter);
  95049. if(parameter == 1u<<k) {
  95050. unsigned pattern;
  95051. FLAC__ASSERT(k <= 30);
  95052. msbs = uval >> k;
  95053. total_bits = 1 + k + msbs;
  95054. pattern = 1 << k; /* the unary end bit */
  95055. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95056. if(total_bits <= 32) {
  95057. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95058. return false;
  95059. }
  95060. else {
  95061. /* write the unary MSBs */
  95062. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95063. return false;
  95064. /* write the unary end bit and binary LSBs */
  95065. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95066. return false;
  95067. }
  95068. }
  95069. else {
  95070. unsigned q, r, d;
  95071. d = (1 << (k+1)) - parameter;
  95072. q = uval / parameter;
  95073. r = uval - (q * parameter);
  95074. /* write the unary MSBs */
  95075. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95076. return false;
  95077. /* write the unary end bit */
  95078. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95079. return false;
  95080. /* write the binary LSBs */
  95081. if(r >= d) {
  95082. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95083. return false;
  95084. }
  95085. else {
  95086. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95087. return false;
  95088. }
  95089. }
  95090. return true;
  95091. }
  95092. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95093. {
  95094. unsigned total_bits, msbs;
  95095. unsigned k;
  95096. FLAC__ASSERT(0 != bw);
  95097. FLAC__ASSERT(0 != bw->buffer);
  95098. FLAC__ASSERT(parameter > 0);
  95099. k = FLAC__bitmath_ilog2(parameter);
  95100. if(parameter == 1u<<k) {
  95101. unsigned pattern;
  95102. FLAC__ASSERT(k <= 30);
  95103. msbs = uval >> k;
  95104. total_bits = 1 + k + msbs;
  95105. pattern = 1 << k; /* the unary end bit */
  95106. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95107. if(total_bits <= 32) {
  95108. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95109. return false;
  95110. }
  95111. else {
  95112. /* write the unary MSBs */
  95113. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95114. return false;
  95115. /* write the unary end bit and binary LSBs */
  95116. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95117. return false;
  95118. }
  95119. }
  95120. else {
  95121. unsigned q, r, d;
  95122. d = (1 << (k+1)) - parameter;
  95123. q = uval / parameter;
  95124. r = uval - (q * parameter);
  95125. /* write the unary MSBs */
  95126. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95127. return false;
  95128. /* write the unary end bit */
  95129. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95130. return false;
  95131. /* write the binary LSBs */
  95132. if(r >= d) {
  95133. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95134. return false;
  95135. }
  95136. else {
  95137. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95138. return false;
  95139. }
  95140. }
  95141. return true;
  95142. }
  95143. #endif /* UNUSED */
  95144. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95145. {
  95146. FLAC__bool ok = 1;
  95147. FLAC__ASSERT(0 != bw);
  95148. FLAC__ASSERT(0 != bw->buffer);
  95149. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95150. if(val < 0x80) {
  95151. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95152. }
  95153. else if(val < 0x800) {
  95154. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95155. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95156. }
  95157. else if(val < 0x10000) {
  95158. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95159. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95160. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95161. }
  95162. else if(val < 0x200000) {
  95163. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95164. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95165. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95166. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95167. }
  95168. else if(val < 0x4000000) {
  95169. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95170. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95171. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95172. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95173. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95174. }
  95175. else {
  95176. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95177. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95178. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95179. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95180. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95181. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95182. }
  95183. return ok;
  95184. }
  95185. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95186. {
  95187. FLAC__bool ok = 1;
  95188. FLAC__ASSERT(0 != bw);
  95189. FLAC__ASSERT(0 != bw->buffer);
  95190. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95191. if(val < 0x80) {
  95192. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95193. }
  95194. else if(val < 0x800) {
  95195. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95196. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95197. }
  95198. else if(val < 0x10000) {
  95199. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95200. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95201. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95202. }
  95203. else if(val < 0x200000) {
  95204. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95205. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95206. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95207. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95208. }
  95209. else if(val < 0x4000000) {
  95210. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95211. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95212. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95213. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95214. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95215. }
  95216. else if(val < 0x80000000) {
  95217. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95218. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95219. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95220. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95221. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95222. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95223. }
  95224. else {
  95225. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95226. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95227. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95228. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95229. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95230. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95231. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95232. }
  95233. return ok;
  95234. }
  95235. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95236. {
  95237. /* 0-pad to byte boundary */
  95238. if(bw->bits & 7u)
  95239. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95240. else
  95241. return true;
  95242. }
  95243. #endif
  95244. /*** End of inlined file: bitwriter.c ***/
  95245. /*** Start of inlined file: cpu.c ***/
  95246. /*** Start of inlined file: juce_FlacHeader.h ***/
  95247. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95248. // tasks..
  95249. #define VERSION "1.2.1"
  95250. #define FLAC__NO_DLL 1
  95251. #if JUCE_MSVC
  95252. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95253. #endif
  95254. #if JUCE_MAC
  95255. #define FLAC__SYS_DARWIN 1
  95256. #endif
  95257. /*** End of inlined file: juce_FlacHeader.h ***/
  95258. #if JUCE_USE_FLAC
  95259. #if HAVE_CONFIG_H
  95260. # include <config.h>
  95261. #endif
  95262. #include <stdlib.h>
  95263. #include <stdio.h>
  95264. #if defined FLAC__CPU_IA32
  95265. # include <signal.h>
  95266. #elif defined FLAC__CPU_PPC
  95267. # if !defined FLAC__NO_ASM
  95268. # if defined FLAC__SYS_DARWIN
  95269. # include <sys/sysctl.h>
  95270. # include <mach/mach.h>
  95271. # include <mach/mach_host.h>
  95272. # include <mach/host_info.h>
  95273. # include <mach/machine.h>
  95274. # ifndef CPU_SUBTYPE_POWERPC_970
  95275. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95276. # endif
  95277. # else /* FLAC__SYS_DARWIN */
  95278. # include <signal.h>
  95279. # include <setjmp.h>
  95280. static sigjmp_buf jmpbuf;
  95281. static volatile sig_atomic_t canjump = 0;
  95282. static void sigill_handler (int sig)
  95283. {
  95284. if (!canjump) {
  95285. signal (sig, SIG_DFL);
  95286. raise (sig);
  95287. }
  95288. canjump = 0;
  95289. siglongjmp (jmpbuf, 1);
  95290. }
  95291. # endif /* FLAC__SYS_DARWIN */
  95292. # endif /* FLAC__NO_ASM */
  95293. #endif /* FLAC__CPU_PPC */
  95294. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95295. #include <sys/param.h>
  95296. #include <sys/sysctl.h>
  95297. #include <machine/cpu.h>
  95298. #endif
  95299. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95300. #include <sys/types.h>
  95301. #include <sys/sysctl.h>
  95302. #endif
  95303. #if defined(__APPLE__)
  95304. /* how to get sysctlbyname()? */
  95305. #endif
  95306. /* these are flags in EDX of CPUID AX=00000001 */
  95307. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95308. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95309. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95310. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95311. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95312. /* these are flags in ECX of CPUID AX=00000001 */
  95313. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95314. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95315. /* these are flags in EDX of CPUID AX=80000001 */
  95316. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95317. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95318. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95319. /*
  95320. * Extra stuff needed for detection of OS support for SSE on IA-32
  95321. */
  95322. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95323. # if defined(__linux__)
  95324. /*
  95325. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95326. * modify the return address to jump over the offending SSE instruction
  95327. * and also the operation following it that indicates the instruction
  95328. * executed successfully. In this way we use no global variables and
  95329. * stay thread-safe.
  95330. *
  95331. * 3 + 3 + 6:
  95332. * 3 bytes for "xorps xmm0,xmm0"
  95333. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95334. * 6 bytes extra in case our estimate is wrong
  95335. * 12 bytes puts us in the NOP "landing zone"
  95336. */
  95337. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95338. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95339. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95340. {
  95341. (void)signal;
  95342. sc.eip += 3 + 3 + 6;
  95343. }
  95344. # else
  95345. # include <sys/ucontext.h>
  95346. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95347. {
  95348. (void)signal, (void)si;
  95349. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95350. }
  95351. # endif
  95352. # elif defined(_MSC_VER)
  95353. # include <windows.h>
  95354. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95355. # ifdef USE_TRY_CATCH_FLAVOR
  95356. # else
  95357. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95358. {
  95359. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95360. ep->ContextRecord->Eip += 3 + 3 + 6;
  95361. return EXCEPTION_CONTINUE_EXECUTION;
  95362. }
  95363. return EXCEPTION_CONTINUE_SEARCH;
  95364. }
  95365. # endif
  95366. # endif
  95367. #endif
  95368. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95369. {
  95370. /*
  95371. * IA32-specific
  95372. */
  95373. #ifdef FLAC__CPU_IA32
  95374. info->type = FLAC__CPUINFO_TYPE_IA32;
  95375. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95376. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95377. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95378. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95379. info->data.ia32.cmov = false;
  95380. info->data.ia32.mmx = false;
  95381. info->data.ia32.fxsr = false;
  95382. info->data.ia32.sse = false;
  95383. info->data.ia32.sse2 = false;
  95384. info->data.ia32.sse3 = false;
  95385. info->data.ia32.ssse3 = false;
  95386. info->data.ia32._3dnow = false;
  95387. info->data.ia32.ext3dnow = false;
  95388. info->data.ia32.extmmx = false;
  95389. if(info->data.ia32.cpuid) {
  95390. /* http://www.sandpile.org/ia32/cpuid.htm */
  95391. FLAC__uint32 flags_edx, flags_ecx;
  95392. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95393. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95394. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95395. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95396. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95397. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95398. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95399. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95400. #ifdef FLAC__USE_3DNOW
  95401. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95402. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95403. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95404. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95405. #else
  95406. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95407. #endif
  95408. #ifdef DEBUG
  95409. fprintf(stderr, "CPU info (IA-32):\n");
  95410. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95411. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95412. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95413. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95414. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95415. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95416. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95417. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95418. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95419. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95420. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95421. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95422. #endif
  95423. /*
  95424. * now have to check for OS support of SSE/SSE2
  95425. */
  95426. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95427. #if defined FLAC__NO_SSE_OS
  95428. /* assume user knows better than us; turn it off */
  95429. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95430. #elif defined FLAC__SSE_OS
  95431. /* assume user knows better than us; leave as detected above */
  95432. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95433. int sse = 0;
  95434. size_t len;
  95435. /* at least one of these must work: */
  95436. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95437. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95438. if(!sse)
  95439. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95440. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95441. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95442. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95443. size_t len = sizeof(val);
  95444. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95445. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95446. else { /* double-check SSE2 */
  95447. mib[1] = CPU_SSE2;
  95448. len = sizeof(val);
  95449. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95450. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95451. }
  95452. # else
  95453. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95454. # endif
  95455. #elif defined(__linux__)
  95456. int sse = 0;
  95457. struct sigaction sigill_save;
  95458. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95459. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95460. #else
  95461. struct sigaction sigill_sse;
  95462. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95463. __sigemptyset(&sigill_sse.sa_mask);
  95464. 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 */
  95465. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95466. #endif
  95467. {
  95468. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95469. /* see sigill_handler_sse_os() for an explanation of the following: */
  95470. asm volatile (
  95471. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95472. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95473. "incl %0\n\t" /* SIGILL handler will jump over this */
  95474. /* landing zone */
  95475. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95476. "nop\n\t"
  95477. "nop\n\t"
  95478. "nop\n\t"
  95479. "nop\n\t"
  95480. "nop\n\t"
  95481. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95482. "nop\n\t"
  95483. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95484. : "=r"(sse)
  95485. : "r"(sse)
  95486. );
  95487. sigaction(SIGILL, &sigill_save, NULL);
  95488. }
  95489. if(!sse)
  95490. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95491. #elif defined(_MSC_VER)
  95492. # ifdef USE_TRY_CATCH_FLAVOR
  95493. _try {
  95494. __asm {
  95495. # if _MSC_VER <= 1200
  95496. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95497. _emit 0x0F
  95498. _emit 0x57
  95499. _emit 0xC0
  95500. # else
  95501. xorps xmm0,xmm0
  95502. # endif
  95503. }
  95504. }
  95505. _except(EXCEPTION_EXECUTE_HANDLER) {
  95506. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95507. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95508. }
  95509. # else
  95510. int sse = 0;
  95511. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95512. /* see GCC version above for explanation */
  95513. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95514. /* http://www.codeproject.com/cpp/gccasm.asp */
  95515. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95516. __asm {
  95517. # if _MSC_VER <= 1200
  95518. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95519. _emit 0x0F
  95520. _emit 0x57
  95521. _emit 0xC0
  95522. # else
  95523. xorps xmm0,xmm0
  95524. # endif
  95525. inc sse
  95526. nop
  95527. nop
  95528. nop
  95529. nop
  95530. nop
  95531. nop
  95532. nop
  95533. nop
  95534. nop
  95535. }
  95536. SetUnhandledExceptionFilter(save);
  95537. if(!sse)
  95538. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95539. # endif
  95540. #else
  95541. /* no way to test, disable to be safe */
  95542. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95543. #endif
  95544. #ifdef DEBUG
  95545. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95546. #endif
  95547. }
  95548. }
  95549. #else
  95550. info->use_asm = false;
  95551. #endif
  95552. /*
  95553. * PPC-specific
  95554. */
  95555. #elif defined FLAC__CPU_PPC
  95556. info->type = FLAC__CPUINFO_TYPE_PPC;
  95557. # if !defined FLAC__NO_ASM
  95558. info->use_asm = true;
  95559. # ifdef FLAC__USE_ALTIVEC
  95560. # if defined FLAC__SYS_DARWIN
  95561. {
  95562. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95563. size_t len = sizeof(val);
  95564. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95565. }
  95566. {
  95567. host_basic_info_data_t hostInfo;
  95568. mach_msg_type_number_t infoCount;
  95569. infoCount = HOST_BASIC_INFO_COUNT;
  95570. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95571. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95572. }
  95573. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95574. {
  95575. /* no Darwin, do it the brute-force way */
  95576. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95577. info->data.ppc.altivec = 0;
  95578. info->data.ppc.ppc64 = 0;
  95579. signal (SIGILL, sigill_handler);
  95580. canjump = 0;
  95581. if (!sigsetjmp (jmpbuf, 1)) {
  95582. canjump = 1;
  95583. asm volatile (
  95584. "mtspr 256, %0\n\t"
  95585. "vand %%v0, %%v0, %%v0"
  95586. :
  95587. : "r" (-1)
  95588. );
  95589. info->data.ppc.altivec = 1;
  95590. }
  95591. canjump = 0;
  95592. if (!sigsetjmp (jmpbuf, 1)) {
  95593. int x = 0;
  95594. canjump = 1;
  95595. /* PPC64 hardware implements the cntlzd instruction */
  95596. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95597. info->data.ppc.ppc64 = 1;
  95598. }
  95599. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95600. }
  95601. # endif
  95602. # else /* !FLAC__USE_ALTIVEC */
  95603. info->data.ppc.altivec = 0;
  95604. info->data.ppc.ppc64 = 0;
  95605. # endif
  95606. # else
  95607. info->use_asm = false;
  95608. # endif
  95609. /*
  95610. * unknown CPI
  95611. */
  95612. #else
  95613. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95614. info->use_asm = false;
  95615. #endif
  95616. }
  95617. #endif
  95618. /*** End of inlined file: cpu.c ***/
  95619. /*** Start of inlined file: crc.c ***/
  95620. /*** Start of inlined file: juce_FlacHeader.h ***/
  95621. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95622. // tasks..
  95623. #define VERSION "1.2.1"
  95624. #define FLAC__NO_DLL 1
  95625. #if JUCE_MSVC
  95626. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95627. #endif
  95628. #if JUCE_MAC
  95629. #define FLAC__SYS_DARWIN 1
  95630. #endif
  95631. /*** End of inlined file: juce_FlacHeader.h ***/
  95632. #if JUCE_USE_FLAC
  95633. #if HAVE_CONFIG_H
  95634. # include <config.h>
  95635. #endif
  95636. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95637. FLAC__byte const FLAC__crc8_table[256] = {
  95638. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95639. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95640. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95641. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95642. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95643. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95644. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95645. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95646. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95647. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95648. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95649. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95650. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95651. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95652. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95653. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95654. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95655. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95656. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95657. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95658. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95659. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95660. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95661. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95662. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95663. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95664. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95665. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95666. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95667. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95668. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95669. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95670. };
  95671. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95672. unsigned FLAC__crc16_table[256] = {
  95673. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95674. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95675. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95676. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95677. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95678. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95679. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95680. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95681. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95682. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95683. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95684. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95685. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95686. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95687. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95688. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95689. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95690. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95691. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95692. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95693. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95694. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95695. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95696. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95697. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95698. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95699. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95700. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95701. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95702. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95703. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95704. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95705. };
  95706. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95707. {
  95708. *crc = FLAC__crc8_table[*crc ^ data];
  95709. }
  95710. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95711. {
  95712. while(len--)
  95713. *crc = FLAC__crc8_table[*crc ^ *data++];
  95714. }
  95715. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95716. {
  95717. FLAC__uint8 crc = 0;
  95718. while(len--)
  95719. crc = FLAC__crc8_table[crc ^ *data++];
  95720. return crc;
  95721. }
  95722. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95723. {
  95724. unsigned crc = 0;
  95725. while(len--)
  95726. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95727. return crc;
  95728. }
  95729. #endif
  95730. /*** End of inlined file: crc.c ***/
  95731. /*** Start of inlined file: fixed.c ***/
  95732. /*** Start of inlined file: juce_FlacHeader.h ***/
  95733. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95734. // tasks..
  95735. #define VERSION "1.2.1"
  95736. #define FLAC__NO_DLL 1
  95737. #if JUCE_MSVC
  95738. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95739. #endif
  95740. #if JUCE_MAC
  95741. #define FLAC__SYS_DARWIN 1
  95742. #endif
  95743. /*** End of inlined file: juce_FlacHeader.h ***/
  95744. #if JUCE_USE_FLAC
  95745. #if HAVE_CONFIG_H
  95746. # include <config.h>
  95747. #endif
  95748. #include <math.h>
  95749. #include <string.h>
  95750. /*** Start of inlined file: fixed.h ***/
  95751. #ifndef FLAC__PRIVATE__FIXED_H
  95752. #define FLAC__PRIVATE__FIXED_H
  95753. #ifdef HAVE_CONFIG_H
  95754. #include <config.h>
  95755. #endif
  95756. /*** Start of inlined file: float.h ***/
  95757. #ifndef FLAC__PRIVATE__FLOAT_H
  95758. #define FLAC__PRIVATE__FLOAT_H
  95759. #ifdef HAVE_CONFIG_H
  95760. #include <config.h>
  95761. #endif
  95762. /*
  95763. * These typedefs make it easier to ensure that integer versions of
  95764. * the library really only contain integer operations. All the code
  95765. * in libFLAC should use FLAC__float and FLAC__double in place of
  95766. * float and double, and be protected by checks of the macro
  95767. * FLAC__INTEGER_ONLY_LIBRARY.
  95768. *
  95769. * FLAC__real is the basic floating point type used in LPC analysis.
  95770. */
  95771. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95772. typedef double FLAC__double;
  95773. typedef float FLAC__float;
  95774. /*
  95775. * WATCHOUT: changing FLAC__real will change the signatures of many
  95776. * functions that have assembly language equivalents and break them.
  95777. */
  95778. typedef float FLAC__real;
  95779. #else
  95780. /*
  95781. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95782. * for the integer part and lower 16 bits for the fractional part.
  95783. */
  95784. typedef FLAC__int32 FLAC__fixedpoint;
  95785. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95786. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95787. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95788. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95789. extern const FLAC__fixedpoint FLAC__FP_E;
  95790. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95791. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95792. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95793. /*
  95794. * FLAC__fixedpoint_log2()
  95795. * --------------------------------------------------------------------
  95796. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95797. * algorithm by Knuth for x >= 1.0
  95798. *
  95799. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95800. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95801. *
  95802. * 'precision' roughly limits the number of iterations that are done;
  95803. * use (unsigned)(-1) for maximum precision.
  95804. *
  95805. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95806. * function will punt and return 0.
  95807. *
  95808. * The return value will also have 'fracbits' fractional bits.
  95809. */
  95810. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95811. #endif
  95812. #endif
  95813. /*** End of inlined file: float.h ***/
  95814. /*** Start of inlined file: format.h ***/
  95815. #ifndef FLAC__PRIVATE__FORMAT_H
  95816. #define FLAC__PRIVATE__FORMAT_H
  95817. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95818. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95819. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95820. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95821. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95822. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95823. #endif
  95824. /*** End of inlined file: format.h ***/
  95825. /*
  95826. * FLAC__fixed_compute_best_predictor()
  95827. * --------------------------------------------------------------------
  95828. * Compute the best fixed predictor and the expected bits-per-sample
  95829. * of the residual signal for each order. The _wide() version uses
  95830. * 64-bit integers which is statistically necessary when bits-per-
  95831. * sample + log2(blocksize) > 30
  95832. *
  95833. * IN data[0,data_len-1]
  95834. * IN data_len
  95835. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95836. */
  95837. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95838. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95839. # ifndef FLAC__NO_ASM
  95840. # ifdef FLAC__CPU_IA32
  95841. # ifdef FLAC__HAS_NASM
  95842. 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]);
  95843. # endif
  95844. # endif
  95845. # endif
  95846. 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]);
  95847. #else
  95848. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95849. 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]);
  95850. #endif
  95851. /*
  95852. * FLAC__fixed_compute_residual()
  95853. * --------------------------------------------------------------------
  95854. * Compute the residual signal obtained from sutracting the predicted
  95855. * signal from the original.
  95856. *
  95857. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95858. * IN data_len length of original signal
  95859. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95860. * OUT residual[0,data_len-1] residual signal
  95861. */
  95862. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95863. /*
  95864. * FLAC__fixed_restore_signal()
  95865. * --------------------------------------------------------------------
  95866. * Restore the original signal by summing the residual and the
  95867. * predictor.
  95868. *
  95869. * IN residual[0,data_len-1] residual signal
  95870. * IN data_len length of original signal
  95871. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95872. * *** IMPORTANT: the caller must pass in the historical samples:
  95873. * IN data[-order,-1] previously-reconstructed historical samples
  95874. * OUT data[0,data_len-1] original signal
  95875. */
  95876. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95877. #endif
  95878. /*** End of inlined file: fixed.h ***/
  95879. #ifndef M_LN2
  95880. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95881. #define M_LN2 0.69314718055994530942
  95882. #endif
  95883. #ifdef min
  95884. #undef min
  95885. #endif
  95886. #define min(x,y) ((x) < (y)? (x) : (y))
  95887. #ifdef local_abs
  95888. #undef local_abs
  95889. #endif
  95890. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95891. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95892. /* rbps stands for residual bits per sample
  95893. *
  95894. * (ln(2) * err)
  95895. * rbps = log (-----------)
  95896. * 2 ( n )
  95897. */
  95898. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95899. {
  95900. FLAC__uint32 rbps;
  95901. unsigned bits; /* the number of bits required to represent a number */
  95902. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95903. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95904. FLAC__ASSERT(err > 0);
  95905. FLAC__ASSERT(n > 0);
  95906. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95907. if(err <= n)
  95908. return 0;
  95909. /*
  95910. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95911. * These allow us later to know we won't lose too much precision in the
  95912. * fixed-point division (err<<fracbits)/n.
  95913. */
  95914. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95915. err <<= fracbits;
  95916. err /= n;
  95917. /* err now holds err/n with fracbits fractional bits */
  95918. /*
  95919. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95920. * our purposes.
  95921. */
  95922. FLAC__ASSERT(err > 0);
  95923. bits = FLAC__bitmath_ilog2(err)+1;
  95924. if(bits > 16) {
  95925. err >>= (bits-16);
  95926. fracbits -= (bits-16);
  95927. }
  95928. rbps = (FLAC__uint32)err;
  95929. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95930. rbps *= FLAC__FP_LN2;
  95931. fracbits += 16;
  95932. FLAC__ASSERT(fracbits >= 0);
  95933. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95934. {
  95935. const int f = fracbits & 3;
  95936. if(f) {
  95937. rbps >>= f;
  95938. fracbits -= f;
  95939. }
  95940. }
  95941. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95942. if(rbps == 0)
  95943. return 0;
  95944. /*
  95945. * The return value must have 16 fractional bits. Since the whole part
  95946. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95947. * must be >= -3, these assertion allows us to be able to shift rbps
  95948. * left if necessary to get 16 fracbits without losing any bits of the
  95949. * whole part of rbps.
  95950. *
  95951. * There is a slight chance due to accumulated error that the whole part
  95952. * will require 6 bits, so we use 6 in the assertion. Really though as
  95953. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95954. */
  95955. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95956. FLAC__ASSERT(fracbits >= -3);
  95957. /* now shift the decimal point into place */
  95958. if(fracbits < 16)
  95959. return rbps << (16-fracbits);
  95960. else if(fracbits > 16)
  95961. return rbps >> (fracbits-16);
  95962. else
  95963. return rbps;
  95964. }
  95965. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95966. {
  95967. FLAC__uint32 rbps;
  95968. unsigned bits; /* the number of bits required to represent a number */
  95969. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95970. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95971. FLAC__ASSERT(err > 0);
  95972. FLAC__ASSERT(n > 0);
  95973. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95974. if(err <= n)
  95975. return 0;
  95976. /*
  95977. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95978. * These allow us later to know we won't lose too much precision in the
  95979. * fixed-point division (err<<fracbits)/n.
  95980. */
  95981. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95982. err <<= fracbits;
  95983. err /= n;
  95984. /* err now holds err/n with fracbits fractional bits */
  95985. /*
  95986. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95987. * our purposes.
  95988. */
  95989. FLAC__ASSERT(err > 0);
  95990. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95991. if(bits > 16) {
  95992. err >>= (bits-16);
  95993. fracbits -= (bits-16);
  95994. }
  95995. rbps = (FLAC__uint32)err;
  95996. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95997. rbps *= FLAC__FP_LN2;
  95998. fracbits += 16;
  95999. FLAC__ASSERT(fracbits >= 0);
  96000. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96001. {
  96002. const int f = fracbits & 3;
  96003. if(f) {
  96004. rbps >>= f;
  96005. fracbits -= f;
  96006. }
  96007. }
  96008. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96009. if(rbps == 0)
  96010. return 0;
  96011. /*
  96012. * The return value must have 16 fractional bits. Since the whole part
  96013. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96014. * must be >= -3, these assertion allows us to be able to shift rbps
  96015. * left if necessary to get 16 fracbits without losing any bits of the
  96016. * whole part of rbps.
  96017. *
  96018. * There is a slight chance due to accumulated error that the whole part
  96019. * will require 6 bits, so we use 6 in the assertion. Really though as
  96020. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96021. */
  96022. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96023. FLAC__ASSERT(fracbits >= -3);
  96024. /* now shift the decimal point into place */
  96025. if(fracbits < 16)
  96026. return rbps << (16-fracbits);
  96027. else if(fracbits > 16)
  96028. return rbps >> (fracbits-16);
  96029. else
  96030. return rbps;
  96031. }
  96032. #endif
  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. #else
  96036. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96037. #endif
  96038. {
  96039. FLAC__int32 last_error_0 = data[-1];
  96040. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96041. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96042. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96043. FLAC__int32 error, save;
  96044. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96045. unsigned i, order;
  96046. for(i = 0; i < data_len; i++) {
  96047. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96048. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96049. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96050. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96051. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96052. }
  96053. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96054. order = 0;
  96055. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96056. order = 1;
  96057. else if(total_error_2 < min(total_error_3, total_error_4))
  96058. order = 2;
  96059. else if(total_error_3 < total_error_4)
  96060. order = 3;
  96061. else
  96062. order = 4;
  96063. /* Estimate the expected number of bits per residual signal sample. */
  96064. /* 'total_error*' is linearly related to the variance of the residual */
  96065. /* signal, so we use it directly to compute E(|x|) */
  96066. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96067. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96068. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96069. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96070. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96071. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96072. 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);
  96073. 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);
  96074. 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);
  96075. 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);
  96076. 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);
  96077. #else
  96078. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96079. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96080. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96081. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96082. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96083. #endif
  96084. return order;
  96085. }
  96086. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96087. 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])
  96088. #else
  96089. 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])
  96090. #endif
  96091. {
  96092. FLAC__int32 last_error_0 = data[-1];
  96093. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96094. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96095. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96096. FLAC__int32 error, save;
  96097. /* total_error_* are 64-bits to avoid overflow when encoding
  96098. * erratic signals when the bits-per-sample and blocksize are
  96099. * large.
  96100. */
  96101. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96102. unsigned i, order;
  96103. for(i = 0; i < data_len; i++) {
  96104. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96105. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96106. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96107. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96108. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96109. }
  96110. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96111. order = 0;
  96112. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96113. order = 1;
  96114. else if(total_error_2 < min(total_error_3, total_error_4))
  96115. order = 2;
  96116. else if(total_error_3 < total_error_4)
  96117. order = 3;
  96118. else
  96119. order = 4;
  96120. /* Estimate the expected number of bits per residual signal sample. */
  96121. /* 'total_error*' is linearly related to the variance of the residual */
  96122. /* signal, so we use it directly to compute E(|x|) */
  96123. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96124. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96125. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96126. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96127. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96128. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96129. #if defined _MSC_VER || defined __MINGW32__
  96130. /* with MSVC you have to spoon feed it the casting */
  96131. 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);
  96132. 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);
  96133. 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);
  96134. 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);
  96135. 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);
  96136. #else
  96137. 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);
  96138. 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);
  96139. 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);
  96140. 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);
  96141. 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);
  96142. #endif
  96143. #else
  96144. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96145. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96146. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96147. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96148. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96149. #endif
  96150. return order;
  96151. }
  96152. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96153. {
  96154. const int idata_len = (int)data_len;
  96155. int i;
  96156. switch(order) {
  96157. case 0:
  96158. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96159. memcpy(residual, data, sizeof(residual[0])*data_len);
  96160. break;
  96161. case 1:
  96162. for(i = 0; i < idata_len; i++)
  96163. residual[i] = data[i] - data[i-1];
  96164. break;
  96165. case 2:
  96166. for(i = 0; i < idata_len; i++)
  96167. #if 1 /* OPT: may be faster with some compilers on some systems */
  96168. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96169. #else
  96170. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96171. #endif
  96172. break;
  96173. case 3:
  96174. for(i = 0; i < idata_len; i++)
  96175. #if 1 /* OPT: may be faster with some compilers on some systems */
  96176. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96177. #else
  96178. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96179. #endif
  96180. break;
  96181. case 4:
  96182. for(i = 0; i < idata_len; i++)
  96183. #if 1 /* OPT: may be faster with some compilers on some systems */
  96184. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96185. #else
  96186. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96187. #endif
  96188. break;
  96189. default:
  96190. FLAC__ASSERT(0);
  96191. }
  96192. }
  96193. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96194. {
  96195. int i, idata_len = (int)data_len;
  96196. switch(order) {
  96197. case 0:
  96198. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96199. memcpy(data, residual, sizeof(residual[0])*data_len);
  96200. break;
  96201. case 1:
  96202. for(i = 0; i < idata_len; i++)
  96203. data[i] = residual[i] + data[i-1];
  96204. break;
  96205. case 2:
  96206. for(i = 0; i < idata_len; i++)
  96207. #if 1 /* OPT: may be faster with some compilers on some systems */
  96208. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96209. #else
  96210. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96211. #endif
  96212. break;
  96213. case 3:
  96214. for(i = 0; i < idata_len; i++)
  96215. #if 1 /* OPT: may be faster with some compilers on some systems */
  96216. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96217. #else
  96218. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96219. #endif
  96220. break;
  96221. case 4:
  96222. for(i = 0; i < idata_len; i++)
  96223. #if 1 /* OPT: may be faster with some compilers on some systems */
  96224. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96225. #else
  96226. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96227. #endif
  96228. break;
  96229. default:
  96230. FLAC__ASSERT(0);
  96231. }
  96232. }
  96233. #endif
  96234. /*** End of inlined file: fixed.c ***/
  96235. /*** Start of inlined file: float.c ***/
  96236. /*** Start of inlined file: juce_FlacHeader.h ***/
  96237. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96238. // tasks..
  96239. #define VERSION "1.2.1"
  96240. #define FLAC__NO_DLL 1
  96241. #if JUCE_MSVC
  96242. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96243. #endif
  96244. #if JUCE_MAC
  96245. #define FLAC__SYS_DARWIN 1
  96246. #endif
  96247. /*** End of inlined file: juce_FlacHeader.h ***/
  96248. #if JUCE_USE_FLAC
  96249. #if HAVE_CONFIG_H
  96250. # include <config.h>
  96251. #endif
  96252. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96253. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96254. #ifdef _MSC_VER
  96255. #define FLAC__U64L(x) x
  96256. #else
  96257. #define FLAC__U64L(x) x##LLU
  96258. #endif
  96259. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96260. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96261. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96262. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96263. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96264. /* Lookup tables for Knuth's logarithm algorithm */
  96265. #define LOG2_LOOKUP_PRECISION 16
  96266. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96267. {
  96268. /*
  96269. * 0 fraction bits
  96270. */
  96271. /* undefined */ 0x00000000,
  96272. /* lg(2/1) = */ 0x00000001,
  96273. /* lg(4/3) = */ 0x00000000,
  96274. /* lg(8/7) = */ 0x00000000,
  96275. /* lg(16/15) = */ 0x00000000,
  96276. /* lg(32/31) = */ 0x00000000,
  96277. /* lg(64/63) = */ 0x00000000,
  96278. /* lg(128/127) = */ 0x00000000,
  96279. /* lg(256/255) = */ 0x00000000,
  96280. /* lg(512/511) = */ 0x00000000,
  96281. /* lg(1024/1023) = */ 0x00000000,
  96282. /* lg(2048/2047) = */ 0x00000000,
  96283. /* lg(4096/4095) = */ 0x00000000,
  96284. /* lg(8192/8191) = */ 0x00000000,
  96285. /* lg(16384/16383) = */ 0x00000000,
  96286. /* lg(32768/32767) = */ 0x00000000
  96287. },
  96288. {
  96289. /*
  96290. * 4 fraction bits
  96291. */
  96292. /* undefined */ 0x00000000,
  96293. /* lg(2/1) = */ 0x00000010,
  96294. /* lg(4/3) = */ 0x00000007,
  96295. /* lg(8/7) = */ 0x00000003,
  96296. /* lg(16/15) = */ 0x00000001,
  96297. /* lg(32/31) = */ 0x00000001,
  96298. /* lg(64/63) = */ 0x00000000,
  96299. /* lg(128/127) = */ 0x00000000,
  96300. /* lg(256/255) = */ 0x00000000,
  96301. /* lg(512/511) = */ 0x00000000,
  96302. /* lg(1024/1023) = */ 0x00000000,
  96303. /* lg(2048/2047) = */ 0x00000000,
  96304. /* lg(4096/4095) = */ 0x00000000,
  96305. /* lg(8192/8191) = */ 0x00000000,
  96306. /* lg(16384/16383) = */ 0x00000000,
  96307. /* lg(32768/32767) = */ 0x00000000
  96308. },
  96309. {
  96310. /*
  96311. * 8 fraction bits
  96312. */
  96313. /* undefined */ 0x00000000,
  96314. /* lg(2/1) = */ 0x00000100,
  96315. /* lg(4/3) = */ 0x0000006a,
  96316. /* lg(8/7) = */ 0x00000031,
  96317. /* lg(16/15) = */ 0x00000018,
  96318. /* lg(32/31) = */ 0x0000000c,
  96319. /* lg(64/63) = */ 0x00000006,
  96320. /* lg(128/127) = */ 0x00000003,
  96321. /* lg(256/255) = */ 0x00000001,
  96322. /* lg(512/511) = */ 0x00000001,
  96323. /* lg(1024/1023) = */ 0x00000000,
  96324. /* lg(2048/2047) = */ 0x00000000,
  96325. /* lg(4096/4095) = */ 0x00000000,
  96326. /* lg(8192/8191) = */ 0x00000000,
  96327. /* lg(16384/16383) = */ 0x00000000,
  96328. /* lg(32768/32767) = */ 0x00000000
  96329. },
  96330. {
  96331. /*
  96332. * 12 fraction bits
  96333. */
  96334. /* undefined */ 0x00000000,
  96335. /* lg(2/1) = */ 0x00001000,
  96336. /* lg(4/3) = */ 0x000006a4,
  96337. /* lg(8/7) = */ 0x00000315,
  96338. /* lg(16/15) = */ 0x0000017d,
  96339. /* lg(32/31) = */ 0x000000bc,
  96340. /* lg(64/63) = */ 0x0000005d,
  96341. /* lg(128/127) = */ 0x0000002e,
  96342. /* lg(256/255) = */ 0x00000017,
  96343. /* lg(512/511) = */ 0x0000000c,
  96344. /* lg(1024/1023) = */ 0x00000006,
  96345. /* lg(2048/2047) = */ 0x00000003,
  96346. /* lg(4096/4095) = */ 0x00000001,
  96347. /* lg(8192/8191) = */ 0x00000001,
  96348. /* lg(16384/16383) = */ 0x00000000,
  96349. /* lg(32768/32767) = */ 0x00000000
  96350. },
  96351. {
  96352. /*
  96353. * 16 fraction bits
  96354. */
  96355. /* undefined */ 0x00000000,
  96356. /* lg(2/1) = */ 0x00010000,
  96357. /* lg(4/3) = */ 0x00006a40,
  96358. /* lg(8/7) = */ 0x00003151,
  96359. /* lg(16/15) = */ 0x000017d6,
  96360. /* lg(32/31) = */ 0x00000bba,
  96361. /* lg(64/63) = */ 0x000005d1,
  96362. /* lg(128/127) = */ 0x000002e6,
  96363. /* lg(256/255) = */ 0x00000172,
  96364. /* lg(512/511) = */ 0x000000b9,
  96365. /* lg(1024/1023) = */ 0x0000005c,
  96366. /* lg(2048/2047) = */ 0x0000002e,
  96367. /* lg(4096/4095) = */ 0x00000017,
  96368. /* lg(8192/8191) = */ 0x0000000c,
  96369. /* lg(16384/16383) = */ 0x00000006,
  96370. /* lg(32768/32767) = */ 0x00000003
  96371. },
  96372. {
  96373. /*
  96374. * 20 fraction bits
  96375. */
  96376. /* undefined */ 0x00000000,
  96377. /* lg(2/1) = */ 0x00100000,
  96378. /* lg(4/3) = */ 0x0006a3fe,
  96379. /* lg(8/7) = */ 0x00031513,
  96380. /* lg(16/15) = */ 0x00017d60,
  96381. /* lg(32/31) = */ 0x0000bb9d,
  96382. /* lg(64/63) = */ 0x00005d10,
  96383. /* lg(128/127) = */ 0x00002e59,
  96384. /* lg(256/255) = */ 0x00001721,
  96385. /* lg(512/511) = */ 0x00000b8e,
  96386. /* lg(1024/1023) = */ 0x000005c6,
  96387. /* lg(2048/2047) = */ 0x000002e3,
  96388. /* lg(4096/4095) = */ 0x00000171,
  96389. /* lg(8192/8191) = */ 0x000000b9,
  96390. /* lg(16384/16383) = */ 0x0000005c,
  96391. /* lg(32768/32767) = */ 0x0000002e
  96392. },
  96393. {
  96394. /*
  96395. * 24 fraction bits
  96396. */
  96397. /* undefined */ 0x00000000,
  96398. /* lg(2/1) = */ 0x01000000,
  96399. /* lg(4/3) = */ 0x006a3fe6,
  96400. /* lg(8/7) = */ 0x00315130,
  96401. /* lg(16/15) = */ 0x0017d605,
  96402. /* lg(32/31) = */ 0x000bb9ca,
  96403. /* lg(64/63) = */ 0x0005d0fc,
  96404. /* lg(128/127) = */ 0x0002e58f,
  96405. /* lg(256/255) = */ 0x0001720e,
  96406. /* lg(512/511) = */ 0x0000b8d8,
  96407. /* lg(1024/1023) = */ 0x00005c61,
  96408. /* lg(2048/2047) = */ 0x00002e2d,
  96409. /* lg(4096/4095) = */ 0x00001716,
  96410. /* lg(8192/8191) = */ 0x00000b8b,
  96411. /* lg(16384/16383) = */ 0x000005c5,
  96412. /* lg(32768/32767) = */ 0x000002e3
  96413. },
  96414. {
  96415. /*
  96416. * 28 fraction bits
  96417. */
  96418. /* undefined */ 0x00000000,
  96419. /* lg(2/1) = */ 0x10000000,
  96420. /* lg(4/3) = */ 0x06a3fe5c,
  96421. /* lg(8/7) = */ 0x03151301,
  96422. /* lg(16/15) = */ 0x017d6049,
  96423. /* lg(32/31) = */ 0x00bb9ca6,
  96424. /* lg(64/63) = */ 0x005d0fba,
  96425. /* lg(128/127) = */ 0x002e58f7,
  96426. /* lg(256/255) = */ 0x001720da,
  96427. /* lg(512/511) = */ 0x000b8d87,
  96428. /* lg(1024/1023) = */ 0x0005c60b,
  96429. /* lg(2048/2047) = */ 0x0002e2d7,
  96430. /* lg(4096/4095) = */ 0x00017160,
  96431. /* lg(8192/8191) = */ 0x0000b8ad,
  96432. /* lg(16384/16383) = */ 0x00005c56,
  96433. /* lg(32768/32767) = */ 0x00002e2b
  96434. }
  96435. };
  96436. #if 0
  96437. static const FLAC__uint64 log2_lookup_wide[] = {
  96438. {
  96439. /*
  96440. * 32 fraction bits
  96441. */
  96442. /* undefined */ 0x00000000,
  96443. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96444. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96445. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96446. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96447. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96448. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96449. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96450. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96451. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96452. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96453. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96454. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96455. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96456. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96457. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96458. },
  96459. {
  96460. /*
  96461. * 48 fraction bits
  96462. */
  96463. /* undefined */ 0x00000000,
  96464. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96465. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96466. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96467. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96468. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96469. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96470. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96471. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96472. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96473. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96474. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96475. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96476. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96477. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96478. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96479. }
  96480. };
  96481. #endif
  96482. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96483. {
  96484. const FLAC__uint32 ONE = (1u << fracbits);
  96485. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96486. FLAC__ASSERT(fracbits < 32);
  96487. FLAC__ASSERT((fracbits & 0x3) == 0);
  96488. if(x < ONE)
  96489. return 0;
  96490. if(precision > LOG2_LOOKUP_PRECISION)
  96491. precision = LOG2_LOOKUP_PRECISION;
  96492. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96493. {
  96494. FLAC__uint32 y = 0;
  96495. FLAC__uint32 z = x >> 1, k = 1;
  96496. while (x > ONE && k < precision) {
  96497. if (x - z >= ONE) {
  96498. x -= z;
  96499. z = x >> k;
  96500. y += table[k];
  96501. }
  96502. else {
  96503. z >>= 1;
  96504. k++;
  96505. }
  96506. }
  96507. return y;
  96508. }
  96509. }
  96510. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96511. #endif
  96512. /*** End of inlined file: float.c ***/
  96513. /*** Start of inlined file: format.c ***/
  96514. /*** Start of inlined file: juce_FlacHeader.h ***/
  96515. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96516. // tasks..
  96517. #define VERSION "1.2.1"
  96518. #define FLAC__NO_DLL 1
  96519. #if JUCE_MSVC
  96520. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96521. #endif
  96522. #if JUCE_MAC
  96523. #define FLAC__SYS_DARWIN 1
  96524. #endif
  96525. /*** End of inlined file: juce_FlacHeader.h ***/
  96526. #if JUCE_USE_FLAC
  96527. #if HAVE_CONFIG_H
  96528. # include <config.h>
  96529. #endif
  96530. #include <stdio.h>
  96531. #include <stdlib.h> /* for qsort() */
  96532. #include <string.h> /* for memset() */
  96533. #ifndef FLaC__INLINE
  96534. #define FLaC__INLINE
  96535. #endif
  96536. #ifdef min
  96537. #undef min
  96538. #endif
  96539. #define min(a,b) ((a)<(b)?(a):(b))
  96540. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96541. #ifdef _MSC_VER
  96542. #define FLAC__U64L(x) x
  96543. #else
  96544. #define FLAC__U64L(x) x##LLU
  96545. #endif
  96546. /* VERSION should come from configure */
  96547. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96548. ;
  96549. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96550. /* yet one more hack because of MSVC6: */
  96551. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96552. #else
  96553. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96554. #endif
  96555. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96556. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96557. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96558. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96559. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96560. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96561. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96562. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96563. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96564. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96565. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96566. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96567. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96568. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96569. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96570. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96571. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96572. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96573. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96574. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96575. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96576. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96577. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96578. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96579. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96580. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96581. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96582. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96583. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96584. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96585. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96586. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96587. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96588. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96589. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96590. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96591. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96592. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96593. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96594. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96595. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96596. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96597. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96598. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96599. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96600. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96601. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96602. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96603. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96604. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96605. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96606. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96607. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96608. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96609. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96610. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96611. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96612. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96613. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96614. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96615. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96616. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96617. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96618. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96619. "PARTITIONED_RICE",
  96620. "PARTITIONED_RICE2"
  96621. };
  96622. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96623. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96624. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96625. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96626. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96627. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96628. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96629. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96630. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96631. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96632. "CONSTANT",
  96633. "VERBATIM",
  96634. "FIXED",
  96635. "LPC"
  96636. };
  96637. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96638. "INDEPENDENT",
  96639. "LEFT_SIDE",
  96640. "RIGHT_SIDE",
  96641. "MID_SIDE"
  96642. };
  96643. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96644. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96645. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96646. };
  96647. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96648. "STREAMINFO",
  96649. "PADDING",
  96650. "APPLICATION",
  96651. "SEEKTABLE",
  96652. "VORBIS_COMMENT",
  96653. "CUESHEET",
  96654. "PICTURE"
  96655. };
  96656. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96657. "Other",
  96658. "32x32 pixels 'file icon' (PNG only)",
  96659. "Other file icon",
  96660. "Cover (front)",
  96661. "Cover (back)",
  96662. "Leaflet page",
  96663. "Media (e.g. label side of CD)",
  96664. "Lead artist/lead performer/soloist",
  96665. "Artist/performer",
  96666. "Conductor",
  96667. "Band/Orchestra",
  96668. "Composer",
  96669. "Lyricist/text writer",
  96670. "Recording Location",
  96671. "During recording",
  96672. "During performance",
  96673. "Movie/video screen capture",
  96674. "A bright coloured fish",
  96675. "Illustration",
  96676. "Band/artist logotype",
  96677. "Publisher/Studio logotype"
  96678. };
  96679. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96680. {
  96681. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96682. return false;
  96683. }
  96684. else
  96685. return true;
  96686. }
  96687. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96688. {
  96689. if(
  96690. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96691. (
  96692. sample_rate >= (1u << 16) &&
  96693. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96694. )
  96695. ) {
  96696. return false;
  96697. }
  96698. else
  96699. return true;
  96700. }
  96701. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96702. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96703. {
  96704. unsigned i;
  96705. FLAC__uint64 prev_sample_number = 0;
  96706. FLAC__bool got_prev = false;
  96707. FLAC__ASSERT(0 != seek_table);
  96708. for(i = 0; i < seek_table->num_points; i++) {
  96709. if(got_prev) {
  96710. if(
  96711. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96712. seek_table->points[i].sample_number <= prev_sample_number
  96713. )
  96714. return false;
  96715. }
  96716. prev_sample_number = seek_table->points[i].sample_number;
  96717. got_prev = true;
  96718. }
  96719. return true;
  96720. }
  96721. /* used as the sort predicate for qsort() */
  96722. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96723. {
  96724. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96725. if(l->sample_number == r->sample_number)
  96726. return 0;
  96727. else if(l->sample_number < r->sample_number)
  96728. return -1;
  96729. else
  96730. return 1;
  96731. }
  96732. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96733. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96734. {
  96735. unsigned i, j;
  96736. FLAC__bool first;
  96737. FLAC__ASSERT(0 != seek_table);
  96738. /* sort the seekpoints */
  96739. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96740. /* uniquify the seekpoints */
  96741. first = true;
  96742. for(i = j = 0; i < seek_table->num_points; i++) {
  96743. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96744. if(!first) {
  96745. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96746. continue;
  96747. }
  96748. }
  96749. first = false;
  96750. seek_table->points[j++] = seek_table->points[i];
  96751. }
  96752. for(i = j; i < seek_table->num_points; i++) {
  96753. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96754. seek_table->points[i].stream_offset = 0;
  96755. seek_table->points[i].frame_samples = 0;
  96756. }
  96757. return j;
  96758. }
  96759. /*
  96760. * also disallows non-shortest-form encodings, c.f.
  96761. * http://www.unicode.org/versions/corrigendum1.html
  96762. * and a more clear explanation at the end of this section:
  96763. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96764. */
  96765. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96766. {
  96767. FLAC__ASSERT(0 != utf8);
  96768. if ((utf8[0] & 0x80) == 0) {
  96769. return 1;
  96770. }
  96771. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96772. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96773. return 0;
  96774. return 2;
  96775. }
  96776. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96777. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96778. return 0;
  96779. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96780. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96781. return 0;
  96782. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96783. return 0;
  96784. return 3;
  96785. }
  96786. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96787. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96788. return 0;
  96789. return 4;
  96790. }
  96791. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96792. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96793. return 0;
  96794. return 5;
  96795. }
  96796. 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) {
  96797. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96798. return 0;
  96799. return 6;
  96800. }
  96801. else {
  96802. return 0;
  96803. }
  96804. }
  96805. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96806. {
  96807. char c;
  96808. for(c = *name; c; c = *(++name))
  96809. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96810. return false;
  96811. return true;
  96812. }
  96813. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96814. {
  96815. if(length == (unsigned)(-1)) {
  96816. while(*value) {
  96817. unsigned n = utf8len_(value);
  96818. if(n == 0)
  96819. return false;
  96820. value += n;
  96821. }
  96822. }
  96823. else {
  96824. const FLAC__byte *end = value + length;
  96825. while(value < end) {
  96826. unsigned n = utf8len_(value);
  96827. if(n == 0)
  96828. return false;
  96829. value += n;
  96830. }
  96831. if(value != end)
  96832. return false;
  96833. }
  96834. return true;
  96835. }
  96836. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96837. {
  96838. const FLAC__byte *s, *end;
  96839. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96840. if(*s < 0x20 || *s > 0x7D)
  96841. return false;
  96842. }
  96843. if(s == end)
  96844. return false;
  96845. s++; /* skip '=' */
  96846. while(s < end) {
  96847. unsigned n = utf8len_(s);
  96848. if(n == 0)
  96849. return false;
  96850. s += n;
  96851. }
  96852. if(s != end)
  96853. return false;
  96854. return true;
  96855. }
  96856. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96857. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96858. {
  96859. unsigned i, j;
  96860. if(check_cd_da_subset) {
  96861. if(cue_sheet->lead_in < 2 * 44100) {
  96862. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96863. return false;
  96864. }
  96865. if(cue_sheet->lead_in % 588 != 0) {
  96866. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96867. return false;
  96868. }
  96869. }
  96870. if(cue_sheet->num_tracks == 0) {
  96871. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96872. return false;
  96873. }
  96874. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96875. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96876. return false;
  96877. }
  96878. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96879. if(cue_sheet->tracks[i].number == 0) {
  96880. if(violation) *violation = "cue sheet may not have a track number 0";
  96881. return false;
  96882. }
  96883. if(check_cd_da_subset) {
  96884. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96885. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96886. return false;
  96887. }
  96888. }
  96889. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96890. if(violation) {
  96891. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96892. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96893. else
  96894. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96895. }
  96896. return false;
  96897. }
  96898. if(i < cue_sheet->num_tracks - 1) {
  96899. if(cue_sheet->tracks[i].num_indices == 0) {
  96900. if(violation) *violation = "cue sheet track must have at least one index point";
  96901. return false;
  96902. }
  96903. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96904. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96905. return false;
  96906. }
  96907. }
  96908. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96909. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96910. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96911. return false;
  96912. }
  96913. if(j > 0) {
  96914. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96915. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96916. return false;
  96917. }
  96918. }
  96919. }
  96920. }
  96921. return true;
  96922. }
  96923. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96924. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96925. {
  96926. char *p;
  96927. FLAC__byte *b;
  96928. for(p = picture->mime_type; *p; p++) {
  96929. if(*p < 0x20 || *p > 0x7e) {
  96930. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96931. return false;
  96932. }
  96933. }
  96934. for(b = picture->description; *b; ) {
  96935. unsigned n = utf8len_(b);
  96936. if(n == 0) {
  96937. if(violation) *violation = "description string must be valid UTF-8";
  96938. return false;
  96939. }
  96940. b += n;
  96941. }
  96942. return true;
  96943. }
  96944. /*
  96945. * These routines are private to libFLAC
  96946. */
  96947. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96948. {
  96949. return
  96950. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96951. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96952. blocksize,
  96953. predictor_order
  96954. );
  96955. }
  96956. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96957. {
  96958. unsigned max_rice_partition_order = 0;
  96959. while(!(blocksize & 1)) {
  96960. max_rice_partition_order++;
  96961. blocksize >>= 1;
  96962. }
  96963. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96964. }
  96965. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96966. {
  96967. unsigned max_rice_partition_order = limit;
  96968. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96969. max_rice_partition_order--;
  96970. FLAC__ASSERT(
  96971. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96972. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96973. );
  96974. return max_rice_partition_order;
  96975. }
  96976. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96977. {
  96978. FLAC__ASSERT(0 != object);
  96979. object->parameters = 0;
  96980. object->raw_bits = 0;
  96981. object->capacity_by_order = 0;
  96982. }
  96983. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96984. {
  96985. FLAC__ASSERT(0 != object);
  96986. if(0 != object->parameters)
  96987. free(object->parameters);
  96988. if(0 != object->raw_bits)
  96989. free(object->raw_bits);
  96990. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96991. }
  96992. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96993. {
  96994. FLAC__ASSERT(0 != object);
  96995. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96996. if(object->capacity_by_order < max_partition_order) {
  96997. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96998. return false;
  96999. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  97000. return false;
  97001. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  97002. object->capacity_by_order = max_partition_order;
  97003. }
  97004. return true;
  97005. }
  97006. #endif
  97007. /*** End of inlined file: format.c ***/
  97008. /*** Start of inlined file: lpc_flac.c ***/
  97009. /*** Start of inlined file: juce_FlacHeader.h ***/
  97010. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97011. // tasks..
  97012. #define VERSION "1.2.1"
  97013. #define FLAC__NO_DLL 1
  97014. #if JUCE_MSVC
  97015. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97016. #endif
  97017. #if JUCE_MAC
  97018. #define FLAC__SYS_DARWIN 1
  97019. #endif
  97020. /*** End of inlined file: juce_FlacHeader.h ***/
  97021. #if JUCE_USE_FLAC
  97022. #if HAVE_CONFIG_H
  97023. # include <config.h>
  97024. #endif
  97025. #include <math.h>
  97026. /*** Start of inlined file: lpc.h ***/
  97027. #ifndef FLAC__PRIVATE__LPC_H
  97028. #define FLAC__PRIVATE__LPC_H
  97029. #ifdef HAVE_CONFIG_H
  97030. #include <config.h>
  97031. #endif
  97032. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97033. /*
  97034. * FLAC__lpc_window_data()
  97035. * --------------------------------------------------------------------
  97036. * Applies the given window to the data.
  97037. * OPT: asm implementation
  97038. *
  97039. * IN in[0,data_len-1]
  97040. * IN window[0,data_len-1]
  97041. * OUT out[0,lag-1]
  97042. * IN data_len
  97043. */
  97044. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97045. /*
  97046. * FLAC__lpc_compute_autocorrelation()
  97047. * --------------------------------------------------------------------
  97048. * Compute the autocorrelation for lags between 0 and lag-1.
  97049. * Assumes data[] outside of [0,data_len-1] == 0.
  97050. * Asserts that lag > 0.
  97051. *
  97052. * IN data[0,data_len-1]
  97053. * IN data_len
  97054. * IN 0 < lag <= data_len
  97055. * OUT autoc[0,lag-1]
  97056. */
  97057. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97058. #ifndef FLAC__NO_ASM
  97059. # ifdef FLAC__CPU_IA32
  97060. # ifdef FLAC__HAS_NASM
  97061. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97062. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97063. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97064. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97065. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97066. # endif
  97067. # endif
  97068. #endif
  97069. /*
  97070. * FLAC__lpc_compute_lp_coefficients()
  97071. * --------------------------------------------------------------------
  97072. * Computes LP coefficients for orders 1..max_order.
  97073. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97074. * and there is no point in calculating a predictor.
  97075. *
  97076. * IN autoc[0,max_order] autocorrelation values
  97077. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97078. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97079. * *** IMPORTANT:
  97080. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97081. * OUT error[0,max_order-1] error for each order (more
  97082. * specifically, the variance of
  97083. * the error signal times # of
  97084. * samples in the signal)
  97085. *
  97086. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97087. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97088. * in lp_coeff[7][0,7], etc.
  97089. */
  97090. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97091. /*
  97092. * FLAC__lpc_quantize_coefficients()
  97093. * --------------------------------------------------------------------
  97094. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97095. * must be less than 32 (sizeof(FLAC__int32)*8).
  97096. *
  97097. * IN lp_coeff[0,order-1] LP coefficients
  97098. * IN order LP order
  97099. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97100. * desired precision (in bits, including sign
  97101. * bit) of largest coefficient
  97102. * OUT qlp_coeff[0,order-1] quantized coefficients
  97103. * OUT shift # of bits to shift right to get approximated
  97104. * LP coefficients. NOTE: could be negative.
  97105. * RETURN 0 => quantization OK
  97106. * 1 => coefficients require too much shifting for *shift to
  97107. * fit in the LPC subframe header. 'shift' is unset.
  97108. * 2 => coefficients are all zero, which is bad. 'shift' is
  97109. * unset.
  97110. */
  97111. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97112. /*
  97113. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97114. * --------------------------------------------------------------------
  97115. * Compute the residual signal obtained from sutracting the predicted
  97116. * signal from the original.
  97117. *
  97118. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97119. * IN data_len length of original signal
  97120. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97121. * IN order > 0 LP order
  97122. * IN lp_quantization quantization of LP coefficients in bits
  97123. * OUT residual[0,data_len-1] residual signal
  97124. */
  97125. 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[]);
  97126. 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[]);
  97127. #ifndef FLAC__NO_ASM
  97128. # ifdef FLAC__CPU_IA32
  97129. # ifdef FLAC__HAS_NASM
  97130. 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[]);
  97131. 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[]);
  97132. # endif
  97133. # endif
  97134. #endif
  97135. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97136. /*
  97137. * FLAC__lpc_restore_signal()
  97138. * --------------------------------------------------------------------
  97139. * Restore the original signal by summing the residual and the
  97140. * predictor.
  97141. *
  97142. * IN residual[0,data_len-1] residual signal
  97143. * IN data_len length of original signal
  97144. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97145. * IN order > 0 LP order
  97146. * IN lp_quantization quantization of LP coefficients in bits
  97147. * *** IMPORTANT: the caller must pass in the historical samples:
  97148. * IN data[-order,-1] previously-reconstructed historical samples
  97149. * OUT data[0,data_len-1] original signal
  97150. */
  97151. 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[]);
  97152. 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[]);
  97153. #ifndef FLAC__NO_ASM
  97154. # ifdef FLAC__CPU_IA32
  97155. # ifdef FLAC__HAS_NASM
  97156. 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[]);
  97157. 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[]);
  97158. # endif /* FLAC__HAS_NASM */
  97159. # elif defined FLAC__CPU_PPC
  97160. 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[]);
  97161. 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[]);
  97162. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97163. #endif /* FLAC__NO_ASM */
  97164. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97165. /*
  97166. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97167. * --------------------------------------------------------------------
  97168. * Compute the expected number of bits per residual signal sample
  97169. * based on the LP error (which is related to the residual variance).
  97170. *
  97171. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97172. * IN total_samples > 0 # of samples in residual signal
  97173. * RETURN expected bits per sample
  97174. */
  97175. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97176. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97177. /*
  97178. * FLAC__lpc_compute_best_order()
  97179. * --------------------------------------------------------------------
  97180. * Compute the best order from the array of signal errors returned
  97181. * during coefficient computation.
  97182. *
  97183. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97184. * IN max_order > 0 max LP order
  97185. * IN total_samples > 0 # of samples in residual signal
  97186. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97187. * (includes warmup sample size and quantized LP coefficient)
  97188. * RETURN [1,max_order] best order
  97189. */
  97190. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97191. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97192. #endif
  97193. /*** End of inlined file: lpc.h ***/
  97194. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97195. #include <stdio.h>
  97196. #endif
  97197. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97198. #ifndef M_LN2
  97199. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97200. #define M_LN2 0.69314718055994530942
  97201. #endif
  97202. /* OPT: #undef'ing this may improve the speed on some architectures */
  97203. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97204. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97205. {
  97206. unsigned i;
  97207. for(i = 0; i < data_len; i++)
  97208. out[i] = in[i] * window[i];
  97209. }
  97210. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97211. {
  97212. /* a readable, but slower, version */
  97213. #if 0
  97214. FLAC__real d;
  97215. unsigned i;
  97216. FLAC__ASSERT(lag > 0);
  97217. FLAC__ASSERT(lag <= data_len);
  97218. /*
  97219. * Technically we should subtract the mean first like so:
  97220. * for(i = 0; i < data_len; i++)
  97221. * data[i] -= mean;
  97222. * but it appears not to make enough of a difference to matter, and
  97223. * most signals are already closely centered around zero
  97224. */
  97225. while(lag--) {
  97226. for(i = lag, d = 0.0; i < data_len; i++)
  97227. d += data[i] * data[i - lag];
  97228. autoc[lag] = d;
  97229. }
  97230. #endif
  97231. /*
  97232. * this version tends to run faster because of better data locality
  97233. * ('data_len' is usually much larger than 'lag')
  97234. */
  97235. FLAC__real d;
  97236. unsigned sample, coeff;
  97237. const unsigned limit = data_len - lag;
  97238. FLAC__ASSERT(lag > 0);
  97239. FLAC__ASSERT(lag <= data_len);
  97240. for(coeff = 0; coeff < lag; coeff++)
  97241. autoc[coeff] = 0.0;
  97242. for(sample = 0; sample <= limit; sample++) {
  97243. d = data[sample];
  97244. for(coeff = 0; coeff < lag; coeff++)
  97245. autoc[coeff] += d * data[sample+coeff];
  97246. }
  97247. for(; sample < data_len; sample++) {
  97248. d = data[sample];
  97249. for(coeff = 0; coeff < data_len - sample; coeff++)
  97250. autoc[coeff] += d * data[sample+coeff];
  97251. }
  97252. }
  97253. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97254. {
  97255. unsigned i, j;
  97256. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97257. FLAC__ASSERT(0 != max_order);
  97258. FLAC__ASSERT(0 < *max_order);
  97259. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97260. FLAC__ASSERT(autoc[0] != 0.0);
  97261. err = autoc[0];
  97262. for(i = 0; i < *max_order; i++) {
  97263. /* Sum up this iteration's reflection coefficient. */
  97264. r = -autoc[i+1];
  97265. for(j = 0; j < i; j++)
  97266. r -= lpc[j] * autoc[i-j];
  97267. ref[i] = (r/=err);
  97268. /* Update LPC coefficients and total error. */
  97269. lpc[i]=r;
  97270. for(j = 0; j < (i>>1); j++) {
  97271. FLAC__double tmp = lpc[j];
  97272. lpc[j] += r * lpc[i-1-j];
  97273. lpc[i-1-j] += r * tmp;
  97274. }
  97275. if(i & 1)
  97276. lpc[j] += lpc[j] * r;
  97277. err *= (1.0 - r * r);
  97278. /* save this order */
  97279. for(j = 0; j <= i; j++)
  97280. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97281. error[i] = err;
  97282. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97283. if(err == 0.0) {
  97284. *max_order = i+1;
  97285. return;
  97286. }
  97287. }
  97288. }
  97289. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97290. {
  97291. unsigned i;
  97292. FLAC__double cmax;
  97293. FLAC__int32 qmax, qmin;
  97294. FLAC__ASSERT(precision > 0);
  97295. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97296. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97297. precision--;
  97298. qmax = 1 << precision;
  97299. qmin = -qmax;
  97300. qmax--;
  97301. /* calc cmax = max( |lp_coeff[i]| ) */
  97302. cmax = 0.0;
  97303. for(i = 0; i < order; i++) {
  97304. const FLAC__double d = fabs(lp_coeff[i]);
  97305. if(d > cmax)
  97306. cmax = d;
  97307. }
  97308. if(cmax <= 0.0) {
  97309. /* => coefficients are all 0, which means our constant-detect didn't work */
  97310. return 2;
  97311. }
  97312. else {
  97313. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97314. const int min_shiftlimit = -max_shiftlimit - 1;
  97315. int log2cmax;
  97316. (void)frexp(cmax, &log2cmax);
  97317. log2cmax--;
  97318. *shift = (int)precision - log2cmax - 1;
  97319. if(*shift > max_shiftlimit)
  97320. *shift = max_shiftlimit;
  97321. else if(*shift < min_shiftlimit)
  97322. return 1;
  97323. }
  97324. if(*shift >= 0) {
  97325. FLAC__double error = 0.0;
  97326. FLAC__int32 q;
  97327. for(i = 0; i < order; i++) {
  97328. error += lp_coeff[i] * (1 << *shift);
  97329. #if 1 /* unfortunately lround() is C99 */
  97330. if(error >= 0.0)
  97331. q = (FLAC__int32)(error + 0.5);
  97332. else
  97333. q = (FLAC__int32)(error - 0.5);
  97334. #else
  97335. q = lround(error);
  97336. #endif
  97337. #ifdef FLAC__OVERFLOW_DETECT
  97338. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97339. 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]);
  97340. else if(q < qmin)
  97341. 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]);
  97342. #endif
  97343. if(q > qmax)
  97344. q = qmax;
  97345. else if(q < qmin)
  97346. q = qmin;
  97347. error -= q;
  97348. qlp_coeff[i] = q;
  97349. }
  97350. }
  97351. /* negative shift is very rare but due to design flaw, negative shift is
  97352. * a NOP in the decoder, so it must be handled specially by scaling down
  97353. * coeffs
  97354. */
  97355. else {
  97356. const int nshift = -(*shift);
  97357. FLAC__double error = 0.0;
  97358. FLAC__int32 q;
  97359. #ifdef DEBUG
  97360. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97361. #endif
  97362. for(i = 0; i < order; i++) {
  97363. error += lp_coeff[i] / (1 << nshift);
  97364. #if 1 /* unfortunately lround() is C99 */
  97365. if(error >= 0.0)
  97366. q = (FLAC__int32)(error + 0.5);
  97367. else
  97368. q = (FLAC__int32)(error - 0.5);
  97369. #else
  97370. q = lround(error);
  97371. #endif
  97372. #ifdef FLAC__OVERFLOW_DETECT
  97373. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97374. 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]);
  97375. else if(q < qmin)
  97376. 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]);
  97377. #endif
  97378. if(q > qmax)
  97379. q = qmax;
  97380. else if(q < qmin)
  97381. q = qmin;
  97382. error -= q;
  97383. qlp_coeff[i] = q;
  97384. }
  97385. *shift = 0;
  97386. }
  97387. return 0;
  97388. }
  97389. 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[])
  97390. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97391. {
  97392. FLAC__int64 sumo;
  97393. unsigned i, j;
  97394. FLAC__int32 sum;
  97395. const FLAC__int32 *history;
  97396. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97397. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97398. for(i=0;i<order;i++)
  97399. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97400. fprintf(stderr,"\n");
  97401. #endif
  97402. FLAC__ASSERT(order > 0);
  97403. for(i = 0; i < data_len; i++) {
  97404. sumo = 0;
  97405. sum = 0;
  97406. history = data;
  97407. for(j = 0; j < order; j++) {
  97408. sum += qlp_coeff[j] * (*(--history));
  97409. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97410. #if defined _MSC_VER
  97411. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97412. 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);
  97413. #else
  97414. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97415. 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);
  97416. #endif
  97417. }
  97418. *(residual++) = *(data++) - (sum >> lp_quantization);
  97419. }
  97420. /* Here's a slower but clearer version:
  97421. for(i = 0; i < data_len; i++) {
  97422. sum = 0;
  97423. for(j = 0; j < order; j++)
  97424. sum += qlp_coeff[j] * data[i-j-1];
  97425. residual[i] = data[i] - (sum >> lp_quantization);
  97426. }
  97427. */
  97428. }
  97429. #else /* fully unrolled version for normal use */
  97430. {
  97431. int i;
  97432. FLAC__int32 sum;
  97433. FLAC__ASSERT(order > 0);
  97434. FLAC__ASSERT(order <= 32);
  97435. /*
  97436. * We do unique versions up to 12th order since that's the subset limit.
  97437. * Also they are roughly ordered to match frequency of occurrence to
  97438. * minimize branching.
  97439. */
  97440. if(order <= 12) {
  97441. if(order > 8) {
  97442. if(order > 10) {
  97443. if(order == 12) {
  97444. for(i = 0; i < (int)data_len; i++) {
  97445. sum = 0;
  97446. sum += qlp_coeff[11] * data[i-12];
  97447. sum += qlp_coeff[10] * data[i-11];
  97448. sum += qlp_coeff[9] * data[i-10];
  97449. sum += qlp_coeff[8] * data[i-9];
  97450. sum += qlp_coeff[7] * data[i-8];
  97451. sum += qlp_coeff[6] * data[i-7];
  97452. sum += qlp_coeff[5] * data[i-6];
  97453. sum += qlp_coeff[4] * data[i-5];
  97454. sum += qlp_coeff[3] * data[i-4];
  97455. sum += qlp_coeff[2] * data[i-3];
  97456. sum += qlp_coeff[1] * data[i-2];
  97457. sum += qlp_coeff[0] * data[i-1];
  97458. residual[i] = data[i] - (sum >> lp_quantization);
  97459. }
  97460. }
  97461. else { /* order == 11 */
  97462. for(i = 0; i < (int)data_len; i++) {
  97463. sum = 0;
  97464. sum += qlp_coeff[10] * data[i-11];
  97465. sum += qlp_coeff[9] * data[i-10];
  97466. sum += qlp_coeff[8] * data[i-9];
  97467. sum += qlp_coeff[7] * data[i-8];
  97468. sum += qlp_coeff[6] * data[i-7];
  97469. sum += qlp_coeff[5] * data[i-6];
  97470. sum += qlp_coeff[4] * data[i-5];
  97471. sum += qlp_coeff[3] * data[i-4];
  97472. sum += qlp_coeff[2] * data[i-3];
  97473. sum += qlp_coeff[1] * data[i-2];
  97474. sum += qlp_coeff[0] * data[i-1];
  97475. residual[i] = data[i] - (sum >> lp_quantization);
  97476. }
  97477. }
  97478. }
  97479. else {
  97480. if(order == 10) {
  97481. for(i = 0; i < (int)data_len; i++) {
  97482. sum = 0;
  97483. sum += qlp_coeff[9] * data[i-10];
  97484. sum += qlp_coeff[8] * data[i-9];
  97485. sum += qlp_coeff[7] * data[i-8];
  97486. sum += qlp_coeff[6] * data[i-7];
  97487. sum += qlp_coeff[5] * data[i-6];
  97488. sum += qlp_coeff[4] * data[i-5];
  97489. sum += qlp_coeff[3] * data[i-4];
  97490. sum += qlp_coeff[2] * data[i-3];
  97491. sum += qlp_coeff[1] * data[i-2];
  97492. sum += qlp_coeff[0] * data[i-1];
  97493. residual[i] = data[i] - (sum >> lp_quantization);
  97494. }
  97495. }
  97496. else { /* order == 9 */
  97497. for(i = 0; i < (int)data_len; i++) {
  97498. sum = 0;
  97499. sum += qlp_coeff[8] * data[i-9];
  97500. sum += qlp_coeff[7] * data[i-8];
  97501. sum += qlp_coeff[6] * data[i-7];
  97502. sum += qlp_coeff[5] * data[i-6];
  97503. sum += qlp_coeff[4] * data[i-5];
  97504. sum += qlp_coeff[3] * data[i-4];
  97505. sum += qlp_coeff[2] * data[i-3];
  97506. sum += qlp_coeff[1] * data[i-2];
  97507. sum += qlp_coeff[0] * data[i-1];
  97508. residual[i] = data[i] - (sum >> lp_quantization);
  97509. }
  97510. }
  97511. }
  97512. }
  97513. else if(order > 4) {
  97514. if(order > 6) {
  97515. if(order == 8) {
  97516. for(i = 0; i < (int)data_len; i++) {
  97517. sum = 0;
  97518. sum += qlp_coeff[7] * data[i-8];
  97519. sum += qlp_coeff[6] * data[i-7];
  97520. sum += qlp_coeff[5] * data[i-6];
  97521. sum += qlp_coeff[4] * data[i-5];
  97522. sum += qlp_coeff[3] * data[i-4];
  97523. sum += qlp_coeff[2] * data[i-3];
  97524. sum += qlp_coeff[1] * data[i-2];
  97525. sum += qlp_coeff[0] * data[i-1];
  97526. residual[i] = data[i] - (sum >> lp_quantization);
  97527. }
  97528. }
  97529. else { /* order == 7 */
  97530. for(i = 0; i < (int)data_len; i++) {
  97531. sum = 0;
  97532. sum += qlp_coeff[6] * data[i-7];
  97533. sum += qlp_coeff[5] * data[i-6];
  97534. sum += qlp_coeff[4] * data[i-5];
  97535. sum += qlp_coeff[3] * data[i-4];
  97536. sum += qlp_coeff[2] * data[i-3];
  97537. sum += qlp_coeff[1] * data[i-2];
  97538. sum += qlp_coeff[0] * data[i-1];
  97539. residual[i] = data[i] - (sum >> lp_quantization);
  97540. }
  97541. }
  97542. }
  97543. else {
  97544. if(order == 6) {
  97545. for(i = 0; i < (int)data_len; i++) {
  97546. sum = 0;
  97547. sum += qlp_coeff[5] * data[i-6];
  97548. sum += qlp_coeff[4] * data[i-5];
  97549. sum += qlp_coeff[3] * data[i-4];
  97550. sum += qlp_coeff[2] * data[i-3];
  97551. sum += qlp_coeff[1] * data[i-2];
  97552. sum += qlp_coeff[0] * data[i-1];
  97553. residual[i] = data[i] - (sum >> lp_quantization);
  97554. }
  97555. }
  97556. else { /* order == 5 */
  97557. for(i = 0; i < (int)data_len; i++) {
  97558. sum = 0;
  97559. sum += qlp_coeff[4] * data[i-5];
  97560. sum += qlp_coeff[3] * data[i-4];
  97561. sum += qlp_coeff[2] * data[i-3];
  97562. sum += qlp_coeff[1] * data[i-2];
  97563. sum += qlp_coeff[0] * data[i-1];
  97564. residual[i] = data[i] - (sum >> lp_quantization);
  97565. }
  97566. }
  97567. }
  97568. }
  97569. else {
  97570. if(order > 2) {
  97571. if(order == 4) {
  97572. for(i = 0; i < (int)data_len; i++) {
  97573. sum = 0;
  97574. sum += qlp_coeff[3] * data[i-4];
  97575. sum += qlp_coeff[2] * data[i-3];
  97576. sum += qlp_coeff[1] * data[i-2];
  97577. sum += qlp_coeff[0] * data[i-1];
  97578. residual[i] = data[i] - (sum >> lp_quantization);
  97579. }
  97580. }
  97581. else { /* order == 3 */
  97582. for(i = 0; i < (int)data_len; i++) {
  97583. sum = 0;
  97584. sum += qlp_coeff[2] * data[i-3];
  97585. sum += qlp_coeff[1] * data[i-2];
  97586. sum += qlp_coeff[0] * data[i-1];
  97587. residual[i] = data[i] - (sum >> lp_quantization);
  97588. }
  97589. }
  97590. }
  97591. else {
  97592. if(order == 2) {
  97593. for(i = 0; i < (int)data_len; i++) {
  97594. sum = 0;
  97595. sum += qlp_coeff[1] * data[i-2];
  97596. sum += qlp_coeff[0] * data[i-1];
  97597. residual[i] = data[i] - (sum >> lp_quantization);
  97598. }
  97599. }
  97600. else { /* order == 1 */
  97601. for(i = 0; i < (int)data_len; i++)
  97602. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97603. }
  97604. }
  97605. }
  97606. }
  97607. else { /* order > 12 */
  97608. for(i = 0; i < (int)data_len; i++) {
  97609. sum = 0;
  97610. switch(order) {
  97611. case 32: sum += qlp_coeff[31] * data[i-32];
  97612. case 31: sum += qlp_coeff[30] * data[i-31];
  97613. case 30: sum += qlp_coeff[29] * data[i-30];
  97614. case 29: sum += qlp_coeff[28] * data[i-29];
  97615. case 28: sum += qlp_coeff[27] * data[i-28];
  97616. case 27: sum += qlp_coeff[26] * data[i-27];
  97617. case 26: sum += qlp_coeff[25] * data[i-26];
  97618. case 25: sum += qlp_coeff[24] * data[i-25];
  97619. case 24: sum += qlp_coeff[23] * data[i-24];
  97620. case 23: sum += qlp_coeff[22] * data[i-23];
  97621. case 22: sum += qlp_coeff[21] * data[i-22];
  97622. case 21: sum += qlp_coeff[20] * data[i-21];
  97623. case 20: sum += qlp_coeff[19] * data[i-20];
  97624. case 19: sum += qlp_coeff[18] * data[i-19];
  97625. case 18: sum += qlp_coeff[17] * data[i-18];
  97626. case 17: sum += qlp_coeff[16] * data[i-17];
  97627. case 16: sum += qlp_coeff[15] * data[i-16];
  97628. case 15: sum += qlp_coeff[14] * data[i-15];
  97629. case 14: sum += qlp_coeff[13] * data[i-14];
  97630. case 13: sum += qlp_coeff[12] * data[i-13];
  97631. sum += qlp_coeff[11] * data[i-12];
  97632. sum += qlp_coeff[10] * data[i-11];
  97633. sum += qlp_coeff[ 9] * data[i-10];
  97634. sum += qlp_coeff[ 8] * data[i- 9];
  97635. sum += qlp_coeff[ 7] * data[i- 8];
  97636. sum += qlp_coeff[ 6] * data[i- 7];
  97637. sum += qlp_coeff[ 5] * data[i- 6];
  97638. sum += qlp_coeff[ 4] * data[i- 5];
  97639. sum += qlp_coeff[ 3] * data[i- 4];
  97640. sum += qlp_coeff[ 2] * data[i- 3];
  97641. sum += qlp_coeff[ 1] * data[i- 2];
  97642. sum += qlp_coeff[ 0] * data[i- 1];
  97643. }
  97644. residual[i] = data[i] - (sum >> lp_quantization);
  97645. }
  97646. }
  97647. }
  97648. #endif
  97649. 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[])
  97650. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97651. {
  97652. unsigned i, j;
  97653. FLAC__int64 sum;
  97654. const FLAC__int32 *history;
  97655. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97656. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97657. for(i=0;i<order;i++)
  97658. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97659. fprintf(stderr,"\n");
  97660. #endif
  97661. FLAC__ASSERT(order > 0);
  97662. for(i = 0; i < data_len; i++) {
  97663. sum = 0;
  97664. history = data;
  97665. for(j = 0; j < order; j++)
  97666. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97667. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97668. #if defined _MSC_VER
  97669. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97670. #else
  97671. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97672. #endif
  97673. break;
  97674. }
  97675. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97676. #if defined _MSC_VER
  97677. 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));
  97678. #else
  97679. 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)));
  97680. #endif
  97681. break;
  97682. }
  97683. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97684. }
  97685. }
  97686. #else /* fully unrolled version for normal use */
  97687. {
  97688. int i;
  97689. FLAC__int64 sum;
  97690. FLAC__ASSERT(order > 0);
  97691. FLAC__ASSERT(order <= 32);
  97692. /*
  97693. * We do unique versions up to 12th order since that's the subset limit.
  97694. * Also they are roughly ordered to match frequency of occurrence to
  97695. * minimize branching.
  97696. */
  97697. if(order <= 12) {
  97698. if(order > 8) {
  97699. if(order > 10) {
  97700. if(order == 12) {
  97701. for(i = 0; i < (int)data_len; i++) {
  97702. sum = 0;
  97703. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97704. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97705. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97706. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97707. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97708. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97709. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97710. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97711. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97712. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97713. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97714. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97715. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97716. }
  97717. }
  97718. else { /* order == 11 */
  97719. for(i = 0; i < (int)data_len; i++) {
  97720. sum = 0;
  97721. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97722. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97723. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97724. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97725. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97726. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97727. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97728. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97729. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97730. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97731. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97732. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97733. }
  97734. }
  97735. }
  97736. else {
  97737. if(order == 10) {
  97738. for(i = 0; i < (int)data_len; i++) {
  97739. sum = 0;
  97740. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97741. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97742. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97743. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97744. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97745. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97746. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97747. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97748. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97749. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97750. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97751. }
  97752. }
  97753. else { /* order == 9 */
  97754. for(i = 0; i < (int)data_len; i++) {
  97755. sum = 0;
  97756. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97757. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97758. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97759. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97760. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97761. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97762. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97763. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97764. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97765. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97766. }
  97767. }
  97768. }
  97769. }
  97770. else if(order > 4) {
  97771. if(order > 6) {
  97772. if(order == 8) {
  97773. for(i = 0; i < (int)data_len; i++) {
  97774. sum = 0;
  97775. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97776. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97777. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97778. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97779. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97780. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97781. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97782. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97783. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97784. }
  97785. }
  97786. else { /* order == 7 */
  97787. for(i = 0; i < (int)data_len; i++) {
  97788. sum = 0;
  97789. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97790. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97791. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97792. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97793. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97794. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97795. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97796. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97797. }
  97798. }
  97799. }
  97800. else {
  97801. if(order == 6) {
  97802. for(i = 0; i < (int)data_len; i++) {
  97803. sum = 0;
  97804. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97805. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97806. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97807. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97808. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97809. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97810. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97811. }
  97812. }
  97813. else { /* order == 5 */
  97814. for(i = 0; i < (int)data_len; i++) {
  97815. sum = 0;
  97816. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97817. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97818. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97819. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97820. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97821. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97822. }
  97823. }
  97824. }
  97825. }
  97826. else {
  97827. if(order > 2) {
  97828. if(order == 4) {
  97829. for(i = 0; i < (int)data_len; i++) {
  97830. sum = 0;
  97831. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97832. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97833. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97834. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97835. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97836. }
  97837. }
  97838. else { /* order == 3 */
  97839. for(i = 0; i < (int)data_len; i++) {
  97840. sum = 0;
  97841. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97842. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97843. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97844. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97845. }
  97846. }
  97847. }
  97848. else {
  97849. if(order == 2) {
  97850. for(i = 0; i < (int)data_len; i++) {
  97851. sum = 0;
  97852. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97853. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97854. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97855. }
  97856. }
  97857. else { /* order == 1 */
  97858. for(i = 0; i < (int)data_len; i++)
  97859. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97860. }
  97861. }
  97862. }
  97863. }
  97864. else { /* order > 12 */
  97865. for(i = 0; i < (int)data_len; i++) {
  97866. sum = 0;
  97867. switch(order) {
  97868. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97869. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97870. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97871. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97872. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97873. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97874. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97875. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97876. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97877. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97878. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97879. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97880. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97881. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97882. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97883. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97884. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97885. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97886. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97887. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97888. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97889. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97890. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97891. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97892. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97893. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97894. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97895. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97896. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97897. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97898. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97899. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97900. }
  97901. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97902. }
  97903. }
  97904. }
  97905. #endif
  97906. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97907. 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[])
  97908. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97909. {
  97910. FLAC__int64 sumo;
  97911. unsigned i, j;
  97912. FLAC__int32 sum;
  97913. const FLAC__int32 *r = residual, *history;
  97914. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97915. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97916. for(i=0;i<order;i++)
  97917. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97918. fprintf(stderr,"\n");
  97919. #endif
  97920. FLAC__ASSERT(order > 0);
  97921. for(i = 0; i < data_len; i++) {
  97922. sumo = 0;
  97923. sum = 0;
  97924. history = data;
  97925. for(j = 0; j < order; j++) {
  97926. sum += qlp_coeff[j] * (*(--history));
  97927. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97928. #if defined _MSC_VER
  97929. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97930. 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);
  97931. #else
  97932. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97933. 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);
  97934. #endif
  97935. }
  97936. *(data++) = *(r++) + (sum >> lp_quantization);
  97937. }
  97938. /* Here's a slower but clearer version:
  97939. for(i = 0; i < data_len; i++) {
  97940. sum = 0;
  97941. for(j = 0; j < order; j++)
  97942. sum += qlp_coeff[j] * data[i-j-1];
  97943. data[i] = residual[i] + (sum >> lp_quantization);
  97944. }
  97945. */
  97946. }
  97947. #else /* fully unrolled version for normal use */
  97948. {
  97949. int i;
  97950. FLAC__int32 sum;
  97951. FLAC__ASSERT(order > 0);
  97952. FLAC__ASSERT(order <= 32);
  97953. /*
  97954. * We do unique versions up to 12th order since that's the subset limit.
  97955. * Also they are roughly ordered to match frequency of occurrence to
  97956. * minimize branching.
  97957. */
  97958. if(order <= 12) {
  97959. if(order > 8) {
  97960. if(order > 10) {
  97961. if(order == 12) {
  97962. for(i = 0; i < (int)data_len; i++) {
  97963. sum = 0;
  97964. sum += qlp_coeff[11] * data[i-12];
  97965. sum += qlp_coeff[10] * data[i-11];
  97966. sum += qlp_coeff[9] * data[i-10];
  97967. sum += qlp_coeff[8] * data[i-9];
  97968. sum += qlp_coeff[7] * data[i-8];
  97969. sum += qlp_coeff[6] * data[i-7];
  97970. sum += qlp_coeff[5] * data[i-6];
  97971. sum += qlp_coeff[4] * data[i-5];
  97972. sum += qlp_coeff[3] * data[i-4];
  97973. sum += qlp_coeff[2] * data[i-3];
  97974. sum += qlp_coeff[1] * data[i-2];
  97975. sum += qlp_coeff[0] * data[i-1];
  97976. data[i] = residual[i] + (sum >> lp_quantization);
  97977. }
  97978. }
  97979. else { /* order == 11 */
  97980. for(i = 0; i < (int)data_len; i++) {
  97981. sum = 0;
  97982. sum += qlp_coeff[10] * data[i-11];
  97983. sum += qlp_coeff[9] * data[i-10];
  97984. sum += qlp_coeff[8] * data[i-9];
  97985. sum += qlp_coeff[7] * data[i-8];
  97986. sum += qlp_coeff[6] * data[i-7];
  97987. sum += qlp_coeff[5] * data[i-6];
  97988. sum += qlp_coeff[4] * data[i-5];
  97989. sum += qlp_coeff[3] * data[i-4];
  97990. sum += qlp_coeff[2] * data[i-3];
  97991. sum += qlp_coeff[1] * data[i-2];
  97992. sum += qlp_coeff[0] * data[i-1];
  97993. data[i] = residual[i] + (sum >> lp_quantization);
  97994. }
  97995. }
  97996. }
  97997. else {
  97998. if(order == 10) {
  97999. for(i = 0; i < (int)data_len; i++) {
  98000. sum = 0;
  98001. sum += qlp_coeff[9] * data[i-10];
  98002. sum += qlp_coeff[8] * data[i-9];
  98003. sum += qlp_coeff[7] * data[i-8];
  98004. sum += qlp_coeff[6] * data[i-7];
  98005. sum += qlp_coeff[5] * data[i-6];
  98006. sum += qlp_coeff[4] * data[i-5];
  98007. sum += qlp_coeff[3] * data[i-4];
  98008. sum += qlp_coeff[2] * data[i-3];
  98009. sum += qlp_coeff[1] * data[i-2];
  98010. sum += qlp_coeff[0] * data[i-1];
  98011. data[i] = residual[i] + (sum >> lp_quantization);
  98012. }
  98013. }
  98014. else { /* order == 9 */
  98015. for(i = 0; i < (int)data_len; i++) {
  98016. sum = 0;
  98017. sum += qlp_coeff[8] * data[i-9];
  98018. sum += qlp_coeff[7] * data[i-8];
  98019. sum += qlp_coeff[6] * data[i-7];
  98020. sum += qlp_coeff[5] * data[i-6];
  98021. sum += qlp_coeff[4] * data[i-5];
  98022. sum += qlp_coeff[3] * data[i-4];
  98023. sum += qlp_coeff[2] * data[i-3];
  98024. sum += qlp_coeff[1] * data[i-2];
  98025. sum += qlp_coeff[0] * data[i-1];
  98026. data[i] = residual[i] + (sum >> lp_quantization);
  98027. }
  98028. }
  98029. }
  98030. }
  98031. else if(order > 4) {
  98032. if(order > 6) {
  98033. if(order == 8) {
  98034. for(i = 0; i < (int)data_len; i++) {
  98035. sum = 0;
  98036. sum += qlp_coeff[7] * data[i-8];
  98037. sum += qlp_coeff[6] * data[i-7];
  98038. sum += qlp_coeff[5] * data[i-6];
  98039. sum += qlp_coeff[4] * data[i-5];
  98040. sum += qlp_coeff[3] * data[i-4];
  98041. sum += qlp_coeff[2] * data[i-3];
  98042. sum += qlp_coeff[1] * data[i-2];
  98043. sum += qlp_coeff[0] * data[i-1];
  98044. data[i] = residual[i] + (sum >> lp_quantization);
  98045. }
  98046. }
  98047. else { /* order == 7 */
  98048. for(i = 0; i < (int)data_len; i++) {
  98049. sum = 0;
  98050. sum += qlp_coeff[6] * data[i-7];
  98051. sum += qlp_coeff[5] * data[i-6];
  98052. sum += qlp_coeff[4] * data[i-5];
  98053. sum += qlp_coeff[3] * data[i-4];
  98054. sum += qlp_coeff[2] * data[i-3];
  98055. sum += qlp_coeff[1] * data[i-2];
  98056. sum += qlp_coeff[0] * data[i-1];
  98057. data[i] = residual[i] + (sum >> lp_quantization);
  98058. }
  98059. }
  98060. }
  98061. else {
  98062. if(order == 6) {
  98063. for(i = 0; i < (int)data_len; i++) {
  98064. sum = 0;
  98065. sum += qlp_coeff[5] * data[i-6];
  98066. sum += qlp_coeff[4] * data[i-5];
  98067. sum += qlp_coeff[3] * data[i-4];
  98068. sum += qlp_coeff[2] * data[i-3];
  98069. sum += qlp_coeff[1] * data[i-2];
  98070. sum += qlp_coeff[0] * data[i-1];
  98071. data[i] = residual[i] + (sum >> lp_quantization);
  98072. }
  98073. }
  98074. else { /* order == 5 */
  98075. for(i = 0; i < (int)data_len; i++) {
  98076. sum = 0;
  98077. sum += qlp_coeff[4] * data[i-5];
  98078. sum += qlp_coeff[3] * data[i-4];
  98079. sum += qlp_coeff[2] * data[i-3];
  98080. sum += qlp_coeff[1] * data[i-2];
  98081. sum += qlp_coeff[0] * data[i-1];
  98082. data[i] = residual[i] + (sum >> lp_quantization);
  98083. }
  98084. }
  98085. }
  98086. }
  98087. else {
  98088. if(order > 2) {
  98089. if(order == 4) {
  98090. for(i = 0; i < (int)data_len; i++) {
  98091. sum = 0;
  98092. sum += qlp_coeff[3] * data[i-4];
  98093. sum += qlp_coeff[2] * data[i-3];
  98094. sum += qlp_coeff[1] * data[i-2];
  98095. sum += qlp_coeff[0] * data[i-1];
  98096. data[i] = residual[i] + (sum >> lp_quantization);
  98097. }
  98098. }
  98099. else { /* order == 3 */
  98100. for(i = 0; i < (int)data_len; i++) {
  98101. sum = 0;
  98102. sum += qlp_coeff[2] * data[i-3];
  98103. sum += qlp_coeff[1] * data[i-2];
  98104. sum += qlp_coeff[0] * data[i-1];
  98105. data[i] = residual[i] + (sum >> lp_quantization);
  98106. }
  98107. }
  98108. }
  98109. else {
  98110. if(order == 2) {
  98111. for(i = 0; i < (int)data_len; i++) {
  98112. sum = 0;
  98113. sum += qlp_coeff[1] * data[i-2];
  98114. sum += qlp_coeff[0] * data[i-1];
  98115. data[i] = residual[i] + (sum >> lp_quantization);
  98116. }
  98117. }
  98118. else { /* order == 1 */
  98119. for(i = 0; i < (int)data_len; i++)
  98120. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98121. }
  98122. }
  98123. }
  98124. }
  98125. else { /* order > 12 */
  98126. for(i = 0; i < (int)data_len; i++) {
  98127. sum = 0;
  98128. switch(order) {
  98129. case 32: sum += qlp_coeff[31] * data[i-32];
  98130. case 31: sum += qlp_coeff[30] * data[i-31];
  98131. case 30: sum += qlp_coeff[29] * data[i-30];
  98132. case 29: sum += qlp_coeff[28] * data[i-29];
  98133. case 28: sum += qlp_coeff[27] * data[i-28];
  98134. case 27: sum += qlp_coeff[26] * data[i-27];
  98135. case 26: sum += qlp_coeff[25] * data[i-26];
  98136. case 25: sum += qlp_coeff[24] * data[i-25];
  98137. case 24: sum += qlp_coeff[23] * data[i-24];
  98138. case 23: sum += qlp_coeff[22] * data[i-23];
  98139. case 22: sum += qlp_coeff[21] * data[i-22];
  98140. case 21: sum += qlp_coeff[20] * data[i-21];
  98141. case 20: sum += qlp_coeff[19] * data[i-20];
  98142. case 19: sum += qlp_coeff[18] * data[i-19];
  98143. case 18: sum += qlp_coeff[17] * data[i-18];
  98144. case 17: sum += qlp_coeff[16] * data[i-17];
  98145. case 16: sum += qlp_coeff[15] * data[i-16];
  98146. case 15: sum += qlp_coeff[14] * data[i-15];
  98147. case 14: sum += qlp_coeff[13] * data[i-14];
  98148. case 13: sum += qlp_coeff[12] * data[i-13];
  98149. sum += qlp_coeff[11] * data[i-12];
  98150. sum += qlp_coeff[10] * data[i-11];
  98151. sum += qlp_coeff[ 9] * data[i-10];
  98152. sum += qlp_coeff[ 8] * data[i- 9];
  98153. sum += qlp_coeff[ 7] * data[i- 8];
  98154. sum += qlp_coeff[ 6] * data[i- 7];
  98155. sum += qlp_coeff[ 5] * data[i- 6];
  98156. sum += qlp_coeff[ 4] * data[i- 5];
  98157. sum += qlp_coeff[ 3] * data[i- 4];
  98158. sum += qlp_coeff[ 2] * data[i- 3];
  98159. sum += qlp_coeff[ 1] * data[i- 2];
  98160. sum += qlp_coeff[ 0] * data[i- 1];
  98161. }
  98162. data[i] = residual[i] + (sum >> lp_quantization);
  98163. }
  98164. }
  98165. }
  98166. #endif
  98167. 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[])
  98168. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98169. {
  98170. unsigned i, j;
  98171. FLAC__int64 sum;
  98172. const FLAC__int32 *r = residual, *history;
  98173. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98174. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98175. for(i=0;i<order;i++)
  98176. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98177. fprintf(stderr,"\n");
  98178. #endif
  98179. FLAC__ASSERT(order > 0);
  98180. for(i = 0; i < data_len; i++) {
  98181. sum = 0;
  98182. history = data;
  98183. for(j = 0; j < order; j++)
  98184. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98185. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98186. #ifdef _MSC_VER
  98187. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98188. #else
  98189. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98190. #endif
  98191. break;
  98192. }
  98193. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98194. #ifdef _MSC_VER
  98195. 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));
  98196. #else
  98197. 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)));
  98198. #endif
  98199. break;
  98200. }
  98201. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98202. }
  98203. }
  98204. #else /* fully unrolled version for normal use */
  98205. {
  98206. int i;
  98207. FLAC__int64 sum;
  98208. FLAC__ASSERT(order > 0);
  98209. FLAC__ASSERT(order <= 32);
  98210. /*
  98211. * We do unique versions up to 12th order since that's the subset limit.
  98212. * Also they are roughly ordered to match frequency of occurrence to
  98213. * minimize branching.
  98214. */
  98215. if(order <= 12) {
  98216. if(order > 8) {
  98217. if(order > 10) {
  98218. if(order == 12) {
  98219. for(i = 0; i < (int)data_len; i++) {
  98220. sum = 0;
  98221. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98222. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98223. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98224. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98225. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98226. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98227. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98228. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98229. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98230. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98231. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98232. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98233. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98234. }
  98235. }
  98236. else { /* order == 11 */
  98237. for(i = 0; i < (int)data_len; i++) {
  98238. sum = 0;
  98239. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98240. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98241. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98242. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98243. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98244. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98245. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98246. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98247. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98248. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98249. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98250. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98251. }
  98252. }
  98253. }
  98254. else {
  98255. if(order == 10) {
  98256. for(i = 0; i < (int)data_len; i++) {
  98257. sum = 0;
  98258. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98259. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98260. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98261. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98262. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98263. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98264. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98265. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98266. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98267. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98268. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98269. }
  98270. }
  98271. else { /* order == 9 */
  98272. for(i = 0; i < (int)data_len; i++) {
  98273. sum = 0;
  98274. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98275. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98276. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98277. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98278. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98279. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98280. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98281. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98282. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98283. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98284. }
  98285. }
  98286. }
  98287. }
  98288. else if(order > 4) {
  98289. if(order > 6) {
  98290. if(order == 8) {
  98291. for(i = 0; i < (int)data_len; i++) {
  98292. sum = 0;
  98293. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98294. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98295. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98296. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98297. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98298. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98299. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98300. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98301. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98302. }
  98303. }
  98304. else { /* order == 7 */
  98305. for(i = 0; i < (int)data_len; i++) {
  98306. sum = 0;
  98307. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98308. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98309. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98310. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98311. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98312. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98313. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98314. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98315. }
  98316. }
  98317. }
  98318. else {
  98319. if(order == 6) {
  98320. for(i = 0; i < (int)data_len; i++) {
  98321. sum = 0;
  98322. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98323. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98324. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98325. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98326. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98327. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98328. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98329. }
  98330. }
  98331. else { /* order == 5 */
  98332. for(i = 0; i < (int)data_len; i++) {
  98333. sum = 0;
  98334. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98335. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98336. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98337. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98338. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98339. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98340. }
  98341. }
  98342. }
  98343. }
  98344. else {
  98345. if(order > 2) {
  98346. if(order == 4) {
  98347. for(i = 0; i < (int)data_len; i++) {
  98348. sum = 0;
  98349. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98350. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98351. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98352. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98353. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98354. }
  98355. }
  98356. else { /* order == 3 */
  98357. for(i = 0; i < (int)data_len; i++) {
  98358. sum = 0;
  98359. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98360. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98361. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98362. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98363. }
  98364. }
  98365. }
  98366. else {
  98367. if(order == 2) {
  98368. for(i = 0; i < (int)data_len; i++) {
  98369. sum = 0;
  98370. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98371. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98372. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98373. }
  98374. }
  98375. else { /* order == 1 */
  98376. for(i = 0; i < (int)data_len; i++)
  98377. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98378. }
  98379. }
  98380. }
  98381. }
  98382. else { /* order > 12 */
  98383. for(i = 0; i < (int)data_len; i++) {
  98384. sum = 0;
  98385. switch(order) {
  98386. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98387. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98388. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98389. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98390. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98391. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98392. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98393. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98394. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98395. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98396. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98397. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98398. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98399. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98400. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98401. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98402. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98403. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98404. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98405. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98406. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98407. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98408. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98409. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98410. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98411. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98412. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98413. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98414. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98415. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98416. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98417. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98418. }
  98419. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98420. }
  98421. }
  98422. }
  98423. #endif
  98424. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98425. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98426. {
  98427. FLAC__double error_scale;
  98428. FLAC__ASSERT(total_samples > 0);
  98429. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98430. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98431. }
  98432. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98433. {
  98434. if(lpc_error > 0.0) {
  98435. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98436. if(bps >= 0.0)
  98437. return bps;
  98438. else
  98439. return 0.0;
  98440. }
  98441. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98442. return 1e32;
  98443. }
  98444. else {
  98445. return 0.0;
  98446. }
  98447. }
  98448. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98449. {
  98450. 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 */
  98451. FLAC__double bits, best_bits, error_scale;
  98452. FLAC__ASSERT(max_order > 0);
  98453. FLAC__ASSERT(total_samples > 0);
  98454. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98455. best_index = 0;
  98456. best_bits = (unsigned)(-1);
  98457. for(index = 0, order = 1; index < max_order; index++, order++) {
  98458. 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);
  98459. if(bits < best_bits) {
  98460. best_index = index;
  98461. best_bits = bits;
  98462. }
  98463. }
  98464. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98465. }
  98466. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98467. #endif
  98468. /*** End of inlined file: lpc_flac.c ***/
  98469. /*** Start of inlined file: md5.c ***/
  98470. /*** Start of inlined file: juce_FlacHeader.h ***/
  98471. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98472. // tasks..
  98473. #define VERSION "1.2.1"
  98474. #define FLAC__NO_DLL 1
  98475. #if JUCE_MSVC
  98476. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98477. #endif
  98478. #if JUCE_MAC
  98479. #define FLAC__SYS_DARWIN 1
  98480. #endif
  98481. /*** End of inlined file: juce_FlacHeader.h ***/
  98482. #if JUCE_USE_FLAC
  98483. #if HAVE_CONFIG_H
  98484. # include <config.h>
  98485. #endif
  98486. #include <stdlib.h> /* for malloc() */
  98487. #include <string.h> /* for memcpy() */
  98488. /*** Start of inlined file: md5.h ***/
  98489. #ifndef FLAC__PRIVATE__MD5_H
  98490. #define FLAC__PRIVATE__MD5_H
  98491. /*
  98492. * This is the header file for the MD5 message-digest algorithm.
  98493. * The algorithm is due to Ron Rivest. This code was
  98494. * written by Colin Plumb in 1993, no copyright is claimed.
  98495. * This code is in the public domain; do with it what you wish.
  98496. *
  98497. * Equivalent code is available from RSA Data Security, Inc.
  98498. * This code has been tested against that, and is equivalent,
  98499. * except that you don't need to include two pages of legalese
  98500. * with every copy.
  98501. *
  98502. * To compute the message digest of a chunk of bytes, declare an
  98503. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98504. * needed on buffers full of bytes, and then call MD5Final, which
  98505. * will fill a supplied 16-byte array with the digest.
  98506. *
  98507. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98508. * header definitions; now uses stuff from dpkg's config.h
  98509. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98510. * Still in the public domain.
  98511. *
  98512. * Josh Coalson: made some changes to integrate with libFLAC.
  98513. * Still in the public domain, with no warranty.
  98514. */
  98515. typedef struct {
  98516. FLAC__uint32 in[16];
  98517. FLAC__uint32 buf[4];
  98518. FLAC__uint32 bytes[2];
  98519. FLAC__byte *internal_buf;
  98520. size_t capacity;
  98521. } FLAC__MD5Context;
  98522. void FLAC__MD5Init(FLAC__MD5Context *context);
  98523. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98524. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98525. #endif
  98526. /*** End of inlined file: md5.h ***/
  98527. #ifndef FLaC__INLINE
  98528. #define FLaC__INLINE
  98529. #endif
  98530. /*
  98531. * This code implements the MD5 message-digest algorithm.
  98532. * The algorithm is due to Ron Rivest. This code was
  98533. * written by Colin Plumb in 1993, no copyright is claimed.
  98534. * This code is in the public domain; do with it what you wish.
  98535. *
  98536. * Equivalent code is available from RSA Data Security, Inc.
  98537. * This code has been tested against that, and is equivalent,
  98538. * except that you don't need to include two pages of legalese
  98539. * with every copy.
  98540. *
  98541. * To compute the message digest of a chunk of bytes, declare an
  98542. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98543. * needed on buffers full of bytes, and then call MD5Final, which
  98544. * will fill a supplied 16-byte array with the digest.
  98545. *
  98546. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98547. * definitions; now uses stuff from dpkg's config.h.
  98548. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98549. * Still in the public domain.
  98550. *
  98551. * Josh Coalson: made some changes to integrate with libFLAC.
  98552. * Still in the public domain.
  98553. */
  98554. /* The four core functions - F1 is optimized somewhat */
  98555. /* #define F1(x, y, z) (x & y | ~x & z) */
  98556. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98557. #define F2(x, y, z) F1(z, x, y)
  98558. #define F3(x, y, z) (x ^ y ^ z)
  98559. #define F4(x, y, z) (y ^ (x | ~z))
  98560. /* This is the central step in the MD5 algorithm. */
  98561. #define MD5STEP(f,w,x,y,z,in,s) \
  98562. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98563. /*
  98564. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98565. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98566. * the data and converts bytes into longwords for this routine.
  98567. */
  98568. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98569. {
  98570. register FLAC__uint32 a, b, c, d;
  98571. a = buf[0];
  98572. b = buf[1];
  98573. c = buf[2];
  98574. d = buf[3];
  98575. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98576. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98577. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98578. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98579. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98580. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98581. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98582. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98583. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98584. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98585. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98586. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98587. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98588. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98589. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98590. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98591. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98592. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98593. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98594. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98595. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98596. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98597. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98598. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98599. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98600. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98601. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98602. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98603. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98604. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98605. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98606. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98607. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98608. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98609. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98610. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98611. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98612. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98613. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98614. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98615. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98616. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98617. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98618. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98619. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98620. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98621. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98622. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98623. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98624. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98625. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98626. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98627. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98628. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98629. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98630. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98631. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98632. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98633. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98634. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98635. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98636. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98637. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98638. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98639. buf[0] += a;
  98640. buf[1] += b;
  98641. buf[2] += c;
  98642. buf[3] += d;
  98643. }
  98644. #if WORDS_BIGENDIAN
  98645. //@@@@@@ OPT: use bswap/intrinsics
  98646. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98647. {
  98648. register FLAC__uint32 x;
  98649. do {
  98650. x = *buf;
  98651. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98652. *buf++ = (x >> 16) | (x << 16);
  98653. } while (--words);
  98654. }
  98655. static void byteSwapX16(FLAC__uint32 *buf)
  98656. {
  98657. register FLAC__uint32 x;
  98658. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98659. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98660. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98661. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98662. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98663. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98664. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98665. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98666. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98667. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98668. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98669. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98670. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98671. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98672. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98673. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98674. }
  98675. #else
  98676. #define byteSwap(buf, words)
  98677. #define byteSwapX16(buf)
  98678. #endif
  98679. /*
  98680. * Update context to reflect the concatenation of another buffer full
  98681. * of bytes.
  98682. */
  98683. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98684. {
  98685. FLAC__uint32 t;
  98686. /* Update byte count */
  98687. t = ctx->bytes[0];
  98688. if ((ctx->bytes[0] = t + len) < t)
  98689. ctx->bytes[1]++; /* Carry from low to high */
  98690. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98691. if (t > len) {
  98692. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98693. return;
  98694. }
  98695. /* First chunk is an odd size */
  98696. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98697. byteSwapX16(ctx->in);
  98698. FLAC__MD5Transform(ctx->buf, ctx->in);
  98699. buf += t;
  98700. len -= t;
  98701. /* Process data in 64-byte chunks */
  98702. while (len >= 64) {
  98703. memcpy(ctx->in, buf, 64);
  98704. byteSwapX16(ctx->in);
  98705. FLAC__MD5Transform(ctx->buf, ctx->in);
  98706. buf += 64;
  98707. len -= 64;
  98708. }
  98709. /* Handle any remaining bytes of data. */
  98710. memcpy(ctx->in, buf, len);
  98711. }
  98712. /*
  98713. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98714. * initialization constants.
  98715. */
  98716. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98717. {
  98718. ctx->buf[0] = 0x67452301;
  98719. ctx->buf[1] = 0xefcdab89;
  98720. ctx->buf[2] = 0x98badcfe;
  98721. ctx->buf[3] = 0x10325476;
  98722. ctx->bytes[0] = 0;
  98723. ctx->bytes[1] = 0;
  98724. ctx->internal_buf = 0;
  98725. ctx->capacity = 0;
  98726. }
  98727. /*
  98728. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98729. * 1 0* (64-bit count of bits processed, MSB-first)
  98730. */
  98731. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98732. {
  98733. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98734. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98735. /* Set the first char of padding to 0x80. There is always room. */
  98736. *p++ = 0x80;
  98737. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98738. count = 56 - 1 - count;
  98739. if (count < 0) { /* Padding forces an extra block */
  98740. memset(p, 0, count + 8);
  98741. byteSwapX16(ctx->in);
  98742. FLAC__MD5Transform(ctx->buf, ctx->in);
  98743. p = (FLAC__byte *)ctx->in;
  98744. count = 56;
  98745. }
  98746. memset(p, 0, count);
  98747. byteSwap(ctx->in, 14);
  98748. /* Append length in bits and transform */
  98749. ctx->in[14] = ctx->bytes[0] << 3;
  98750. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98751. FLAC__MD5Transform(ctx->buf, ctx->in);
  98752. byteSwap(ctx->buf, 4);
  98753. memcpy(digest, ctx->buf, 16);
  98754. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98755. if(0 != ctx->internal_buf) {
  98756. free(ctx->internal_buf);
  98757. ctx->internal_buf = 0;
  98758. ctx->capacity = 0;
  98759. }
  98760. }
  98761. /*
  98762. * Convert the incoming audio signal to a byte stream
  98763. */
  98764. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98765. {
  98766. unsigned channel, sample;
  98767. register FLAC__int32 a_word;
  98768. register FLAC__byte *buf_ = buf;
  98769. #if WORDS_BIGENDIAN
  98770. #else
  98771. if(channels == 2 && bytes_per_sample == 2) {
  98772. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98773. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98774. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98775. *buf1_ = (FLAC__int16)signal[1][sample];
  98776. }
  98777. else if(channels == 1 && bytes_per_sample == 2) {
  98778. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98779. for(sample = 0; sample < samples; sample++)
  98780. *buf1_++ = (FLAC__int16)signal[0][sample];
  98781. }
  98782. else
  98783. #endif
  98784. if(bytes_per_sample == 2) {
  98785. if(channels == 2) {
  98786. for(sample = 0; sample < samples; sample++) {
  98787. a_word = signal[0][sample];
  98788. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98789. *buf_++ = (FLAC__byte)a_word;
  98790. a_word = signal[1][sample];
  98791. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98792. *buf_++ = (FLAC__byte)a_word;
  98793. }
  98794. }
  98795. else if(channels == 1) {
  98796. for(sample = 0; sample < samples; sample++) {
  98797. a_word = signal[0][sample];
  98798. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98799. *buf_++ = (FLAC__byte)a_word;
  98800. }
  98801. }
  98802. else {
  98803. for(sample = 0; sample < samples; sample++) {
  98804. for(channel = 0; channel < channels; channel++) {
  98805. a_word = signal[channel][sample];
  98806. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98807. *buf_++ = (FLAC__byte)a_word;
  98808. }
  98809. }
  98810. }
  98811. }
  98812. else if(bytes_per_sample == 3) {
  98813. if(channels == 2) {
  98814. for(sample = 0; sample < samples; sample++) {
  98815. a_word = signal[0][sample];
  98816. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98817. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98818. *buf_++ = (FLAC__byte)a_word;
  98819. a_word = signal[1][sample];
  98820. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98821. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98822. *buf_++ = (FLAC__byte)a_word;
  98823. }
  98824. }
  98825. else if(channels == 1) {
  98826. for(sample = 0; sample < samples; sample++) {
  98827. a_word = signal[0][sample];
  98828. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98829. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98830. *buf_++ = (FLAC__byte)a_word;
  98831. }
  98832. }
  98833. else {
  98834. for(sample = 0; sample < samples; sample++) {
  98835. for(channel = 0; channel < channels; channel++) {
  98836. a_word = signal[channel][sample];
  98837. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98838. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98839. *buf_++ = (FLAC__byte)a_word;
  98840. }
  98841. }
  98842. }
  98843. }
  98844. else if(bytes_per_sample == 1) {
  98845. if(channels == 2) {
  98846. for(sample = 0; sample < samples; sample++) {
  98847. a_word = signal[0][sample];
  98848. *buf_++ = (FLAC__byte)a_word;
  98849. a_word = signal[1][sample];
  98850. *buf_++ = (FLAC__byte)a_word;
  98851. }
  98852. }
  98853. else if(channels == 1) {
  98854. for(sample = 0; sample < samples; sample++) {
  98855. a_word = signal[0][sample];
  98856. *buf_++ = (FLAC__byte)a_word;
  98857. }
  98858. }
  98859. else {
  98860. for(sample = 0; sample < samples; sample++) {
  98861. for(channel = 0; channel < channels; channel++) {
  98862. a_word = signal[channel][sample];
  98863. *buf_++ = (FLAC__byte)a_word;
  98864. }
  98865. }
  98866. }
  98867. }
  98868. else { /* bytes_per_sample == 4, maybe optimize more later */
  98869. for(sample = 0; sample < samples; sample++) {
  98870. for(channel = 0; channel < channels; channel++) {
  98871. a_word = signal[channel][sample];
  98872. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98873. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98874. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98875. *buf_++ = (FLAC__byte)a_word;
  98876. }
  98877. }
  98878. }
  98879. }
  98880. /*
  98881. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98882. */
  98883. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98884. {
  98885. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98886. /* overflow check */
  98887. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98888. return false;
  98889. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98890. return false;
  98891. if(ctx->capacity < bytes_needed) {
  98892. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98893. if(0 == tmp) {
  98894. free(ctx->internal_buf);
  98895. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98896. return false;
  98897. }
  98898. ctx->internal_buf = tmp;
  98899. ctx->capacity = bytes_needed;
  98900. }
  98901. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98902. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98903. return true;
  98904. }
  98905. #endif
  98906. /*** End of inlined file: md5.c ***/
  98907. /*** Start of inlined file: memory.c ***/
  98908. /*** Start of inlined file: juce_FlacHeader.h ***/
  98909. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98910. // tasks..
  98911. #define VERSION "1.2.1"
  98912. #define FLAC__NO_DLL 1
  98913. #if JUCE_MSVC
  98914. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98915. #endif
  98916. #if JUCE_MAC
  98917. #define FLAC__SYS_DARWIN 1
  98918. #endif
  98919. /*** End of inlined file: juce_FlacHeader.h ***/
  98920. #if JUCE_USE_FLAC
  98921. #if HAVE_CONFIG_H
  98922. # include <config.h>
  98923. #endif
  98924. /*** Start of inlined file: memory.h ***/
  98925. #ifndef FLAC__PRIVATE__MEMORY_H
  98926. #define FLAC__PRIVATE__MEMORY_H
  98927. #ifdef HAVE_CONFIG_H
  98928. #include <config.h>
  98929. #endif
  98930. #include <stdlib.h> /* for size_t */
  98931. /* Returns the unaligned address returned by malloc.
  98932. * Use free() on this address to deallocate.
  98933. */
  98934. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98935. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98936. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98937. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98938. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98939. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98940. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98941. #endif
  98942. #endif
  98943. /*** End of inlined file: memory.h ***/
  98944. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98945. {
  98946. void *x;
  98947. FLAC__ASSERT(0 != aligned_address);
  98948. #ifdef FLAC__ALIGN_MALLOC_DATA
  98949. /* align on 32-byte (256-bit) boundary */
  98950. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98951. #ifdef SIZEOF_VOIDP
  98952. #if SIZEOF_VOIDP == 4
  98953. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98954. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98955. #elif SIZEOF_VOIDP == 8
  98956. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98957. #else
  98958. # error Unsupported sizeof(void*)
  98959. #endif
  98960. #else
  98961. /* there's got to be a better way to do this right for all archs */
  98962. if(sizeof(void*) == sizeof(unsigned))
  98963. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98964. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98965. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98966. else
  98967. return 0;
  98968. #endif
  98969. #else
  98970. x = safe_malloc_(bytes);
  98971. *aligned_address = x;
  98972. #endif
  98973. return x;
  98974. }
  98975. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98976. {
  98977. FLAC__int32 *pu; /* unaligned pointer */
  98978. union { /* union needed to comply with C99 pointer aliasing rules */
  98979. FLAC__int32 *pa; /* aligned pointer */
  98980. void *pv; /* aligned pointer alias */
  98981. } u;
  98982. FLAC__ASSERT(elements > 0);
  98983. FLAC__ASSERT(0 != unaligned_pointer);
  98984. FLAC__ASSERT(0 != aligned_pointer);
  98985. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98986. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98987. if(0 == pu) {
  98988. return false;
  98989. }
  98990. else {
  98991. if(*unaligned_pointer != 0)
  98992. free(*unaligned_pointer);
  98993. *unaligned_pointer = pu;
  98994. *aligned_pointer = u.pa;
  98995. return true;
  98996. }
  98997. }
  98998. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98999. {
  99000. FLAC__uint32 *pu; /* unaligned pointer */
  99001. union { /* union needed to comply with C99 pointer aliasing rules */
  99002. FLAC__uint32 *pa; /* aligned pointer */
  99003. void *pv; /* aligned pointer alias */
  99004. } u;
  99005. FLAC__ASSERT(elements > 0);
  99006. FLAC__ASSERT(0 != unaligned_pointer);
  99007. FLAC__ASSERT(0 != aligned_pointer);
  99008. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99009. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99010. if(0 == pu) {
  99011. return false;
  99012. }
  99013. else {
  99014. if(*unaligned_pointer != 0)
  99015. free(*unaligned_pointer);
  99016. *unaligned_pointer = pu;
  99017. *aligned_pointer = u.pa;
  99018. return true;
  99019. }
  99020. }
  99021. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  99022. {
  99023. FLAC__uint64 *pu; /* unaligned pointer */
  99024. union { /* union needed to comply with C99 pointer aliasing rules */
  99025. FLAC__uint64 *pa; /* aligned pointer */
  99026. void *pv; /* aligned pointer alias */
  99027. } u;
  99028. FLAC__ASSERT(elements > 0);
  99029. FLAC__ASSERT(0 != unaligned_pointer);
  99030. FLAC__ASSERT(0 != aligned_pointer);
  99031. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99032. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99033. if(0 == pu) {
  99034. return false;
  99035. }
  99036. else {
  99037. if(*unaligned_pointer != 0)
  99038. free(*unaligned_pointer);
  99039. *unaligned_pointer = pu;
  99040. *aligned_pointer = u.pa;
  99041. return true;
  99042. }
  99043. }
  99044. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99045. {
  99046. unsigned *pu; /* unaligned pointer */
  99047. union { /* union needed to comply with C99 pointer aliasing rules */
  99048. unsigned *pa; /* aligned pointer */
  99049. void *pv; /* aligned pointer alias */
  99050. } u;
  99051. FLAC__ASSERT(elements > 0);
  99052. FLAC__ASSERT(0 != unaligned_pointer);
  99053. FLAC__ASSERT(0 != aligned_pointer);
  99054. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99055. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99056. if(0 == pu) {
  99057. return false;
  99058. }
  99059. else {
  99060. if(*unaligned_pointer != 0)
  99061. free(*unaligned_pointer);
  99062. *unaligned_pointer = pu;
  99063. *aligned_pointer = u.pa;
  99064. return true;
  99065. }
  99066. }
  99067. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99068. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99069. {
  99070. FLAC__real *pu; /* unaligned pointer */
  99071. union { /* union needed to comply with C99 pointer aliasing rules */
  99072. FLAC__real *pa; /* aligned pointer */
  99073. void *pv; /* aligned pointer alias */
  99074. } u;
  99075. FLAC__ASSERT(elements > 0);
  99076. FLAC__ASSERT(0 != unaligned_pointer);
  99077. FLAC__ASSERT(0 != aligned_pointer);
  99078. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99079. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99080. if(0 == pu) {
  99081. return false;
  99082. }
  99083. else {
  99084. if(*unaligned_pointer != 0)
  99085. free(*unaligned_pointer);
  99086. *unaligned_pointer = pu;
  99087. *aligned_pointer = u.pa;
  99088. return true;
  99089. }
  99090. }
  99091. #endif
  99092. #endif
  99093. /*** End of inlined file: memory.c ***/
  99094. /*** Start of inlined file: stream_decoder.c ***/
  99095. /*** Start of inlined file: juce_FlacHeader.h ***/
  99096. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99097. // tasks..
  99098. #define VERSION "1.2.1"
  99099. #define FLAC__NO_DLL 1
  99100. #if JUCE_MSVC
  99101. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99102. #endif
  99103. #if JUCE_MAC
  99104. #define FLAC__SYS_DARWIN 1
  99105. #endif
  99106. /*** End of inlined file: juce_FlacHeader.h ***/
  99107. #if JUCE_USE_FLAC
  99108. #if HAVE_CONFIG_H
  99109. # include <config.h>
  99110. #endif
  99111. #if defined _MSC_VER || defined __MINGW32__
  99112. #include <io.h> /* for _setmode() */
  99113. #include <fcntl.h> /* for _O_BINARY */
  99114. #endif
  99115. #if defined __CYGWIN__ || defined __EMX__
  99116. #include <io.h> /* for setmode(), O_BINARY */
  99117. #include <fcntl.h> /* for _O_BINARY */
  99118. #endif
  99119. #include <stdio.h>
  99120. #include <stdlib.h> /* for malloc() */
  99121. #include <string.h> /* for memset/memcpy() */
  99122. #include <sys/stat.h> /* for stat() */
  99123. #include <sys/types.h> /* for off_t */
  99124. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99125. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99126. #define fseeko fseek
  99127. #define ftello ftell
  99128. #endif
  99129. #endif
  99130. /*** Start of inlined file: stream_decoder.h ***/
  99131. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99132. #define FLAC__PROTECTED__STREAM_DECODER_H
  99133. #if FLAC__HAS_OGG
  99134. #include "include/private/ogg_decoder_aspect.h"
  99135. #endif
  99136. typedef struct FLAC__StreamDecoderProtected {
  99137. FLAC__StreamDecoderState state;
  99138. unsigned channels;
  99139. FLAC__ChannelAssignment channel_assignment;
  99140. unsigned bits_per_sample;
  99141. unsigned sample_rate; /* in Hz */
  99142. unsigned blocksize; /* in samples (per channel) */
  99143. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99144. #if FLAC__HAS_OGG
  99145. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99146. #endif
  99147. } FLAC__StreamDecoderProtected;
  99148. /*
  99149. * return the number of input bytes consumed
  99150. */
  99151. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99152. #endif
  99153. /*** End of inlined file: stream_decoder.h ***/
  99154. #ifdef max
  99155. #undef max
  99156. #endif
  99157. #define max(a,b) ((a)>(b)?(a):(b))
  99158. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99159. #ifdef _MSC_VER
  99160. #define FLAC__U64L(x) x
  99161. #else
  99162. #define FLAC__U64L(x) x##LLU
  99163. #endif
  99164. /* technically this should be in an "export.c" but this is convenient enough */
  99165. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99166. #if FLAC__HAS_OGG
  99167. 1
  99168. #else
  99169. 0
  99170. #endif
  99171. ;
  99172. /***********************************************************************
  99173. *
  99174. * Private static data
  99175. *
  99176. ***********************************************************************/
  99177. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99178. /***********************************************************************
  99179. *
  99180. * Private class method prototypes
  99181. *
  99182. ***********************************************************************/
  99183. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99184. static FILE *get_binary_stdin_(void);
  99185. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99186. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99187. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99188. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99189. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99190. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99191. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99192. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99193. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99194. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99195. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99196. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99197. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99198. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99199. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99200. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99201. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99202. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99203. 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);
  99204. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99205. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99206. #if FLAC__HAS_OGG
  99207. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99208. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99209. #endif
  99210. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99211. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99212. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99213. #if FLAC__HAS_OGG
  99214. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99215. #endif
  99216. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99217. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99218. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99219. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99220. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99221. /***********************************************************************
  99222. *
  99223. * Private class data
  99224. *
  99225. ***********************************************************************/
  99226. typedef struct FLAC__StreamDecoderPrivate {
  99227. #if FLAC__HAS_OGG
  99228. FLAC__bool is_ogg;
  99229. #endif
  99230. FLAC__StreamDecoderReadCallback read_callback;
  99231. FLAC__StreamDecoderSeekCallback seek_callback;
  99232. FLAC__StreamDecoderTellCallback tell_callback;
  99233. FLAC__StreamDecoderLengthCallback length_callback;
  99234. FLAC__StreamDecoderEofCallback eof_callback;
  99235. FLAC__StreamDecoderWriteCallback write_callback;
  99236. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99237. FLAC__StreamDecoderErrorCallback error_callback;
  99238. /* generic 32-bit datapath: */
  99239. 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[]);
  99240. /* generic 64-bit datapath: */
  99241. 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[]);
  99242. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99243. 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[]);
  99244. /* 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: */
  99245. 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[]);
  99246. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99247. void *client_data;
  99248. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99249. FLAC__BitReader *input;
  99250. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99251. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99252. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99253. unsigned output_capacity, output_channels;
  99254. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99255. FLAC__uint64 samples_decoded;
  99256. FLAC__bool has_stream_info, has_seek_table;
  99257. FLAC__StreamMetadata stream_info;
  99258. FLAC__StreamMetadata seek_table;
  99259. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99260. FLAC__byte *metadata_filter_ids;
  99261. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99262. FLAC__Frame frame;
  99263. FLAC__bool cached; /* true if there is a byte in lookahead */
  99264. FLAC__CPUInfo cpuinfo;
  99265. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99266. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99267. /* unaligned (original) pointers to allocated data */
  99268. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99269. 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 */
  99270. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99271. FLAC__bool is_seeking;
  99272. FLAC__MD5Context md5context;
  99273. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99274. /* (the rest of these are only used for seeking) */
  99275. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99276. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99277. FLAC__uint64 target_sample;
  99278. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99279. #if FLAC__HAS_OGG
  99280. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99281. #endif
  99282. } FLAC__StreamDecoderPrivate;
  99283. /***********************************************************************
  99284. *
  99285. * Public static class data
  99286. *
  99287. ***********************************************************************/
  99288. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99289. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99290. "FLAC__STREAM_DECODER_READ_METADATA",
  99291. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99292. "FLAC__STREAM_DECODER_READ_FRAME",
  99293. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99294. "FLAC__STREAM_DECODER_OGG_ERROR",
  99295. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99296. "FLAC__STREAM_DECODER_ABORTED",
  99297. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99298. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99299. };
  99300. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99301. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99302. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99303. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99304. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99305. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99306. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99307. };
  99308. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99309. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99310. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99311. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99312. };
  99313. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99314. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99315. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99316. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99317. };
  99318. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99319. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99320. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99321. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99322. };
  99323. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99324. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99325. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99326. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99327. };
  99328. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99329. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99330. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99331. };
  99332. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99333. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99334. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99335. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99336. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99337. };
  99338. /***********************************************************************
  99339. *
  99340. * Class constructor/destructor
  99341. *
  99342. ***********************************************************************/
  99343. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99344. {
  99345. FLAC__StreamDecoder *decoder;
  99346. unsigned i;
  99347. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99348. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99349. if(decoder == 0) {
  99350. return 0;
  99351. }
  99352. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99353. if(decoder->protected_ == 0) {
  99354. free(decoder);
  99355. return 0;
  99356. }
  99357. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99358. if(decoder->private_ == 0) {
  99359. free(decoder->protected_);
  99360. free(decoder);
  99361. return 0;
  99362. }
  99363. decoder->private_->input = FLAC__bitreader_new();
  99364. if(decoder->private_->input == 0) {
  99365. free(decoder->private_);
  99366. free(decoder->protected_);
  99367. free(decoder);
  99368. return 0;
  99369. }
  99370. decoder->private_->metadata_filter_ids_capacity = 16;
  99371. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99372. FLAC__bitreader_delete(decoder->private_->input);
  99373. free(decoder->private_);
  99374. free(decoder->protected_);
  99375. free(decoder);
  99376. return 0;
  99377. }
  99378. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99379. decoder->private_->output[i] = 0;
  99380. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99381. }
  99382. decoder->private_->output_capacity = 0;
  99383. decoder->private_->output_channels = 0;
  99384. decoder->private_->has_seek_table = false;
  99385. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99386. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99387. decoder->private_->file = 0;
  99388. set_defaults_dec(decoder);
  99389. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99390. return decoder;
  99391. }
  99392. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99393. {
  99394. unsigned i;
  99395. FLAC__ASSERT(0 != decoder);
  99396. FLAC__ASSERT(0 != decoder->protected_);
  99397. FLAC__ASSERT(0 != decoder->private_);
  99398. FLAC__ASSERT(0 != decoder->private_->input);
  99399. (void)FLAC__stream_decoder_finish(decoder);
  99400. if(0 != decoder->private_->metadata_filter_ids)
  99401. free(decoder->private_->metadata_filter_ids);
  99402. FLAC__bitreader_delete(decoder->private_->input);
  99403. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99404. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99405. free(decoder->private_);
  99406. free(decoder->protected_);
  99407. free(decoder);
  99408. }
  99409. /***********************************************************************
  99410. *
  99411. * Public class methods
  99412. *
  99413. ***********************************************************************/
  99414. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99415. FLAC__StreamDecoder *decoder,
  99416. FLAC__StreamDecoderReadCallback read_callback,
  99417. FLAC__StreamDecoderSeekCallback seek_callback,
  99418. FLAC__StreamDecoderTellCallback tell_callback,
  99419. FLAC__StreamDecoderLengthCallback length_callback,
  99420. FLAC__StreamDecoderEofCallback eof_callback,
  99421. FLAC__StreamDecoderWriteCallback write_callback,
  99422. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99423. FLAC__StreamDecoderErrorCallback error_callback,
  99424. void *client_data,
  99425. FLAC__bool is_ogg
  99426. )
  99427. {
  99428. FLAC__ASSERT(0 != decoder);
  99429. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99430. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99431. #if !FLAC__HAS_OGG
  99432. if(is_ogg)
  99433. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99434. #endif
  99435. if(
  99436. 0 == read_callback ||
  99437. 0 == write_callback ||
  99438. 0 == error_callback ||
  99439. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99440. )
  99441. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99442. #if FLAC__HAS_OGG
  99443. decoder->private_->is_ogg = is_ogg;
  99444. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99445. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99446. #endif
  99447. /*
  99448. * get the CPU info and set the function pointers
  99449. */
  99450. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99451. /* first default to the non-asm routines */
  99452. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99453. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99454. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99455. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99456. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99457. /* now override with asm where appropriate */
  99458. #ifndef FLAC__NO_ASM
  99459. if(decoder->private_->cpuinfo.use_asm) {
  99460. #ifdef FLAC__CPU_IA32
  99461. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99462. #ifdef FLAC__HAS_NASM
  99463. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99464. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99465. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99466. #endif
  99467. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99468. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99469. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99470. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99471. }
  99472. else {
  99473. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99474. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99475. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99476. }
  99477. #endif
  99478. #elif defined FLAC__CPU_PPC
  99479. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99480. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99481. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99482. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99483. }
  99484. #endif
  99485. }
  99486. #endif
  99487. /* from here on, errors are fatal */
  99488. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99489. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99490. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99491. }
  99492. decoder->private_->read_callback = read_callback;
  99493. decoder->private_->seek_callback = seek_callback;
  99494. decoder->private_->tell_callback = tell_callback;
  99495. decoder->private_->length_callback = length_callback;
  99496. decoder->private_->eof_callback = eof_callback;
  99497. decoder->private_->write_callback = write_callback;
  99498. decoder->private_->metadata_callback = metadata_callback;
  99499. decoder->private_->error_callback = error_callback;
  99500. decoder->private_->client_data = client_data;
  99501. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99502. decoder->private_->samples_decoded = 0;
  99503. decoder->private_->has_stream_info = false;
  99504. decoder->private_->cached = false;
  99505. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99506. decoder->private_->is_seeking = false;
  99507. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99508. if(!FLAC__stream_decoder_reset(decoder)) {
  99509. /* above call sets the state for us */
  99510. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99511. }
  99512. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99513. }
  99514. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99515. FLAC__StreamDecoder *decoder,
  99516. FLAC__StreamDecoderReadCallback read_callback,
  99517. FLAC__StreamDecoderSeekCallback seek_callback,
  99518. FLAC__StreamDecoderTellCallback tell_callback,
  99519. FLAC__StreamDecoderLengthCallback length_callback,
  99520. FLAC__StreamDecoderEofCallback eof_callback,
  99521. FLAC__StreamDecoderWriteCallback write_callback,
  99522. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99523. FLAC__StreamDecoderErrorCallback error_callback,
  99524. void *client_data
  99525. )
  99526. {
  99527. return init_stream_internal_dec(
  99528. decoder,
  99529. read_callback,
  99530. seek_callback,
  99531. tell_callback,
  99532. length_callback,
  99533. eof_callback,
  99534. write_callback,
  99535. metadata_callback,
  99536. error_callback,
  99537. client_data,
  99538. /*is_ogg=*/false
  99539. );
  99540. }
  99541. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99542. FLAC__StreamDecoder *decoder,
  99543. FLAC__StreamDecoderReadCallback read_callback,
  99544. FLAC__StreamDecoderSeekCallback seek_callback,
  99545. FLAC__StreamDecoderTellCallback tell_callback,
  99546. FLAC__StreamDecoderLengthCallback length_callback,
  99547. FLAC__StreamDecoderEofCallback eof_callback,
  99548. FLAC__StreamDecoderWriteCallback write_callback,
  99549. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99550. FLAC__StreamDecoderErrorCallback error_callback,
  99551. void *client_data
  99552. )
  99553. {
  99554. return init_stream_internal_dec(
  99555. decoder,
  99556. read_callback,
  99557. seek_callback,
  99558. tell_callback,
  99559. length_callback,
  99560. eof_callback,
  99561. write_callback,
  99562. metadata_callback,
  99563. error_callback,
  99564. client_data,
  99565. /*is_ogg=*/true
  99566. );
  99567. }
  99568. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99569. FLAC__StreamDecoder *decoder,
  99570. FILE *file,
  99571. FLAC__StreamDecoderWriteCallback write_callback,
  99572. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99573. FLAC__StreamDecoderErrorCallback error_callback,
  99574. void *client_data,
  99575. FLAC__bool is_ogg
  99576. )
  99577. {
  99578. FLAC__ASSERT(0 != decoder);
  99579. FLAC__ASSERT(0 != file);
  99580. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99581. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99582. if(0 == write_callback || 0 == error_callback)
  99583. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99584. /*
  99585. * To make sure that our file does not go unclosed after an error, we
  99586. * must assign the FILE pointer before any further error can occur in
  99587. * this routine.
  99588. */
  99589. if(file == stdin)
  99590. file = get_binary_stdin_(); /* just to be safe */
  99591. decoder->private_->file = file;
  99592. return init_stream_internal_dec(
  99593. decoder,
  99594. file_read_callback_dec,
  99595. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99596. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99597. decoder->private_->file == stdin? 0: file_length_callback_,
  99598. file_eof_callback_,
  99599. write_callback,
  99600. metadata_callback,
  99601. error_callback,
  99602. client_data,
  99603. is_ogg
  99604. );
  99605. }
  99606. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99607. FLAC__StreamDecoder *decoder,
  99608. FILE *file,
  99609. FLAC__StreamDecoderWriteCallback write_callback,
  99610. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99611. FLAC__StreamDecoderErrorCallback error_callback,
  99612. void *client_data
  99613. )
  99614. {
  99615. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99616. }
  99617. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99618. FLAC__StreamDecoder *decoder,
  99619. FILE *file,
  99620. FLAC__StreamDecoderWriteCallback write_callback,
  99621. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99622. FLAC__StreamDecoderErrorCallback error_callback,
  99623. void *client_data
  99624. )
  99625. {
  99626. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99627. }
  99628. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99629. FLAC__StreamDecoder *decoder,
  99630. const char *filename,
  99631. FLAC__StreamDecoderWriteCallback write_callback,
  99632. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99633. FLAC__StreamDecoderErrorCallback error_callback,
  99634. void *client_data,
  99635. FLAC__bool is_ogg
  99636. )
  99637. {
  99638. FILE *file;
  99639. FLAC__ASSERT(0 != decoder);
  99640. /*
  99641. * To make sure that our file does not go unclosed after an error, we
  99642. * have to do the same entrance checks here that are later performed
  99643. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99644. */
  99645. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99646. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99647. if(0 == write_callback || 0 == error_callback)
  99648. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99649. file = filename? fopen(filename, "rb") : stdin;
  99650. if(0 == file)
  99651. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99652. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99653. }
  99654. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99655. FLAC__StreamDecoder *decoder,
  99656. const char *filename,
  99657. FLAC__StreamDecoderWriteCallback write_callback,
  99658. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99659. FLAC__StreamDecoderErrorCallback error_callback,
  99660. void *client_data
  99661. )
  99662. {
  99663. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99664. }
  99665. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99666. FLAC__StreamDecoder *decoder,
  99667. const char *filename,
  99668. FLAC__StreamDecoderWriteCallback write_callback,
  99669. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99670. FLAC__StreamDecoderErrorCallback error_callback,
  99671. void *client_data
  99672. )
  99673. {
  99674. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99675. }
  99676. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99677. {
  99678. FLAC__bool md5_failed = false;
  99679. unsigned i;
  99680. FLAC__ASSERT(0 != decoder);
  99681. FLAC__ASSERT(0 != decoder->private_);
  99682. FLAC__ASSERT(0 != decoder->protected_);
  99683. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99684. return true;
  99685. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99686. * always call FLAC__MD5Final()
  99687. */
  99688. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99689. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99690. free(decoder->private_->seek_table.data.seek_table.points);
  99691. decoder->private_->seek_table.data.seek_table.points = 0;
  99692. decoder->private_->has_seek_table = false;
  99693. }
  99694. FLAC__bitreader_free(decoder->private_->input);
  99695. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99696. /* WATCHOUT:
  99697. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99698. * output arrays have a buffer of up to 3 zeroes in front
  99699. * (at negative indices) for alignment purposes; we use 4
  99700. * to keep the data well-aligned.
  99701. */
  99702. if(0 != decoder->private_->output[i]) {
  99703. free(decoder->private_->output[i]-4);
  99704. decoder->private_->output[i] = 0;
  99705. }
  99706. if(0 != decoder->private_->residual_unaligned[i]) {
  99707. free(decoder->private_->residual_unaligned[i]);
  99708. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99709. }
  99710. }
  99711. decoder->private_->output_capacity = 0;
  99712. decoder->private_->output_channels = 0;
  99713. #if FLAC__HAS_OGG
  99714. if(decoder->private_->is_ogg)
  99715. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99716. #endif
  99717. if(0 != decoder->private_->file) {
  99718. if(decoder->private_->file != stdin)
  99719. fclose(decoder->private_->file);
  99720. decoder->private_->file = 0;
  99721. }
  99722. if(decoder->private_->do_md5_checking) {
  99723. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99724. md5_failed = true;
  99725. }
  99726. decoder->private_->is_seeking = false;
  99727. set_defaults_dec(decoder);
  99728. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99729. return !md5_failed;
  99730. }
  99731. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99732. {
  99733. FLAC__ASSERT(0 != decoder);
  99734. FLAC__ASSERT(0 != decoder->private_);
  99735. FLAC__ASSERT(0 != decoder->protected_);
  99736. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99737. return false;
  99738. #if FLAC__HAS_OGG
  99739. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99740. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99741. return true;
  99742. #else
  99743. (void)value;
  99744. return false;
  99745. #endif
  99746. }
  99747. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99748. {
  99749. FLAC__ASSERT(0 != decoder);
  99750. FLAC__ASSERT(0 != decoder->protected_);
  99751. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99752. return false;
  99753. decoder->protected_->md5_checking = value;
  99754. return true;
  99755. }
  99756. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99757. {
  99758. FLAC__ASSERT(0 != decoder);
  99759. FLAC__ASSERT(0 != decoder->private_);
  99760. FLAC__ASSERT(0 != decoder->protected_);
  99761. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99762. /* double protection */
  99763. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99764. return false;
  99765. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99766. return false;
  99767. decoder->private_->metadata_filter[type] = true;
  99768. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99769. decoder->private_->metadata_filter_ids_count = 0;
  99770. return true;
  99771. }
  99772. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99773. {
  99774. FLAC__ASSERT(0 != decoder);
  99775. FLAC__ASSERT(0 != decoder->private_);
  99776. FLAC__ASSERT(0 != decoder->protected_);
  99777. FLAC__ASSERT(0 != id);
  99778. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99779. return false;
  99780. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99781. return true;
  99782. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99783. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99784. 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))) {
  99785. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99786. return false;
  99787. }
  99788. decoder->private_->metadata_filter_ids_capacity *= 2;
  99789. }
  99790. 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));
  99791. decoder->private_->metadata_filter_ids_count++;
  99792. return true;
  99793. }
  99794. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99795. {
  99796. unsigned i;
  99797. FLAC__ASSERT(0 != decoder);
  99798. FLAC__ASSERT(0 != decoder->private_);
  99799. FLAC__ASSERT(0 != decoder->protected_);
  99800. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99801. return false;
  99802. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99803. decoder->private_->metadata_filter[i] = true;
  99804. decoder->private_->metadata_filter_ids_count = 0;
  99805. return true;
  99806. }
  99807. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99808. {
  99809. FLAC__ASSERT(0 != decoder);
  99810. FLAC__ASSERT(0 != decoder->private_);
  99811. FLAC__ASSERT(0 != decoder->protected_);
  99812. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99813. /* double protection */
  99814. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99815. return false;
  99816. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99817. return false;
  99818. decoder->private_->metadata_filter[type] = false;
  99819. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99820. decoder->private_->metadata_filter_ids_count = 0;
  99821. return true;
  99822. }
  99823. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99824. {
  99825. FLAC__ASSERT(0 != decoder);
  99826. FLAC__ASSERT(0 != decoder->private_);
  99827. FLAC__ASSERT(0 != decoder->protected_);
  99828. FLAC__ASSERT(0 != id);
  99829. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99830. return false;
  99831. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99832. return true;
  99833. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99834. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99835. 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))) {
  99836. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99837. return false;
  99838. }
  99839. decoder->private_->metadata_filter_ids_capacity *= 2;
  99840. }
  99841. 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));
  99842. decoder->private_->metadata_filter_ids_count++;
  99843. return true;
  99844. }
  99845. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99846. {
  99847. FLAC__ASSERT(0 != decoder);
  99848. FLAC__ASSERT(0 != decoder->private_);
  99849. FLAC__ASSERT(0 != decoder->protected_);
  99850. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99851. return false;
  99852. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99853. decoder->private_->metadata_filter_ids_count = 0;
  99854. return true;
  99855. }
  99856. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99857. {
  99858. FLAC__ASSERT(0 != decoder);
  99859. FLAC__ASSERT(0 != decoder->protected_);
  99860. return decoder->protected_->state;
  99861. }
  99862. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99863. {
  99864. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99865. }
  99866. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99867. {
  99868. FLAC__ASSERT(0 != decoder);
  99869. FLAC__ASSERT(0 != decoder->protected_);
  99870. return decoder->protected_->md5_checking;
  99871. }
  99872. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99873. {
  99874. FLAC__ASSERT(0 != decoder);
  99875. FLAC__ASSERT(0 != decoder->protected_);
  99876. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99877. }
  99878. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99879. {
  99880. FLAC__ASSERT(0 != decoder);
  99881. FLAC__ASSERT(0 != decoder->protected_);
  99882. return decoder->protected_->channels;
  99883. }
  99884. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99885. {
  99886. FLAC__ASSERT(0 != decoder);
  99887. FLAC__ASSERT(0 != decoder->protected_);
  99888. return decoder->protected_->channel_assignment;
  99889. }
  99890. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99891. {
  99892. FLAC__ASSERT(0 != decoder);
  99893. FLAC__ASSERT(0 != decoder->protected_);
  99894. return decoder->protected_->bits_per_sample;
  99895. }
  99896. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99897. {
  99898. FLAC__ASSERT(0 != decoder);
  99899. FLAC__ASSERT(0 != decoder->protected_);
  99900. return decoder->protected_->sample_rate;
  99901. }
  99902. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99903. {
  99904. FLAC__ASSERT(0 != decoder);
  99905. FLAC__ASSERT(0 != decoder->protected_);
  99906. return decoder->protected_->blocksize;
  99907. }
  99908. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99909. {
  99910. FLAC__ASSERT(0 != decoder);
  99911. FLAC__ASSERT(0 != decoder->private_);
  99912. FLAC__ASSERT(0 != position);
  99913. #if FLAC__HAS_OGG
  99914. if(decoder->private_->is_ogg)
  99915. return false;
  99916. #endif
  99917. if(0 == decoder->private_->tell_callback)
  99918. return false;
  99919. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99920. return false;
  99921. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99922. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99923. return false;
  99924. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99925. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99926. return true;
  99927. }
  99928. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99929. {
  99930. FLAC__ASSERT(0 != decoder);
  99931. FLAC__ASSERT(0 != decoder->private_);
  99932. FLAC__ASSERT(0 != decoder->protected_);
  99933. decoder->private_->samples_decoded = 0;
  99934. decoder->private_->do_md5_checking = false;
  99935. #if FLAC__HAS_OGG
  99936. if(decoder->private_->is_ogg)
  99937. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99938. #endif
  99939. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99940. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99941. return false;
  99942. }
  99943. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99944. return true;
  99945. }
  99946. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99947. {
  99948. FLAC__ASSERT(0 != decoder);
  99949. FLAC__ASSERT(0 != decoder->private_);
  99950. FLAC__ASSERT(0 != decoder->protected_);
  99951. if(!FLAC__stream_decoder_flush(decoder)) {
  99952. /* above call sets the state for us */
  99953. return false;
  99954. }
  99955. #if FLAC__HAS_OGG
  99956. /*@@@ could go in !internal_reset_hack block below */
  99957. if(decoder->private_->is_ogg)
  99958. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99959. #endif
  99960. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99961. * (internal_reset_hack) don't try to rewind since we are already at
  99962. * the beginning of the stream and don't want to fail if the input is
  99963. * not seekable.
  99964. */
  99965. if(!decoder->private_->internal_reset_hack) {
  99966. if(decoder->private_->file == stdin)
  99967. return false; /* can't rewind stdin, reset fails */
  99968. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99969. return false; /* seekable and seek fails, reset fails */
  99970. }
  99971. else
  99972. decoder->private_->internal_reset_hack = false;
  99973. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99974. decoder->private_->has_stream_info = false;
  99975. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99976. free(decoder->private_->seek_table.data.seek_table.points);
  99977. decoder->private_->seek_table.data.seek_table.points = 0;
  99978. decoder->private_->has_seek_table = false;
  99979. }
  99980. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99981. /*
  99982. * This goes in reset() and not flush() because according to the spec, a
  99983. * fixed-blocksize stream must stay that way through the whole stream.
  99984. */
  99985. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99986. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99987. * is because md5 checking may be turned on to start and then turned off if
  99988. * a seek occurs. So we init the context here and finalize it in
  99989. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99990. * properly.
  99991. */
  99992. FLAC__MD5Init(&decoder->private_->md5context);
  99993. decoder->private_->first_frame_offset = 0;
  99994. decoder->private_->unparseable_frame_count = 0;
  99995. return true;
  99996. }
  99997. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99998. {
  99999. FLAC__bool got_a_frame;
  100000. FLAC__ASSERT(0 != decoder);
  100001. FLAC__ASSERT(0 != decoder->protected_);
  100002. while(1) {
  100003. switch(decoder->protected_->state) {
  100004. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100005. if(!find_metadata_(decoder))
  100006. return false; /* above function sets the status for us */
  100007. break;
  100008. case FLAC__STREAM_DECODER_READ_METADATA:
  100009. if(!read_metadata_(decoder))
  100010. return false; /* above function sets the status for us */
  100011. else
  100012. return true;
  100013. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100014. if(!frame_sync_(decoder))
  100015. return true; /* above function sets the status for us */
  100016. break;
  100017. case FLAC__STREAM_DECODER_READ_FRAME:
  100018. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  100019. return false; /* above function sets the status for us */
  100020. if(got_a_frame)
  100021. return true; /* above function sets the status for us */
  100022. break;
  100023. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100024. case FLAC__STREAM_DECODER_ABORTED:
  100025. return true;
  100026. default:
  100027. FLAC__ASSERT(0);
  100028. return false;
  100029. }
  100030. }
  100031. }
  100032. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100033. {
  100034. FLAC__ASSERT(0 != decoder);
  100035. FLAC__ASSERT(0 != decoder->protected_);
  100036. while(1) {
  100037. switch(decoder->protected_->state) {
  100038. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100039. if(!find_metadata_(decoder))
  100040. return false; /* above function sets the status for us */
  100041. break;
  100042. case FLAC__STREAM_DECODER_READ_METADATA:
  100043. if(!read_metadata_(decoder))
  100044. return false; /* above function sets the status for us */
  100045. break;
  100046. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100047. case FLAC__STREAM_DECODER_READ_FRAME:
  100048. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100049. case FLAC__STREAM_DECODER_ABORTED:
  100050. return true;
  100051. default:
  100052. FLAC__ASSERT(0);
  100053. return false;
  100054. }
  100055. }
  100056. }
  100057. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100058. {
  100059. FLAC__bool dummy;
  100060. FLAC__ASSERT(0 != decoder);
  100061. FLAC__ASSERT(0 != decoder->protected_);
  100062. while(1) {
  100063. switch(decoder->protected_->state) {
  100064. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100065. if(!find_metadata_(decoder))
  100066. return false; /* above function sets the status for us */
  100067. break;
  100068. case FLAC__STREAM_DECODER_READ_METADATA:
  100069. if(!read_metadata_(decoder))
  100070. return false; /* above function sets the status for us */
  100071. break;
  100072. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100073. if(!frame_sync_(decoder))
  100074. return true; /* above function sets the status for us */
  100075. break;
  100076. case FLAC__STREAM_DECODER_READ_FRAME:
  100077. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100078. return false; /* above function sets the status for us */
  100079. break;
  100080. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100081. case FLAC__STREAM_DECODER_ABORTED:
  100082. return true;
  100083. default:
  100084. FLAC__ASSERT(0);
  100085. return false;
  100086. }
  100087. }
  100088. }
  100089. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100090. {
  100091. FLAC__bool got_a_frame;
  100092. FLAC__ASSERT(0 != decoder);
  100093. FLAC__ASSERT(0 != decoder->protected_);
  100094. while(1) {
  100095. switch(decoder->protected_->state) {
  100096. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100097. case FLAC__STREAM_DECODER_READ_METADATA:
  100098. return false; /* above function sets the status for us */
  100099. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100100. if(!frame_sync_(decoder))
  100101. return true; /* above function sets the status for us */
  100102. break;
  100103. case FLAC__STREAM_DECODER_READ_FRAME:
  100104. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100105. return false; /* above function sets the status for us */
  100106. if(got_a_frame)
  100107. return true; /* above function sets the status for us */
  100108. break;
  100109. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100110. case FLAC__STREAM_DECODER_ABORTED:
  100111. return true;
  100112. default:
  100113. FLAC__ASSERT(0);
  100114. return false;
  100115. }
  100116. }
  100117. }
  100118. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100119. {
  100120. FLAC__uint64 length;
  100121. FLAC__ASSERT(0 != decoder);
  100122. if(
  100123. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100124. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100125. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100126. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100127. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100128. )
  100129. return false;
  100130. if(0 == decoder->private_->seek_callback)
  100131. return false;
  100132. FLAC__ASSERT(decoder->private_->seek_callback);
  100133. FLAC__ASSERT(decoder->private_->tell_callback);
  100134. FLAC__ASSERT(decoder->private_->length_callback);
  100135. FLAC__ASSERT(decoder->private_->eof_callback);
  100136. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100137. return false;
  100138. decoder->private_->is_seeking = true;
  100139. /* turn off md5 checking if a seek is attempted */
  100140. decoder->private_->do_md5_checking = false;
  100141. /* 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) */
  100142. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100143. decoder->private_->is_seeking = false;
  100144. return false;
  100145. }
  100146. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100147. if(
  100148. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100149. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100150. ) {
  100151. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100152. /* above call sets the state for us */
  100153. decoder->private_->is_seeking = false;
  100154. return false;
  100155. }
  100156. /* check this again in case we didn't know total_samples the first time */
  100157. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100158. decoder->private_->is_seeking = false;
  100159. return false;
  100160. }
  100161. }
  100162. {
  100163. const FLAC__bool ok =
  100164. #if FLAC__HAS_OGG
  100165. decoder->private_->is_ogg?
  100166. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100167. #endif
  100168. seek_to_absolute_sample_(decoder, length, sample)
  100169. ;
  100170. decoder->private_->is_seeking = false;
  100171. return ok;
  100172. }
  100173. }
  100174. /***********************************************************************
  100175. *
  100176. * Protected class methods
  100177. *
  100178. ***********************************************************************/
  100179. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100180. {
  100181. FLAC__ASSERT(0 != decoder);
  100182. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100183. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100184. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100185. }
  100186. /***********************************************************************
  100187. *
  100188. * Private class methods
  100189. *
  100190. ***********************************************************************/
  100191. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100192. {
  100193. #if FLAC__HAS_OGG
  100194. decoder->private_->is_ogg = false;
  100195. #endif
  100196. decoder->private_->read_callback = 0;
  100197. decoder->private_->seek_callback = 0;
  100198. decoder->private_->tell_callback = 0;
  100199. decoder->private_->length_callback = 0;
  100200. decoder->private_->eof_callback = 0;
  100201. decoder->private_->write_callback = 0;
  100202. decoder->private_->metadata_callback = 0;
  100203. decoder->private_->error_callback = 0;
  100204. decoder->private_->client_data = 0;
  100205. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100206. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100207. decoder->private_->metadata_filter_ids_count = 0;
  100208. decoder->protected_->md5_checking = false;
  100209. #if FLAC__HAS_OGG
  100210. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100211. #endif
  100212. }
  100213. /*
  100214. * This will forcibly set stdin to binary mode (for OSes that require it)
  100215. */
  100216. FILE *get_binary_stdin_(void)
  100217. {
  100218. /* if something breaks here it is probably due to the presence or
  100219. * absence of an underscore before the identifiers 'setmode',
  100220. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100221. */
  100222. #if defined _MSC_VER || defined __MINGW32__
  100223. _setmode(_fileno(stdin), _O_BINARY);
  100224. #elif defined __CYGWIN__
  100225. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100226. setmode(_fileno(stdin), _O_BINARY);
  100227. #elif defined __EMX__
  100228. setmode(fileno(stdin), O_BINARY);
  100229. #endif
  100230. return stdin;
  100231. }
  100232. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100233. {
  100234. unsigned i;
  100235. FLAC__int32 *tmp;
  100236. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100237. return true;
  100238. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100239. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100240. if(0 != decoder->private_->output[i]) {
  100241. free(decoder->private_->output[i]-4);
  100242. decoder->private_->output[i] = 0;
  100243. }
  100244. if(0 != decoder->private_->residual_unaligned[i]) {
  100245. free(decoder->private_->residual_unaligned[i]);
  100246. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100247. }
  100248. }
  100249. for(i = 0; i < channels; i++) {
  100250. /* WATCHOUT:
  100251. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100252. * output arrays have a buffer of up to 3 zeroes in front
  100253. * (at negative indices) for alignment purposes; we use 4
  100254. * to keep the data well-aligned.
  100255. */
  100256. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100257. if(tmp == 0) {
  100258. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100259. return false;
  100260. }
  100261. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100262. decoder->private_->output[i] = tmp + 4;
  100263. /* WATCHOUT:
  100264. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100265. */
  100266. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100267. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100268. return false;
  100269. }
  100270. }
  100271. decoder->private_->output_capacity = size;
  100272. decoder->private_->output_channels = channels;
  100273. return true;
  100274. }
  100275. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100276. {
  100277. size_t i;
  100278. FLAC__ASSERT(0 != decoder);
  100279. FLAC__ASSERT(0 != decoder->private_);
  100280. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100281. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100282. return true;
  100283. return false;
  100284. }
  100285. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100286. {
  100287. FLAC__uint32 x;
  100288. unsigned i, id_;
  100289. FLAC__bool first = true;
  100290. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100291. for(i = id_ = 0; i < 4; ) {
  100292. if(decoder->private_->cached) {
  100293. x = (FLAC__uint32)decoder->private_->lookahead;
  100294. decoder->private_->cached = false;
  100295. }
  100296. else {
  100297. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100298. return false; /* read_callback_ sets the state for us */
  100299. }
  100300. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100301. first = true;
  100302. i++;
  100303. id_ = 0;
  100304. continue;
  100305. }
  100306. if(x == ID3V2_TAG_[id_]) {
  100307. id_++;
  100308. i = 0;
  100309. if(id_ == 3) {
  100310. if(!skip_id3v2_tag_(decoder))
  100311. return false; /* skip_id3v2_tag_ sets the state for us */
  100312. }
  100313. continue;
  100314. }
  100315. id_ = 0;
  100316. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100317. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100318. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100319. return false; /* read_callback_ sets the state for us */
  100320. /* 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 */
  100321. /* else we have to check if the second byte is the end of a sync code */
  100322. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100323. decoder->private_->lookahead = (FLAC__byte)x;
  100324. decoder->private_->cached = true;
  100325. }
  100326. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100327. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100328. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100329. return true;
  100330. }
  100331. }
  100332. i = 0;
  100333. if(first) {
  100334. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100335. first = false;
  100336. }
  100337. }
  100338. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100339. return true;
  100340. }
  100341. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100342. {
  100343. FLAC__bool is_last;
  100344. FLAC__uint32 i, x, type, length;
  100345. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100346. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100347. return false; /* read_callback_ sets the state for us */
  100348. is_last = x? true : false;
  100349. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100350. return false; /* read_callback_ sets the state for us */
  100351. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100352. return false; /* read_callback_ sets the state for us */
  100353. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100354. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100355. return false;
  100356. decoder->private_->has_stream_info = true;
  100357. 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))
  100358. decoder->private_->do_md5_checking = false;
  100359. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100360. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100361. }
  100362. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100363. if(!read_metadata_seektable_(decoder, is_last, length))
  100364. return false;
  100365. decoder->private_->has_seek_table = true;
  100366. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100367. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100368. }
  100369. else {
  100370. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100371. unsigned real_length = length;
  100372. FLAC__StreamMetadata block;
  100373. block.is_last = is_last;
  100374. block.type = (FLAC__MetadataType)type;
  100375. block.length = length;
  100376. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100377. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100378. return false; /* read_callback_ sets the state for us */
  100379. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100380. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100381. return false;
  100382. }
  100383. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100384. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100385. skip_it = !skip_it;
  100386. }
  100387. if(skip_it) {
  100388. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100389. return false; /* read_callback_ sets the state for us */
  100390. }
  100391. else {
  100392. switch(type) {
  100393. case FLAC__METADATA_TYPE_PADDING:
  100394. /* skip the padding bytes */
  100395. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100396. return false; /* read_callback_ sets the state for us */
  100397. break;
  100398. case FLAC__METADATA_TYPE_APPLICATION:
  100399. /* remember, we read the ID already */
  100400. if(real_length > 0) {
  100401. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100402. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100403. return false;
  100404. }
  100405. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100406. return false; /* read_callback_ sets the state for us */
  100407. }
  100408. else
  100409. block.data.application.data = 0;
  100410. break;
  100411. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100412. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100413. return false;
  100414. break;
  100415. case FLAC__METADATA_TYPE_CUESHEET:
  100416. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100417. return false;
  100418. break;
  100419. case FLAC__METADATA_TYPE_PICTURE:
  100420. if(!read_metadata_picture_(decoder, &block.data.picture))
  100421. return false;
  100422. break;
  100423. case FLAC__METADATA_TYPE_STREAMINFO:
  100424. case FLAC__METADATA_TYPE_SEEKTABLE:
  100425. FLAC__ASSERT(0);
  100426. break;
  100427. default:
  100428. if(real_length > 0) {
  100429. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100430. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100431. return false;
  100432. }
  100433. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100434. return false; /* read_callback_ sets the state for us */
  100435. }
  100436. else
  100437. block.data.unknown.data = 0;
  100438. break;
  100439. }
  100440. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100441. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100442. /* now we have to free any malloc()ed data in the block */
  100443. switch(type) {
  100444. case FLAC__METADATA_TYPE_PADDING:
  100445. break;
  100446. case FLAC__METADATA_TYPE_APPLICATION:
  100447. if(0 != block.data.application.data)
  100448. free(block.data.application.data);
  100449. break;
  100450. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100451. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100452. free(block.data.vorbis_comment.vendor_string.entry);
  100453. if(block.data.vorbis_comment.num_comments > 0)
  100454. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100455. if(0 != block.data.vorbis_comment.comments[i].entry)
  100456. free(block.data.vorbis_comment.comments[i].entry);
  100457. if(0 != block.data.vorbis_comment.comments)
  100458. free(block.data.vorbis_comment.comments);
  100459. break;
  100460. case FLAC__METADATA_TYPE_CUESHEET:
  100461. if(block.data.cue_sheet.num_tracks > 0)
  100462. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100463. if(0 != block.data.cue_sheet.tracks[i].indices)
  100464. free(block.data.cue_sheet.tracks[i].indices);
  100465. if(0 != block.data.cue_sheet.tracks)
  100466. free(block.data.cue_sheet.tracks);
  100467. break;
  100468. case FLAC__METADATA_TYPE_PICTURE:
  100469. if(0 != block.data.picture.mime_type)
  100470. free(block.data.picture.mime_type);
  100471. if(0 != block.data.picture.description)
  100472. free(block.data.picture.description);
  100473. if(0 != block.data.picture.data)
  100474. free(block.data.picture.data);
  100475. break;
  100476. case FLAC__METADATA_TYPE_STREAMINFO:
  100477. case FLAC__METADATA_TYPE_SEEKTABLE:
  100478. FLAC__ASSERT(0);
  100479. default:
  100480. if(0 != block.data.unknown.data)
  100481. free(block.data.unknown.data);
  100482. break;
  100483. }
  100484. }
  100485. }
  100486. if(is_last) {
  100487. /* if this fails, it's OK, it's just a hint for the seek routine */
  100488. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100489. decoder->private_->first_frame_offset = 0;
  100490. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100491. }
  100492. return true;
  100493. }
  100494. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100495. {
  100496. FLAC__uint32 x;
  100497. unsigned bits, used_bits = 0;
  100498. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100499. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100500. decoder->private_->stream_info.is_last = is_last;
  100501. decoder->private_->stream_info.length = length;
  100502. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100503. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100504. return false; /* read_callback_ sets the state for us */
  100505. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100506. used_bits += bits;
  100507. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100508. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100509. return false; /* read_callback_ sets the state for us */
  100510. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100511. used_bits += bits;
  100512. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100513. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100514. return false; /* read_callback_ sets the state for us */
  100515. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100516. used_bits += bits;
  100517. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100518. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100519. return false; /* read_callback_ sets the state for us */
  100520. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100521. used_bits += bits;
  100522. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100523. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100524. return false; /* read_callback_ sets the state for us */
  100525. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100526. used_bits += bits;
  100527. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100528. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100529. return false; /* read_callback_ sets the state for us */
  100530. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100531. used_bits += bits;
  100532. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100533. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100534. return false; /* read_callback_ sets the state for us */
  100535. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100536. used_bits += bits;
  100537. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100538. 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))
  100539. return false; /* read_callback_ sets the state for us */
  100540. used_bits += bits;
  100541. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100542. return false; /* read_callback_ sets the state for us */
  100543. used_bits += 16*8;
  100544. /* skip the rest of the block */
  100545. FLAC__ASSERT(used_bits % 8 == 0);
  100546. length -= (used_bits / 8);
  100547. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100548. return false; /* read_callback_ sets the state for us */
  100549. return true;
  100550. }
  100551. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100552. {
  100553. FLAC__uint32 i, x;
  100554. FLAC__uint64 xx;
  100555. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100556. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100557. decoder->private_->seek_table.is_last = is_last;
  100558. decoder->private_->seek_table.length = length;
  100559. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100560. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100561. 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)))) {
  100562. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100563. return false;
  100564. }
  100565. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100566. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100567. return false; /* read_callback_ sets the state for us */
  100568. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100569. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100570. return false; /* read_callback_ sets the state for us */
  100571. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100572. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100573. return false; /* read_callback_ sets the state for us */
  100574. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100575. }
  100576. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100577. /* if there is a partial point left, skip over it */
  100578. if(length > 0) {
  100579. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100580. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100581. return false; /* read_callback_ sets the state for us */
  100582. }
  100583. return true;
  100584. }
  100585. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100586. {
  100587. FLAC__uint32 i;
  100588. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100589. /* read vendor string */
  100590. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100591. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100592. return false; /* read_callback_ sets the state for us */
  100593. if(obj->vendor_string.length > 0) {
  100594. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100595. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100596. return false;
  100597. }
  100598. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100599. return false; /* read_callback_ sets the state for us */
  100600. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100601. }
  100602. else
  100603. obj->vendor_string.entry = 0;
  100604. /* read num comments */
  100605. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100606. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100607. return false; /* read_callback_ sets the state for us */
  100608. /* read comments */
  100609. if(obj->num_comments > 0) {
  100610. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100611. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100612. return false;
  100613. }
  100614. for(i = 0; i < obj->num_comments; i++) {
  100615. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100616. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100617. return false; /* read_callback_ sets the state for us */
  100618. if(obj->comments[i].length > 0) {
  100619. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100620. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100621. return false;
  100622. }
  100623. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100624. return false; /* read_callback_ sets the state for us */
  100625. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100626. }
  100627. else
  100628. obj->comments[i].entry = 0;
  100629. }
  100630. }
  100631. else {
  100632. obj->comments = 0;
  100633. }
  100634. return true;
  100635. }
  100636. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100637. {
  100638. FLAC__uint32 i, j, x;
  100639. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100640. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100641. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100642. 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))
  100643. return false; /* read_callback_ sets the state for us */
  100644. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100645. return false; /* read_callback_ sets the state for us */
  100646. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100647. return false; /* read_callback_ sets the state for us */
  100648. obj->is_cd = x? true : false;
  100649. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100650. return false; /* read_callback_ sets the state for us */
  100651. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100652. return false; /* read_callback_ sets the state for us */
  100653. obj->num_tracks = x;
  100654. if(obj->num_tracks > 0) {
  100655. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100656. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100657. return false;
  100658. }
  100659. for(i = 0; i < obj->num_tracks; i++) {
  100660. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100661. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100662. return false; /* read_callback_ sets the state for us */
  100663. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100664. return false; /* read_callback_ sets the state for us */
  100665. track->number = (FLAC__byte)x;
  100666. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100667. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100668. return false; /* read_callback_ sets the state for us */
  100669. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100670. return false; /* read_callback_ sets the state for us */
  100671. track->type = x;
  100672. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100673. return false; /* read_callback_ sets the state for us */
  100674. track->pre_emphasis = x;
  100675. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100676. return false; /* read_callback_ sets the state for us */
  100677. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100678. return false; /* read_callback_ sets the state for us */
  100679. track->num_indices = (FLAC__byte)x;
  100680. if(track->num_indices > 0) {
  100681. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100682. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100683. return false;
  100684. }
  100685. for(j = 0; j < track->num_indices; j++) {
  100686. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100687. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100688. return false; /* read_callback_ sets the state for us */
  100689. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100690. return false; /* read_callback_ sets the state for us */
  100691. index->number = (FLAC__byte)x;
  100692. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100693. return false; /* read_callback_ sets the state for us */
  100694. }
  100695. }
  100696. }
  100697. }
  100698. return true;
  100699. }
  100700. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100701. {
  100702. FLAC__uint32 x;
  100703. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100704. /* read type */
  100705. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100706. return false; /* read_callback_ sets the state for us */
  100707. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100708. /* read MIME type */
  100709. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100710. return false; /* read_callback_ sets the state for us */
  100711. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100712. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100713. return false;
  100714. }
  100715. if(x > 0) {
  100716. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100717. return false; /* read_callback_ sets the state for us */
  100718. }
  100719. obj->mime_type[x] = '\0';
  100720. /* read description */
  100721. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100722. return false; /* read_callback_ sets the state for us */
  100723. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100724. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100725. return false;
  100726. }
  100727. if(x > 0) {
  100728. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100729. return false; /* read_callback_ sets the state for us */
  100730. }
  100731. obj->description[x] = '\0';
  100732. /* read width */
  100733. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100734. return false; /* read_callback_ sets the state for us */
  100735. /* read height */
  100736. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100737. return false; /* read_callback_ sets the state for us */
  100738. /* read depth */
  100739. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100740. return false; /* read_callback_ sets the state for us */
  100741. /* read colors */
  100742. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100743. return false; /* read_callback_ sets the state for us */
  100744. /* read data */
  100745. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100746. return false; /* read_callback_ sets the state for us */
  100747. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100748. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100749. return false;
  100750. }
  100751. if(obj->data_length > 0) {
  100752. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100753. return false; /* read_callback_ sets the state for us */
  100754. }
  100755. return true;
  100756. }
  100757. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100758. {
  100759. FLAC__uint32 x;
  100760. unsigned i, skip;
  100761. /* skip the version and flags bytes */
  100762. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100763. return false; /* read_callback_ sets the state for us */
  100764. /* get the size (in bytes) to skip */
  100765. skip = 0;
  100766. for(i = 0; i < 4; i++) {
  100767. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100768. return false; /* read_callback_ sets the state for us */
  100769. skip <<= 7;
  100770. skip |= (x & 0x7f);
  100771. }
  100772. /* skip the rest of the tag */
  100773. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100774. return false; /* read_callback_ sets the state for us */
  100775. return true;
  100776. }
  100777. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100778. {
  100779. FLAC__uint32 x;
  100780. FLAC__bool first = true;
  100781. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100782. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100783. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100784. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100785. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100786. return true;
  100787. }
  100788. }
  100789. /* make sure we're byte aligned */
  100790. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100791. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100792. return false; /* read_callback_ sets the state for us */
  100793. }
  100794. while(1) {
  100795. if(decoder->private_->cached) {
  100796. x = (FLAC__uint32)decoder->private_->lookahead;
  100797. decoder->private_->cached = false;
  100798. }
  100799. else {
  100800. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100801. return false; /* read_callback_ sets the state for us */
  100802. }
  100803. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100804. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100805. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100806. return false; /* read_callback_ sets the state for us */
  100807. /* 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 */
  100808. /* else we have to check if the second byte is the end of a sync code */
  100809. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100810. decoder->private_->lookahead = (FLAC__byte)x;
  100811. decoder->private_->cached = true;
  100812. }
  100813. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100814. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100815. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100816. return true;
  100817. }
  100818. }
  100819. if(first) {
  100820. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100821. first = false;
  100822. }
  100823. }
  100824. return true;
  100825. }
  100826. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100827. {
  100828. unsigned channel;
  100829. unsigned i;
  100830. FLAC__int32 mid, side;
  100831. unsigned frame_crc; /* the one we calculate from the input stream */
  100832. FLAC__uint32 x;
  100833. *got_a_frame = false;
  100834. /* init the CRC */
  100835. frame_crc = 0;
  100836. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100837. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100838. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100839. if(!read_frame_header_(decoder))
  100840. return false;
  100841. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100842. return true;
  100843. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100844. return false;
  100845. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100846. /*
  100847. * first figure the correct bits-per-sample of the subframe
  100848. */
  100849. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100850. switch(decoder->private_->frame.header.channel_assignment) {
  100851. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100852. /* no adjustment needed */
  100853. break;
  100854. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100855. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100856. if(channel == 1)
  100857. bps++;
  100858. break;
  100859. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100860. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100861. if(channel == 0)
  100862. bps++;
  100863. break;
  100864. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100865. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100866. if(channel == 1)
  100867. bps++;
  100868. break;
  100869. default:
  100870. FLAC__ASSERT(0);
  100871. }
  100872. /*
  100873. * now read it
  100874. */
  100875. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100876. return false;
  100877. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100878. return true;
  100879. }
  100880. if(!read_zero_padding_(decoder))
  100881. return false;
  100882. 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) */
  100883. return true;
  100884. /*
  100885. * Read the frame CRC-16 from the footer and check
  100886. */
  100887. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100888. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100889. return false; /* read_callback_ sets the state for us */
  100890. if(frame_crc == x) {
  100891. if(do_full_decode) {
  100892. /* Undo any special channel coding */
  100893. switch(decoder->private_->frame.header.channel_assignment) {
  100894. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100895. /* do nothing */
  100896. break;
  100897. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100898. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100899. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100900. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100901. break;
  100902. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100903. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100904. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100905. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100906. break;
  100907. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100908. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100909. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100910. #if 1
  100911. mid = decoder->private_->output[0][i];
  100912. side = decoder->private_->output[1][i];
  100913. mid <<= 1;
  100914. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100915. decoder->private_->output[0][i] = (mid + side) >> 1;
  100916. decoder->private_->output[1][i] = (mid - side) >> 1;
  100917. #else
  100918. /* OPT: without 'side' temp variable */
  100919. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100920. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100921. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100922. #endif
  100923. }
  100924. break;
  100925. default:
  100926. FLAC__ASSERT(0);
  100927. break;
  100928. }
  100929. }
  100930. }
  100931. else {
  100932. /* Bad frame, emit error and zero the output signal */
  100933. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100934. if(do_full_decode) {
  100935. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100936. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100937. }
  100938. }
  100939. }
  100940. *got_a_frame = true;
  100941. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100942. if(decoder->private_->next_fixed_block_size)
  100943. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100944. /* put the latest values into the public section of the decoder instance */
  100945. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100946. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100947. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100948. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100949. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100950. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100951. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100952. /* write it */
  100953. if(do_full_decode) {
  100954. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100955. return false;
  100956. }
  100957. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100958. return true;
  100959. }
  100960. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100961. {
  100962. FLAC__uint32 x;
  100963. FLAC__uint64 xx;
  100964. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100965. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100966. unsigned raw_header_len;
  100967. FLAC__bool is_unparseable = false;
  100968. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100969. /* init the raw header with the saved bits from synchronization */
  100970. raw_header[0] = decoder->private_->header_warmup[0];
  100971. raw_header[1] = decoder->private_->header_warmup[1];
  100972. raw_header_len = 2;
  100973. /* check to make sure that reserved bit is 0 */
  100974. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100975. is_unparseable = true;
  100976. /*
  100977. * Note that along the way as we read the header, we look for a sync
  100978. * code inside. If we find one it would indicate that our original
  100979. * sync was bad since there cannot be a sync code in a valid header.
  100980. *
  100981. * Three kinds of things can go wrong when reading the frame header:
  100982. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100983. * If we don't find a sync code, it can end up looking like we read
  100984. * a valid but unparseable header, until getting to the frame header
  100985. * CRC. Even then we could get a false positive on the CRC.
  100986. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100987. * future encoder).
  100988. * 3) We may be on a damaged frame which appears valid but unparseable.
  100989. *
  100990. * For all these reasons, we try and read a complete frame header as
  100991. * long as it seems valid, even if unparseable, up until the frame
  100992. * header CRC.
  100993. */
  100994. /*
  100995. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100996. */
  100997. for(i = 0; i < 2; i++) {
  100998. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100999. return false; /* read_callback_ sets the state for us */
  101000. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101001. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  101002. decoder->private_->lookahead = (FLAC__byte)x;
  101003. decoder->private_->cached = true;
  101004. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101005. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101006. return true;
  101007. }
  101008. raw_header[raw_header_len++] = (FLAC__byte)x;
  101009. }
  101010. switch(x = raw_header[2] >> 4) {
  101011. case 0:
  101012. is_unparseable = true;
  101013. break;
  101014. case 1:
  101015. decoder->private_->frame.header.blocksize = 192;
  101016. break;
  101017. case 2:
  101018. case 3:
  101019. case 4:
  101020. case 5:
  101021. decoder->private_->frame.header.blocksize = 576 << (x-2);
  101022. break;
  101023. case 6:
  101024. case 7:
  101025. blocksize_hint = x;
  101026. break;
  101027. case 8:
  101028. case 9:
  101029. case 10:
  101030. case 11:
  101031. case 12:
  101032. case 13:
  101033. case 14:
  101034. case 15:
  101035. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101036. break;
  101037. default:
  101038. FLAC__ASSERT(0);
  101039. break;
  101040. }
  101041. switch(x = raw_header[2] & 0x0f) {
  101042. case 0:
  101043. if(decoder->private_->has_stream_info)
  101044. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101045. else
  101046. is_unparseable = true;
  101047. break;
  101048. case 1:
  101049. decoder->private_->frame.header.sample_rate = 88200;
  101050. break;
  101051. case 2:
  101052. decoder->private_->frame.header.sample_rate = 176400;
  101053. break;
  101054. case 3:
  101055. decoder->private_->frame.header.sample_rate = 192000;
  101056. break;
  101057. case 4:
  101058. decoder->private_->frame.header.sample_rate = 8000;
  101059. break;
  101060. case 5:
  101061. decoder->private_->frame.header.sample_rate = 16000;
  101062. break;
  101063. case 6:
  101064. decoder->private_->frame.header.sample_rate = 22050;
  101065. break;
  101066. case 7:
  101067. decoder->private_->frame.header.sample_rate = 24000;
  101068. break;
  101069. case 8:
  101070. decoder->private_->frame.header.sample_rate = 32000;
  101071. break;
  101072. case 9:
  101073. decoder->private_->frame.header.sample_rate = 44100;
  101074. break;
  101075. case 10:
  101076. decoder->private_->frame.header.sample_rate = 48000;
  101077. break;
  101078. case 11:
  101079. decoder->private_->frame.header.sample_rate = 96000;
  101080. break;
  101081. case 12:
  101082. case 13:
  101083. case 14:
  101084. sample_rate_hint = x;
  101085. break;
  101086. case 15:
  101087. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101088. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101089. return true;
  101090. default:
  101091. FLAC__ASSERT(0);
  101092. }
  101093. x = (unsigned)(raw_header[3] >> 4);
  101094. if(x & 8) {
  101095. decoder->private_->frame.header.channels = 2;
  101096. switch(x & 7) {
  101097. case 0:
  101098. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101099. break;
  101100. case 1:
  101101. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101102. break;
  101103. case 2:
  101104. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101105. break;
  101106. default:
  101107. is_unparseable = true;
  101108. break;
  101109. }
  101110. }
  101111. else {
  101112. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101113. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101114. }
  101115. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101116. case 0:
  101117. if(decoder->private_->has_stream_info)
  101118. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101119. else
  101120. is_unparseable = true;
  101121. break;
  101122. case 1:
  101123. decoder->private_->frame.header.bits_per_sample = 8;
  101124. break;
  101125. case 2:
  101126. decoder->private_->frame.header.bits_per_sample = 12;
  101127. break;
  101128. case 4:
  101129. decoder->private_->frame.header.bits_per_sample = 16;
  101130. break;
  101131. case 5:
  101132. decoder->private_->frame.header.bits_per_sample = 20;
  101133. break;
  101134. case 6:
  101135. decoder->private_->frame.header.bits_per_sample = 24;
  101136. break;
  101137. case 3:
  101138. case 7:
  101139. is_unparseable = true;
  101140. break;
  101141. default:
  101142. FLAC__ASSERT(0);
  101143. break;
  101144. }
  101145. /* check to make sure that reserved bit is 0 */
  101146. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101147. is_unparseable = true;
  101148. /* read the frame's starting sample number (or frame number as the case may be) */
  101149. if(
  101150. raw_header[1] & 0x01 ||
  101151. /*@@@ 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 */
  101152. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101153. ) { /* variable blocksize */
  101154. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101155. return false; /* read_callback_ sets the state for us */
  101156. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101157. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101158. decoder->private_->cached = true;
  101159. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101160. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101161. return true;
  101162. }
  101163. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101164. decoder->private_->frame.header.number.sample_number = xx;
  101165. }
  101166. else { /* fixed blocksize */
  101167. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101168. return false; /* read_callback_ sets the state for us */
  101169. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101170. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101171. decoder->private_->cached = true;
  101172. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101173. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101174. return true;
  101175. }
  101176. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101177. decoder->private_->frame.header.number.frame_number = x;
  101178. }
  101179. if(blocksize_hint) {
  101180. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101181. return false; /* read_callback_ sets the state for us */
  101182. raw_header[raw_header_len++] = (FLAC__byte)x;
  101183. if(blocksize_hint == 7) {
  101184. FLAC__uint32 _x;
  101185. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101186. return false; /* read_callback_ sets the state for us */
  101187. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101188. x = (x << 8) | _x;
  101189. }
  101190. decoder->private_->frame.header.blocksize = x+1;
  101191. }
  101192. if(sample_rate_hint) {
  101193. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101194. return false; /* read_callback_ sets the state for us */
  101195. raw_header[raw_header_len++] = (FLAC__byte)x;
  101196. if(sample_rate_hint != 12) {
  101197. FLAC__uint32 _x;
  101198. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101199. return false; /* read_callback_ sets the state for us */
  101200. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101201. x = (x << 8) | _x;
  101202. }
  101203. if(sample_rate_hint == 12)
  101204. decoder->private_->frame.header.sample_rate = x*1000;
  101205. else if(sample_rate_hint == 13)
  101206. decoder->private_->frame.header.sample_rate = x;
  101207. else
  101208. decoder->private_->frame.header.sample_rate = x*10;
  101209. }
  101210. /* read the CRC-8 byte */
  101211. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101212. return false; /* read_callback_ sets the state for us */
  101213. crc8 = (FLAC__byte)x;
  101214. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101215. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101216. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101217. return true;
  101218. }
  101219. /* calculate the sample number from the frame number if needed */
  101220. decoder->private_->next_fixed_block_size = 0;
  101221. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101222. x = decoder->private_->frame.header.number.frame_number;
  101223. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101224. if(decoder->private_->fixed_block_size)
  101225. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101226. else if(decoder->private_->has_stream_info) {
  101227. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101228. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101229. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101230. }
  101231. else
  101232. is_unparseable = true;
  101233. }
  101234. else if(x == 0) {
  101235. decoder->private_->frame.header.number.sample_number = 0;
  101236. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101237. }
  101238. else {
  101239. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101240. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101241. }
  101242. }
  101243. if(is_unparseable) {
  101244. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101245. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101246. return true;
  101247. }
  101248. return true;
  101249. }
  101250. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101251. {
  101252. FLAC__uint32 x;
  101253. FLAC__bool wasted_bits;
  101254. unsigned i;
  101255. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101256. return false; /* read_callback_ sets the state for us */
  101257. wasted_bits = (x & 1);
  101258. x &= 0xfe;
  101259. if(wasted_bits) {
  101260. unsigned u;
  101261. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101262. return false; /* read_callback_ sets the state for us */
  101263. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101264. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101265. }
  101266. else
  101267. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101268. /*
  101269. * Lots of magic numbers here
  101270. */
  101271. if(x & 0x80) {
  101272. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101273. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101274. return true;
  101275. }
  101276. else if(x == 0) {
  101277. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101278. return false;
  101279. }
  101280. else if(x == 2) {
  101281. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101282. return false;
  101283. }
  101284. else if(x < 16) {
  101285. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101286. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101287. return true;
  101288. }
  101289. else if(x <= 24) {
  101290. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101291. return false;
  101292. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101293. return true;
  101294. }
  101295. else if(x < 64) {
  101296. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101297. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101298. return true;
  101299. }
  101300. else {
  101301. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101302. return false;
  101303. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101304. return true;
  101305. }
  101306. if(wasted_bits && do_full_decode) {
  101307. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101308. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101309. decoder->private_->output[channel][i] <<= x;
  101310. }
  101311. return true;
  101312. }
  101313. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101314. {
  101315. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101316. FLAC__int32 x;
  101317. unsigned i;
  101318. FLAC__int32 *output = decoder->private_->output[channel];
  101319. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101320. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101321. return false; /* read_callback_ sets the state for us */
  101322. subframe->value = x;
  101323. /* decode the subframe */
  101324. if(do_full_decode) {
  101325. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101326. output[i] = x;
  101327. }
  101328. return true;
  101329. }
  101330. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101331. {
  101332. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101333. FLAC__int32 i32;
  101334. FLAC__uint32 u32;
  101335. unsigned u;
  101336. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101337. subframe->residual = decoder->private_->residual[channel];
  101338. subframe->order = order;
  101339. /* read warm-up samples */
  101340. for(u = 0; u < order; u++) {
  101341. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101342. return false; /* read_callback_ sets the state for us */
  101343. subframe->warmup[u] = i32;
  101344. }
  101345. /* read entropy coding method info */
  101346. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101347. return false; /* read_callback_ sets the state for us */
  101348. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101349. switch(subframe->entropy_coding_method.type) {
  101350. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101351. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101352. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101353. return false; /* read_callback_ sets the state for us */
  101354. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101355. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101356. break;
  101357. default:
  101358. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101359. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101360. return true;
  101361. }
  101362. /* read residual */
  101363. switch(subframe->entropy_coding_method.type) {
  101364. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101365. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101366. 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))
  101367. return false;
  101368. break;
  101369. default:
  101370. FLAC__ASSERT(0);
  101371. }
  101372. /* decode the subframe */
  101373. if(do_full_decode) {
  101374. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101375. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101376. }
  101377. return true;
  101378. }
  101379. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101380. {
  101381. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101382. FLAC__int32 i32;
  101383. FLAC__uint32 u32;
  101384. unsigned u;
  101385. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101386. subframe->residual = decoder->private_->residual[channel];
  101387. subframe->order = order;
  101388. /* read warm-up samples */
  101389. for(u = 0; u < order; u++) {
  101390. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101391. return false; /* read_callback_ sets the state for us */
  101392. subframe->warmup[u] = i32;
  101393. }
  101394. /* read qlp coeff precision */
  101395. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101396. return false; /* read_callback_ sets the state for us */
  101397. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101398. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101399. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101400. return true;
  101401. }
  101402. subframe->qlp_coeff_precision = u32+1;
  101403. /* read qlp shift */
  101404. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101405. return false; /* read_callback_ sets the state for us */
  101406. subframe->quantization_level = i32;
  101407. /* read quantized lp coefficiencts */
  101408. for(u = 0; u < order; u++) {
  101409. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101410. return false; /* read_callback_ sets the state for us */
  101411. subframe->qlp_coeff[u] = i32;
  101412. }
  101413. /* read entropy coding method info */
  101414. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101415. return false; /* read_callback_ sets the state for us */
  101416. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101417. switch(subframe->entropy_coding_method.type) {
  101418. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101419. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101420. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101421. return false; /* read_callback_ sets the state for us */
  101422. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101423. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101424. break;
  101425. default:
  101426. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101427. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101428. return true;
  101429. }
  101430. /* read residual */
  101431. switch(subframe->entropy_coding_method.type) {
  101432. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101433. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101434. 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))
  101435. return false;
  101436. break;
  101437. default:
  101438. FLAC__ASSERT(0);
  101439. }
  101440. /* decode the subframe */
  101441. if(do_full_decode) {
  101442. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101443. /*@@@@@@ technically not pessimistic enough, should be more like
  101444. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101445. */
  101446. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101447. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101448. if(order <= 8)
  101449. 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);
  101450. else
  101451. 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);
  101452. }
  101453. else
  101454. 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);
  101455. else
  101456. 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);
  101457. }
  101458. return true;
  101459. }
  101460. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101461. {
  101462. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101463. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101464. unsigned i;
  101465. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101466. subframe->data = residual;
  101467. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101468. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101469. return false; /* read_callback_ sets the state for us */
  101470. residual[i] = x;
  101471. }
  101472. /* decode the subframe */
  101473. if(do_full_decode)
  101474. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101475. return true;
  101476. }
  101477. 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)
  101478. {
  101479. FLAC__uint32 rice_parameter;
  101480. int i;
  101481. unsigned partition, sample, u;
  101482. const unsigned partitions = 1u << partition_order;
  101483. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101484. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101485. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101486. /* sanity checks */
  101487. if(partition_order == 0) {
  101488. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101489. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101490. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101491. return true;
  101492. }
  101493. }
  101494. else {
  101495. if(partition_samples < predictor_order) {
  101496. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101497. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101498. return true;
  101499. }
  101500. }
  101501. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101502. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101503. return false;
  101504. }
  101505. sample = 0;
  101506. for(partition = 0; partition < partitions; partition++) {
  101507. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101508. return false; /* read_callback_ sets the state for us */
  101509. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101510. if(rice_parameter < pesc) {
  101511. partitioned_rice_contents->raw_bits[partition] = 0;
  101512. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101513. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101514. return false; /* read_callback_ sets the state for us */
  101515. sample += u;
  101516. }
  101517. else {
  101518. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101519. return false; /* read_callback_ sets the state for us */
  101520. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101521. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101522. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101523. return false; /* read_callback_ sets the state for us */
  101524. residual[sample] = i;
  101525. }
  101526. }
  101527. }
  101528. return true;
  101529. }
  101530. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101531. {
  101532. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101533. FLAC__uint32 zero = 0;
  101534. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101535. return false; /* read_callback_ sets the state for us */
  101536. if(zero != 0) {
  101537. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101538. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101539. }
  101540. }
  101541. return true;
  101542. }
  101543. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101544. {
  101545. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101546. if(
  101547. #if FLAC__HAS_OGG
  101548. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101549. !decoder->private_->is_ogg &&
  101550. #endif
  101551. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101552. ) {
  101553. *bytes = 0;
  101554. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101555. return false;
  101556. }
  101557. else if(*bytes > 0) {
  101558. /* While seeking, it is possible for our seek to land in the
  101559. * middle of audio data that looks exactly like a frame header
  101560. * from a future version of an encoder. When that happens, our
  101561. * error callback will get an
  101562. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101563. * unparseable_frame_count. But there is a remote possibility
  101564. * that it is properly synced at such a "future-codec frame",
  101565. * so to make sure, we wait to see many "unparseable" errors in
  101566. * a row before bailing out.
  101567. */
  101568. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101569. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101570. return false;
  101571. }
  101572. else {
  101573. const FLAC__StreamDecoderReadStatus status =
  101574. #if FLAC__HAS_OGG
  101575. decoder->private_->is_ogg?
  101576. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101577. #endif
  101578. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101579. ;
  101580. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101581. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101582. return false;
  101583. }
  101584. else if(*bytes == 0) {
  101585. if(
  101586. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101587. (
  101588. #if FLAC__HAS_OGG
  101589. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101590. !decoder->private_->is_ogg &&
  101591. #endif
  101592. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101593. )
  101594. ) {
  101595. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101596. return false;
  101597. }
  101598. else
  101599. return true;
  101600. }
  101601. else
  101602. return true;
  101603. }
  101604. }
  101605. else {
  101606. /* abort to avoid a deadlock */
  101607. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101608. return false;
  101609. }
  101610. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101611. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101612. * and at the same time hit the end of the stream (for example, seeking
  101613. * to a point that is after the beginning of the last Ogg page). There
  101614. * is no way to report an Ogg sync loss through the callbacks (see note
  101615. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101616. * So to keep the decoder from stopping at this point we gate the call
  101617. * to the eof_callback and let the Ogg decoder aspect set the
  101618. * end-of-stream state when it is needed.
  101619. */
  101620. }
  101621. #if FLAC__HAS_OGG
  101622. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101623. {
  101624. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101625. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101626. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101627. /* we don't really have a way to handle lost sync via read
  101628. * callback so we'll let it pass and let the underlying
  101629. * FLAC decoder catch the error
  101630. */
  101631. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101632. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101633. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101634. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101635. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101636. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101637. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101638. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101639. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101640. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101641. default:
  101642. FLAC__ASSERT(0);
  101643. /* double protection */
  101644. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101645. }
  101646. }
  101647. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101648. {
  101649. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101650. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101651. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101652. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101653. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101654. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101655. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101656. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101657. default:
  101658. /* double protection: */
  101659. FLAC__ASSERT(0);
  101660. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101661. }
  101662. }
  101663. #endif
  101664. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101665. {
  101666. if(decoder->private_->is_seeking) {
  101667. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101668. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101669. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101670. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101671. #if FLAC__HAS_OGG
  101672. decoder->private_->got_a_frame = true;
  101673. #endif
  101674. decoder->private_->last_frame = *frame; /* save the frame */
  101675. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101676. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101677. /* kick out of seek mode */
  101678. decoder->private_->is_seeking = false;
  101679. /* shift out the samples before target_sample */
  101680. if(delta > 0) {
  101681. unsigned channel;
  101682. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101683. for(channel = 0; channel < frame->header.channels; channel++)
  101684. newbuffer[channel] = buffer[channel] + delta;
  101685. decoder->private_->last_frame.header.blocksize -= delta;
  101686. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101687. /* write the relevant samples */
  101688. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101689. }
  101690. else {
  101691. /* write the relevant samples */
  101692. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101693. }
  101694. }
  101695. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101696. }
  101697. /*
  101698. * If we never got STREAMINFO, turn off MD5 checking to save
  101699. * cycles since we don't have a sum to compare to anyway
  101700. */
  101701. if(!decoder->private_->has_stream_info)
  101702. decoder->private_->do_md5_checking = false;
  101703. if(decoder->private_->do_md5_checking) {
  101704. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101705. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101706. }
  101707. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101708. }
  101709. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101710. {
  101711. if(!decoder->private_->is_seeking)
  101712. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101713. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101714. decoder->private_->unparseable_frame_count++;
  101715. }
  101716. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101717. {
  101718. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101719. FLAC__int64 pos = -1;
  101720. int i;
  101721. unsigned approx_bytes_per_frame;
  101722. FLAC__bool first_seek = true;
  101723. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101724. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101725. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101726. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101727. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101728. /* take these from the current frame in case they've changed mid-stream */
  101729. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101730. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101731. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101732. /* use values from stream info if we didn't decode a frame */
  101733. if(channels == 0)
  101734. channels = decoder->private_->stream_info.data.stream_info.channels;
  101735. if(bps == 0)
  101736. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101737. /* we are just guessing here */
  101738. if(max_framesize > 0)
  101739. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101740. /*
  101741. * Check if it's a known fixed-blocksize stream. Note that though
  101742. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101743. * never get a STREAMINFO block when decoding so the value of
  101744. * min_blocksize might be zero.
  101745. */
  101746. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101747. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101748. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101749. }
  101750. else
  101751. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101752. /*
  101753. * First, we set an upper and lower bound on where in the
  101754. * stream we will search. For now we assume the worst case
  101755. * scenario, which is our best guess at the beginning of
  101756. * the first frame and end of the stream.
  101757. */
  101758. lower_bound = first_frame_offset;
  101759. lower_bound_sample = 0;
  101760. upper_bound = stream_length;
  101761. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101762. /*
  101763. * Now we refine the bounds if we have a seektable with
  101764. * suitable points. Note that according to the spec they
  101765. * must be ordered by ascending sample number.
  101766. *
  101767. * Note: to protect against invalid seek tables we will ignore points
  101768. * that have frame_samples==0 or sample_number>=total_samples
  101769. */
  101770. if(seek_table) {
  101771. FLAC__uint64 new_lower_bound = lower_bound;
  101772. FLAC__uint64 new_upper_bound = upper_bound;
  101773. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101774. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101775. /* find the closest seek point <= target_sample, if it exists */
  101776. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101777. if(
  101778. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101779. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101780. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101781. seek_table->points[i].sample_number <= target_sample
  101782. )
  101783. break;
  101784. }
  101785. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101786. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101787. new_lower_bound_sample = seek_table->points[i].sample_number;
  101788. }
  101789. /* find the closest seek point > target_sample, if it exists */
  101790. for(i = 0; i < (int)seek_table->num_points; i++) {
  101791. if(
  101792. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101793. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101794. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101795. seek_table->points[i].sample_number > target_sample
  101796. )
  101797. break;
  101798. }
  101799. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101800. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101801. new_upper_bound_sample = seek_table->points[i].sample_number;
  101802. }
  101803. /* final protection against unsorted seek tables; keep original values if bogus */
  101804. if(new_upper_bound >= new_lower_bound) {
  101805. lower_bound = new_lower_bound;
  101806. upper_bound = new_upper_bound;
  101807. lower_bound_sample = new_lower_bound_sample;
  101808. upper_bound_sample = new_upper_bound_sample;
  101809. }
  101810. }
  101811. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101812. /* there are 2 insidious ways that the following equality occurs, which
  101813. * we need to fix:
  101814. * 1) total_samples is 0 (unknown) and target_sample is 0
  101815. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101816. * exactly equal to the last seek point in the seek table; this
  101817. * means there is no seek point above it, and upper_bound_samples
  101818. * remains equal to the estimate (of target_samples) we made above
  101819. * in either case it does not hurt to move upper_bound_sample up by 1
  101820. */
  101821. if(upper_bound_sample == lower_bound_sample)
  101822. upper_bound_sample++;
  101823. decoder->private_->target_sample = target_sample;
  101824. while(1) {
  101825. /* check if the bounds are still ok */
  101826. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101827. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101828. return false;
  101829. }
  101830. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101831. #if defined _MSC_VER || defined __MINGW32__
  101832. /* with VC++ you have to spoon feed it the casting */
  101833. 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;
  101834. #else
  101835. 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;
  101836. #endif
  101837. #else
  101838. /* a little less accurate: */
  101839. if(upper_bound - lower_bound < 0xffffffff)
  101840. 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;
  101841. else /* @@@ WATCHOUT, ~2TB limit */
  101842. 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;
  101843. #endif
  101844. if(pos >= (FLAC__int64)upper_bound)
  101845. pos = (FLAC__int64)upper_bound - 1;
  101846. if(pos < (FLAC__int64)lower_bound)
  101847. pos = (FLAC__int64)lower_bound;
  101848. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101849. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101850. return false;
  101851. }
  101852. if(!FLAC__stream_decoder_flush(decoder)) {
  101853. /* above call sets the state for us */
  101854. return false;
  101855. }
  101856. /* Now we need to get a frame. First we need to reset our
  101857. * unparseable_frame_count; if we get too many unparseable
  101858. * frames in a row, the read callback will return
  101859. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101860. * FLAC__stream_decoder_process_single() to return false.
  101861. */
  101862. decoder->private_->unparseable_frame_count = 0;
  101863. if(!FLAC__stream_decoder_process_single(decoder)) {
  101864. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101865. return false;
  101866. }
  101867. /* our write callback will change the state when it gets to the target frame */
  101868. /* 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 */
  101869. #if 0
  101870. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101871. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101872. break;
  101873. #endif
  101874. if(!decoder->private_->is_seeking)
  101875. break;
  101876. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101877. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101878. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101879. if (pos == (FLAC__int64)lower_bound) {
  101880. /* can't move back any more than the first frame, something is fatally wrong */
  101881. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101882. return false;
  101883. }
  101884. /* our last move backwards wasn't big enough, try again */
  101885. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101886. continue;
  101887. }
  101888. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101889. first_seek = false;
  101890. /* make sure we are not seeking in corrupted stream */
  101891. if (this_frame_sample < lower_bound_sample) {
  101892. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101893. return false;
  101894. }
  101895. /* we need to narrow the search */
  101896. if(target_sample < this_frame_sample) {
  101897. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101898. /*@@@@@@ what will decode position be if at end of stream? */
  101899. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101900. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101901. return false;
  101902. }
  101903. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101904. }
  101905. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101906. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101907. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101908. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101909. return false;
  101910. }
  101911. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101912. }
  101913. }
  101914. return true;
  101915. }
  101916. #if FLAC__HAS_OGG
  101917. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101918. {
  101919. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101920. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101921. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101922. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101923. FLAC__bool did_a_seek;
  101924. unsigned iteration = 0;
  101925. /* In the first iterations, we will calculate the target byte position
  101926. * by the distance from the target sample to left_sample and
  101927. * right_sample (let's call it "proportional search"). After that, we
  101928. * will switch to binary search.
  101929. */
  101930. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101931. /* We will switch to a linear search once our current sample is less
  101932. * than this number of samples ahead of the target sample
  101933. */
  101934. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101935. /* If the total number of samples is unknown, use a large value, and
  101936. * force binary search immediately.
  101937. */
  101938. if(right_sample == 0) {
  101939. right_sample = (FLAC__uint64)(-1);
  101940. BINARY_SEARCH_AFTER_ITERATION = 0;
  101941. }
  101942. decoder->private_->target_sample = target_sample;
  101943. for( ; ; iteration++) {
  101944. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101945. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101946. pos = (right_pos + left_pos) / 2;
  101947. }
  101948. else {
  101949. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101950. #if defined _MSC_VER || defined __MINGW32__
  101951. /* with MSVC you have to spoon feed it the casting */
  101952. 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));
  101953. #else
  101954. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101955. #endif
  101956. #else
  101957. /* a little less accurate: */
  101958. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101959. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101960. else /* @@@ WATCHOUT, ~2TB limit */
  101961. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101962. #endif
  101963. /* @@@ TODO: might want to limit pos to some distance
  101964. * before EOF, to make sure we land before the last frame,
  101965. * thereby getting a this_frame_sample and so having a better
  101966. * estimate.
  101967. */
  101968. }
  101969. /* physical seek */
  101970. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101971. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101972. return false;
  101973. }
  101974. if(!FLAC__stream_decoder_flush(decoder)) {
  101975. /* above call sets the state for us */
  101976. return false;
  101977. }
  101978. did_a_seek = true;
  101979. }
  101980. else
  101981. did_a_seek = false;
  101982. decoder->private_->got_a_frame = false;
  101983. if(!FLAC__stream_decoder_process_single(decoder)) {
  101984. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101985. return false;
  101986. }
  101987. if(!decoder->private_->got_a_frame) {
  101988. if(did_a_seek) {
  101989. /* this can happen if we seek to a point after the last frame; we drop
  101990. * to binary search right away in this case to avoid any wasted
  101991. * iterations of proportional search.
  101992. */
  101993. right_pos = pos;
  101994. BINARY_SEARCH_AFTER_ITERATION = 0;
  101995. }
  101996. else {
  101997. /* this can probably only happen if total_samples is unknown and the
  101998. * target_sample is past the end of the stream
  101999. */
  102000. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102001. return false;
  102002. }
  102003. }
  102004. /* our write callback will change the state when it gets to the target frame */
  102005. else if(!decoder->private_->is_seeking) {
  102006. break;
  102007. }
  102008. else {
  102009. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102010. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102011. if (did_a_seek) {
  102012. if (this_frame_sample <= target_sample) {
  102013. /* The 'equal' case should not happen, since
  102014. * FLAC__stream_decoder_process_single()
  102015. * should recognize that it has hit the
  102016. * target sample and we would exit through
  102017. * the 'break' above.
  102018. */
  102019. FLAC__ASSERT(this_frame_sample != target_sample);
  102020. left_sample = this_frame_sample;
  102021. /* sanity check to avoid infinite loop */
  102022. if (left_pos == pos) {
  102023. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102024. return false;
  102025. }
  102026. left_pos = pos;
  102027. }
  102028. else if(this_frame_sample > target_sample) {
  102029. right_sample = this_frame_sample;
  102030. /* sanity check to avoid infinite loop */
  102031. if (right_pos == pos) {
  102032. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102033. return false;
  102034. }
  102035. right_pos = pos;
  102036. }
  102037. }
  102038. }
  102039. }
  102040. return true;
  102041. }
  102042. #endif
  102043. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102044. {
  102045. (void)client_data;
  102046. if(*bytes > 0) {
  102047. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102048. if(ferror(decoder->private_->file))
  102049. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102050. else if(*bytes == 0)
  102051. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102052. else
  102053. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102054. }
  102055. else
  102056. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102057. }
  102058. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102059. {
  102060. (void)client_data;
  102061. if(decoder->private_->file == stdin)
  102062. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102063. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102064. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102065. else
  102066. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102067. }
  102068. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102069. {
  102070. off_t pos;
  102071. (void)client_data;
  102072. if(decoder->private_->file == stdin)
  102073. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102074. else if((pos = ftello(decoder->private_->file)) < 0)
  102075. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102076. else {
  102077. *absolute_byte_offset = (FLAC__uint64)pos;
  102078. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102079. }
  102080. }
  102081. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102082. {
  102083. struct stat filestats;
  102084. (void)client_data;
  102085. if(decoder->private_->file == stdin)
  102086. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102087. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102088. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102089. else {
  102090. *stream_length = (FLAC__uint64)filestats.st_size;
  102091. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102092. }
  102093. }
  102094. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102095. {
  102096. (void)client_data;
  102097. return feof(decoder->private_->file)? true : false;
  102098. }
  102099. #endif
  102100. /*** End of inlined file: stream_decoder.c ***/
  102101. /*** Start of inlined file: stream_encoder.c ***/
  102102. /*** Start of inlined file: juce_FlacHeader.h ***/
  102103. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102104. // tasks..
  102105. #define VERSION "1.2.1"
  102106. #define FLAC__NO_DLL 1
  102107. #if JUCE_MSVC
  102108. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102109. #endif
  102110. #if JUCE_MAC
  102111. #define FLAC__SYS_DARWIN 1
  102112. #endif
  102113. /*** End of inlined file: juce_FlacHeader.h ***/
  102114. #if JUCE_USE_FLAC
  102115. #if HAVE_CONFIG_H
  102116. # include <config.h>
  102117. #endif
  102118. #if defined _MSC_VER || defined __MINGW32__
  102119. #include <io.h> /* for _setmode() */
  102120. #include <fcntl.h> /* for _O_BINARY */
  102121. #endif
  102122. #if defined __CYGWIN__ || defined __EMX__
  102123. #include <io.h> /* for setmode(), O_BINARY */
  102124. #include <fcntl.h> /* for _O_BINARY */
  102125. #endif
  102126. #include <limits.h>
  102127. #include <stdio.h>
  102128. #include <stdlib.h> /* for malloc() */
  102129. #include <string.h> /* for memcpy() */
  102130. #include <sys/types.h> /* for off_t */
  102131. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102132. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102133. #define fseeko fseek
  102134. #define ftello ftell
  102135. #endif
  102136. #endif
  102137. /*** Start of inlined file: stream_encoder.h ***/
  102138. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102139. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102140. #if FLAC__HAS_OGG
  102141. #include "private/ogg_encoder_aspect.h"
  102142. #endif
  102143. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102144. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102145. typedef enum {
  102146. FLAC__APODIZATION_BARTLETT,
  102147. FLAC__APODIZATION_BARTLETT_HANN,
  102148. FLAC__APODIZATION_BLACKMAN,
  102149. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102150. FLAC__APODIZATION_CONNES,
  102151. FLAC__APODIZATION_FLATTOP,
  102152. FLAC__APODIZATION_GAUSS,
  102153. FLAC__APODIZATION_HAMMING,
  102154. FLAC__APODIZATION_HANN,
  102155. FLAC__APODIZATION_KAISER_BESSEL,
  102156. FLAC__APODIZATION_NUTTALL,
  102157. FLAC__APODIZATION_RECTANGLE,
  102158. FLAC__APODIZATION_TRIANGLE,
  102159. FLAC__APODIZATION_TUKEY,
  102160. FLAC__APODIZATION_WELCH
  102161. } FLAC__ApodizationFunction;
  102162. typedef struct {
  102163. FLAC__ApodizationFunction type;
  102164. union {
  102165. struct {
  102166. FLAC__real stddev;
  102167. } gauss;
  102168. struct {
  102169. FLAC__real p;
  102170. } tukey;
  102171. } parameters;
  102172. } FLAC__ApodizationSpecification;
  102173. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102174. typedef struct FLAC__StreamEncoderProtected {
  102175. FLAC__StreamEncoderState state;
  102176. FLAC__bool verify;
  102177. FLAC__bool streamable_subset;
  102178. FLAC__bool do_md5;
  102179. FLAC__bool do_mid_side_stereo;
  102180. FLAC__bool loose_mid_side_stereo;
  102181. unsigned channels;
  102182. unsigned bits_per_sample;
  102183. unsigned sample_rate;
  102184. unsigned blocksize;
  102185. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102186. unsigned num_apodizations;
  102187. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102188. #endif
  102189. unsigned max_lpc_order;
  102190. unsigned qlp_coeff_precision;
  102191. FLAC__bool do_qlp_coeff_prec_search;
  102192. FLAC__bool do_exhaustive_model_search;
  102193. FLAC__bool do_escape_coding;
  102194. unsigned min_residual_partition_order;
  102195. unsigned max_residual_partition_order;
  102196. unsigned rice_parameter_search_dist;
  102197. FLAC__uint64 total_samples_estimate;
  102198. FLAC__StreamMetadata **metadata;
  102199. unsigned num_metadata_blocks;
  102200. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102201. #if FLAC__HAS_OGG
  102202. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102203. #endif
  102204. } FLAC__StreamEncoderProtected;
  102205. #endif
  102206. /*** End of inlined file: stream_encoder.h ***/
  102207. #if FLAC__HAS_OGG
  102208. #include "include/private/ogg_helper.h"
  102209. #include "include/private/ogg_mapping.h"
  102210. #endif
  102211. /*** Start of inlined file: stream_encoder_framing.h ***/
  102212. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102213. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102214. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102215. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102216. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102217. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102218. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102219. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102220. #endif
  102221. /*** End of inlined file: stream_encoder_framing.h ***/
  102222. /*** Start of inlined file: window.h ***/
  102223. #ifndef FLAC__PRIVATE__WINDOW_H
  102224. #define FLAC__PRIVATE__WINDOW_H
  102225. #ifdef HAVE_CONFIG_H
  102226. #include <config.h>
  102227. #endif
  102228. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102229. /*
  102230. * FLAC__window_*()
  102231. * --------------------------------------------------------------------
  102232. * Calculates window coefficients according to different apodization
  102233. * functions.
  102234. *
  102235. * OUT window[0,L-1]
  102236. * IN L (number of points in window)
  102237. */
  102238. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102239. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102240. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102241. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102242. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102243. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102244. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102245. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102246. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102247. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102248. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102249. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102250. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102251. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102252. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102253. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102254. #endif
  102255. /*** End of inlined file: window.h ***/
  102256. #ifndef FLaC__INLINE
  102257. #define FLaC__INLINE
  102258. #endif
  102259. #ifdef min
  102260. #undef min
  102261. #endif
  102262. #define min(x,y) ((x)<(y)?(x):(y))
  102263. #ifdef max
  102264. #undef max
  102265. #endif
  102266. #define max(x,y) ((x)>(y)?(x):(y))
  102267. /* Exact Rice codeword length calculation is off by default. The simple
  102268. * (and fast) estimation (of how many bits a residual value will be
  102269. * encoded with) in this encoder is very good, almost always yielding
  102270. * compression within 0.1% of exact calculation.
  102271. */
  102272. #undef EXACT_RICE_BITS_CALCULATION
  102273. /* Rice parameter searching is off by default. The simple (and fast)
  102274. * parameter estimation in this encoder is very good, almost always
  102275. * yielding compression within 0.1% of the optimal parameters.
  102276. */
  102277. #undef ENABLE_RICE_PARAMETER_SEARCH
  102278. typedef struct {
  102279. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102280. unsigned size; /* of each data[] in samples */
  102281. unsigned tail;
  102282. } verify_input_fifo;
  102283. typedef struct {
  102284. const FLAC__byte *data;
  102285. unsigned capacity;
  102286. unsigned bytes;
  102287. } verify_output;
  102288. typedef enum {
  102289. ENCODER_IN_MAGIC = 0,
  102290. ENCODER_IN_METADATA = 1,
  102291. ENCODER_IN_AUDIO = 2
  102292. } EncoderStateHint;
  102293. static struct CompressionLevels {
  102294. FLAC__bool do_mid_side_stereo;
  102295. FLAC__bool loose_mid_side_stereo;
  102296. unsigned max_lpc_order;
  102297. unsigned qlp_coeff_precision;
  102298. FLAC__bool do_qlp_coeff_prec_search;
  102299. FLAC__bool do_escape_coding;
  102300. FLAC__bool do_exhaustive_model_search;
  102301. unsigned min_residual_partition_order;
  102302. unsigned max_residual_partition_order;
  102303. unsigned rice_parameter_search_dist;
  102304. } compression_levels_[] = {
  102305. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102306. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102307. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102308. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102309. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102310. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102311. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102312. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102313. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102314. };
  102315. /***********************************************************************
  102316. *
  102317. * Private class method prototypes
  102318. *
  102319. ***********************************************************************/
  102320. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102321. static void free_(FLAC__StreamEncoder *encoder);
  102322. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102323. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102324. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102325. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102326. #if FLAC__HAS_OGG
  102327. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102328. #endif
  102329. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102330. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102331. static FLAC__bool process_subframe_(
  102332. FLAC__StreamEncoder *encoder,
  102333. unsigned min_partition_order,
  102334. unsigned max_partition_order,
  102335. const FLAC__FrameHeader *frame_header,
  102336. unsigned subframe_bps,
  102337. const FLAC__int32 integer_signal[],
  102338. FLAC__Subframe *subframe[2],
  102339. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102340. FLAC__int32 *residual[2],
  102341. unsigned *best_subframe,
  102342. unsigned *best_bits
  102343. );
  102344. static FLAC__bool add_subframe_(
  102345. FLAC__StreamEncoder *encoder,
  102346. unsigned blocksize,
  102347. unsigned subframe_bps,
  102348. const FLAC__Subframe *subframe,
  102349. FLAC__BitWriter *frame
  102350. );
  102351. static unsigned evaluate_constant_subframe_(
  102352. FLAC__StreamEncoder *encoder,
  102353. const FLAC__int32 signal,
  102354. unsigned blocksize,
  102355. unsigned subframe_bps,
  102356. FLAC__Subframe *subframe
  102357. );
  102358. static unsigned evaluate_fixed_subframe_(
  102359. FLAC__StreamEncoder *encoder,
  102360. const FLAC__int32 signal[],
  102361. FLAC__int32 residual[],
  102362. FLAC__uint64 abs_residual_partition_sums[],
  102363. unsigned raw_bits_per_partition[],
  102364. unsigned blocksize,
  102365. unsigned subframe_bps,
  102366. unsigned order,
  102367. unsigned rice_parameter,
  102368. unsigned rice_parameter_limit,
  102369. unsigned min_partition_order,
  102370. unsigned max_partition_order,
  102371. FLAC__bool do_escape_coding,
  102372. unsigned rice_parameter_search_dist,
  102373. FLAC__Subframe *subframe,
  102374. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102375. );
  102376. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102377. static unsigned evaluate_lpc_subframe_(
  102378. FLAC__StreamEncoder *encoder,
  102379. const FLAC__int32 signal[],
  102380. FLAC__int32 residual[],
  102381. FLAC__uint64 abs_residual_partition_sums[],
  102382. unsigned raw_bits_per_partition[],
  102383. const FLAC__real lp_coeff[],
  102384. unsigned blocksize,
  102385. unsigned subframe_bps,
  102386. unsigned order,
  102387. unsigned qlp_coeff_precision,
  102388. unsigned rice_parameter,
  102389. unsigned rice_parameter_limit,
  102390. unsigned min_partition_order,
  102391. unsigned max_partition_order,
  102392. FLAC__bool do_escape_coding,
  102393. unsigned rice_parameter_search_dist,
  102394. FLAC__Subframe *subframe,
  102395. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102396. );
  102397. #endif
  102398. static unsigned evaluate_verbatim_subframe_(
  102399. FLAC__StreamEncoder *encoder,
  102400. const FLAC__int32 signal[],
  102401. unsigned blocksize,
  102402. unsigned subframe_bps,
  102403. FLAC__Subframe *subframe
  102404. );
  102405. static unsigned find_best_partition_order_(
  102406. struct FLAC__StreamEncoderPrivate *private_,
  102407. const FLAC__int32 residual[],
  102408. FLAC__uint64 abs_residual_partition_sums[],
  102409. unsigned raw_bits_per_partition[],
  102410. unsigned residual_samples,
  102411. unsigned predictor_order,
  102412. unsigned rice_parameter,
  102413. unsigned rice_parameter_limit,
  102414. unsigned min_partition_order,
  102415. unsigned max_partition_order,
  102416. unsigned bps,
  102417. FLAC__bool do_escape_coding,
  102418. unsigned rice_parameter_search_dist,
  102419. FLAC__EntropyCodingMethod *best_ecm
  102420. );
  102421. static void precompute_partition_info_sums_(
  102422. const FLAC__int32 residual[],
  102423. FLAC__uint64 abs_residual_partition_sums[],
  102424. unsigned residual_samples,
  102425. unsigned predictor_order,
  102426. unsigned min_partition_order,
  102427. unsigned max_partition_order,
  102428. unsigned bps
  102429. );
  102430. static void precompute_partition_info_escapes_(
  102431. const FLAC__int32 residual[],
  102432. unsigned raw_bits_per_partition[],
  102433. unsigned residual_samples,
  102434. unsigned predictor_order,
  102435. unsigned min_partition_order,
  102436. unsigned max_partition_order
  102437. );
  102438. static FLAC__bool set_partitioned_rice_(
  102439. #ifdef EXACT_RICE_BITS_CALCULATION
  102440. const FLAC__int32 residual[],
  102441. #endif
  102442. const FLAC__uint64 abs_residual_partition_sums[],
  102443. const unsigned raw_bits_per_partition[],
  102444. const unsigned residual_samples,
  102445. const unsigned predictor_order,
  102446. const unsigned suggested_rice_parameter,
  102447. const unsigned rice_parameter_limit,
  102448. const unsigned rice_parameter_search_dist,
  102449. const unsigned partition_order,
  102450. const FLAC__bool search_for_escapes,
  102451. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102452. unsigned *bits
  102453. );
  102454. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102455. /* verify-related routines: */
  102456. static void append_to_verify_fifo_(
  102457. verify_input_fifo *fifo,
  102458. const FLAC__int32 * const input[],
  102459. unsigned input_offset,
  102460. unsigned channels,
  102461. unsigned wide_samples
  102462. );
  102463. static void append_to_verify_fifo_interleaved_(
  102464. verify_input_fifo *fifo,
  102465. const FLAC__int32 input[],
  102466. unsigned input_offset,
  102467. unsigned channels,
  102468. unsigned wide_samples
  102469. );
  102470. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102471. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102472. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102473. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102474. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102475. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102476. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102477. 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);
  102478. static FILE *get_binary_stdout_(void);
  102479. /***********************************************************************
  102480. *
  102481. * Private class data
  102482. *
  102483. ***********************************************************************/
  102484. typedef struct FLAC__StreamEncoderPrivate {
  102485. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102486. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102487. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102488. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102489. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102490. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102491. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102492. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102493. #endif
  102494. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102495. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102496. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102497. FLAC__int32 *residual_workspace_mid_side[2][2];
  102498. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102499. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102500. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102501. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102502. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102503. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102504. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102505. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102506. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102507. unsigned best_subframe_mid_side[2];
  102508. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102509. unsigned best_subframe_bits_mid_side[2];
  102510. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102511. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102512. FLAC__BitWriter *frame; /* the current frame being worked on */
  102513. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102514. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102515. FLAC__ChannelAssignment last_channel_assignment;
  102516. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102517. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102518. unsigned current_sample_number;
  102519. unsigned current_frame_number;
  102520. FLAC__MD5Context md5context;
  102521. FLAC__CPUInfo cpuinfo;
  102522. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102523. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102524. #else
  102525. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102526. #endif
  102527. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102528. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102529. 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[]);
  102530. 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[]);
  102531. 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[]);
  102532. #endif
  102533. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102534. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102535. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102536. FLAC__bool disable_constant_subframes;
  102537. FLAC__bool disable_fixed_subframes;
  102538. FLAC__bool disable_verbatim_subframes;
  102539. #if FLAC__HAS_OGG
  102540. FLAC__bool is_ogg;
  102541. #endif
  102542. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102543. FLAC__StreamEncoderSeekCallback seek_callback;
  102544. FLAC__StreamEncoderTellCallback tell_callback;
  102545. FLAC__StreamEncoderWriteCallback write_callback;
  102546. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102547. FLAC__StreamEncoderProgressCallback progress_callback;
  102548. void *client_data;
  102549. unsigned first_seekpoint_to_check;
  102550. FILE *file; /* only used when encoding to a file */
  102551. FLAC__uint64 bytes_written;
  102552. FLAC__uint64 samples_written;
  102553. unsigned frames_written;
  102554. unsigned total_frames_estimate;
  102555. /* unaligned (original) pointers to allocated data */
  102556. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102557. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102558. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102559. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102560. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102561. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102562. FLAC__real *windowed_signal_unaligned;
  102563. #endif
  102564. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102565. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102566. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102567. unsigned *raw_bits_per_partition_unaligned;
  102568. /*
  102569. * These fields have been moved here from private function local
  102570. * declarations merely to save stack space during encoding.
  102571. */
  102572. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102573. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102574. #endif
  102575. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102576. /*
  102577. * The data for the verify section
  102578. */
  102579. struct {
  102580. FLAC__StreamDecoder *decoder;
  102581. EncoderStateHint state_hint;
  102582. FLAC__bool needs_magic_hack;
  102583. verify_input_fifo input_fifo;
  102584. verify_output output;
  102585. struct {
  102586. FLAC__uint64 absolute_sample;
  102587. unsigned frame_number;
  102588. unsigned channel;
  102589. unsigned sample;
  102590. FLAC__int32 expected;
  102591. FLAC__int32 got;
  102592. } error_stats;
  102593. } verify;
  102594. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102595. } FLAC__StreamEncoderPrivate;
  102596. /***********************************************************************
  102597. *
  102598. * Public static class data
  102599. *
  102600. ***********************************************************************/
  102601. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102602. "FLAC__STREAM_ENCODER_OK",
  102603. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102604. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102605. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102606. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102607. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102608. "FLAC__STREAM_ENCODER_IO_ERROR",
  102609. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102610. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102611. };
  102612. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102613. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102614. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102615. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102616. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102617. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102618. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102619. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102620. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102621. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102622. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102623. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102624. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102625. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102626. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102627. };
  102628. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102629. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102630. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102631. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102632. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102633. };
  102634. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102635. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102636. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102637. };
  102638. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102639. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102640. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102641. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102642. };
  102643. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102644. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102645. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102646. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102647. };
  102648. /* Number of samples that will be overread to watch for end of stream. By
  102649. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102650. * always try to read blocksize+1 samples before encoding a block, so that
  102651. * even if the stream has a total sample count that is an integral multiple
  102652. * of the blocksize, we will still notice when we are encoding the last
  102653. * block. This is needed, for example, to correctly set the end-of-stream
  102654. * marker in Ogg FLAC.
  102655. *
  102656. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102657. * not really any reason to change it.
  102658. */
  102659. static const unsigned OVERREAD_ = 1;
  102660. /***********************************************************************
  102661. *
  102662. * Class constructor/destructor
  102663. *
  102664. */
  102665. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102666. {
  102667. FLAC__StreamEncoder *encoder;
  102668. unsigned i;
  102669. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102670. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102671. if(encoder == 0) {
  102672. return 0;
  102673. }
  102674. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102675. if(encoder->protected_ == 0) {
  102676. free(encoder);
  102677. return 0;
  102678. }
  102679. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102680. if(encoder->private_ == 0) {
  102681. free(encoder->protected_);
  102682. free(encoder);
  102683. return 0;
  102684. }
  102685. encoder->private_->frame = FLAC__bitwriter_new();
  102686. if(encoder->private_->frame == 0) {
  102687. free(encoder->private_);
  102688. free(encoder->protected_);
  102689. free(encoder);
  102690. return 0;
  102691. }
  102692. encoder->private_->file = 0;
  102693. set_defaults_enc(encoder);
  102694. encoder->private_->is_being_deleted = false;
  102695. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102696. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102697. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102698. }
  102699. for(i = 0; i < 2; i++) {
  102700. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102701. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102702. }
  102703. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102704. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102705. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102706. }
  102707. for(i = 0; i < 2; i++) {
  102708. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102709. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102710. }
  102711. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102712. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102713. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102714. }
  102715. for(i = 0; i < 2; i++) {
  102716. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102717. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102718. }
  102719. for(i = 0; i < 2; i++)
  102720. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102721. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102722. return encoder;
  102723. }
  102724. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102725. {
  102726. unsigned i;
  102727. FLAC__ASSERT(0 != encoder);
  102728. FLAC__ASSERT(0 != encoder->protected_);
  102729. FLAC__ASSERT(0 != encoder->private_);
  102730. FLAC__ASSERT(0 != encoder->private_->frame);
  102731. encoder->private_->is_being_deleted = true;
  102732. (void)FLAC__stream_encoder_finish(encoder);
  102733. if(0 != encoder->private_->verify.decoder)
  102734. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102735. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102736. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102737. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102738. }
  102739. for(i = 0; i < 2; i++) {
  102740. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102741. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102742. }
  102743. for(i = 0; i < 2; i++)
  102744. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102745. FLAC__bitwriter_delete(encoder->private_->frame);
  102746. free(encoder->private_);
  102747. free(encoder->protected_);
  102748. free(encoder);
  102749. }
  102750. /***********************************************************************
  102751. *
  102752. * Public class methods
  102753. *
  102754. ***********************************************************************/
  102755. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102756. FLAC__StreamEncoder *encoder,
  102757. FLAC__StreamEncoderReadCallback read_callback,
  102758. FLAC__StreamEncoderWriteCallback write_callback,
  102759. FLAC__StreamEncoderSeekCallback seek_callback,
  102760. FLAC__StreamEncoderTellCallback tell_callback,
  102761. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102762. void *client_data,
  102763. FLAC__bool is_ogg
  102764. )
  102765. {
  102766. unsigned i;
  102767. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102768. FLAC__ASSERT(0 != encoder);
  102769. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102770. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102771. #if !FLAC__HAS_OGG
  102772. if(is_ogg)
  102773. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102774. #endif
  102775. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102776. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102777. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102778. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102779. if(encoder->protected_->channels != 2) {
  102780. encoder->protected_->do_mid_side_stereo = false;
  102781. encoder->protected_->loose_mid_side_stereo = false;
  102782. }
  102783. else if(!encoder->protected_->do_mid_side_stereo)
  102784. encoder->protected_->loose_mid_side_stereo = false;
  102785. if(encoder->protected_->bits_per_sample >= 32)
  102786. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102787. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102788. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102789. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102790. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102791. if(encoder->protected_->blocksize == 0) {
  102792. if(encoder->protected_->max_lpc_order == 0)
  102793. encoder->protected_->blocksize = 1152;
  102794. else
  102795. encoder->protected_->blocksize = 4096;
  102796. }
  102797. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102798. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102799. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102800. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102801. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102802. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102803. if(encoder->protected_->qlp_coeff_precision == 0) {
  102804. if(encoder->protected_->bits_per_sample < 16) {
  102805. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102806. /* @@@ until then we'll make a guess */
  102807. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102808. }
  102809. else if(encoder->protected_->bits_per_sample == 16) {
  102810. if(encoder->protected_->blocksize <= 192)
  102811. encoder->protected_->qlp_coeff_precision = 7;
  102812. else if(encoder->protected_->blocksize <= 384)
  102813. encoder->protected_->qlp_coeff_precision = 8;
  102814. else if(encoder->protected_->blocksize <= 576)
  102815. encoder->protected_->qlp_coeff_precision = 9;
  102816. else if(encoder->protected_->blocksize <= 1152)
  102817. encoder->protected_->qlp_coeff_precision = 10;
  102818. else if(encoder->protected_->blocksize <= 2304)
  102819. encoder->protected_->qlp_coeff_precision = 11;
  102820. else if(encoder->protected_->blocksize <= 4608)
  102821. encoder->protected_->qlp_coeff_precision = 12;
  102822. else
  102823. encoder->protected_->qlp_coeff_precision = 13;
  102824. }
  102825. else {
  102826. if(encoder->protected_->blocksize <= 384)
  102827. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102828. else if(encoder->protected_->blocksize <= 1152)
  102829. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102830. else
  102831. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102832. }
  102833. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102834. }
  102835. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102836. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102837. if(encoder->protected_->streamable_subset) {
  102838. if(
  102839. encoder->protected_->blocksize != 192 &&
  102840. encoder->protected_->blocksize != 576 &&
  102841. encoder->protected_->blocksize != 1152 &&
  102842. encoder->protected_->blocksize != 2304 &&
  102843. encoder->protected_->blocksize != 4608 &&
  102844. encoder->protected_->blocksize != 256 &&
  102845. encoder->protected_->blocksize != 512 &&
  102846. encoder->protected_->blocksize != 1024 &&
  102847. encoder->protected_->blocksize != 2048 &&
  102848. encoder->protected_->blocksize != 4096 &&
  102849. encoder->protected_->blocksize != 8192 &&
  102850. encoder->protected_->blocksize != 16384
  102851. )
  102852. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102853. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102854. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102855. if(
  102856. encoder->protected_->bits_per_sample != 8 &&
  102857. encoder->protected_->bits_per_sample != 12 &&
  102858. encoder->protected_->bits_per_sample != 16 &&
  102859. encoder->protected_->bits_per_sample != 20 &&
  102860. encoder->protected_->bits_per_sample != 24
  102861. )
  102862. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102863. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102864. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102865. if(
  102866. encoder->protected_->sample_rate <= 48000 &&
  102867. (
  102868. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102869. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102870. )
  102871. ) {
  102872. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102873. }
  102874. }
  102875. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102876. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102877. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102878. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102879. #if FLAC__HAS_OGG
  102880. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102881. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102882. unsigned i;
  102883. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102884. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102885. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102886. for( ; i > 0; i--)
  102887. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102888. encoder->protected_->metadata[0] = vc;
  102889. break;
  102890. }
  102891. }
  102892. }
  102893. #endif
  102894. /* keep track of any SEEKTABLE block */
  102895. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102896. unsigned i;
  102897. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102898. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102899. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102900. break; /* take only the first one */
  102901. }
  102902. }
  102903. }
  102904. /* validate metadata */
  102905. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102906. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102907. metadata_has_seektable = false;
  102908. metadata_has_vorbis_comment = false;
  102909. metadata_picture_has_type1 = false;
  102910. metadata_picture_has_type2 = false;
  102911. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102912. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102913. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102914. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102915. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102916. if(metadata_has_seektable) /* only one is allowed */
  102917. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102918. metadata_has_seektable = true;
  102919. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102920. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102921. }
  102922. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102923. if(metadata_has_vorbis_comment) /* only one is allowed */
  102924. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102925. metadata_has_vorbis_comment = true;
  102926. }
  102927. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102928. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102929. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102930. }
  102931. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102932. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102933. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102934. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102935. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102936. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102937. metadata_picture_has_type1 = true;
  102938. /* standard icon must be 32x32 pixel PNG */
  102939. if(
  102940. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102941. (
  102942. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102943. m->data.picture.width != 32 ||
  102944. m->data.picture.height != 32
  102945. )
  102946. )
  102947. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102948. }
  102949. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102950. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102951. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102952. metadata_picture_has_type2 = true;
  102953. }
  102954. }
  102955. }
  102956. encoder->private_->input_capacity = 0;
  102957. for(i = 0; i < encoder->protected_->channels; i++) {
  102958. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102959. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102960. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102961. #endif
  102962. }
  102963. for(i = 0; i < 2; i++) {
  102964. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102965. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102966. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102967. #endif
  102968. }
  102969. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102970. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102971. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102972. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102973. #endif
  102974. for(i = 0; i < encoder->protected_->channels; i++) {
  102975. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102976. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102977. encoder->private_->best_subframe[i] = 0;
  102978. }
  102979. for(i = 0; i < 2; i++) {
  102980. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102981. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102982. encoder->private_->best_subframe_mid_side[i] = 0;
  102983. }
  102984. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102985. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102986. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102987. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102988. #else
  102989. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102990. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102991. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102992. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102993. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102994. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102995. 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);
  102996. #endif
  102997. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102998. encoder->private_->loose_mid_side_stereo_frames = 1;
  102999. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103000. encoder->private_->current_sample_number = 0;
  103001. encoder->private_->current_frame_number = 0;
  103002. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  103003. 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? */
  103004. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  103005. /*
  103006. * get the CPU info and set the function pointers
  103007. */
  103008. FLAC__cpu_info(&encoder->private_->cpuinfo);
  103009. /* first default to the non-asm routines */
  103010. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103011. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  103012. #endif
  103013. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  103014. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103015. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103016. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  103017. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103018. #endif
  103019. /* now override with asm where appropriate */
  103020. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103021. # ifndef FLAC__NO_ASM
  103022. if(encoder->private_->cpuinfo.use_asm) {
  103023. # ifdef FLAC__CPU_IA32
  103024. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  103025. # ifdef FLAC__HAS_NASM
  103026. if(encoder->private_->cpuinfo.data.ia32.sse) {
  103027. if(encoder->protected_->max_lpc_order < 4)
  103028. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  103029. else if(encoder->protected_->max_lpc_order < 8)
  103030. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103031. else if(encoder->protected_->max_lpc_order < 12)
  103032. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103033. else
  103034. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103035. }
  103036. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103037. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103038. else
  103039. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103040. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103041. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103042. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103043. }
  103044. else {
  103045. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103046. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103047. }
  103048. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103049. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103050. # endif /* FLAC__HAS_NASM */
  103051. # endif /* FLAC__CPU_IA32 */
  103052. }
  103053. # endif /* !FLAC__NO_ASM */
  103054. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103055. /* finally override based on wide-ness if necessary */
  103056. if(encoder->private_->use_wide_by_block) {
  103057. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103058. }
  103059. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103060. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103061. #if FLAC__HAS_OGG
  103062. encoder->private_->is_ogg = is_ogg;
  103063. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103064. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103065. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103066. }
  103067. #endif
  103068. encoder->private_->read_callback = read_callback;
  103069. encoder->private_->write_callback = write_callback;
  103070. encoder->private_->seek_callback = seek_callback;
  103071. encoder->private_->tell_callback = tell_callback;
  103072. encoder->private_->metadata_callback = metadata_callback;
  103073. encoder->private_->client_data = client_data;
  103074. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103075. /* the above function sets the state for us in case of an error */
  103076. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103077. }
  103078. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103079. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103080. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103081. }
  103082. /*
  103083. * Set up the verify stuff if necessary
  103084. */
  103085. if(encoder->protected_->verify) {
  103086. /*
  103087. * First, set up the fifo which will hold the
  103088. * original signal to compare against
  103089. */
  103090. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103091. for(i = 0; i < encoder->protected_->channels; i++) {
  103092. 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))) {
  103093. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103094. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103095. }
  103096. }
  103097. encoder->private_->verify.input_fifo.tail = 0;
  103098. /*
  103099. * Now set up a stream decoder for verification
  103100. */
  103101. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103102. if(0 == encoder->private_->verify.decoder) {
  103103. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103104. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103105. }
  103106. 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) {
  103107. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103108. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103109. }
  103110. }
  103111. encoder->private_->verify.error_stats.absolute_sample = 0;
  103112. encoder->private_->verify.error_stats.frame_number = 0;
  103113. encoder->private_->verify.error_stats.channel = 0;
  103114. encoder->private_->verify.error_stats.sample = 0;
  103115. encoder->private_->verify.error_stats.expected = 0;
  103116. encoder->private_->verify.error_stats.got = 0;
  103117. /*
  103118. * These must be done before we write any metadata, because that
  103119. * calls the write_callback, which uses these values.
  103120. */
  103121. encoder->private_->first_seekpoint_to_check = 0;
  103122. encoder->private_->samples_written = 0;
  103123. encoder->protected_->streaminfo_offset = 0;
  103124. encoder->protected_->seektable_offset = 0;
  103125. encoder->protected_->audio_offset = 0;
  103126. /*
  103127. * write the stream header
  103128. */
  103129. if(encoder->protected_->verify)
  103130. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103131. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103132. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103133. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103134. }
  103135. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103136. /* the above function sets the state for us in case of an error */
  103137. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103138. }
  103139. /*
  103140. * write the STREAMINFO metadata block
  103141. */
  103142. if(encoder->protected_->verify)
  103143. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103144. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103145. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103146. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103147. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103148. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103149. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103150. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103151. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103152. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103153. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103154. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103155. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103156. if(encoder->protected_->do_md5)
  103157. FLAC__MD5Init(&encoder->private_->md5context);
  103158. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103159. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103160. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103161. }
  103162. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103163. /* the above function sets the state for us in case of an error */
  103164. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103165. }
  103166. /*
  103167. * Now that the STREAMINFO block is written, we can init this to an
  103168. * absurdly-high value...
  103169. */
  103170. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103171. /* ... and clear this to 0 */
  103172. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103173. /*
  103174. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103175. * if not, we will write an empty one (FLAC__add_metadata_block()
  103176. * automatically supplies the vendor string).
  103177. *
  103178. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103179. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103180. * true it will have already insured that the metadata list is properly
  103181. * ordered.)
  103182. */
  103183. if(!metadata_has_vorbis_comment) {
  103184. FLAC__StreamMetadata vorbis_comment;
  103185. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103186. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103187. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103188. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103189. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103190. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103191. vorbis_comment.data.vorbis_comment.comments = 0;
  103192. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103193. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103194. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103195. }
  103196. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103197. /* the above function sets the state for us in case of an error */
  103198. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103199. }
  103200. }
  103201. /*
  103202. * write the user's metadata blocks
  103203. */
  103204. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103205. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103206. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103207. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103208. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103209. }
  103210. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103211. /* the above function sets the state for us in case of an error */
  103212. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103213. }
  103214. }
  103215. /* now that all the metadata is written, we save the stream offset */
  103216. 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 */
  103217. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103218. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103219. }
  103220. if(encoder->protected_->verify)
  103221. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103222. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103223. }
  103224. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103225. FLAC__StreamEncoder *encoder,
  103226. FLAC__StreamEncoderWriteCallback write_callback,
  103227. FLAC__StreamEncoderSeekCallback seek_callback,
  103228. FLAC__StreamEncoderTellCallback tell_callback,
  103229. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103230. void *client_data
  103231. )
  103232. {
  103233. return init_stream_internal_enc(
  103234. encoder,
  103235. /*read_callback=*/0,
  103236. write_callback,
  103237. seek_callback,
  103238. tell_callback,
  103239. metadata_callback,
  103240. client_data,
  103241. /*is_ogg=*/false
  103242. );
  103243. }
  103244. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103245. FLAC__StreamEncoder *encoder,
  103246. FLAC__StreamEncoderReadCallback read_callback,
  103247. FLAC__StreamEncoderWriteCallback write_callback,
  103248. FLAC__StreamEncoderSeekCallback seek_callback,
  103249. FLAC__StreamEncoderTellCallback tell_callback,
  103250. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103251. void *client_data
  103252. )
  103253. {
  103254. return init_stream_internal_enc(
  103255. encoder,
  103256. read_callback,
  103257. write_callback,
  103258. seek_callback,
  103259. tell_callback,
  103260. metadata_callback,
  103261. client_data,
  103262. /*is_ogg=*/true
  103263. );
  103264. }
  103265. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103266. FLAC__StreamEncoder *encoder,
  103267. FILE *file,
  103268. FLAC__StreamEncoderProgressCallback progress_callback,
  103269. void *client_data,
  103270. FLAC__bool is_ogg
  103271. )
  103272. {
  103273. FLAC__StreamEncoderInitStatus init_status;
  103274. FLAC__ASSERT(0 != encoder);
  103275. FLAC__ASSERT(0 != file);
  103276. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103277. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103278. /* double protection */
  103279. if(file == 0) {
  103280. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103281. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103282. }
  103283. /*
  103284. * To make sure that our file does not go unclosed after an error, we
  103285. * must assign the FILE pointer before any further error can occur in
  103286. * this routine.
  103287. */
  103288. if(file == stdout)
  103289. file = get_binary_stdout_(); /* just to be safe */
  103290. encoder->private_->file = file;
  103291. encoder->private_->progress_callback = progress_callback;
  103292. encoder->private_->bytes_written = 0;
  103293. encoder->private_->samples_written = 0;
  103294. encoder->private_->frames_written = 0;
  103295. init_status = init_stream_internal_enc(
  103296. encoder,
  103297. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103298. file_write_callback_,
  103299. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103300. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103301. /*metadata_callback=*/0,
  103302. client_data,
  103303. is_ogg
  103304. );
  103305. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103306. /* the above function sets the state for us in case of an error */
  103307. return init_status;
  103308. }
  103309. {
  103310. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103311. FLAC__ASSERT(blocksize != 0);
  103312. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103313. }
  103314. return init_status;
  103315. }
  103316. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103317. FLAC__StreamEncoder *encoder,
  103318. FILE *file,
  103319. FLAC__StreamEncoderProgressCallback progress_callback,
  103320. void *client_data
  103321. )
  103322. {
  103323. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103324. }
  103325. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103326. FLAC__StreamEncoder *encoder,
  103327. FILE *file,
  103328. FLAC__StreamEncoderProgressCallback progress_callback,
  103329. void *client_data
  103330. )
  103331. {
  103332. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103333. }
  103334. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103335. FLAC__StreamEncoder *encoder,
  103336. const char *filename,
  103337. FLAC__StreamEncoderProgressCallback progress_callback,
  103338. void *client_data,
  103339. FLAC__bool is_ogg
  103340. )
  103341. {
  103342. FILE *file;
  103343. FLAC__ASSERT(0 != encoder);
  103344. /*
  103345. * To make sure that our file does not go unclosed after an error, we
  103346. * have to do the same entrance checks here that are later performed
  103347. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103348. */
  103349. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103350. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103351. file = filename? fopen(filename, "w+b") : stdout;
  103352. if(file == 0) {
  103353. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103354. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103355. }
  103356. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103357. }
  103358. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103359. FLAC__StreamEncoder *encoder,
  103360. const char *filename,
  103361. FLAC__StreamEncoderProgressCallback progress_callback,
  103362. void *client_data
  103363. )
  103364. {
  103365. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103366. }
  103367. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103368. FLAC__StreamEncoder *encoder,
  103369. const char *filename,
  103370. FLAC__StreamEncoderProgressCallback progress_callback,
  103371. void *client_data
  103372. )
  103373. {
  103374. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103375. }
  103376. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103377. {
  103378. FLAC__bool error = false;
  103379. FLAC__ASSERT(0 != encoder);
  103380. FLAC__ASSERT(0 != encoder->private_);
  103381. FLAC__ASSERT(0 != encoder->protected_);
  103382. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103383. return true;
  103384. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103385. if(encoder->private_->current_sample_number != 0) {
  103386. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103387. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103388. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103389. error = true;
  103390. }
  103391. }
  103392. if(encoder->protected_->do_md5)
  103393. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103394. if(!encoder->private_->is_being_deleted) {
  103395. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103396. if(encoder->private_->seek_callback) {
  103397. #if FLAC__HAS_OGG
  103398. if(encoder->private_->is_ogg)
  103399. update_ogg_metadata_(encoder);
  103400. else
  103401. #endif
  103402. update_metadata_(encoder);
  103403. /* check if an error occurred while updating metadata */
  103404. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103405. error = true;
  103406. }
  103407. if(encoder->private_->metadata_callback)
  103408. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103409. }
  103410. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103411. if(!error)
  103412. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103413. error = true;
  103414. }
  103415. }
  103416. if(0 != encoder->private_->file) {
  103417. if(encoder->private_->file != stdout)
  103418. fclose(encoder->private_->file);
  103419. encoder->private_->file = 0;
  103420. }
  103421. #if FLAC__HAS_OGG
  103422. if(encoder->private_->is_ogg)
  103423. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103424. #endif
  103425. free_(encoder);
  103426. set_defaults_enc(encoder);
  103427. if(!error)
  103428. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103429. return !error;
  103430. }
  103431. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103432. {
  103433. FLAC__ASSERT(0 != encoder);
  103434. FLAC__ASSERT(0 != encoder->private_);
  103435. FLAC__ASSERT(0 != encoder->protected_);
  103436. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103437. return false;
  103438. #if FLAC__HAS_OGG
  103439. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103440. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103441. return true;
  103442. #else
  103443. (void)value;
  103444. return false;
  103445. #endif
  103446. }
  103447. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103448. {
  103449. FLAC__ASSERT(0 != encoder);
  103450. FLAC__ASSERT(0 != encoder->private_);
  103451. FLAC__ASSERT(0 != encoder->protected_);
  103452. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103453. return false;
  103454. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103455. encoder->protected_->verify = value;
  103456. #endif
  103457. return true;
  103458. }
  103459. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103460. {
  103461. FLAC__ASSERT(0 != encoder);
  103462. FLAC__ASSERT(0 != encoder->private_);
  103463. FLAC__ASSERT(0 != encoder->protected_);
  103464. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103465. return false;
  103466. encoder->protected_->streamable_subset = value;
  103467. return true;
  103468. }
  103469. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103470. {
  103471. FLAC__ASSERT(0 != encoder);
  103472. FLAC__ASSERT(0 != encoder->private_);
  103473. FLAC__ASSERT(0 != encoder->protected_);
  103474. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103475. return false;
  103476. encoder->protected_->do_md5 = value;
  103477. return true;
  103478. }
  103479. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103480. {
  103481. FLAC__ASSERT(0 != encoder);
  103482. FLAC__ASSERT(0 != encoder->private_);
  103483. FLAC__ASSERT(0 != encoder->protected_);
  103484. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103485. return false;
  103486. encoder->protected_->channels = value;
  103487. return true;
  103488. }
  103489. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103490. {
  103491. FLAC__ASSERT(0 != encoder);
  103492. FLAC__ASSERT(0 != encoder->private_);
  103493. FLAC__ASSERT(0 != encoder->protected_);
  103494. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103495. return false;
  103496. encoder->protected_->bits_per_sample = value;
  103497. return true;
  103498. }
  103499. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103500. {
  103501. FLAC__ASSERT(0 != encoder);
  103502. FLAC__ASSERT(0 != encoder->private_);
  103503. FLAC__ASSERT(0 != encoder->protected_);
  103504. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103505. return false;
  103506. encoder->protected_->sample_rate = value;
  103507. return true;
  103508. }
  103509. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103510. {
  103511. FLAC__bool ok = true;
  103512. FLAC__ASSERT(0 != encoder);
  103513. FLAC__ASSERT(0 != encoder->private_);
  103514. FLAC__ASSERT(0 != encoder->protected_);
  103515. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103516. return false;
  103517. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103518. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103519. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103520. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103521. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103522. #if 0
  103523. /* was: */
  103524. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103525. /* but it's too hard to specify the string in a locale-specific way */
  103526. #else
  103527. encoder->protected_->num_apodizations = 1;
  103528. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103529. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103530. #endif
  103531. #endif
  103532. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103533. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103534. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103535. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103536. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103537. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103538. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103539. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103540. return ok;
  103541. }
  103542. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103543. {
  103544. FLAC__ASSERT(0 != encoder);
  103545. FLAC__ASSERT(0 != encoder->private_);
  103546. FLAC__ASSERT(0 != encoder->protected_);
  103547. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103548. return false;
  103549. encoder->protected_->blocksize = value;
  103550. return true;
  103551. }
  103552. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103553. {
  103554. FLAC__ASSERT(0 != encoder);
  103555. FLAC__ASSERT(0 != encoder->private_);
  103556. FLAC__ASSERT(0 != encoder->protected_);
  103557. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103558. return false;
  103559. encoder->protected_->do_mid_side_stereo = value;
  103560. return true;
  103561. }
  103562. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103563. {
  103564. FLAC__ASSERT(0 != encoder);
  103565. FLAC__ASSERT(0 != encoder->private_);
  103566. FLAC__ASSERT(0 != encoder->protected_);
  103567. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103568. return false;
  103569. encoder->protected_->loose_mid_side_stereo = value;
  103570. return true;
  103571. }
  103572. /*@@@@add to tests*/
  103573. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103574. {
  103575. FLAC__ASSERT(0 != encoder);
  103576. FLAC__ASSERT(0 != encoder->private_);
  103577. FLAC__ASSERT(0 != encoder->protected_);
  103578. FLAC__ASSERT(0 != specification);
  103579. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103580. return false;
  103581. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103582. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103583. #else
  103584. encoder->protected_->num_apodizations = 0;
  103585. while(1) {
  103586. const char *s = strchr(specification, ';');
  103587. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103588. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103589. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103590. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103591. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103592. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103593. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103594. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103595. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103596. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103597. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103598. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103599. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103600. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103601. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103602. if (stddev > 0.0 && stddev <= 0.5) {
  103603. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103604. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103605. }
  103606. }
  103607. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103608. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103609. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103610. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103611. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103612. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103613. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103614. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103615. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103616. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103617. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103618. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103619. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103620. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103621. if (p >= 0.0 && p <= 1.0) {
  103622. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103623. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103624. }
  103625. }
  103626. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103627. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103628. if (encoder->protected_->num_apodizations == 32)
  103629. break;
  103630. if (s)
  103631. specification = s+1;
  103632. else
  103633. break;
  103634. }
  103635. if(encoder->protected_->num_apodizations == 0) {
  103636. encoder->protected_->num_apodizations = 1;
  103637. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103638. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103639. }
  103640. #endif
  103641. return true;
  103642. }
  103643. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned 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. encoder->protected_->max_lpc_order = value;
  103651. return true;
  103652. }
  103653. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103654. {
  103655. FLAC__ASSERT(0 != encoder);
  103656. FLAC__ASSERT(0 != encoder->private_);
  103657. FLAC__ASSERT(0 != encoder->protected_);
  103658. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103659. return false;
  103660. encoder->protected_->qlp_coeff_precision = value;
  103661. return true;
  103662. }
  103663. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103664. {
  103665. FLAC__ASSERT(0 != encoder);
  103666. FLAC__ASSERT(0 != encoder->private_);
  103667. FLAC__ASSERT(0 != encoder->protected_);
  103668. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103669. return false;
  103670. encoder->protected_->do_qlp_coeff_prec_search = value;
  103671. return true;
  103672. }
  103673. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103674. {
  103675. FLAC__ASSERT(0 != encoder);
  103676. FLAC__ASSERT(0 != encoder->private_);
  103677. FLAC__ASSERT(0 != encoder->protected_);
  103678. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103679. return false;
  103680. #if 0
  103681. /*@@@ deprecated: */
  103682. encoder->protected_->do_escape_coding = value;
  103683. #else
  103684. (void)value;
  103685. #endif
  103686. return true;
  103687. }
  103688. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103689. {
  103690. FLAC__ASSERT(0 != encoder);
  103691. FLAC__ASSERT(0 != encoder->private_);
  103692. FLAC__ASSERT(0 != encoder->protected_);
  103693. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103694. return false;
  103695. encoder->protected_->do_exhaustive_model_search = value;
  103696. return true;
  103697. }
  103698. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103699. {
  103700. FLAC__ASSERT(0 != encoder);
  103701. FLAC__ASSERT(0 != encoder->private_);
  103702. FLAC__ASSERT(0 != encoder->protected_);
  103703. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103704. return false;
  103705. encoder->protected_->min_residual_partition_order = value;
  103706. return true;
  103707. }
  103708. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103709. {
  103710. FLAC__ASSERT(0 != encoder);
  103711. FLAC__ASSERT(0 != encoder->private_);
  103712. FLAC__ASSERT(0 != encoder->protected_);
  103713. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103714. return false;
  103715. encoder->protected_->max_residual_partition_order = value;
  103716. return true;
  103717. }
  103718. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103719. {
  103720. FLAC__ASSERT(0 != encoder);
  103721. FLAC__ASSERT(0 != encoder->private_);
  103722. FLAC__ASSERT(0 != encoder->protected_);
  103723. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103724. return false;
  103725. #if 0
  103726. /*@@@ deprecated: */
  103727. encoder->protected_->rice_parameter_search_dist = value;
  103728. #else
  103729. (void)value;
  103730. #endif
  103731. return true;
  103732. }
  103733. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103734. {
  103735. FLAC__ASSERT(0 != encoder);
  103736. FLAC__ASSERT(0 != encoder->private_);
  103737. FLAC__ASSERT(0 != encoder->protected_);
  103738. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103739. return false;
  103740. encoder->protected_->total_samples_estimate = value;
  103741. return true;
  103742. }
  103743. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103744. {
  103745. FLAC__ASSERT(0 != encoder);
  103746. FLAC__ASSERT(0 != encoder->private_);
  103747. FLAC__ASSERT(0 != encoder->protected_);
  103748. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103749. return false;
  103750. if(0 == metadata)
  103751. num_blocks = 0;
  103752. if(0 == num_blocks)
  103753. metadata = 0;
  103754. /* realloc() does not do exactly what we want so... */
  103755. if(encoder->protected_->metadata) {
  103756. free(encoder->protected_->metadata);
  103757. encoder->protected_->metadata = 0;
  103758. encoder->protected_->num_metadata_blocks = 0;
  103759. }
  103760. if(num_blocks) {
  103761. FLAC__StreamMetadata **m;
  103762. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103763. return false;
  103764. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103765. encoder->protected_->metadata = m;
  103766. encoder->protected_->num_metadata_blocks = num_blocks;
  103767. }
  103768. #if FLAC__HAS_OGG
  103769. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103770. return false;
  103771. #endif
  103772. return true;
  103773. }
  103774. /*
  103775. * These three functions are not static, but not publically exposed in
  103776. * include/FLAC/ either. They are used by the test suite.
  103777. */
  103778. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103779. {
  103780. FLAC__ASSERT(0 != encoder);
  103781. FLAC__ASSERT(0 != encoder->private_);
  103782. FLAC__ASSERT(0 != encoder->protected_);
  103783. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103784. return false;
  103785. encoder->private_->disable_constant_subframes = value;
  103786. return true;
  103787. }
  103788. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103789. {
  103790. FLAC__ASSERT(0 != encoder);
  103791. FLAC__ASSERT(0 != encoder->private_);
  103792. FLAC__ASSERT(0 != encoder->protected_);
  103793. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103794. return false;
  103795. encoder->private_->disable_fixed_subframes = value;
  103796. return true;
  103797. }
  103798. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103799. {
  103800. FLAC__ASSERT(0 != encoder);
  103801. FLAC__ASSERT(0 != encoder->private_);
  103802. FLAC__ASSERT(0 != encoder->protected_);
  103803. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103804. return false;
  103805. encoder->private_->disable_verbatim_subframes = value;
  103806. return true;
  103807. }
  103808. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103809. {
  103810. FLAC__ASSERT(0 != encoder);
  103811. FLAC__ASSERT(0 != encoder->private_);
  103812. FLAC__ASSERT(0 != encoder->protected_);
  103813. return encoder->protected_->state;
  103814. }
  103815. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103816. {
  103817. FLAC__ASSERT(0 != encoder);
  103818. FLAC__ASSERT(0 != encoder->private_);
  103819. FLAC__ASSERT(0 != encoder->protected_);
  103820. if(encoder->protected_->verify)
  103821. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103822. else
  103823. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103824. }
  103825. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103826. {
  103827. FLAC__ASSERT(0 != encoder);
  103828. FLAC__ASSERT(0 != encoder->private_);
  103829. FLAC__ASSERT(0 != encoder->protected_);
  103830. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103831. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103832. else
  103833. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103834. }
  103835. 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)
  103836. {
  103837. FLAC__ASSERT(0 != encoder);
  103838. FLAC__ASSERT(0 != encoder->private_);
  103839. FLAC__ASSERT(0 != encoder->protected_);
  103840. if(0 != absolute_sample)
  103841. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103842. if(0 != frame_number)
  103843. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103844. if(0 != channel)
  103845. *channel = encoder->private_->verify.error_stats.channel;
  103846. if(0 != sample)
  103847. *sample = encoder->private_->verify.error_stats.sample;
  103848. if(0 != expected)
  103849. *expected = encoder->private_->verify.error_stats.expected;
  103850. if(0 != got)
  103851. *got = encoder->private_->verify.error_stats.got;
  103852. }
  103853. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103854. {
  103855. FLAC__ASSERT(0 != encoder);
  103856. FLAC__ASSERT(0 != encoder->private_);
  103857. FLAC__ASSERT(0 != encoder->protected_);
  103858. return encoder->protected_->verify;
  103859. }
  103860. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103861. {
  103862. FLAC__ASSERT(0 != encoder);
  103863. FLAC__ASSERT(0 != encoder->private_);
  103864. FLAC__ASSERT(0 != encoder->protected_);
  103865. return encoder->protected_->streamable_subset;
  103866. }
  103867. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103868. {
  103869. FLAC__ASSERT(0 != encoder);
  103870. FLAC__ASSERT(0 != encoder->private_);
  103871. FLAC__ASSERT(0 != encoder->protected_);
  103872. return encoder->protected_->do_md5;
  103873. }
  103874. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103875. {
  103876. FLAC__ASSERT(0 != encoder);
  103877. FLAC__ASSERT(0 != encoder->private_);
  103878. FLAC__ASSERT(0 != encoder->protected_);
  103879. return encoder->protected_->channels;
  103880. }
  103881. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103882. {
  103883. FLAC__ASSERT(0 != encoder);
  103884. FLAC__ASSERT(0 != encoder->private_);
  103885. FLAC__ASSERT(0 != encoder->protected_);
  103886. return encoder->protected_->bits_per_sample;
  103887. }
  103888. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103889. {
  103890. FLAC__ASSERT(0 != encoder);
  103891. FLAC__ASSERT(0 != encoder->private_);
  103892. FLAC__ASSERT(0 != encoder->protected_);
  103893. return encoder->protected_->sample_rate;
  103894. }
  103895. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103896. {
  103897. FLAC__ASSERT(0 != encoder);
  103898. FLAC__ASSERT(0 != encoder->private_);
  103899. FLAC__ASSERT(0 != encoder->protected_);
  103900. return encoder->protected_->blocksize;
  103901. }
  103902. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103903. {
  103904. FLAC__ASSERT(0 != encoder);
  103905. FLAC__ASSERT(0 != encoder->private_);
  103906. FLAC__ASSERT(0 != encoder->protected_);
  103907. return encoder->protected_->do_mid_side_stereo;
  103908. }
  103909. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103910. {
  103911. FLAC__ASSERT(0 != encoder);
  103912. FLAC__ASSERT(0 != encoder->private_);
  103913. FLAC__ASSERT(0 != encoder->protected_);
  103914. return encoder->protected_->loose_mid_side_stereo;
  103915. }
  103916. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103917. {
  103918. FLAC__ASSERT(0 != encoder);
  103919. FLAC__ASSERT(0 != encoder->private_);
  103920. FLAC__ASSERT(0 != encoder->protected_);
  103921. return encoder->protected_->max_lpc_order;
  103922. }
  103923. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103924. {
  103925. FLAC__ASSERT(0 != encoder);
  103926. FLAC__ASSERT(0 != encoder->private_);
  103927. FLAC__ASSERT(0 != encoder->protected_);
  103928. return encoder->protected_->qlp_coeff_precision;
  103929. }
  103930. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103931. {
  103932. FLAC__ASSERT(0 != encoder);
  103933. FLAC__ASSERT(0 != encoder->private_);
  103934. FLAC__ASSERT(0 != encoder->protected_);
  103935. return encoder->protected_->do_qlp_coeff_prec_search;
  103936. }
  103937. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103938. {
  103939. FLAC__ASSERT(0 != encoder);
  103940. FLAC__ASSERT(0 != encoder->private_);
  103941. FLAC__ASSERT(0 != encoder->protected_);
  103942. return encoder->protected_->do_escape_coding;
  103943. }
  103944. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103945. {
  103946. FLAC__ASSERT(0 != encoder);
  103947. FLAC__ASSERT(0 != encoder->private_);
  103948. FLAC__ASSERT(0 != encoder->protected_);
  103949. return encoder->protected_->do_exhaustive_model_search;
  103950. }
  103951. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103952. {
  103953. FLAC__ASSERT(0 != encoder);
  103954. FLAC__ASSERT(0 != encoder->private_);
  103955. FLAC__ASSERT(0 != encoder->protected_);
  103956. return encoder->protected_->min_residual_partition_order;
  103957. }
  103958. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103959. {
  103960. FLAC__ASSERT(0 != encoder);
  103961. FLAC__ASSERT(0 != encoder->private_);
  103962. FLAC__ASSERT(0 != encoder->protected_);
  103963. return encoder->protected_->max_residual_partition_order;
  103964. }
  103965. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103966. {
  103967. FLAC__ASSERT(0 != encoder);
  103968. FLAC__ASSERT(0 != encoder->private_);
  103969. FLAC__ASSERT(0 != encoder->protected_);
  103970. return encoder->protected_->rice_parameter_search_dist;
  103971. }
  103972. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103973. {
  103974. FLAC__ASSERT(0 != encoder);
  103975. FLAC__ASSERT(0 != encoder->private_);
  103976. FLAC__ASSERT(0 != encoder->protected_);
  103977. return encoder->protected_->total_samples_estimate;
  103978. }
  103979. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103980. {
  103981. unsigned i, j = 0, channel;
  103982. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103983. FLAC__ASSERT(0 != encoder);
  103984. FLAC__ASSERT(0 != encoder->private_);
  103985. FLAC__ASSERT(0 != encoder->protected_);
  103986. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103987. do {
  103988. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103989. if(encoder->protected_->verify)
  103990. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103991. for(channel = 0; channel < channels; channel++)
  103992. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103993. if(encoder->protected_->do_mid_side_stereo) {
  103994. FLAC__ASSERT(channels == 2);
  103995. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103996. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103997. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103998. 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' ! */
  103999. }
  104000. }
  104001. else
  104002. j += n;
  104003. encoder->private_->current_sample_number += n;
  104004. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104005. if(encoder->private_->current_sample_number > blocksize) {
  104006. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  104007. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104008. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104009. return false;
  104010. /* move unprocessed overread samples to beginnings of arrays */
  104011. for(channel = 0; channel < channels; channel++)
  104012. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104013. if(encoder->protected_->do_mid_side_stereo) {
  104014. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104015. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104016. }
  104017. encoder->private_->current_sample_number = 1;
  104018. }
  104019. } while(j < samples);
  104020. return true;
  104021. }
  104022. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  104023. {
  104024. unsigned i, j, k, channel;
  104025. FLAC__int32 x, mid, side;
  104026. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104027. FLAC__ASSERT(0 != encoder);
  104028. FLAC__ASSERT(0 != encoder->private_);
  104029. FLAC__ASSERT(0 != encoder->protected_);
  104030. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104031. j = k = 0;
  104032. /*
  104033. * we have several flavors of the same basic loop, optimized for
  104034. * different conditions:
  104035. */
  104036. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104037. /*
  104038. * stereo coding: unroll channel loop
  104039. */
  104040. do {
  104041. if(encoder->protected_->verify)
  104042. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104043. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104044. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104045. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104046. x = buffer[k++];
  104047. encoder->private_->integer_signal[1][i] = x;
  104048. mid += x;
  104049. side -= x;
  104050. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104051. encoder->private_->integer_signal_mid_side[1][i] = side;
  104052. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104053. }
  104054. encoder->private_->current_sample_number = i;
  104055. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104056. if(i > blocksize) {
  104057. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104058. return false;
  104059. /* move unprocessed overread samples to beginnings of arrays */
  104060. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104061. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104062. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104063. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104064. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104065. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104066. encoder->private_->current_sample_number = 1;
  104067. }
  104068. } while(j < samples);
  104069. }
  104070. else {
  104071. /*
  104072. * independent channel coding: buffer each channel in inner loop
  104073. */
  104074. do {
  104075. if(encoder->protected_->verify)
  104076. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104077. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104078. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104079. for(channel = 0; channel < channels; channel++)
  104080. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104081. }
  104082. encoder->private_->current_sample_number = i;
  104083. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104084. if(i > blocksize) {
  104085. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104086. return false;
  104087. /* move unprocessed overread samples to beginnings of arrays */
  104088. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104089. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104090. for(channel = 0; channel < channels; channel++)
  104091. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104092. encoder->private_->current_sample_number = 1;
  104093. }
  104094. } while(j < samples);
  104095. }
  104096. return true;
  104097. }
  104098. /***********************************************************************
  104099. *
  104100. * Private class methods
  104101. *
  104102. ***********************************************************************/
  104103. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104104. {
  104105. FLAC__ASSERT(0 != encoder);
  104106. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104107. encoder->protected_->verify = true;
  104108. #else
  104109. encoder->protected_->verify = false;
  104110. #endif
  104111. encoder->protected_->streamable_subset = true;
  104112. encoder->protected_->do_md5 = true;
  104113. encoder->protected_->do_mid_side_stereo = false;
  104114. encoder->protected_->loose_mid_side_stereo = false;
  104115. encoder->protected_->channels = 2;
  104116. encoder->protected_->bits_per_sample = 16;
  104117. encoder->protected_->sample_rate = 44100;
  104118. encoder->protected_->blocksize = 0;
  104119. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104120. encoder->protected_->num_apodizations = 1;
  104121. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104122. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104123. #endif
  104124. encoder->protected_->max_lpc_order = 0;
  104125. encoder->protected_->qlp_coeff_precision = 0;
  104126. encoder->protected_->do_qlp_coeff_prec_search = false;
  104127. encoder->protected_->do_exhaustive_model_search = false;
  104128. encoder->protected_->do_escape_coding = false;
  104129. encoder->protected_->min_residual_partition_order = 0;
  104130. encoder->protected_->max_residual_partition_order = 0;
  104131. encoder->protected_->rice_parameter_search_dist = 0;
  104132. encoder->protected_->total_samples_estimate = 0;
  104133. encoder->protected_->metadata = 0;
  104134. encoder->protected_->num_metadata_blocks = 0;
  104135. encoder->private_->seek_table = 0;
  104136. encoder->private_->disable_constant_subframes = false;
  104137. encoder->private_->disable_fixed_subframes = false;
  104138. encoder->private_->disable_verbatim_subframes = false;
  104139. #if FLAC__HAS_OGG
  104140. encoder->private_->is_ogg = false;
  104141. #endif
  104142. encoder->private_->read_callback = 0;
  104143. encoder->private_->write_callback = 0;
  104144. encoder->private_->seek_callback = 0;
  104145. encoder->private_->tell_callback = 0;
  104146. encoder->private_->metadata_callback = 0;
  104147. encoder->private_->progress_callback = 0;
  104148. encoder->private_->client_data = 0;
  104149. #if FLAC__HAS_OGG
  104150. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104151. #endif
  104152. }
  104153. void free_(FLAC__StreamEncoder *encoder)
  104154. {
  104155. unsigned i, channel;
  104156. FLAC__ASSERT(0 != encoder);
  104157. if(encoder->protected_->metadata) {
  104158. free(encoder->protected_->metadata);
  104159. encoder->protected_->metadata = 0;
  104160. encoder->protected_->num_metadata_blocks = 0;
  104161. }
  104162. for(i = 0; i < encoder->protected_->channels; i++) {
  104163. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104164. free(encoder->private_->integer_signal_unaligned[i]);
  104165. encoder->private_->integer_signal_unaligned[i] = 0;
  104166. }
  104167. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104168. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104169. free(encoder->private_->real_signal_unaligned[i]);
  104170. encoder->private_->real_signal_unaligned[i] = 0;
  104171. }
  104172. #endif
  104173. }
  104174. for(i = 0; i < 2; i++) {
  104175. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104176. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104177. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104178. }
  104179. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104180. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104181. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104182. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104183. }
  104184. #endif
  104185. }
  104186. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104187. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104188. if(0 != encoder->private_->window_unaligned[i]) {
  104189. free(encoder->private_->window_unaligned[i]);
  104190. encoder->private_->window_unaligned[i] = 0;
  104191. }
  104192. }
  104193. if(0 != encoder->private_->windowed_signal_unaligned) {
  104194. free(encoder->private_->windowed_signal_unaligned);
  104195. encoder->private_->windowed_signal_unaligned = 0;
  104196. }
  104197. #endif
  104198. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104199. for(i = 0; i < 2; i++) {
  104200. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104201. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104202. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104203. }
  104204. }
  104205. }
  104206. for(channel = 0; channel < 2; channel++) {
  104207. for(i = 0; i < 2; i++) {
  104208. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104209. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104210. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104211. }
  104212. }
  104213. }
  104214. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104215. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104216. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104217. }
  104218. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104219. free(encoder->private_->raw_bits_per_partition_unaligned);
  104220. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104221. }
  104222. if(encoder->protected_->verify) {
  104223. for(i = 0; i < encoder->protected_->channels; i++) {
  104224. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104225. free(encoder->private_->verify.input_fifo.data[i]);
  104226. encoder->private_->verify.input_fifo.data[i] = 0;
  104227. }
  104228. }
  104229. }
  104230. FLAC__bitwriter_free(encoder->private_->frame);
  104231. }
  104232. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104233. {
  104234. FLAC__bool ok;
  104235. unsigned i, channel;
  104236. FLAC__ASSERT(new_blocksize > 0);
  104237. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104238. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104239. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104240. if(new_blocksize <= encoder->private_->input_capacity)
  104241. return true;
  104242. ok = true;
  104243. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104244. * requires that the input arrays (in our case the integer signals)
  104245. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104246. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104247. */
  104248. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104249. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104250. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104251. encoder->private_->integer_signal[i] += 4;
  104252. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104253. #if 0 /* @@@ currently unused */
  104254. if(encoder->protected_->max_lpc_order > 0)
  104255. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104256. #endif
  104257. #endif
  104258. }
  104259. for(i = 0; ok && i < 2; i++) {
  104260. 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]);
  104261. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104262. encoder->private_->integer_signal_mid_side[i] += 4;
  104263. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104264. #if 0 /* @@@ currently unused */
  104265. if(encoder->protected_->max_lpc_order > 0)
  104266. 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]);
  104267. #endif
  104268. #endif
  104269. }
  104270. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104271. if(ok && encoder->protected_->max_lpc_order > 0) {
  104272. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104273. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104274. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104275. }
  104276. #endif
  104277. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104278. for(i = 0; ok && i < 2; i++) {
  104279. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104280. }
  104281. }
  104282. for(channel = 0; ok && channel < 2; channel++) {
  104283. for(i = 0; ok && i < 2; i++) {
  104284. 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]);
  104285. }
  104286. }
  104287. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104288. /*@@@ 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) */
  104289. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104290. if(encoder->protected_->do_escape_coding)
  104291. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104292. /* now adjust the windows if the blocksize has changed */
  104293. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104294. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104295. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104296. switch(encoder->protected_->apodizations[i].type) {
  104297. case FLAC__APODIZATION_BARTLETT:
  104298. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104299. break;
  104300. case FLAC__APODIZATION_BARTLETT_HANN:
  104301. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104302. break;
  104303. case FLAC__APODIZATION_BLACKMAN:
  104304. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104305. break;
  104306. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104307. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104308. break;
  104309. case FLAC__APODIZATION_CONNES:
  104310. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104311. break;
  104312. case FLAC__APODIZATION_FLATTOP:
  104313. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104314. break;
  104315. case FLAC__APODIZATION_GAUSS:
  104316. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104317. break;
  104318. case FLAC__APODIZATION_HAMMING:
  104319. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104320. break;
  104321. case FLAC__APODIZATION_HANN:
  104322. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104323. break;
  104324. case FLAC__APODIZATION_KAISER_BESSEL:
  104325. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104326. break;
  104327. case FLAC__APODIZATION_NUTTALL:
  104328. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104329. break;
  104330. case FLAC__APODIZATION_RECTANGLE:
  104331. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104332. break;
  104333. case FLAC__APODIZATION_TRIANGLE:
  104334. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104335. break;
  104336. case FLAC__APODIZATION_TUKEY:
  104337. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104338. break;
  104339. case FLAC__APODIZATION_WELCH:
  104340. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104341. break;
  104342. default:
  104343. FLAC__ASSERT(0);
  104344. /* double protection */
  104345. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104346. break;
  104347. }
  104348. }
  104349. }
  104350. #endif
  104351. if(ok)
  104352. encoder->private_->input_capacity = new_blocksize;
  104353. else
  104354. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104355. return ok;
  104356. }
  104357. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104358. {
  104359. const FLAC__byte *buffer;
  104360. size_t bytes;
  104361. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104362. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104363. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104364. return false;
  104365. }
  104366. if(encoder->protected_->verify) {
  104367. encoder->private_->verify.output.data = buffer;
  104368. encoder->private_->verify.output.bytes = bytes;
  104369. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104370. encoder->private_->verify.needs_magic_hack = true;
  104371. }
  104372. else {
  104373. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104374. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104375. FLAC__bitwriter_clear(encoder->private_->frame);
  104376. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104377. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104378. return false;
  104379. }
  104380. }
  104381. }
  104382. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104383. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104384. FLAC__bitwriter_clear(encoder->private_->frame);
  104385. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104386. return false;
  104387. }
  104388. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104389. FLAC__bitwriter_clear(encoder->private_->frame);
  104390. if(samples > 0) {
  104391. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104392. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104393. }
  104394. return true;
  104395. }
  104396. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104397. {
  104398. FLAC__StreamEncoderWriteStatus status;
  104399. FLAC__uint64 output_position = 0;
  104400. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104401. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104402. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104403. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104404. }
  104405. /*
  104406. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104407. */
  104408. if(samples == 0) {
  104409. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104410. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104411. encoder->protected_->streaminfo_offset = output_position;
  104412. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104413. encoder->protected_->seektable_offset = output_position;
  104414. }
  104415. /*
  104416. * Mark the current seek point if hit (if audio_offset == 0 that
  104417. * means we're still writing metadata and haven't hit the first
  104418. * frame yet)
  104419. */
  104420. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104421. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104422. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104423. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104424. FLAC__uint64 test_sample;
  104425. unsigned i;
  104426. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104427. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104428. if(test_sample > frame_last_sample) {
  104429. break;
  104430. }
  104431. else if(test_sample >= frame_first_sample) {
  104432. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104433. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104434. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104435. encoder->private_->first_seekpoint_to_check++;
  104436. /* DO NOT: "break;" and here's why:
  104437. * The seektable template may contain more than one target
  104438. * sample for any given frame; we will keep looping, generating
  104439. * duplicate seekpoints for them, and we'll clean it up later,
  104440. * just before writing the seektable back to the metadata.
  104441. */
  104442. }
  104443. else {
  104444. encoder->private_->first_seekpoint_to_check++;
  104445. }
  104446. }
  104447. }
  104448. #if FLAC__HAS_OGG
  104449. if(encoder->private_->is_ogg) {
  104450. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104451. &encoder->protected_->ogg_encoder_aspect,
  104452. buffer,
  104453. bytes,
  104454. samples,
  104455. encoder->private_->current_frame_number,
  104456. is_last_block,
  104457. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104458. encoder,
  104459. encoder->private_->client_data
  104460. );
  104461. }
  104462. else
  104463. #endif
  104464. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104465. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104466. encoder->private_->bytes_written += bytes;
  104467. encoder->private_->samples_written += samples;
  104468. /* we keep a high watermark on the number of frames written because
  104469. * when the encoder goes back to write metadata, 'current_frame'
  104470. * will drop back to 0.
  104471. */
  104472. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104473. }
  104474. else
  104475. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104476. return status;
  104477. }
  104478. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104479. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104480. {
  104481. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104482. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104483. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104484. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104485. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104486. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104487. FLAC__StreamEncoderSeekStatus seek_status;
  104488. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104489. /* All this is based on intimate knowledge of the stream header
  104490. * layout, but a change to the header format that would break this
  104491. * would also break all streams encoded in the previous format.
  104492. */
  104493. /*
  104494. * Write MD5 signature
  104495. */
  104496. {
  104497. const unsigned md5_offset =
  104498. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104499. (
  104500. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104501. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104502. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104503. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104504. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104505. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104506. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104507. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104508. ) / 8;
  104509. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104510. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104511. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104512. return;
  104513. }
  104514. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104515. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104516. return;
  104517. }
  104518. }
  104519. /*
  104520. * Write total samples
  104521. */
  104522. {
  104523. const unsigned total_samples_byte_offset =
  104524. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104525. (
  104526. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104527. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104528. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104529. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104530. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104531. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104532. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104533. - 4
  104534. ) / 8;
  104535. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104536. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104537. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104538. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104539. b[4] = (FLAC__byte)(samples & 0xFF);
  104540. 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) {
  104541. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104542. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104543. return;
  104544. }
  104545. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104546. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104547. return;
  104548. }
  104549. }
  104550. /*
  104551. * Write min/max framesize
  104552. */
  104553. {
  104554. const unsigned min_framesize_offset =
  104555. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104556. (
  104557. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104558. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104559. ) / 8;
  104560. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104561. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104562. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104563. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104564. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104565. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104566. 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) {
  104567. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104568. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104569. return;
  104570. }
  104571. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104572. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104573. return;
  104574. }
  104575. }
  104576. /*
  104577. * Write seektable
  104578. */
  104579. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104580. unsigned i;
  104581. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104582. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104583. 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) {
  104584. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104585. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104586. return;
  104587. }
  104588. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104589. FLAC__uint64 xx;
  104590. unsigned x;
  104591. xx = encoder->private_->seek_table->points[i].sample_number;
  104592. b[7] = (FLAC__byte)xx; xx >>= 8;
  104593. b[6] = (FLAC__byte)xx; xx >>= 8;
  104594. b[5] = (FLAC__byte)xx; xx >>= 8;
  104595. b[4] = (FLAC__byte)xx; xx >>= 8;
  104596. b[3] = (FLAC__byte)xx; xx >>= 8;
  104597. b[2] = (FLAC__byte)xx; xx >>= 8;
  104598. b[1] = (FLAC__byte)xx; xx >>= 8;
  104599. b[0] = (FLAC__byte)xx; xx >>= 8;
  104600. xx = encoder->private_->seek_table->points[i].stream_offset;
  104601. b[15] = (FLAC__byte)xx; xx >>= 8;
  104602. b[14] = (FLAC__byte)xx; xx >>= 8;
  104603. b[13] = (FLAC__byte)xx; xx >>= 8;
  104604. b[12] = (FLAC__byte)xx; xx >>= 8;
  104605. b[11] = (FLAC__byte)xx; xx >>= 8;
  104606. b[10] = (FLAC__byte)xx; xx >>= 8;
  104607. b[9] = (FLAC__byte)xx; xx >>= 8;
  104608. b[8] = (FLAC__byte)xx; xx >>= 8;
  104609. x = encoder->private_->seek_table->points[i].frame_samples;
  104610. b[17] = (FLAC__byte)x; x >>= 8;
  104611. b[16] = (FLAC__byte)x; x >>= 8;
  104612. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104613. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104614. return;
  104615. }
  104616. }
  104617. }
  104618. }
  104619. #if FLAC__HAS_OGG
  104620. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104621. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104622. {
  104623. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104624. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104625. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104626. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104627. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104628. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104629. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104630. FLAC__STREAM_SYNC_LENGTH
  104631. ;
  104632. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104633. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104634. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104635. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104636. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104637. ogg_page page;
  104638. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104639. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104640. /* Pre-check that client supports seeking, since we don't want the
  104641. * ogg_helper code to ever have to deal with this condition.
  104642. */
  104643. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104644. return;
  104645. /* All this is based on intimate knowledge of the stream header
  104646. * layout, but a change to the header format that would break this
  104647. * would also break all streams encoded in the previous format.
  104648. */
  104649. /**
  104650. ** Write STREAMINFO stats
  104651. **/
  104652. simple_ogg_page__init(&page);
  104653. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104654. simple_ogg_page__clear(&page);
  104655. return; /* state already set */
  104656. }
  104657. /*
  104658. * Write MD5 signature
  104659. */
  104660. {
  104661. const unsigned md5_offset =
  104662. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104663. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104664. (
  104665. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104666. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104667. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104668. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104669. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104670. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104671. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104672. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104673. ) / 8;
  104674. if(md5_offset + 16 > (unsigned)page.body_len) {
  104675. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104676. simple_ogg_page__clear(&page);
  104677. return;
  104678. }
  104679. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104680. }
  104681. /*
  104682. * Write total samples
  104683. */
  104684. {
  104685. const unsigned total_samples_byte_offset =
  104686. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104687. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104688. (
  104689. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104690. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104691. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104692. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104693. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104694. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104695. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104696. - 4
  104697. ) / 8;
  104698. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104699. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104700. simple_ogg_page__clear(&page);
  104701. return;
  104702. }
  104703. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104704. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104705. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104706. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104707. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104708. b[4] = (FLAC__byte)(samples & 0xFF);
  104709. memcpy(page.body + total_samples_byte_offset, b, 5);
  104710. }
  104711. /*
  104712. * Write min/max framesize
  104713. */
  104714. {
  104715. const unsigned min_framesize_offset =
  104716. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104717. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104718. (
  104719. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104720. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104721. ) / 8;
  104722. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104723. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104724. simple_ogg_page__clear(&page);
  104725. return;
  104726. }
  104727. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104728. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104729. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104730. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104731. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104732. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104733. memcpy(page.body + min_framesize_offset, b, 6);
  104734. }
  104735. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104736. simple_ogg_page__clear(&page);
  104737. return; /* state already set */
  104738. }
  104739. simple_ogg_page__clear(&page);
  104740. /*
  104741. * Write seektable
  104742. */
  104743. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104744. unsigned i;
  104745. FLAC__byte *p;
  104746. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104747. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104748. simple_ogg_page__init(&page);
  104749. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104750. simple_ogg_page__clear(&page);
  104751. return; /* state already set */
  104752. }
  104753. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104754. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104755. simple_ogg_page__clear(&page);
  104756. return;
  104757. }
  104758. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104759. FLAC__uint64 xx;
  104760. unsigned x;
  104761. xx = encoder->private_->seek_table->points[i].sample_number;
  104762. b[7] = (FLAC__byte)xx; xx >>= 8;
  104763. b[6] = (FLAC__byte)xx; xx >>= 8;
  104764. b[5] = (FLAC__byte)xx; xx >>= 8;
  104765. b[4] = (FLAC__byte)xx; xx >>= 8;
  104766. b[3] = (FLAC__byte)xx; xx >>= 8;
  104767. b[2] = (FLAC__byte)xx; xx >>= 8;
  104768. b[1] = (FLAC__byte)xx; xx >>= 8;
  104769. b[0] = (FLAC__byte)xx; xx >>= 8;
  104770. xx = encoder->private_->seek_table->points[i].stream_offset;
  104771. b[15] = (FLAC__byte)xx; xx >>= 8;
  104772. b[14] = (FLAC__byte)xx; xx >>= 8;
  104773. b[13] = (FLAC__byte)xx; xx >>= 8;
  104774. b[12] = (FLAC__byte)xx; xx >>= 8;
  104775. b[11] = (FLAC__byte)xx; xx >>= 8;
  104776. b[10] = (FLAC__byte)xx; xx >>= 8;
  104777. b[9] = (FLAC__byte)xx; xx >>= 8;
  104778. b[8] = (FLAC__byte)xx; xx >>= 8;
  104779. x = encoder->private_->seek_table->points[i].frame_samples;
  104780. b[17] = (FLAC__byte)x; x >>= 8;
  104781. b[16] = (FLAC__byte)x; x >>= 8;
  104782. memcpy(p, b, 18);
  104783. }
  104784. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104785. simple_ogg_page__clear(&page);
  104786. return; /* state already set */
  104787. }
  104788. simple_ogg_page__clear(&page);
  104789. }
  104790. }
  104791. #endif
  104792. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104793. {
  104794. FLAC__uint16 crc;
  104795. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104796. /*
  104797. * Accumulate raw signal to the MD5 signature
  104798. */
  104799. 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)) {
  104800. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104801. return false;
  104802. }
  104803. /*
  104804. * Process the frame header and subframes into the frame bitbuffer
  104805. */
  104806. if(!process_subframes_(encoder, is_fractional_block)) {
  104807. /* the above function sets the state for us in case of an error */
  104808. return false;
  104809. }
  104810. /*
  104811. * Zero-pad the frame to a byte_boundary
  104812. */
  104813. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104814. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104815. return false;
  104816. }
  104817. /*
  104818. * CRC-16 the whole thing
  104819. */
  104820. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104821. if(
  104822. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104823. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104824. ) {
  104825. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104826. return false;
  104827. }
  104828. /*
  104829. * Write it
  104830. */
  104831. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104832. /* the above function sets the state for us in case of an error */
  104833. return false;
  104834. }
  104835. /*
  104836. * Get ready for the next frame
  104837. */
  104838. encoder->private_->current_sample_number = 0;
  104839. encoder->private_->current_frame_number++;
  104840. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104841. return true;
  104842. }
  104843. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104844. {
  104845. FLAC__FrameHeader frame_header;
  104846. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104847. FLAC__bool do_independent, do_mid_side;
  104848. /*
  104849. * Calculate the min,max Rice partition orders
  104850. */
  104851. if(is_fractional_block) {
  104852. max_partition_order = 0;
  104853. }
  104854. else {
  104855. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104856. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104857. }
  104858. min_partition_order = min(min_partition_order, max_partition_order);
  104859. /*
  104860. * Setup the frame
  104861. */
  104862. frame_header.blocksize = encoder->protected_->blocksize;
  104863. frame_header.sample_rate = encoder->protected_->sample_rate;
  104864. frame_header.channels = encoder->protected_->channels;
  104865. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104866. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104867. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104868. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104869. /*
  104870. * Figure out what channel assignments to try
  104871. */
  104872. if(encoder->protected_->do_mid_side_stereo) {
  104873. if(encoder->protected_->loose_mid_side_stereo) {
  104874. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104875. do_independent = true;
  104876. do_mid_side = true;
  104877. }
  104878. else {
  104879. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104880. do_mid_side = !do_independent;
  104881. }
  104882. }
  104883. else {
  104884. do_independent = true;
  104885. do_mid_side = true;
  104886. }
  104887. }
  104888. else {
  104889. do_independent = true;
  104890. do_mid_side = false;
  104891. }
  104892. FLAC__ASSERT(do_independent || do_mid_side);
  104893. /*
  104894. * Check for wasted bits; set effective bps for each subframe
  104895. */
  104896. if(do_independent) {
  104897. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104898. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104899. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104900. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104901. }
  104902. }
  104903. if(do_mid_side) {
  104904. FLAC__ASSERT(encoder->protected_->channels == 2);
  104905. for(channel = 0; channel < 2; channel++) {
  104906. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104907. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104908. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104909. }
  104910. }
  104911. /*
  104912. * First do a normal encoding pass of each independent channel
  104913. */
  104914. if(do_independent) {
  104915. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104916. if(!
  104917. process_subframe_(
  104918. encoder,
  104919. min_partition_order,
  104920. max_partition_order,
  104921. &frame_header,
  104922. encoder->private_->subframe_bps[channel],
  104923. encoder->private_->integer_signal[channel],
  104924. encoder->private_->subframe_workspace_ptr[channel],
  104925. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104926. encoder->private_->residual_workspace[channel],
  104927. encoder->private_->best_subframe+channel,
  104928. encoder->private_->best_subframe_bits+channel
  104929. )
  104930. )
  104931. return false;
  104932. }
  104933. }
  104934. /*
  104935. * Now do mid and side channels if requested
  104936. */
  104937. if(do_mid_side) {
  104938. FLAC__ASSERT(encoder->protected_->channels == 2);
  104939. for(channel = 0; channel < 2; channel++) {
  104940. if(!
  104941. process_subframe_(
  104942. encoder,
  104943. min_partition_order,
  104944. max_partition_order,
  104945. &frame_header,
  104946. encoder->private_->subframe_bps_mid_side[channel],
  104947. encoder->private_->integer_signal_mid_side[channel],
  104948. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104949. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104950. encoder->private_->residual_workspace_mid_side[channel],
  104951. encoder->private_->best_subframe_mid_side+channel,
  104952. encoder->private_->best_subframe_bits_mid_side+channel
  104953. )
  104954. )
  104955. return false;
  104956. }
  104957. }
  104958. /*
  104959. * Compose the frame bitbuffer
  104960. */
  104961. if(do_mid_side) {
  104962. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104963. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104964. FLAC__ChannelAssignment channel_assignment;
  104965. FLAC__ASSERT(encoder->protected_->channels == 2);
  104966. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104967. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104968. }
  104969. else {
  104970. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104971. unsigned min_bits;
  104972. int ca;
  104973. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104974. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104975. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104976. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104977. FLAC__ASSERT(do_independent && do_mid_side);
  104978. /* We have to figure out which channel assignent results in the smallest frame */
  104979. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104980. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104981. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104982. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104983. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104984. min_bits = bits[channel_assignment];
  104985. for(ca = 1; ca <= 3; ca++) {
  104986. if(bits[ca] < min_bits) {
  104987. min_bits = bits[ca];
  104988. channel_assignment = (FLAC__ChannelAssignment)ca;
  104989. }
  104990. }
  104991. }
  104992. frame_header.channel_assignment = channel_assignment;
  104993. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104994. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104995. return false;
  104996. }
  104997. switch(channel_assignment) {
  104998. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104999. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105000. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105001. break;
  105002. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105003. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105004. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105005. break;
  105006. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105007. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105008. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105009. break;
  105010. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105011. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  105012. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105013. break;
  105014. default:
  105015. FLAC__ASSERT(0);
  105016. }
  105017. switch(channel_assignment) {
  105018. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105019. left_bps = encoder->private_->subframe_bps [0];
  105020. right_bps = encoder->private_->subframe_bps [1];
  105021. break;
  105022. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105023. left_bps = encoder->private_->subframe_bps [0];
  105024. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105025. break;
  105026. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105027. left_bps = encoder->private_->subframe_bps_mid_side[1];
  105028. right_bps = encoder->private_->subframe_bps [1];
  105029. break;
  105030. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105031. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105032. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105033. break;
  105034. default:
  105035. FLAC__ASSERT(0);
  105036. }
  105037. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105038. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105039. return false;
  105040. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105041. return false;
  105042. }
  105043. else {
  105044. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105045. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105046. return false;
  105047. }
  105048. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105049. 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)) {
  105050. /* the above function sets the state for us in case of an error */
  105051. return false;
  105052. }
  105053. }
  105054. }
  105055. if(encoder->protected_->loose_mid_side_stereo) {
  105056. encoder->private_->loose_mid_side_stereo_frame_count++;
  105057. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105058. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105059. }
  105060. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105061. return true;
  105062. }
  105063. FLAC__bool process_subframe_(
  105064. FLAC__StreamEncoder *encoder,
  105065. unsigned min_partition_order,
  105066. unsigned max_partition_order,
  105067. const FLAC__FrameHeader *frame_header,
  105068. unsigned subframe_bps,
  105069. const FLAC__int32 integer_signal[],
  105070. FLAC__Subframe *subframe[2],
  105071. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105072. FLAC__int32 *residual[2],
  105073. unsigned *best_subframe,
  105074. unsigned *best_bits
  105075. )
  105076. {
  105077. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105078. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105079. #else
  105080. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105081. #endif
  105082. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105083. FLAC__double lpc_residual_bits_per_sample;
  105084. 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 */
  105085. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105086. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105087. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105088. #endif
  105089. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105090. unsigned rice_parameter;
  105091. unsigned _candidate_bits, _best_bits;
  105092. unsigned _best_subframe;
  105093. /* only use RICE2 partitions if stream bps > 16 */
  105094. 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;
  105095. FLAC__ASSERT(frame_header->blocksize > 0);
  105096. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105097. _best_subframe = 0;
  105098. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105099. _best_bits = UINT_MAX;
  105100. else
  105101. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105102. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105103. unsigned signal_is_constant = false;
  105104. 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);
  105105. /* check for constant subframe */
  105106. if(
  105107. !encoder->private_->disable_constant_subframes &&
  105108. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105109. fixed_residual_bits_per_sample[1] == 0.0
  105110. #else
  105111. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105112. #endif
  105113. ) {
  105114. /* the above means it's possible all samples are the same value; now double-check it: */
  105115. unsigned i;
  105116. signal_is_constant = true;
  105117. for(i = 1; i < frame_header->blocksize; i++) {
  105118. if(integer_signal[0] != integer_signal[i]) {
  105119. signal_is_constant = false;
  105120. break;
  105121. }
  105122. }
  105123. }
  105124. if(signal_is_constant) {
  105125. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105126. if(_candidate_bits < _best_bits) {
  105127. _best_subframe = !_best_subframe;
  105128. _best_bits = _candidate_bits;
  105129. }
  105130. }
  105131. else {
  105132. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105133. /* encode fixed */
  105134. if(encoder->protected_->do_exhaustive_model_search) {
  105135. min_fixed_order = 0;
  105136. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105137. }
  105138. else {
  105139. min_fixed_order = max_fixed_order = guess_fixed_order;
  105140. }
  105141. if(max_fixed_order >= frame_header->blocksize)
  105142. max_fixed_order = frame_header->blocksize - 1;
  105143. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105144. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105145. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105146. continue; /* don't even try */
  105147. 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 */
  105148. #else
  105149. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105150. continue; /* don't even try */
  105151. 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 */
  105152. #endif
  105153. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105154. if(rice_parameter >= rice_parameter_limit) {
  105155. #ifdef DEBUG_VERBOSE
  105156. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105157. #endif
  105158. rice_parameter = rice_parameter_limit - 1;
  105159. }
  105160. _candidate_bits =
  105161. evaluate_fixed_subframe_(
  105162. encoder,
  105163. integer_signal,
  105164. residual[!_best_subframe],
  105165. encoder->private_->abs_residual_partition_sums,
  105166. encoder->private_->raw_bits_per_partition,
  105167. frame_header->blocksize,
  105168. subframe_bps,
  105169. fixed_order,
  105170. rice_parameter,
  105171. rice_parameter_limit,
  105172. min_partition_order,
  105173. max_partition_order,
  105174. encoder->protected_->do_escape_coding,
  105175. encoder->protected_->rice_parameter_search_dist,
  105176. subframe[!_best_subframe],
  105177. partitioned_rice_contents[!_best_subframe]
  105178. );
  105179. if(_candidate_bits < _best_bits) {
  105180. _best_subframe = !_best_subframe;
  105181. _best_bits = _candidate_bits;
  105182. }
  105183. }
  105184. }
  105185. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105186. /* encode lpc */
  105187. if(encoder->protected_->max_lpc_order > 0) {
  105188. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105189. max_lpc_order = frame_header->blocksize-1;
  105190. else
  105191. max_lpc_order = encoder->protected_->max_lpc_order;
  105192. if(max_lpc_order > 0) {
  105193. unsigned a;
  105194. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105195. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105196. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105197. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105198. if(autoc[0] != 0.0) {
  105199. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105200. if(encoder->protected_->do_exhaustive_model_search) {
  105201. min_lpc_order = 1;
  105202. }
  105203. else {
  105204. const unsigned guess_lpc_order =
  105205. FLAC__lpc_compute_best_order(
  105206. lpc_error,
  105207. max_lpc_order,
  105208. frame_header->blocksize,
  105209. subframe_bps + (
  105210. encoder->protected_->do_qlp_coeff_prec_search?
  105211. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105212. encoder->protected_->qlp_coeff_precision
  105213. )
  105214. );
  105215. min_lpc_order = max_lpc_order = guess_lpc_order;
  105216. }
  105217. if(max_lpc_order >= frame_header->blocksize)
  105218. max_lpc_order = frame_header->blocksize - 1;
  105219. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105220. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105221. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105222. continue; /* don't even try */
  105223. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105224. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105225. if(rice_parameter >= rice_parameter_limit) {
  105226. #ifdef DEBUG_VERBOSE
  105227. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105228. #endif
  105229. rice_parameter = rice_parameter_limit - 1;
  105230. }
  105231. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105232. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105233. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105234. if(subframe_bps <= 17) {
  105235. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105236. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105237. }
  105238. else
  105239. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105240. }
  105241. else {
  105242. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105243. }
  105244. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105245. _candidate_bits =
  105246. evaluate_lpc_subframe_(
  105247. encoder,
  105248. integer_signal,
  105249. residual[!_best_subframe],
  105250. encoder->private_->abs_residual_partition_sums,
  105251. encoder->private_->raw_bits_per_partition,
  105252. encoder->private_->lp_coeff[lpc_order-1],
  105253. frame_header->blocksize,
  105254. subframe_bps,
  105255. lpc_order,
  105256. qlp_coeff_precision,
  105257. rice_parameter,
  105258. rice_parameter_limit,
  105259. min_partition_order,
  105260. max_partition_order,
  105261. encoder->protected_->do_escape_coding,
  105262. encoder->protected_->rice_parameter_search_dist,
  105263. subframe[!_best_subframe],
  105264. partitioned_rice_contents[!_best_subframe]
  105265. );
  105266. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105267. if(_candidate_bits < _best_bits) {
  105268. _best_subframe = !_best_subframe;
  105269. _best_bits = _candidate_bits;
  105270. }
  105271. }
  105272. }
  105273. }
  105274. }
  105275. }
  105276. }
  105277. }
  105278. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105279. }
  105280. }
  105281. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105282. if(_best_bits == UINT_MAX) {
  105283. FLAC__ASSERT(_best_subframe == 0);
  105284. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105285. }
  105286. *best_subframe = _best_subframe;
  105287. *best_bits = _best_bits;
  105288. return true;
  105289. }
  105290. FLAC__bool add_subframe_(
  105291. FLAC__StreamEncoder *encoder,
  105292. unsigned blocksize,
  105293. unsigned subframe_bps,
  105294. const FLAC__Subframe *subframe,
  105295. FLAC__BitWriter *frame
  105296. )
  105297. {
  105298. switch(subframe->type) {
  105299. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105300. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105301. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105302. return false;
  105303. }
  105304. break;
  105305. case FLAC__SUBFRAME_TYPE_FIXED:
  105306. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105307. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105308. return false;
  105309. }
  105310. break;
  105311. case FLAC__SUBFRAME_TYPE_LPC:
  105312. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105313. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105314. return false;
  105315. }
  105316. break;
  105317. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105318. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105319. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105320. return false;
  105321. }
  105322. break;
  105323. default:
  105324. FLAC__ASSERT(0);
  105325. }
  105326. return true;
  105327. }
  105328. #define SPOTCHECK_ESTIMATE 0
  105329. #if SPOTCHECK_ESTIMATE
  105330. static void spotcheck_subframe_estimate_(
  105331. FLAC__StreamEncoder *encoder,
  105332. unsigned blocksize,
  105333. unsigned subframe_bps,
  105334. const FLAC__Subframe *subframe,
  105335. unsigned estimate
  105336. )
  105337. {
  105338. FLAC__bool ret;
  105339. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105340. if(frame == 0) {
  105341. fprintf(stderr, "EST: can't allocate frame\n");
  105342. return;
  105343. }
  105344. if(!FLAC__bitwriter_init(frame)) {
  105345. fprintf(stderr, "EST: can't init frame\n");
  105346. return;
  105347. }
  105348. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105349. FLAC__ASSERT(ret);
  105350. {
  105351. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105352. if(estimate != actual)
  105353. 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);
  105354. }
  105355. FLAC__bitwriter_delete(frame);
  105356. }
  105357. #endif
  105358. unsigned evaluate_constant_subframe_(
  105359. FLAC__StreamEncoder *encoder,
  105360. const FLAC__int32 signal,
  105361. unsigned blocksize,
  105362. unsigned subframe_bps,
  105363. FLAC__Subframe *subframe
  105364. )
  105365. {
  105366. unsigned estimate;
  105367. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105368. subframe->data.constant.value = signal;
  105369. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105370. #if SPOTCHECK_ESTIMATE
  105371. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105372. #else
  105373. (void)encoder, (void)blocksize;
  105374. #endif
  105375. return estimate;
  105376. }
  105377. unsigned evaluate_fixed_subframe_(
  105378. FLAC__StreamEncoder *encoder,
  105379. const FLAC__int32 signal[],
  105380. FLAC__int32 residual[],
  105381. FLAC__uint64 abs_residual_partition_sums[],
  105382. unsigned raw_bits_per_partition[],
  105383. unsigned blocksize,
  105384. unsigned subframe_bps,
  105385. unsigned order,
  105386. unsigned rice_parameter,
  105387. unsigned rice_parameter_limit,
  105388. unsigned min_partition_order,
  105389. unsigned max_partition_order,
  105390. FLAC__bool do_escape_coding,
  105391. unsigned rice_parameter_search_dist,
  105392. FLAC__Subframe *subframe,
  105393. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105394. )
  105395. {
  105396. unsigned i, residual_bits, estimate;
  105397. const unsigned residual_samples = blocksize - order;
  105398. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105399. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105400. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105401. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105402. subframe->data.fixed.residual = residual;
  105403. residual_bits =
  105404. find_best_partition_order_(
  105405. encoder->private_,
  105406. residual,
  105407. abs_residual_partition_sums,
  105408. raw_bits_per_partition,
  105409. residual_samples,
  105410. order,
  105411. rice_parameter,
  105412. rice_parameter_limit,
  105413. min_partition_order,
  105414. max_partition_order,
  105415. subframe_bps,
  105416. do_escape_coding,
  105417. rice_parameter_search_dist,
  105418. &subframe->data.fixed.entropy_coding_method
  105419. );
  105420. subframe->data.fixed.order = order;
  105421. for(i = 0; i < order; i++)
  105422. subframe->data.fixed.warmup[i] = signal[i];
  105423. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105424. #if SPOTCHECK_ESTIMATE
  105425. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105426. #endif
  105427. return estimate;
  105428. }
  105429. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105430. unsigned evaluate_lpc_subframe_(
  105431. FLAC__StreamEncoder *encoder,
  105432. const FLAC__int32 signal[],
  105433. FLAC__int32 residual[],
  105434. FLAC__uint64 abs_residual_partition_sums[],
  105435. unsigned raw_bits_per_partition[],
  105436. const FLAC__real lp_coeff[],
  105437. unsigned blocksize,
  105438. unsigned subframe_bps,
  105439. unsigned order,
  105440. unsigned qlp_coeff_precision,
  105441. unsigned rice_parameter,
  105442. unsigned rice_parameter_limit,
  105443. unsigned min_partition_order,
  105444. unsigned max_partition_order,
  105445. FLAC__bool do_escape_coding,
  105446. unsigned rice_parameter_search_dist,
  105447. FLAC__Subframe *subframe,
  105448. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105449. )
  105450. {
  105451. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105452. unsigned i, residual_bits, estimate;
  105453. int quantization, ret;
  105454. const unsigned residual_samples = blocksize - order;
  105455. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105456. if(subframe_bps <= 16) {
  105457. FLAC__ASSERT(order > 0);
  105458. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105459. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105460. }
  105461. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105462. if(ret != 0)
  105463. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105464. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105465. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105466. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105467. else
  105468. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105469. else
  105470. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105471. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105472. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105473. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105474. subframe->data.lpc.residual = residual;
  105475. residual_bits =
  105476. find_best_partition_order_(
  105477. encoder->private_,
  105478. residual,
  105479. abs_residual_partition_sums,
  105480. raw_bits_per_partition,
  105481. residual_samples,
  105482. order,
  105483. rice_parameter,
  105484. rice_parameter_limit,
  105485. min_partition_order,
  105486. max_partition_order,
  105487. subframe_bps,
  105488. do_escape_coding,
  105489. rice_parameter_search_dist,
  105490. &subframe->data.lpc.entropy_coding_method
  105491. );
  105492. subframe->data.lpc.order = order;
  105493. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105494. subframe->data.lpc.quantization_level = quantization;
  105495. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105496. for(i = 0; i < order; i++)
  105497. subframe->data.lpc.warmup[i] = signal[i];
  105498. 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;
  105499. #if SPOTCHECK_ESTIMATE
  105500. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105501. #endif
  105502. return estimate;
  105503. }
  105504. #endif
  105505. unsigned evaluate_verbatim_subframe_(
  105506. FLAC__StreamEncoder *encoder,
  105507. const FLAC__int32 signal[],
  105508. unsigned blocksize,
  105509. unsigned subframe_bps,
  105510. FLAC__Subframe *subframe
  105511. )
  105512. {
  105513. unsigned estimate;
  105514. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105515. subframe->data.verbatim.data = signal;
  105516. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105517. #if SPOTCHECK_ESTIMATE
  105518. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105519. #else
  105520. (void)encoder;
  105521. #endif
  105522. return estimate;
  105523. }
  105524. unsigned find_best_partition_order_(
  105525. FLAC__StreamEncoderPrivate *private_,
  105526. const FLAC__int32 residual[],
  105527. FLAC__uint64 abs_residual_partition_sums[],
  105528. unsigned raw_bits_per_partition[],
  105529. unsigned residual_samples,
  105530. unsigned predictor_order,
  105531. unsigned rice_parameter,
  105532. unsigned rice_parameter_limit,
  105533. unsigned min_partition_order,
  105534. unsigned max_partition_order,
  105535. unsigned bps,
  105536. FLAC__bool do_escape_coding,
  105537. unsigned rice_parameter_search_dist,
  105538. FLAC__EntropyCodingMethod *best_ecm
  105539. )
  105540. {
  105541. unsigned residual_bits, best_residual_bits = 0;
  105542. unsigned best_parameters_index = 0;
  105543. unsigned best_partition_order = 0;
  105544. const unsigned blocksize = residual_samples + predictor_order;
  105545. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105546. min_partition_order = min(min_partition_order, max_partition_order);
  105547. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105548. if(do_escape_coding)
  105549. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105550. {
  105551. int partition_order;
  105552. unsigned sum;
  105553. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105554. if(!
  105555. set_partitioned_rice_(
  105556. #ifdef EXACT_RICE_BITS_CALCULATION
  105557. residual,
  105558. #endif
  105559. abs_residual_partition_sums+sum,
  105560. raw_bits_per_partition+sum,
  105561. residual_samples,
  105562. predictor_order,
  105563. rice_parameter,
  105564. rice_parameter_limit,
  105565. rice_parameter_search_dist,
  105566. (unsigned)partition_order,
  105567. do_escape_coding,
  105568. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105569. &residual_bits
  105570. )
  105571. )
  105572. {
  105573. FLAC__ASSERT(best_residual_bits != 0);
  105574. break;
  105575. }
  105576. sum += 1u << partition_order;
  105577. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105578. best_residual_bits = residual_bits;
  105579. best_parameters_index = !best_parameters_index;
  105580. best_partition_order = partition_order;
  105581. }
  105582. }
  105583. }
  105584. best_ecm->data.partitioned_rice.order = best_partition_order;
  105585. {
  105586. /*
  105587. * We are allowed to de-const the pointer based on our special
  105588. * knowledge; it is const to the outside world.
  105589. */
  105590. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105591. unsigned partition;
  105592. /* save best parameters and raw_bits */
  105593. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105594. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105595. if(do_escape_coding)
  105596. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105597. /*
  105598. * Now need to check if the type should be changed to
  105599. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105600. * size of the rice parameters.
  105601. */
  105602. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105603. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105604. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105605. break;
  105606. }
  105607. }
  105608. }
  105609. return best_residual_bits;
  105610. }
  105611. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105612. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105613. const FLAC__int32 residual[],
  105614. FLAC__uint64 abs_residual_partition_sums[],
  105615. unsigned blocksize,
  105616. unsigned predictor_order,
  105617. unsigned min_partition_order,
  105618. unsigned max_partition_order
  105619. );
  105620. #endif
  105621. void precompute_partition_info_sums_(
  105622. const FLAC__int32 residual[],
  105623. FLAC__uint64 abs_residual_partition_sums[],
  105624. unsigned residual_samples,
  105625. unsigned predictor_order,
  105626. unsigned min_partition_order,
  105627. unsigned max_partition_order,
  105628. unsigned bps
  105629. )
  105630. {
  105631. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105632. unsigned partitions = 1u << max_partition_order;
  105633. FLAC__ASSERT(default_partition_samples > predictor_order);
  105634. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105635. /* slightly pessimistic but still catches all common cases */
  105636. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105637. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105638. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105639. return;
  105640. }
  105641. #endif
  105642. /* first do max_partition_order */
  105643. {
  105644. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105645. /* slightly pessimistic but still catches all common cases */
  105646. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105647. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105648. FLAC__uint32 abs_residual_partition_sum;
  105649. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105650. end += default_partition_samples;
  105651. abs_residual_partition_sum = 0;
  105652. for( ; residual_sample < end; residual_sample++)
  105653. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105654. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105655. }
  105656. }
  105657. else { /* have to pessimistically use 64 bits for accumulator */
  105658. FLAC__uint64 abs_residual_partition_sum;
  105659. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105660. end += default_partition_samples;
  105661. abs_residual_partition_sum = 0;
  105662. for( ; residual_sample < end; residual_sample++)
  105663. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105664. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105665. }
  105666. }
  105667. }
  105668. /* now merge partitions for lower orders */
  105669. {
  105670. unsigned from_partition = 0, to_partition = partitions;
  105671. int partition_order;
  105672. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105673. unsigned i;
  105674. partitions >>= 1;
  105675. for(i = 0; i < partitions; i++) {
  105676. abs_residual_partition_sums[to_partition++] =
  105677. abs_residual_partition_sums[from_partition ] +
  105678. abs_residual_partition_sums[from_partition+1];
  105679. from_partition += 2;
  105680. }
  105681. }
  105682. }
  105683. }
  105684. void precompute_partition_info_escapes_(
  105685. const FLAC__int32 residual[],
  105686. unsigned raw_bits_per_partition[],
  105687. unsigned residual_samples,
  105688. unsigned predictor_order,
  105689. unsigned min_partition_order,
  105690. unsigned max_partition_order
  105691. )
  105692. {
  105693. int partition_order;
  105694. unsigned from_partition, to_partition = 0;
  105695. const unsigned blocksize = residual_samples + predictor_order;
  105696. /* first do max_partition_order */
  105697. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105698. FLAC__int32 r;
  105699. FLAC__uint32 rmax;
  105700. unsigned partition, partition_sample, partition_samples, residual_sample;
  105701. const unsigned partitions = 1u << partition_order;
  105702. const unsigned default_partition_samples = blocksize >> partition_order;
  105703. FLAC__ASSERT(default_partition_samples > predictor_order);
  105704. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105705. partition_samples = default_partition_samples;
  105706. if(partition == 0)
  105707. partition_samples -= predictor_order;
  105708. rmax = 0;
  105709. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105710. r = residual[residual_sample++];
  105711. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105712. if(r < 0)
  105713. rmax |= ~r;
  105714. else
  105715. rmax |= r;
  105716. }
  105717. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105718. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105719. }
  105720. to_partition = partitions;
  105721. break; /*@@@ yuck, should remove the 'for' loop instead */
  105722. }
  105723. /* now merge partitions for lower orders */
  105724. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105725. unsigned m;
  105726. unsigned i;
  105727. const unsigned partitions = 1u << partition_order;
  105728. for(i = 0; i < partitions; i++) {
  105729. m = raw_bits_per_partition[from_partition];
  105730. from_partition++;
  105731. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105732. from_partition++;
  105733. to_partition++;
  105734. }
  105735. }
  105736. }
  105737. #ifdef EXACT_RICE_BITS_CALCULATION
  105738. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105739. const unsigned rice_parameter,
  105740. const unsigned partition_samples,
  105741. const FLAC__int32 *residual
  105742. )
  105743. {
  105744. unsigned i, partition_bits =
  105745. 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 */
  105746. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105747. ;
  105748. for(i = 0; i < partition_samples; i++)
  105749. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105750. return partition_bits;
  105751. }
  105752. #else
  105753. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105754. const unsigned rice_parameter,
  105755. const unsigned partition_samples,
  105756. const FLAC__uint64 abs_residual_partition_sum
  105757. )
  105758. {
  105759. return
  105760. 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 */
  105761. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105762. (
  105763. rice_parameter?
  105764. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105765. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105766. )
  105767. - (partition_samples >> 1)
  105768. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105769. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105770. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105771. * So the subtraction term tries to guess how many extra bits were contributed.
  105772. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105773. */
  105774. ;
  105775. }
  105776. #endif
  105777. FLAC__bool set_partitioned_rice_(
  105778. #ifdef EXACT_RICE_BITS_CALCULATION
  105779. const FLAC__int32 residual[],
  105780. #endif
  105781. const FLAC__uint64 abs_residual_partition_sums[],
  105782. const unsigned raw_bits_per_partition[],
  105783. const unsigned residual_samples,
  105784. const unsigned predictor_order,
  105785. const unsigned suggested_rice_parameter,
  105786. const unsigned rice_parameter_limit,
  105787. const unsigned rice_parameter_search_dist,
  105788. const unsigned partition_order,
  105789. const FLAC__bool search_for_escapes,
  105790. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105791. unsigned *bits
  105792. )
  105793. {
  105794. unsigned rice_parameter, partition_bits;
  105795. unsigned best_partition_bits, best_rice_parameter = 0;
  105796. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105797. unsigned *parameters, *raw_bits;
  105798. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105799. unsigned min_rice_parameter, max_rice_parameter;
  105800. #else
  105801. (void)rice_parameter_search_dist;
  105802. #endif
  105803. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105804. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105805. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105806. parameters = partitioned_rice_contents->parameters;
  105807. raw_bits = partitioned_rice_contents->raw_bits;
  105808. if(partition_order == 0) {
  105809. best_partition_bits = (unsigned)(-1);
  105810. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105811. if(rice_parameter_search_dist) {
  105812. if(suggested_rice_parameter < rice_parameter_search_dist)
  105813. min_rice_parameter = 0;
  105814. else
  105815. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105816. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105817. if(max_rice_parameter >= rice_parameter_limit) {
  105818. #ifdef DEBUG_VERBOSE
  105819. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105820. #endif
  105821. max_rice_parameter = rice_parameter_limit - 1;
  105822. }
  105823. }
  105824. else
  105825. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105826. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105827. #else
  105828. rice_parameter = suggested_rice_parameter;
  105829. #endif
  105830. #ifdef EXACT_RICE_BITS_CALCULATION
  105831. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105832. #else
  105833. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105834. #endif
  105835. if(partition_bits < best_partition_bits) {
  105836. best_rice_parameter = rice_parameter;
  105837. best_partition_bits = partition_bits;
  105838. }
  105839. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105840. }
  105841. #endif
  105842. if(search_for_escapes) {
  105843. 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;
  105844. if(partition_bits <= best_partition_bits) {
  105845. raw_bits[0] = raw_bits_per_partition[0];
  105846. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105847. best_partition_bits = partition_bits;
  105848. }
  105849. else
  105850. raw_bits[0] = 0;
  105851. }
  105852. parameters[0] = best_rice_parameter;
  105853. bits_ += best_partition_bits;
  105854. }
  105855. else {
  105856. unsigned partition, residual_sample;
  105857. unsigned partition_samples;
  105858. FLAC__uint64 mean, k;
  105859. const unsigned partitions = 1u << partition_order;
  105860. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105861. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105862. if(partition == 0) {
  105863. if(partition_samples <= predictor_order)
  105864. return false;
  105865. else
  105866. partition_samples -= predictor_order;
  105867. }
  105868. mean = abs_residual_partition_sums[partition];
  105869. /* we are basically calculating the size in bits of the
  105870. * average residual magnitude in the partition:
  105871. * rice_parameter = floor(log2(mean/partition_samples))
  105872. * 'mean' is not a good name for the variable, it is
  105873. * actually the sum of magnitudes of all residual values
  105874. * in the partition, so the actual mean is
  105875. * mean/partition_samples
  105876. */
  105877. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105878. ;
  105879. if(rice_parameter >= rice_parameter_limit) {
  105880. #ifdef DEBUG_VERBOSE
  105881. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105882. #endif
  105883. rice_parameter = rice_parameter_limit - 1;
  105884. }
  105885. best_partition_bits = (unsigned)(-1);
  105886. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105887. if(rice_parameter_search_dist) {
  105888. if(rice_parameter < rice_parameter_search_dist)
  105889. min_rice_parameter = 0;
  105890. else
  105891. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105892. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105893. if(max_rice_parameter >= rice_parameter_limit) {
  105894. #ifdef DEBUG_VERBOSE
  105895. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105896. #endif
  105897. max_rice_parameter = rice_parameter_limit - 1;
  105898. }
  105899. }
  105900. else
  105901. min_rice_parameter = max_rice_parameter = rice_parameter;
  105902. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105903. #endif
  105904. #ifdef EXACT_RICE_BITS_CALCULATION
  105905. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105906. #else
  105907. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105908. #endif
  105909. if(partition_bits < best_partition_bits) {
  105910. best_rice_parameter = rice_parameter;
  105911. best_partition_bits = partition_bits;
  105912. }
  105913. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105914. }
  105915. #endif
  105916. if(search_for_escapes) {
  105917. 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;
  105918. if(partition_bits <= best_partition_bits) {
  105919. raw_bits[partition] = raw_bits_per_partition[partition];
  105920. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105921. best_partition_bits = partition_bits;
  105922. }
  105923. else
  105924. raw_bits[partition] = 0;
  105925. }
  105926. parameters[partition] = best_rice_parameter;
  105927. bits_ += best_partition_bits;
  105928. residual_sample += partition_samples;
  105929. }
  105930. }
  105931. *bits = bits_;
  105932. return true;
  105933. }
  105934. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105935. {
  105936. unsigned i, shift;
  105937. FLAC__int32 x = 0;
  105938. for(i = 0; i < samples && !(x&1); i++)
  105939. x |= signal[i];
  105940. if(x == 0) {
  105941. shift = 0;
  105942. }
  105943. else {
  105944. for(shift = 0; !(x&1); shift++)
  105945. x >>= 1;
  105946. }
  105947. if(shift > 0) {
  105948. for(i = 0; i < samples; i++)
  105949. signal[i] >>= shift;
  105950. }
  105951. return shift;
  105952. }
  105953. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105954. {
  105955. unsigned channel;
  105956. for(channel = 0; channel < channels; channel++)
  105957. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105958. fifo->tail += wide_samples;
  105959. FLAC__ASSERT(fifo->tail <= fifo->size);
  105960. }
  105961. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105962. {
  105963. unsigned channel;
  105964. unsigned sample, wide_sample;
  105965. unsigned tail = fifo->tail;
  105966. sample = input_offset * channels;
  105967. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105968. for(channel = 0; channel < channels; channel++)
  105969. fifo->data[channel][tail] = input[sample++];
  105970. tail++;
  105971. }
  105972. fifo->tail = tail;
  105973. FLAC__ASSERT(fifo->tail <= fifo->size);
  105974. }
  105975. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105976. {
  105977. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105978. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105979. (void)decoder;
  105980. if(encoder->private_->verify.needs_magic_hack) {
  105981. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105982. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105983. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105984. encoder->private_->verify.needs_magic_hack = false;
  105985. }
  105986. else {
  105987. if(encoded_bytes == 0) {
  105988. /*
  105989. * If we get here, a FIFO underflow has occurred,
  105990. * which means there is a bug somewhere.
  105991. */
  105992. FLAC__ASSERT(0);
  105993. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105994. }
  105995. else if(encoded_bytes < *bytes)
  105996. *bytes = encoded_bytes;
  105997. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105998. encoder->private_->verify.output.data += *bytes;
  105999. encoder->private_->verify.output.bytes -= *bytes;
  106000. }
  106001. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106002. }
  106003. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  106004. {
  106005. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  106006. unsigned channel;
  106007. const unsigned channels = frame->header.channels;
  106008. const unsigned blocksize = frame->header.blocksize;
  106009. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  106010. (void)decoder;
  106011. for(channel = 0; channel < channels; channel++) {
  106012. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  106013. unsigned i, sample = 0;
  106014. FLAC__int32 expect = 0, got = 0;
  106015. for(i = 0; i < blocksize; i++) {
  106016. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  106017. sample = i;
  106018. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  106019. got = (FLAC__int32)buffer[channel][i];
  106020. break;
  106021. }
  106022. }
  106023. FLAC__ASSERT(i < blocksize);
  106024. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  106025. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  106026. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  106027. encoder->private_->verify.error_stats.channel = channel;
  106028. encoder->private_->verify.error_stats.sample = sample;
  106029. encoder->private_->verify.error_stats.expected = expect;
  106030. encoder->private_->verify.error_stats.got = got;
  106031. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106032. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106033. }
  106034. }
  106035. /* dequeue the frame from the fifo */
  106036. encoder->private_->verify.input_fifo.tail -= blocksize;
  106037. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106038. for(channel = 0; channel < channels; channel++)
  106039. 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]));
  106040. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106041. }
  106042. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106043. {
  106044. (void)decoder, (void)metadata, (void)client_data;
  106045. }
  106046. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106047. {
  106048. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106049. (void)decoder, (void)status;
  106050. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106051. }
  106052. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106053. {
  106054. (void)client_data;
  106055. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106056. if (*bytes == 0) {
  106057. if (feof(encoder->private_->file))
  106058. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106059. else if (ferror(encoder->private_->file))
  106060. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106061. }
  106062. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106063. }
  106064. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106065. {
  106066. (void)client_data;
  106067. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106068. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106069. else
  106070. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106071. }
  106072. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106073. {
  106074. off_t offset;
  106075. (void)client_data;
  106076. offset = ftello(encoder->private_->file);
  106077. if(offset < 0) {
  106078. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106079. }
  106080. else {
  106081. *absolute_byte_offset = (FLAC__uint64)offset;
  106082. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106083. }
  106084. }
  106085. #ifdef FLAC__VALGRIND_TESTING
  106086. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106087. {
  106088. size_t ret = fwrite(ptr, size, nmemb, stream);
  106089. if(!ferror(stream))
  106090. fflush(stream);
  106091. return ret;
  106092. }
  106093. #else
  106094. #define local__fwrite fwrite
  106095. #endif
  106096. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106097. {
  106098. (void)client_data, (void)current_frame;
  106099. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106100. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106101. #if FLAC__HAS_OGG
  106102. /* We would like to be able to use 'samples > 0' in the
  106103. * clause here but currently because of the nature of our
  106104. * Ogg writing implementation, 'samples' is always 0 (see
  106105. * ogg_encoder_aspect.c). The downside is extra progress
  106106. * callbacks.
  106107. */
  106108. encoder->private_->is_ogg? true :
  106109. #endif
  106110. samples > 0
  106111. );
  106112. if(call_it) {
  106113. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106114. * because at this point in the callback chain, the stats
  106115. * have not been updated. Only after we return and control
  106116. * gets back to write_frame_() are the stats updated
  106117. */
  106118. 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);
  106119. }
  106120. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106121. }
  106122. else
  106123. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106124. }
  106125. /*
  106126. * This will forcibly set stdout to binary mode (for OSes that require it)
  106127. */
  106128. FILE *get_binary_stdout_(void)
  106129. {
  106130. /* if something breaks here it is probably due to the presence or
  106131. * absence of an underscore before the identifiers 'setmode',
  106132. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106133. */
  106134. #if defined _MSC_VER || defined __MINGW32__
  106135. _setmode(_fileno(stdout), _O_BINARY);
  106136. #elif defined __CYGWIN__
  106137. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106138. setmode(_fileno(stdout), _O_BINARY);
  106139. #elif defined __EMX__
  106140. setmode(fileno(stdout), O_BINARY);
  106141. #endif
  106142. return stdout;
  106143. }
  106144. #endif
  106145. /*** End of inlined file: stream_encoder.c ***/
  106146. /*** Start of inlined file: stream_encoder_framing.c ***/
  106147. /*** Start of inlined file: juce_FlacHeader.h ***/
  106148. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106149. // tasks..
  106150. #define VERSION "1.2.1"
  106151. #define FLAC__NO_DLL 1
  106152. #if JUCE_MSVC
  106153. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106154. #endif
  106155. #if JUCE_MAC
  106156. #define FLAC__SYS_DARWIN 1
  106157. #endif
  106158. /*** End of inlined file: juce_FlacHeader.h ***/
  106159. #if JUCE_USE_FLAC
  106160. #if HAVE_CONFIG_H
  106161. # include <config.h>
  106162. #endif
  106163. #include <stdio.h>
  106164. #include <string.h> /* for strlen() */
  106165. #ifdef max
  106166. #undef max
  106167. #endif
  106168. #define max(x,y) ((x)>(y)?(x):(y))
  106169. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106170. 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);
  106171. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106172. {
  106173. unsigned i, j;
  106174. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106175. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106176. return false;
  106177. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106178. return false;
  106179. /*
  106180. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106181. */
  106182. i = metadata->length;
  106183. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106184. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106185. i -= metadata->data.vorbis_comment.vendor_string.length;
  106186. i += vendor_string_length;
  106187. }
  106188. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106189. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106190. return false;
  106191. switch(metadata->type) {
  106192. case FLAC__METADATA_TYPE_STREAMINFO:
  106193. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106194. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106195. return false;
  106196. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106197. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106198. return false;
  106199. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106200. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106201. return false;
  106202. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106203. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106204. return false;
  106205. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106206. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106207. return false;
  106208. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106209. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106210. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106211. return false;
  106212. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106213. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106214. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106215. return false;
  106216. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106217. return false;
  106218. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106219. return false;
  106220. break;
  106221. case FLAC__METADATA_TYPE_PADDING:
  106222. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106223. return false;
  106224. break;
  106225. case FLAC__METADATA_TYPE_APPLICATION:
  106226. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106227. return false;
  106228. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106229. return false;
  106230. break;
  106231. case FLAC__METADATA_TYPE_SEEKTABLE:
  106232. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106233. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106234. return false;
  106235. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106236. return false;
  106237. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106238. return false;
  106239. }
  106240. break;
  106241. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106242. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106243. return false;
  106244. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106245. return false;
  106246. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106247. return false;
  106248. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106249. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106250. return false;
  106251. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106252. return false;
  106253. }
  106254. break;
  106255. case FLAC__METADATA_TYPE_CUESHEET:
  106256. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106257. 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))
  106258. return false;
  106259. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106260. return false;
  106261. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106262. return false;
  106263. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106264. return false;
  106265. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106266. return false;
  106267. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106268. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106269. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106270. return false;
  106271. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106272. return false;
  106273. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106274. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106275. return false;
  106276. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106277. return false;
  106278. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106279. return false;
  106280. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106281. return false;
  106282. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106283. return false;
  106284. for(j = 0; j < track->num_indices; j++) {
  106285. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106286. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106287. return false;
  106288. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106289. return false;
  106290. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106291. return false;
  106292. }
  106293. }
  106294. break;
  106295. case FLAC__METADATA_TYPE_PICTURE:
  106296. {
  106297. size_t len;
  106298. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106299. return false;
  106300. len = strlen(metadata->data.picture.mime_type);
  106301. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106302. return false;
  106303. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106304. return false;
  106305. len = strlen((const char *)metadata->data.picture.description);
  106306. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106307. return false;
  106308. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106309. return false;
  106310. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106311. return false;
  106312. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106313. return false;
  106314. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106315. return false;
  106316. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106317. return false;
  106318. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106319. return false;
  106320. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106321. return false;
  106322. }
  106323. break;
  106324. default:
  106325. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106326. return false;
  106327. break;
  106328. }
  106329. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106330. return true;
  106331. }
  106332. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106333. {
  106334. unsigned u, blocksize_hint, sample_rate_hint;
  106335. FLAC__byte crc;
  106336. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106337. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106338. return false;
  106339. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106340. return false;
  106341. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106342. return false;
  106343. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106344. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106345. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106346. blocksize_hint = 0;
  106347. switch(header->blocksize) {
  106348. case 192: u = 1; break;
  106349. case 576: u = 2; break;
  106350. case 1152: u = 3; break;
  106351. case 2304: u = 4; break;
  106352. case 4608: u = 5; break;
  106353. case 256: u = 8; break;
  106354. case 512: u = 9; break;
  106355. case 1024: u = 10; break;
  106356. case 2048: u = 11; break;
  106357. case 4096: u = 12; break;
  106358. case 8192: u = 13; break;
  106359. case 16384: u = 14; break;
  106360. case 32768: u = 15; break;
  106361. default:
  106362. if(header->blocksize <= 0x100)
  106363. blocksize_hint = u = 6;
  106364. else
  106365. blocksize_hint = u = 7;
  106366. break;
  106367. }
  106368. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106369. return false;
  106370. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106371. sample_rate_hint = 0;
  106372. switch(header->sample_rate) {
  106373. case 88200: u = 1; break;
  106374. case 176400: u = 2; break;
  106375. case 192000: u = 3; break;
  106376. case 8000: u = 4; break;
  106377. case 16000: u = 5; break;
  106378. case 22050: u = 6; break;
  106379. case 24000: u = 7; break;
  106380. case 32000: u = 8; break;
  106381. case 44100: u = 9; break;
  106382. case 48000: u = 10; break;
  106383. case 96000: u = 11; break;
  106384. default:
  106385. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106386. sample_rate_hint = u = 12;
  106387. else if(header->sample_rate % 10 == 0)
  106388. sample_rate_hint = u = 14;
  106389. else if(header->sample_rate <= 0xffff)
  106390. sample_rate_hint = u = 13;
  106391. else
  106392. u = 0;
  106393. break;
  106394. }
  106395. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106396. return false;
  106397. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106398. switch(header->channel_assignment) {
  106399. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106400. u = header->channels - 1;
  106401. break;
  106402. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106403. FLAC__ASSERT(header->channels == 2);
  106404. u = 8;
  106405. break;
  106406. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106407. FLAC__ASSERT(header->channels == 2);
  106408. u = 9;
  106409. break;
  106410. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106411. FLAC__ASSERT(header->channels == 2);
  106412. u = 10;
  106413. break;
  106414. default:
  106415. FLAC__ASSERT(0);
  106416. }
  106417. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106418. return false;
  106419. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106420. switch(header->bits_per_sample) {
  106421. case 8 : u = 1; break;
  106422. case 12: u = 2; break;
  106423. case 16: u = 4; break;
  106424. case 20: u = 5; break;
  106425. case 24: u = 6; break;
  106426. default: u = 0; break;
  106427. }
  106428. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106429. return false;
  106430. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106431. return false;
  106432. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106433. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106434. return false;
  106435. }
  106436. else {
  106437. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106438. return false;
  106439. }
  106440. if(blocksize_hint)
  106441. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106442. return false;
  106443. switch(sample_rate_hint) {
  106444. case 12:
  106445. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106446. return false;
  106447. break;
  106448. case 13:
  106449. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106450. return false;
  106451. break;
  106452. case 14:
  106453. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106454. return false;
  106455. break;
  106456. }
  106457. /* write the CRC */
  106458. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106459. return false;
  106460. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106461. return false;
  106462. return true;
  106463. }
  106464. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106465. {
  106466. FLAC__bool ok;
  106467. ok =
  106468. 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) &&
  106469. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106470. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106471. ;
  106472. return ok;
  106473. }
  106474. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106475. {
  106476. unsigned i;
  106477. 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))
  106478. return false;
  106479. if(wasted_bits)
  106480. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106481. return false;
  106482. for(i = 0; i < subframe->order; i++)
  106483. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106484. return false;
  106485. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106486. return false;
  106487. switch(subframe->entropy_coding_method.type) {
  106488. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106489. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106490. if(!add_residual_partitioned_rice_(
  106491. bw,
  106492. subframe->residual,
  106493. residual_samples,
  106494. subframe->order,
  106495. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106496. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106497. subframe->entropy_coding_method.data.partitioned_rice.order,
  106498. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106499. ))
  106500. return false;
  106501. break;
  106502. default:
  106503. FLAC__ASSERT(0);
  106504. }
  106505. return true;
  106506. }
  106507. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106508. {
  106509. unsigned i;
  106510. 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))
  106511. return false;
  106512. if(wasted_bits)
  106513. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106514. return false;
  106515. for(i = 0; i < subframe->order; i++)
  106516. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106517. return false;
  106518. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106519. return false;
  106520. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106521. return false;
  106522. for(i = 0; i < subframe->order; i++)
  106523. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106524. return false;
  106525. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106526. return false;
  106527. switch(subframe->entropy_coding_method.type) {
  106528. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106529. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106530. if(!add_residual_partitioned_rice_(
  106531. bw,
  106532. subframe->residual,
  106533. residual_samples,
  106534. subframe->order,
  106535. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106536. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106537. subframe->entropy_coding_method.data.partitioned_rice.order,
  106538. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106539. ))
  106540. return false;
  106541. break;
  106542. default:
  106543. FLAC__ASSERT(0);
  106544. }
  106545. return true;
  106546. }
  106547. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106548. {
  106549. unsigned i;
  106550. const FLAC__int32 *signal = subframe->data;
  106551. 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))
  106552. return false;
  106553. if(wasted_bits)
  106554. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106555. return false;
  106556. for(i = 0; i < samples; i++)
  106557. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106558. return false;
  106559. return true;
  106560. }
  106561. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106562. {
  106563. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106564. return false;
  106565. switch(method->type) {
  106566. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106567. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106568. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106569. return false;
  106570. break;
  106571. default:
  106572. FLAC__ASSERT(0);
  106573. }
  106574. return true;
  106575. }
  106576. 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)
  106577. {
  106578. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106579. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106580. if(partition_order == 0) {
  106581. unsigned i;
  106582. if(raw_bits[0] == 0) {
  106583. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106584. return false;
  106585. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106586. return false;
  106587. }
  106588. else {
  106589. FLAC__ASSERT(rice_parameters[0] == 0);
  106590. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106591. return false;
  106592. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106593. return false;
  106594. for(i = 0; i < residual_samples; i++) {
  106595. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106596. return false;
  106597. }
  106598. }
  106599. return true;
  106600. }
  106601. else {
  106602. unsigned i, j, k = 0, k_last = 0;
  106603. unsigned partition_samples;
  106604. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106605. for(i = 0; i < (1u<<partition_order); i++) {
  106606. partition_samples = default_partition_samples;
  106607. if(i == 0)
  106608. partition_samples -= predictor_order;
  106609. k += partition_samples;
  106610. if(raw_bits[i] == 0) {
  106611. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106612. return false;
  106613. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106614. return false;
  106615. }
  106616. else {
  106617. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106618. return false;
  106619. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106620. return false;
  106621. for(j = k_last; j < k; j++) {
  106622. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106623. return false;
  106624. }
  106625. }
  106626. k_last = k;
  106627. }
  106628. return true;
  106629. }
  106630. }
  106631. #endif
  106632. /*** End of inlined file: stream_encoder_framing.c ***/
  106633. /*** Start of inlined file: window_flac.c ***/
  106634. /*** Start of inlined file: juce_FlacHeader.h ***/
  106635. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106636. // tasks..
  106637. #define VERSION "1.2.1"
  106638. #define FLAC__NO_DLL 1
  106639. #if JUCE_MSVC
  106640. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106641. #endif
  106642. #if JUCE_MAC
  106643. #define FLAC__SYS_DARWIN 1
  106644. #endif
  106645. /*** End of inlined file: juce_FlacHeader.h ***/
  106646. #if JUCE_USE_FLAC
  106647. #if HAVE_CONFIG_H
  106648. # include <config.h>
  106649. #endif
  106650. #include <math.h>
  106651. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106652. #ifndef M_PI
  106653. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106654. #define M_PI 3.14159265358979323846
  106655. #endif
  106656. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106657. {
  106658. const FLAC__int32 N = L - 1;
  106659. FLAC__int32 n;
  106660. if (L & 1) {
  106661. for (n = 0; n <= N/2; n++)
  106662. window[n] = 2.0f * n / (float)N;
  106663. for (; n <= N; n++)
  106664. window[n] = 2.0f - 2.0f * n / (float)N;
  106665. }
  106666. else {
  106667. for (n = 0; n <= L/2-1; n++)
  106668. window[n] = 2.0f * n / (float)N;
  106669. for (; n <= N; n++)
  106670. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106671. }
  106672. }
  106673. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106674. {
  106675. const FLAC__int32 N = L - 1;
  106676. FLAC__int32 n;
  106677. for (n = 0; n < L; n++)
  106678. 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)));
  106679. }
  106680. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106681. {
  106682. const FLAC__int32 N = L - 1;
  106683. FLAC__int32 n;
  106684. for (n = 0; n < L; n++)
  106685. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106686. }
  106687. /* 4-term -92dB side-lobe */
  106688. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106689. {
  106690. const FLAC__int32 N = L - 1;
  106691. FLAC__int32 n;
  106692. for (n = 0; n <= N; n++)
  106693. 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));
  106694. }
  106695. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106696. {
  106697. const FLAC__int32 N = L - 1;
  106698. const double N2 = (double)N / 2.;
  106699. FLAC__int32 n;
  106700. for (n = 0; n <= N; n++) {
  106701. double k = ((double)n - N2) / N2;
  106702. k = 1.0f - k * k;
  106703. window[n] = (FLAC__real)(k * k);
  106704. }
  106705. }
  106706. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106707. {
  106708. const FLAC__int32 N = L - 1;
  106709. FLAC__int32 n;
  106710. for (n = 0; n < L; n++)
  106711. 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));
  106712. }
  106713. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106714. {
  106715. const FLAC__int32 N = L - 1;
  106716. const double N2 = (double)N / 2.;
  106717. FLAC__int32 n;
  106718. for (n = 0; n <= N; n++) {
  106719. const double k = ((double)n - N2) / (stddev * N2);
  106720. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106721. }
  106722. }
  106723. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106724. {
  106725. const FLAC__int32 N = L - 1;
  106726. FLAC__int32 n;
  106727. for (n = 0; n < L; n++)
  106728. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106729. }
  106730. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106731. {
  106732. const FLAC__int32 N = L - 1;
  106733. FLAC__int32 n;
  106734. for (n = 0; n < L; n++)
  106735. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106736. }
  106737. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106738. {
  106739. const FLAC__int32 N = L - 1;
  106740. FLAC__int32 n;
  106741. for (n = 0; n < L; n++)
  106742. 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));
  106743. }
  106744. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106745. {
  106746. const FLAC__int32 N = L - 1;
  106747. FLAC__int32 n;
  106748. for (n = 0; n < L; n++)
  106749. 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));
  106750. }
  106751. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106752. {
  106753. FLAC__int32 n;
  106754. for (n = 0; n < L; n++)
  106755. window[n] = 1.0f;
  106756. }
  106757. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106758. {
  106759. FLAC__int32 n;
  106760. if (L & 1) {
  106761. for (n = 1; n <= L+1/2; n++)
  106762. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106763. for (; n <= L; n++)
  106764. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106765. }
  106766. else {
  106767. for (n = 1; n <= L/2; n++)
  106768. window[n-1] = 2.0f * n / (float)L;
  106769. for (; n <= L; n++)
  106770. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106771. }
  106772. }
  106773. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106774. {
  106775. if (p <= 0.0)
  106776. FLAC__window_rectangle(window, L);
  106777. else if (p >= 1.0)
  106778. FLAC__window_hann(window, L);
  106779. else {
  106780. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106781. FLAC__int32 n;
  106782. /* start with rectangle... */
  106783. FLAC__window_rectangle(window, L);
  106784. /* ...replace ends with hann */
  106785. if (Np > 0) {
  106786. for (n = 0; n <= Np; n++) {
  106787. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106788. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106789. }
  106790. }
  106791. }
  106792. }
  106793. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106794. {
  106795. const FLAC__int32 N = L - 1;
  106796. const double N2 = (double)N / 2.;
  106797. FLAC__int32 n;
  106798. for (n = 0; n <= N; n++) {
  106799. const double k = ((double)n - N2) / N2;
  106800. window[n] = (FLAC__real)(1.0f - k * k);
  106801. }
  106802. }
  106803. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106804. #endif
  106805. /*** End of inlined file: window_flac.c ***/
  106806. #else
  106807. #include <FLAC/all.h>
  106808. #endif
  106809. }
  106810. #undef max
  106811. #undef min
  106812. BEGIN_JUCE_NAMESPACE
  106813. static const char* const flacFormatName = "FLAC file";
  106814. static const char* const flacExtensions[] = { ".flac", 0 };
  106815. class FlacReader : public AudioFormatReader
  106816. {
  106817. public:
  106818. FlacReader (InputStream* const in)
  106819. : AudioFormatReader (in, TRANS (flacFormatName)),
  106820. reservoir (2, 0),
  106821. reservoirStart (0),
  106822. samplesInReservoir (0),
  106823. scanningForLength (false)
  106824. {
  106825. using namespace FlacNamespace;
  106826. lengthInSamples = 0;
  106827. decoder = FLAC__stream_decoder_new();
  106828. ok = FLAC__stream_decoder_init_stream (decoder,
  106829. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106830. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106831. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106832. if (ok)
  106833. {
  106834. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106835. if (lengthInSamples == 0 && sampleRate > 0)
  106836. {
  106837. // the length hasn't been stored in the metadata, so we'll need to
  106838. // work it out the length the hard way, by scanning the whole file..
  106839. scanningForLength = true;
  106840. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106841. scanningForLength = false;
  106842. const int64 tempLength = lengthInSamples;
  106843. FLAC__stream_decoder_reset (decoder);
  106844. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106845. lengthInSamples = tempLength;
  106846. }
  106847. }
  106848. }
  106849. ~FlacReader()
  106850. {
  106851. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106852. }
  106853. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106854. {
  106855. sampleRate = info.sample_rate;
  106856. bitsPerSample = info.bits_per_sample;
  106857. lengthInSamples = (unsigned int) info.total_samples;
  106858. numChannels = info.channels;
  106859. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106860. }
  106861. // returns the number of samples read
  106862. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106863. int64 startSampleInFile, int numSamples)
  106864. {
  106865. using namespace FlacNamespace;
  106866. if (! ok)
  106867. return false;
  106868. while (numSamples > 0)
  106869. {
  106870. if (startSampleInFile >= reservoirStart
  106871. && startSampleInFile < reservoirStart + samplesInReservoir)
  106872. {
  106873. const int num = (int) jmin ((int64) numSamples,
  106874. reservoirStart + samplesInReservoir - startSampleInFile);
  106875. jassert (num > 0);
  106876. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106877. if (destSamples[i] != 0)
  106878. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106879. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106880. sizeof (int) * num);
  106881. startOffsetInDestBuffer += num;
  106882. startSampleInFile += num;
  106883. numSamples -= num;
  106884. }
  106885. else
  106886. {
  106887. if (startSampleInFile >= (int) lengthInSamples)
  106888. {
  106889. samplesInReservoir = 0;
  106890. }
  106891. else if (startSampleInFile < reservoirStart
  106892. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106893. {
  106894. // had some problems with flac crashing if the read pos is aligned more
  106895. // accurately than this. Probably fixed in newer versions of the library, though.
  106896. reservoirStart = (int) (startSampleInFile & ~511);
  106897. samplesInReservoir = 0;
  106898. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106899. }
  106900. else
  106901. {
  106902. reservoirStart += samplesInReservoir;
  106903. samplesInReservoir = 0;
  106904. FLAC__stream_decoder_process_single (decoder);
  106905. }
  106906. if (samplesInReservoir == 0)
  106907. break;
  106908. }
  106909. }
  106910. if (numSamples > 0)
  106911. {
  106912. for (int i = numDestChannels; --i >= 0;)
  106913. if (destSamples[i] != 0)
  106914. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106915. sizeof (int) * numSamples);
  106916. }
  106917. return true;
  106918. }
  106919. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106920. {
  106921. if (scanningForLength)
  106922. {
  106923. lengthInSamples += numSamples;
  106924. }
  106925. else
  106926. {
  106927. if (numSamples > reservoir.getNumSamples())
  106928. reservoir.setSize (numChannels, numSamples, false, false, true);
  106929. const int bitsToShift = 32 - bitsPerSample;
  106930. for (int i = 0; i < (int) numChannels; ++i)
  106931. {
  106932. const FlacNamespace::FLAC__int32* src = buffer[i];
  106933. int n = i;
  106934. while (src == 0 && n > 0)
  106935. src = buffer [--n];
  106936. if (src != 0)
  106937. {
  106938. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106939. for (int j = 0; j < numSamples; ++j)
  106940. dest[j] = src[j] << bitsToShift;
  106941. }
  106942. }
  106943. samplesInReservoir = numSamples;
  106944. }
  106945. }
  106946. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106947. {
  106948. using namespace FlacNamespace;
  106949. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106950. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106951. }
  106952. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106953. {
  106954. using namespace FlacNamespace;
  106955. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106956. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106957. }
  106958. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106959. {
  106960. using namespace FlacNamespace;
  106961. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106962. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106963. }
  106964. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106965. {
  106966. using namespace FlacNamespace;
  106967. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106968. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106969. }
  106970. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106971. {
  106972. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106973. }
  106974. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106975. const FlacNamespace::FLAC__Frame* frame,
  106976. const FlacNamespace::FLAC__int32* const buffer[],
  106977. void* client_data)
  106978. {
  106979. using namespace FlacNamespace;
  106980. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106981. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106982. }
  106983. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106984. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106985. void* client_data)
  106986. {
  106987. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106988. }
  106989. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106990. {
  106991. }
  106992. juce_UseDebuggingNewOperator
  106993. private:
  106994. FlacNamespace::FLAC__StreamDecoder* decoder;
  106995. AudioSampleBuffer reservoir;
  106996. int reservoirStart, samplesInReservoir;
  106997. bool ok, scanningForLength;
  106998. FlacReader (const FlacReader&);
  106999. FlacReader& operator= (const FlacReader&);
  107000. };
  107001. class FlacWriter : public AudioFormatWriter
  107002. {
  107003. public:
  107004. FlacWriter (OutputStream* const out, double sampleRate_,
  107005. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  107006. : AudioFormatWriter (out, TRANS (flacFormatName),
  107007. sampleRate_, numChannels_, bitsPerSample_)
  107008. {
  107009. using namespace FlacNamespace;
  107010. encoder = FLAC__stream_encoder_new();
  107011. if (qualityOptionIndex > 0)
  107012. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  107013. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  107014. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  107015. FLAC__stream_encoder_set_channels (encoder, numChannels);
  107016. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  107017. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  107018. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  107019. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  107020. ok = FLAC__stream_encoder_init_stream (encoder,
  107021. encodeWriteCallback, encodeSeekCallback,
  107022. encodeTellCallback, encodeMetadataCallback,
  107023. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  107024. }
  107025. ~FlacWriter()
  107026. {
  107027. if (ok)
  107028. {
  107029. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  107030. output->flush();
  107031. }
  107032. else
  107033. {
  107034. output = 0; // to stop the base class deleting this, as it needs to be returned
  107035. // to the caller of createWriter()
  107036. }
  107037. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107038. }
  107039. bool write (const int** samplesToWrite, int numSamples)
  107040. {
  107041. using namespace FlacNamespace;
  107042. if (! ok)
  107043. return false;
  107044. int* buf[3];
  107045. HeapBlock<int> temp;
  107046. const int bitsToShift = 32 - bitsPerSample;
  107047. if (bitsToShift > 0)
  107048. {
  107049. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107050. temp.malloc (numSamples * numChannelsToWrite);
  107051. buf[0] = temp.getData();
  107052. buf[1] = temp.getData() + numSamples;
  107053. buf[2] = 0;
  107054. for (int i = numChannelsToWrite; --i >= 0;)
  107055. if (samplesToWrite[i] != 0)
  107056. for (int j = 0; j < numSamples; ++j)
  107057. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107058. samplesToWrite = const_cast<const int**> (buf);
  107059. }
  107060. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  107061. }
  107062. bool writeData (const void* const data, const int size) const
  107063. {
  107064. return output->write (data, size);
  107065. }
  107066. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107067. {
  107068. using namespace FlacNamespace;
  107069. b += bytes;
  107070. for (int i = 0; i < bytes; ++i)
  107071. {
  107072. *(--b) = (FLAC__byte) (val & 0xff);
  107073. val >>= 8;
  107074. }
  107075. }
  107076. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107077. {
  107078. using namespace FlacNamespace;
  107079. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107080. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107081. const unsigned int channelsMinus1 = info.channels - 1;
  107082. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107083. packUint32 (info.min_blocksize, buffer, 2);
  107084. packUint32 (info.max_blocksize, buffer + 2, 2);
  107085. packUint32 (info.min_framesize, buffer + 4, 3);
  107086. packUint32 (info.max_framesize, buffer + 7, 3);
  107087. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107088. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107089. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107090. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107091. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107092. memcpy (buffer + 18, info.md5sum, 16);
  107093. const bool seekOk = output->setPosition (4);
  107094. (void) seekOk;
  107095. // if this fails, you've given it an output stream that can't seek! It needs
  107096. // to be able to seek back to write the header
  107097. jassert (seekOk);
  107098. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107099. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107100. }
  107101. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107102. const FlacNamespace::FLAC__byte buffer[],
  107103. size_t bytes,
  107104. unsigned int /*samples*/,
  107105. unsigned int /*current_frame*/,
  107106. void* client_data)
  107107. {
  107108. using namespace FlacNamespace;
  107109. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107110. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107111. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107112. }
  107113. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107114. {
  107115. using namespace FlacNamespace;
  107116. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107117. }
  107118. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107119. {
  107120. using namespace FlacNamespace;
  107121. if (client_data == 0)
  107122. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107123. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107124. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107125. }
  107126. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107127. {
  107128. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107129. }
  107130. juce_UseDebuggingNewOperator
  107131. bool ok;
  107132. private:
  107133. FlacNamespace::FLAC__StreamEncoder* encoder;
  107134. FlacWriter (const FlacWriter&);
  107135. FlacWriter& operator= (const FlacWriter&);
  107136. };
  107137. FlacAudioFormat::FlacAudioFormat()
  107138. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107139. {
  107140. }
  107141. FlacAudioFormat::~FlacAudioFormat()
  107142. {
  107143. }
  107144. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107145. {
  107146. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107147. return Array <int> (rates);
  107148. }
  107149. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107150. {
  107151. const int depths[] = { 16, 24, 0 };
  107152. return Array <int> (depths);
  107153. }
  107154. bool FlacAudioFormat::canDoStereo() { return true; }
  107155. bool FlacAudioFormat::canDoMono() { return true; }
  107156. bool FlacAudioFormat::isCompressed() { return true; }
  107157. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107158. const bool deleteStreamIfOpeningFails)
  107159. {
  107160. ScopedPointer<FlacReader> r (new FlacReader (in));
  107161. if (r->sampleRate != 0)
  107162. return r.release();
  107163. if (! deleteStreamIfOpeningFails)
  107164. r->input = 0;
  107165. return 0;
  107166. }
  107167. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107168. double sampleRate,
  107169. unsigned int numberOfChannels,
  107170. int bitsPerSample,
  107171. const StringPairArray& /*metadataValues*/,
  107172. int qualityOptionIndex)
  107173. {
  107174. if (getPossibleBitDepths().contains (bitsPerSample))
  107175. {
  107176. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107177. if (w->ok)
  107178. return w.release();
  107179. }
  107180. return 0;
  107181. }
  107182. END_JUCE_NAMESPACE
  107183. #endif
  107184. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107185. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107186. #if JUCE_USE_OGGVORBIS
  107187. #if JUCE_MAC
  107188. #define __MACOSX__ 1
  107189. #endif
  107190. namespace OggVorbisNamespace
  107191. {
  107192. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107193. /*** Start of inlined file: vorbisenc.h ***/
  107194. #ifndef _OV_ENC_H_
  107195. #define _OV_ENC_H_
  107196. #ifdef __cplusplus
  107197. extern "C"
  107198. {
  107199. #endif /* __cplusplus */
  107200. /*** Start of inlined file: codec.h ***/
  107201. #ifndef _vorbis_codec_h_
  107202. #define _vorbis_codec_h_
  107203. #ifdef __cplusplus
  107204. extern "C"
  107205. {
  107206. #endif /* __cplusplus */
  107207. /*** Start of inlined file: ogg.h ***/
  107208. #ifndef _OGG_H
  107209. #define _OGG_H
  107210. #ifdef __cplusplus
  107211. extern "C" {
  107212. #endif
  107213. /*** Start of inlined file: os_types.h ***/
  107214. #ifndef _OS_TYPES_H
  107215. #define _OS_TYPES_H
  107216. /* make it easy on the folks that want to compile the libs with a
  107217. different malloc than stdlib */
  107218. #define _ogg_malloc malloc
  107219. #define _ogg_calloc calloc
  107220. #define _ogg_realloc realloc
  107221. #define _ogg_free free
  107222. #if defined(_WIN32)
  107223. # if defined(__CYGWIN__)
  107224. # include <_G_config.h>
  107225. typedef _G_int64_t ogg_int64_t;
  107226. typedef _G_int32_t ogg_int32_t;
  107227. typedef _G_uint32_t ogg_uint32_t;
  107228. typedef _G_int16_t ogg_int16_t;
  107229. typedef _G_uint16_t ogg_uint16_t;
  107230. # elif defined(__MINGW32__)
  107231. typedef short ogg_int16_t;
  107232. typedef unsigned short ogg_uint16_t;
  107233. typedef int ogg_int32_t;
  107234. typedef unsigned int ogg_uint32_t;
  107235. typedef long long ogg_int64_t;
  107236. typedef unsigned long long ogg_uint64_t;
  107237. # elif defined(__MWERKS__)
  107238. typedef long long ogg_int64_t;
  107239. typedef int ogg_int32_t;
  107240. typedef unsigned int ogg_uint32_t;
  107241. typedef short ogg_int16_t;
  107242. typedef unsigned short ogg_uint16_t;
  107243. # else
  107244. /* MSVC/Borland */
  107245. typedef __int64 ogg_int64_t;
  107246. typedef __int32 ogg_int32_t;
  107247. typedef unsigned __int32 ogg_uint32_t;
  107248. typedef __int16 ogg_int16_t;
  107249. typedef unsigned __int16 ogg_uint16_t;
  107250. # endif
  107251. #elif defined(__MACOS__)
  107252. # include <sys/types.h>
  107253. typedef SInt16 ogg_int16_t;
  107254. typedef UInt16 ogg_uint16_t;
  107255. typedef SInt32 ogg_int32_t;
  107256. typedef UInt32 ogg_uint32_t;
  107257. typedef SInt64 ogg_int64_t;
  107258. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107259. # include <sys/types.h>
  107260. typedef int16_t ogg_int16_t;
  107261. typedef u_int16_t ogg_uint16_t;
  107262. typedef int32_t ogg_int32_t;
  107263. typedef u_int32_t ogg_uint32_t;
  107264. typedef int64_t ogg_int64_t;
  107265. #elif defined(__BEOS__)
  107266. /* Be */
  107267. # include <inttypes.h>
  107268. typedef int16_t ogg_int16_t;
  107269. typedef u_int16_t ogg_uint16_t;
  107270. typedef int32_t ogg_int32_t;
  107271. typedef u_int32_t ogg_uint32_t;
  107272. typedef int64_t ogg_int64_t;
  107273. #elif defined (__EMX__)
  107274. /* OS/2 GCC */
  107275. typedef short ogg_int16_t;
  107276. typedef unsigned short ogg_uint16_t;
  107277. typedef int ogg_int32_t;
  107278. typedef unsigned int ogg_uint32_t;
  107279. typedef long long ogg_int64_t;
  107280. #elif defined (DJGPP)
  107281. /* DJGPP */
  107282. typedef short ogg_int16_t;
  107283. typedef int ogg_int32_t;
  107284. typedef unsigned int ogg_uint32_t;
  107285. typedef long long ogg_int64_t;
  107286. #elif defined(R5900)
  107287. /* PS2 EE */
  107288. typedef long ogg_int64_t;
  107289. typedef int ogg_int32_t;
  107290. typedef unsigned ogg_uint32_t;
  107291. typedef short ogg_int16_t;
  107292. #elif defined(__SYMBIAN32__)
  107293. /* Symbian GCC */
  107294. typedef signed short ogg_int16_t;
  107295. typedef unsigned short ogg_uint16_t;
  107296. typedef signed int ogg_int32_t;
  107297. typedef unsigned int ogg_uint32_t;
  107298. typedef long long int ogg_int64_t;
  107299. #else
  107300. # include <sys/types.h>
  107301. /*** Start of inlined file: config_types.h ***/
  107302. #ifndef __CONFIG_TYPES_H__
  107303. #define __CONFIG_TYPES_H__
  107304. typedef int16_t ogg_int16_t;
  107305. typedef unsigned short ogg_uint16_t;
  107306. typedef int32_t ogg_int32_t;
  107307. typedef unsigned int ogg_uint32_t;
  107308. typedef int64_t ogg_int64_t;
  107309. #endif
  107310. /*** End of inlined file: config_types.h ***/
  107311. #endif
  107312. #endif /* _OS_TYPES_H */
  107313. /*** End of inlined file: os_types.h ***/
  107314. typedef struct {
  107315. long endbyte;
  107316. int endbit;
  107317. unsigned char *buffer;
  107318. unsigned char *ptr;
  107319. long storage;
  107320. } oggpack_buffer;
  107321. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107322. typedef struct {
  107323. unsigned char *header;
  107324. long header_len;
  107325. unsigned char *body;
  107326. long body_len;
  107327. } ogg_page;
  107328. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107329. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107330. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107331. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107332. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107333. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107334. }
  107335. /* ogg_stream_state contains the current encode/decode state of a logical
  107336. Ogg bitstream **********************************************************/
  107337. typedef struct {
  107338. unsigned char *body_data; /* bytes from packet bodies */
  107339. long body_storage; /* storage elements allocated */
  107340. long body_fill; /* elements stored; fill mark */
  107341. long body_returned; /* elements of fill returned */
  107342. int *lacing_vals; /* The values that will go to the segment table */
  107343. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107344. this way, but it is simple coupled to the
  107345. lacing fifo */
  107346. long lacing_storage;
  107347. long lacing_fill;
  107348. long lacing_packet;
  107349. long lacing_returned;
  107350. unsigned char header[282]; /* working space for header encode */
  107351. int header_fill;
  107352. int e_o_s; /* set when we have buffered the last packet in the
  107353. logical bitstream */
  107354. int b_o_s; /* set after we've written the initial page
  107355. of a logical bitstream */
  107356. long serialno;
  107357. long pageno;
  107358. ogg_int64_t packetno; /* sequence number for decode; the framing
  107359. knows where there's a hole in the data,
  107360. but we need coupling so that the codec
  107361. (which is in a seperate abstraction
  107362. layer) also knows about the gap */
  107363. ogg_int64_t granulepos;
  107364. } ogg_stream_state;
  107365. /* ogg_packet is used to encapsulate the data and metadata belonging
  107366. to a single raw Ogg/Vorbis packet *************************************/
  107367. typedef struct {
  107368. unsigned char *packet;
  107369. long bytes;
  107370. long b_o_s;
  107371. long e_o_s;
  107372. ogg_int64_t granulepos;
  107373. ogg_int64_t packetno; /* sequence number for decode; the framing
  107374. knows where there's a hole in the data,
  107375. but we need coupling so that the codec
  107376. (which is in a seperate abstraction
  107377. layer) also knows about the gap */
  107378. } ogg_packet;
  107379. typedef struct {
  107380. unsigned char *data;
  107381. int storage;
  107382. int fill;
  107383. int returned;
  107384. int unsynced;
  107385. int headerbytes;
  107386. int bodybytes;
  107387. } ogg_sync_state;
  107388. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107389. extern void oggpack_writeinit(oggpack_buffer *b);
  107390. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107391. extern void oggpack_writealign(oggpack_buffer *b);
  107392. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107393. extern void oggpack_reset(oggpack_buffer *b);
  107394. extern void oggpack_writeclear(oggpack_buffer *b);
  107395. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107396. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107397. extern long oggpack_look(oggpack_buffer *b,int bits);
  107398. extern long oggpack_look1(oggpack_buffer *b);
  107399. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107400. extern void oggpack_adv1(oggpack_buffer *b);
  107401. extern long oggpack_read(oggpack_buffer *b,int bits);
  107402. extern long oggpack_read1(oggpack_buffer *b);
  107403. extern long oggpack_bytes(oggpack_buffer *b);
  107404. extern long oggpack_bits(oggpack_buffer *b);
  107405. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107406. extern void oggpackB_writeinit(oggpack_buffer *b);
  107407. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107408. extern void oggpackB_writealign(oggpack_buffer *b);
  107409. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107410. extern void oggpackB_reset(oggpack_buffer *b);
  107411. extern void oggpackB_writeclear(oggpack_buffer *b);
  107412. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107413. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107414. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107415. extern long oggpackB_look1(oggpack_buffer *b);
  107416. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107417. extern void oggpackB_adv1(oggpack_buffer *b);
  107418. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107419. extern long oggpackB_read1(oggpack_buffer *b);
  107420. extern long oggpackB_bytes(oggpack_buffer *b);
  107421. extern long oggpackB_bits(oggpack_buffer *b);
  107422. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107423. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107424. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107425. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107426. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107427. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107428. extern int ogg_sync_init(ogg_sync_state *oy);
  107429. extern int ogg_sync_clear(ogg_sync_state *oy);
  107430. extern int ogg_sync_reset(ogg_sync_state *oy);
  107431. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107432. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107433. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107434. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107435. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107436. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107437. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107438. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107439. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107440. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107441. extern int ogg_stream_clear(ogg_stream_state *os);
  107442. extern int ogg_stream_reset(ogg_stream_state *os);
  107443. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107444. extern int ogg_stream_destroy(ogg_stream_state *os);
  107445. extern int ogg_stream_eos(ogg_stream_state *os);
  107446. extern void ogg_page_checksum_set(ogg_page *og);
  107447. extern int ogg_page_version(ogg_page *og);
  107448. extern int ogg_page_continued(ogg_page *og);
  107449. extern int ogg_page_bos(ogg_page *og);
  107450. extern int ogg_page_eos(ogg_page *og);
  107451. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107452. extern int ogg_page_serialno(ogg_page *og);
  107453. extern long ogg_page_pageno(ogg_page *og);
  107454. extern int ogg_page_packets(ogg_page *og);
  107455. extern void ogg_packet_clear(ogg_packet *op);
  107456. #ifdef __cplusplus
  107457. }
  107458. #endif
  107459. #endif /* _OGG_H */
  107460. /*** End of inlined file: ogg.h ***/
  107461. typedef struct vorbis_info{
  107462. int version;
  107463. int channels;
  107464. long rate;
  107465. /* The below bitrate declarations are *hints*.
  107466. Combinations of the three values carry the following implications:
  107467. all three set to the same value:
  107468. implies a fixed rate bitstream
  107469. only nominal set:
  107470. implies a VBR stream that averages the nominal bitrate. No hard
  107471. upper/lower limit
  107472. upper and or lower set:
  107473. implies a VBR bitstream that obeys the bitrate limits. nominal
  107474. may also be set to give a nominal rate.
  107475. none set:
  107476. the coder does not care to speculate.
  107477. */
  107478. long bitrate_upper;
  107479. long bitrate_nominal;
  107480. long bitrate_lower;
  107481. long bitrate_window;
  107482. void *codec_setup;
  107483. } vorbis_info;
  107484. /* vorbis_dsp_state buffers the current vorbis audio
  107485. analysis/synthesis state. The DSP state belongs to a specific
  107486. logical bitstream ****************************************************/
  107487. typedef struct vorbis_dsp_state{
  107488. int analysisp;
  107489. vorbis_info *vi;
  107490. float **pcm;
  107491. float **pcmret;
  107492. int pcm_storage;
  107493. int pcm_current;
  107494. int pcm_returned;
  107495. int preextrapolate;
  107496. int eofflag;
  107497. long lW;
  107498. long W;
  107499. long nW;
  107500. long centerW;
  107501. ogg_int64_t granulepos;
  107502. ogg_int64_t sequence;
  107503. ogg_int64_t glue_bits;
  107504. ogg_int64_t time_bits;
  107505. ogg_int64_t floor_bits;
  107506. ogg_int64_t res_bits;
  107507. void *backend_state;
  107508. } vorbis_dsp_state;
  107509. typedef struct vorbis_block{
  107510. /* necessary stream state for linking to the framing abstraction */
  107511. float **pcm; /* this is a pointer into local storage */
  107512. oggpack_buffer opb;
  107513. long lW;
  107514. long W;
  107515. long nW;
  107516. int pcmend;
  107517. int mode;
  107518. int eofflag;
  107519. ogg_int64_t granulepos;
  107520. ogg_int64_t sequence;
  107521. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107522. /* local storage to avoid remallocing; it's up to the mapping to
  107523. structure it */
  107524. void *localstore;
  107525. long localtop;
  107526. long localalloc;
  107527. long totaluse;
  107528. struct alloc_chain *reap;
  107529. /* bitmetrics for the frame */
  107530. long glue_bits;
  107531. long time_bits;
  107532. long floor_bits;
  107533. long res_bits;
  107534. void *internal;
  107535. } vorbis_block;
  107536. /* vorbis_block is a single block of data to be processed as part of
  107537. the analysis/synthesis stream; it belongs to a specific logical
  107538. bitstream, but is independant from other vorbis_blocks belonging to
  107539. that logical bitstream. *************************************************/
  107540. struct alloc_chain{
  107541. void *ptr;
  107542. struct alloc_chain *next;
  107543. };
  107544. /* vorbis_info contains all the setup information specific to the
  107545. specific compression/decompression mode in progress (eg,
  107546. psychoacoustic settings, channel setup, options, codebook
  107547. etc). vorbis_info and substructures are in backends.h.
  107548. *********************************************************************/
  107549. /* the comments are not part of vorbis_info so that vorbis_info can be
  107550. static storage */
  107551. typedef struct vorbis_comment{
  107552. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107553. whatever vendor is set to in encode */
  107554. char **user_comments;
  107555. int *comment_lengths;
  107556. int comments;
  107557. char *vendor;
  107558. } vorbis_comment;
  107559. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107560. and produce a packet (see docs/analysis.txt). The packet is then
  107561. coded into a framed OggSquish bitstream by the second layer (see
  107562. docs/framing.txt). Decode is the reverse process; we sync/frame
  107563. the bitstream and extract individual packets, then decode the
  107564. packet back into PCM audio.
  107565. The extra framing/packetizing is used in streaming formats, such as
  107566. files. Over the net (such as with UDP), the framing and
  107567. packetization aren't necessary as they're provided by the transport
  107568. and the streaming layer is not used */
  107569. /* Vorbis PRIMITIVES: general ***************************************/
  107570. extern void vorbis_info_init(vorbis_info *vi);
  107571. extern void vorbis_info_clear(vorbis_info *vi);
  107572. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107573. extern void vorbis_comment_init(vorbis_comment *vc);
  107574. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107575. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107576. const char *tag, char *contents);
  107577. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107578. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107579. extern void vorbis_comment_clear(vorbis_comment *vc);
  107580. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107581. extern int vorbis_block_clear(vorbis_block *vb);
  107582. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107583. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107584. ogg_int64_t granulepos);
  107585. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107586. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107587. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107588. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107589. vorbis_comment *vc,
  107590. ogg_packet *op,
  107591. ogg_packet *op_comm,
  107592. ogg_packet *op_code);
  107593. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107594. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107595. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107596. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107597. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107598. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107599. ogg_packet *op);
  107600. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107601. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107602. ogg_packet *op);
  107603. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107604. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107605. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107606. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107607. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107608. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107609. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107610. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107611. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107612. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107613. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107614. /* Vorbis ERRORS and return codes ***********************************/
  107615. #define OV_FALSE -1
  107616. #define OV_EOF -2
  107617. #define OV_HOLE -3
  107618. #define OV_EREAD -128
  107619. #define OV_EFAULT -129
  107620. #define OV_EIMPL -130
  107621. #define OV_EINVAL -131
  107622. #define OV_ENOTVORBIS -132
  107623. #define OV_EBADHEADER -133
  107624. #define OV_EVERSION -134
  107625. #define OV_ENOTAUDIO -135
  107626. #define OV_EBADPACKET -136
  107627. #define OV_EBADLINK -137
  107628. #define OV_ENOSEEK -138
  107629. #ifdef __cplusplus
  107630. }
  107631. #endif /* __cplusplus */
  107632. #endif
  107633. /*** End of inlined file: codec.h ***/
  107634. extern int vorbis_encode_init(vorbis_info *vi,
  107635. long channels,
  107636. long rate,
  107637. long max_bitrate,
  107638. long nominal_bitrate,
  107639. long min_bitrate);
  107640. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107641. long channels,
  107642. long rate,
  107643. long max_bitrate,
  107644. long nominal_bitrate,
  107645. long min_bitrate);
  107646. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107647. long channels,
  107648. long rate,
  107649. float quality /* quality level from 0. (lo) to 1. (hi) */
  107650. );
  107651. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107652. long channels,
  107653. long rate,
  107654. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107655. );
  107656. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107657. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107658. /* deprecated rate management supported only for compatability */
  107659. #define OV_ECTL_RATEMANAGE_GET 0x10
  107660. #define OV_ECTL_RATEMANAGE_SET 0x11
  107661. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107662. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107663. struct ovectl_ratemanage_arg {
  107664. int management_active;
  107665. long bitrate_hard_min;
  107666. long bitrate_hard_max;
  107667. double bitrate_hard_window;
  107668. long bitrate_av_lo;
  107669. long bitrate_av_hi;
  107670. double bitrate_av_window;
  107671. double bitrate_av_window_center;
  107672. };
  107673. /* new rate setup */
  107674. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107675. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107676. struct ovectl_ratemanage2_arg {
  107677. int management_active;
  107678. long bitrate_limit_min_kbps;
  107679. long bitrate_limit_max_kbps;
  107680. long bitrate_limit_reservoir_bits;
  107681. double bitrate_limit_reservoir_bias;
  107682. long bitrate_average_kbps;
  107683. double bitrate_average_damping;
  107684. };
  107685. #define OV_ECTL_LOWPASS_GET 0x20
  107686. #define OV_ECTL_LOWPASS_SET 0x21
  107687. #define OV_ECTL_IBLOCK_GET 0x30
  107688. #define OV_ECTL_IBLOCK_SET 0x31
  107689. #ifdef __cplusplus
  107690. }
  107691. #endif /* __cplusplus */
  107692. #endif
  107693. /*** End of inlined file: vorbisenc.h ***/
  107694. /*** Start of inlined file: vorbisfile.h ***/
  107695. #ifndef _OV_FILE_H_
  107696. #define _OV_FILE_H_
  107697. #ifdef __cplusplus
  107698. extern "C"
  107699. {
  107700. #endif /* __cplusplus */
  107701. #include <stdio.h>
  107702. /* The function prototypes for the callbacks are basically the same as for
  107703. * the stdio functions fread, fseek, fclose, ftell.
  107704. * The one difference is that the FILE * arguments have been replaced with
  107705. * a void * - this is to be used as a pointer to whatever internal data these
  107706. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107707. *
  107708. * If you use other functions, check the docs for these functions and return
  107709. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107710. * unseekable
  107711. */
  107712. typedef struct {
  107713. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107714. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107715. int (*close_func) (void *datasource);
  107716. long (*tell_func) (void *datasource);
  107717. } ov_callbacks;
  107718. #define NOTOPEN 0
  107719. #define PARTOPEN 1
  107720. #define OPENED 2
  107721. #define STREAMSET 3
  107722. #define INITSET 4
  107723. typedef struct OggVorbis_File {
  107724. void *datasource; /* Pointer to a FILE *, etc. */
  107725. int seekable;
  107726. ogg_int64_t offset;
  107727. ogg_int64_t end;
  107728. ogg_sync_state oy;
  107729. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107730. stream appears */
  107731. int links;
  107732. ogg_int64_t *offsets;
  107733. ogg_int64_t *dataoffsets;
  107734. long *serialnos;
  107735. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107736. compatability; x2 size, stores both
  107737. beginning and end values */
  107738. vorbis_info *vi;
  107739. vorbis_comment *vc;
  107740. /* Decoding working state local storage */
  107741. ogg_int64_t pcm_offset;
  107742. int ready_state;
  107743. long current_serialno;
  107744. int current_link;
  107745. double bittrack;
  107746. double samptrack;
  107747. ogg_stream_state os; /* take physical pages, weld into a logical
  107748. stream of packets */
  107749. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107750. vorbis_block vb; /* local working space for packet->PCM decode */
  107751. ov_callbacks callbacks;
  107752. } OggVorbis_File;
  107753. extern int ov_clear(OggVorbis_File *vf);
  107754. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107755. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107756. char *initial, long ibytes, ov_callbacks callbacks);
  107757. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107758. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107759. char *initial, long ibytes, ov_callbacks callbacks);
  107760. extern int ov_test_open(OggVorbis_File *vf);
  107761. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107762. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107763. extern long ov_streams(OggVorbis_File *vf);
  107764. extern long ov_seekable(OggVorbis_File *vf);
  107765. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107766. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107767. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107768. extern double ov_time_total(OggVorbis_File *vf,int i);
  107769. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107770. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107771. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107772. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107773. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107774. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107775. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107776. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107777. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107778. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107779. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107780. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107781. extern double ov_time_tell(OggVorbis_File *vf);
  107782. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107783. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107784. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107785. int *bitstream);
  107786. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107787. int bigendianp,int word,int sgned,int *bitstream);
  107788. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107789. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107790. extern int ov_halfrate_p(OggVorbis_File *vf);
  107791. #ifdef __cplusplus
  107792. }
  107793. #endif /* __cplusplus */
  107794. #endif
  107795. /*** End of inlined file: vorbisfile.h ***/
  107796. /*** Start of inlined file: bitwise.c ***/
  107797. /* We're 'LSb' endian; if we write a word but read individual bits,
  107798. then we'll read the lsb first */
  107799. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107800. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107801. // tasks..
  107802. #if JUCE_MSVC
  107803. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107804. #endif
  107805. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107806. #if JUCE_USE_OGGVORBIS
  107807. #include <string.h>
  107808. #include <stdlib.h>
  107809. #define BUFFER_INCREMENT 256
  107810. static const unsigned long mask[]=
  107811. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107812. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107813. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107814. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107815. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107816. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107817. 0x3fffffff,0x7fffffff,0xffffffff };
  107818. static const unsigned int mask8B[]=
  107819. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107820. void oggpack_writeinit(oggpack_buffer *b){
  107821. memset(b,0,sizeof(*b));
  107822. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107823. b->buffer[0]='\0';
  107824. b->storage=BUFFER_INCREMENT;
  107825. }
  107826. void oggpackB_writeinit(oggpack_buffer *b){
  107827. oggpack_writeinit(b);
  107828. }
  107829. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107830. long bytes=bits>>3;
  107831. bits-=bytes*8;
  107832. b->ptr=b->buffer+bytes;
  107833. b->endbit=bits;
  107834. b->endbyte=bytes;
  107835. *b->ptr&=mask[bits];
  107836. }
  107837. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107838. long bytes=bits>>3;
  107839. bits-=bytes*8;
  107840. b->ptr=b->buffer+bytes;
  107841. b->endbit=bits;
  107842. b->endbyte=bytes;
  107843. *b->ptr&=mask8B[bits];
  107844. }
  107845. /* Takes only up to 32 bits. */
  107846. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107847. if(b->endbyte+4>=b->storage){
  107848. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107849. b->storage+=BUFFER_INCREMENT;
  107850. b->ptr=b->buffer+b->endbyte;
  107851. }
  107852. value&=mask[bits];
  107853. bits+=b->endbit;
  107854. b->ptr[0]|=value<<b->endbit;
  107855. if(bits>=8){
  107856. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107857. if(bits>=16){
  107858. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107859. if(bits>=24){
  107860. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107861. if(bits>=32){
  107862. if(b->endbit)
  107863. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107864. else
  107865. b->ptr[4]=0;
  107866. }
  107867. }
  107868. }
  107869. }
  107870. b->endbyte+=bits/8;
  107871. b->ptr+=bits/8;
  107872. b->endbit=bits&7;
  107873. }
  107874. /* Takes only up to 32 bits. */
  107875. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107876. if(b->endbyte+4>=b->storage){
  107877. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107878. b->storage+=BUFFER_INCREMENT;
  107879. b->ptr=b->buffer+b->endbyte;
  107880. }
  107881. value=(value&mask[bits])<<(32-bits);
  107882. bits+=b->endbit;
  107883. b->ptr[0]|=value>>(24+b->endbit);
  107884. if(bits>=8){
  107885. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107886. if(bits>=16){
  107887. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107888. if(bits>=24){
  107889. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107890. if(bits>=32){
  107891. if(b->endbit)
  107892. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107893. else
  107894. b->ptr[4]=0;
  107895. }
  107896. }
  107897. }
  107898. }
  107899. b->endbyte+=bits/8;
  107900. b->ptr+=bits/8;
  107901. b->endbit=bits&7;
  107902. }
  107903. void oggpack_writealign(oggpack_buffer *b){
  107904. int bits=8-b->endbit;
  107905. if(bits<8)
  107906. oggpack_write(b,0,bits);
  107907. }
  107908. void oggpackB_writealign(oggpack_buffer *b){
  107909. int bits=8-b->endbit;
  107910. if(bits<8)
  107911. oggpackB_write(b,0,bits);
  107912. }
  107913. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107914. void *source,
  107915. long bits,
  107916. void (*w)(oggpack_buffer *,
  107917. unsigned long,
  107918. int),
  107919. int msb){
  107920. unsigned char *ptr=(unsigned char *)source;
  107921. long bytes=bits/8;
  107922. bits-=bytes*8;
  107923. if(b->endbit){
  107924. int i;
  107925. /* unaligned copy. Do it the hard way. */
  107926. for(i=0;i<bytes;i++)
  107927. w(b,(unsigned long)(ptr[i]),8);
  107928. }else{
  107929. /* aligned block copy */
  107930. if(b->endbyte+bytes+1>=b->storage){
  107931. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107932. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107933. b->ptr=b->buffer+b->endbyte;
  107934. }
  107935. memmove(b->ptr,source,bytes);
  107936. b->ptr+=bytes;
  107937. b->endbyte+=bytes;
  107938. *b->ptr=0;
  107939. }
  107940. if(bits){
  107941. if(msb)
  107942. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107943. else
  107944. w(b,(unsigned long)(ptr[bytes]),bits);
  107945. }
  107946. }
  107947. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107948. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107949. }
  107950. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107951. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107952. }
  107953. void oggpack_reset(oggpack_buffer *b){
  107954. b->ptr=b->buffer;
  107955. b->buffer[0]=0;
  107956. b->endbit=b->endbyte=0;
  107957. }
  107958. void oggpackB_reset(oggpack_buffer *b){
  107959. oggpack_reset(b);
  107960. }
  107961. void oggpack_writeclear(oggpack_buffer *b){
  107962. _ogg_free(b->buffer);
  107963. memset(b,0,sizeof(*b));
  107964. }
  107965. void oggpackB_writeclear(oggpack_buffer *b){
  107966. oggpack_writeclear(b);
  107967. }
  107968. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107969. memset(b,0,sizeof(*b));
  107970. b->buffer=b->ptr=buf;
  107971. b->storage=bytes;
  107972. }
  107973. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107974. oggpack_readinit(b,buf,bytes);
  107975. }
  107976. /* Read in bits without advancing the bitptr; bits <= 32 */
  107977. long oggpack_look(oggpack_buffer *b,int bits){
  107978. unsigned long ret;
  107979. unsigned long m=mask[bits];
  107980. bits+=b->endbit;
  107981. if(b->endbyte+4>=b->storage){
  107982. /* not the main path */
  107983. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107984. }
  107985. ret=b->ptr[0]>>b->endbit;
  107986. if(bits>8){
  107987. ret|=b->ptr[1]<<(8-b->endbit);
  107988. if(bits>16){
  107989. ret|=b->ptr[2]<<(16-b->endbit);
  107990. if(bits>24){
  107991. ret|=b->ptr[3]<<(24-b->endbit);
  107992. if(bits>32 && b->endbit)
  107993. ret|=b->ptr[4]<<(32-b->endbit);
  107994. }
  107995. }
  107996. }
  107997. return(m&ret);
  107998. }
  107999. /* Read in bits without advancing the bitptr; bits <= 32 */
  108000. long oggpackB_look(oggpack_buffer *b,int bits){
  108001. unsigned long ret;
  108002. int m=32-bits;
  108003. bits+=b->endbit;
  108004. if(b->endbyte+4>=b->storage){
  108005. /* not the main path */
  108006. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108007. }
  108008. ret=b->ptr[0]<<(24+b->endbit);
  108009. if(bits>8){
  108010. ret|=b->ptr[1]<<(16+b->endbit);
  108011. if(bits>16){
  108012. ret|=b->ptr[2]<<(8+b->endbit);
  108013. if(bits>24){
  108014. ret|=b->ptr[3]<<(b->endbit);
  108015. if(bits>32 && b->endbit)
  108016. ret|=b->ptr[4]>>(8-b->endbit);
  108017. }
  108018. }
  108019. }
  108020. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  108021. }
  108022. long oggpack_look1(oggpack_buffer *b){
  108023. if(b->endbyte>=b->storage)return(-1);
  108024. return((b->ptr[0]>>b->endbit)&1);
  108025. }
  108026. long oggpackB_look1(oggpack_buffer *b){
  108027. if(b->endbyte>=b->storage)return(-1);
  108028. return((b->ptr[0]>>(7-b->endbit))&1);
  108029. }
  108030. void oggpack_adv(oggpack_buffer *b,int bits){
  108031. bits+=b->endbit;
  108032. b->ptr+=bits/8;
  108033. b->endbyte+=bits/8;
  108034. b->endbit=bits&7;
  108035. }
  108036. void oggpackB_adv(oggpack_buffer *b,int bits){
  108037. oggpack_adv(b,bits);
  108038. }
  108039. void oggpack_adv1(oggpack_buffer *b){
  108040. if(++(b->endbit)>7){
  108041. b->endbit=0;
  108042. b->ptr++;
  108043. b->endbyte++;
  108044. }
  108045. }
  108046. void oggpackB_adv1(oggpack_buffer *b){
  108047. oggpack_adv1(b);
  108048. }
  108049. /* bits <= 32 */
  108050. long oggpack_read(oggpack_buffer *b,int bits){
  108051. long ret;
  108052. unsigned long m=mask[bits];
  108053. bits+=b->endbit;
  108054. if(b->endbyte+4>=b->storage){
  108055. /* not the main path */
  108056. ret=-1L;
  108057. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108058. }
  108059. ret=b->ptr[0]>>b->endbit;
  108060. if(bits>8){
  108061. ret|=b->ptr[1]<<(8-b->endbit);
  108062. if(bits>16){
  108063. ret|=b->ptr[2]<<(16-b->endbit);
  108064. if(bits>24){
  108065. ret|=b->ptr[3]<<(24-b->endbit);
  108066. if(bits>32 && b->endbit){
  108067. ret|=b->ptr[4]<<(32-b->endbit);
  108068. }
  108069. }
  108070. }
  108071. }
  108072. ret&=m;
  108073. overflow:
  108074. b->ptr+=bits/8;
  108075. b->endbyte+=bits/8;
  108076. b->endbit=bits&7;
  108077. return(ret);
  108078. }
  108079. /* bits <= 32 */
  108080. long oggpackB_read(oggpack_buffer *b,int bits){
  108081. long ret;
  108082. long m=32-bits;
  108083. bits+=b->endbit;
  108084. if(b->endbyte+4>=b->storage){
  108085. /* not the main path */
  108086. ret=-1L;
  108087. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108088. }
  108089. ret=b->ptr[0]<<(24+b->endbit);
  108090. if(bits>8){
  108091. ret|=b->ptr[1]<<(16+b->endbit);
  108092. if(bits>16){
  108093. ret|=b->ptr[2]<<(8+b->endbit);
  108094. if(bits>24){
  108095. ret|=b->ptr[3]<<(b->endbit);
  108096. if(bits>32 && b->endbit)
  108097. ret|=b->ptr[4]>>(8-b->endbit);
  108098. }
  108099. }
  108100. }
  108101. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108102. overflow:
  108103. b->ptr+=bits/8;
  108104. b->endbyte+=bits/8;
  108105. b->endbit=bits&7;
  108106. return(ret);
  108107. }
  108108. long oggpack_read1(oggpack_buffer *b){
  108109. long ret;
  108110. if(b->endbyte>=b->storage){
  108111. /* not the main path */
  108112. ret=-1L;
  108113. goto overflow;
  108114. }
  108115. ret=(b->ptr[0]>>b->endbit)&1;
  108116. overflow:
  108117. b->endbit++;
  108118. if(b->endbit>7){
  108119. b->endbit=0;
  108120. b->ptr++;
  108121. b->endbyte++;
  108122. }
  108123. return(ret);
  108124. }
  108125. long oggpackB_read1(oggpack_buffer *b){
  108126. long ret;
  108127. if(b->endbyte>=b->storage){
  108128. /* not the main path */
  108129. ret=-1L;
  108130. goto overflow;
  108131. }
  108132. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108133. overflow:
  108134. b->endbit++;
  108135. if(b->endbit>7){
  108136. b->endbit=0;
  108137. b->ptr++;
  108138. b->endbyte++;
  108139. }
  108140. return(ret);
  108141. }
  108142. long oggpack_bytes(oggpack_buffer *b){
  108143. return(b->endbyte+(b->endbit+7)/8);
  108144. }
  108145. long oggpack_bits(oggpack_buffer *b){
  108146. return(b->endbyte*8+b->endbit);
  108147. }
  108148. long oggpackB_bytes(oggpack_buffer *b){
  108149. return oggpack_bytes(b);
  108150. }
  108151. long oggpackB_bits(oggpack_buffer *b){
  108152. return oggpack_bits(b);
  108153. }
  108154. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108155. return(b->buffer);
  108156. }
  108157. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108158. return oggpack_get_buffer(b);
  108159. }
  108160. /* Self test of the bitwise routines; everything else is based on
  108161. them, so they damned well better be solid. */
  108162. #ifdef _V_SELFTEST
  108163. #include <stdio.h>
  108164. static int ilog(unsigned int v){
  108165. int ret=0;
  108166. while(v){
  108167. ret++;
  108168. v>>=1;
  108169. }
  108170. return(ret);
  108171. }
  108172. oggpack_buffer o;
  108173. oggpack_buffer r;
  108174. void report(char *in){
  108175. fprintf(stderr,"%s",in);
  108176. exit(1);
  108177. }
  108178. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108179. long bytes,i;
  108180. unsigned char *buffer;
  108181. oggpack_reset(&o);
  108182. for(i=0;i<vals;i++)
  108183. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108184. buffer=oggpack_get_buffer(&o);
  108185. bytes=oggpack_bytes(&o);
  108186. if(bytes!=compsize)report("wrong number of bytes!\n");
  108187. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108188. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108189. report("wrote incorrect value!\n");
  108190. }
  108191. oggpack_readinit(&r,buffer,bytes);
  108192. for(i=0;i<vals;i++){
  108193. int tbit=bits?bits:ilog(b[i]);
  108194. if(oggpack_look(&r,tbit)==-1)
  108195. report("out of data!\n");
  108196. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108197. report("looked at incorrect value!\n");
  108198. if(tbit==1)
  108199. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108200. report("looked at single bit incorrect value!\n");
  108201. if(tbit==1){
  108202. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108203. report("read incorrect single bit value!\n");
  108204. }else{
  108205. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108206. report("read incorrect value!\n");
  108207. }
  108208. }
  108209. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108210. }
  108211. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108212. long bytes,i;
  108213. unsigned char *buffer;
  108214. oggpackB_reset(&o);
  108215. for(i=0;i<vals;i++)
  108216. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108217. buffer=oggpackB_get_buffer(&o);
  108218. bytes=oggpackB_bytes(&o);
  108219. if(bytes!=compsize)report("wrong number of bytes!\n");
  108220. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108221. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108222. report("wrote incorrect value!\n");
  108223. }
  108224. oggpackB_readinit(&r,buffer,bytes);
  108225. for(i=0;i<vals;i++){
  108226. int tbit=bits?bits:ilog(b[i]);
  108227. if(oggpackB_look(&r,tbit)==-1)
  108228. report("out of data!\n");
  108229. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108230. report("looked at incorrect value!\n");
  108231. if(tbit==1)
  108232. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108233. report("looked at single bit incorrect value!\n");
  108234. if(tbit==1){
  108235. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108236. report("read incorrect single bit value!\n");
  108237. }else{
  108238. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108239. report("read incorrect value!\n");
  108240. }
  108241. }
  108242. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108243. }
  108244. int main(void){
  108245. unsigned char *buffer;
  108246. long bytes,i;
  108247. static unsigned long testbuffer1[]=
  108248. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108249. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108250. int test1size=43;
  108251. static unsigned long testbuffer2[]=
  108252. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108253. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108254. 85525151,0,12321,1,349528352};
  108255. int test2size=21;
  108256. static unsigned long testbuffer3[]=
  108257. {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,
  108258. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108259. int test3size=56;
  108260. static unsigned long large[]=
  108261. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108262. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108263. 85525151,0,12321,1,2146528352};
  108264. int onesize=33;
  108265. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108266. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108267. 223,4};
  108268. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108269. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108270. 245,251,128};
  108271. int twosize=6;
  108272. static int two[6]={61,255,255,251,231,29};
  108273. static int twoB[6]={247,63,255,253,249,120};
  108274. int threesize=54;
  108275. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108276. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108277. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108278. 100,52,4,14,18,86,77,1};
  108279. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108280. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108281. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108282. 200,20,254,4,58,106,176,144,0};
  108283. int foursize=38;
  108284. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108285. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108286. 28,2,133,0,1};
  108287. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108288. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108289. 129,10,4,32};
  108290. int fivesize=45;
  108291. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108292. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108293. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108294. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108295. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108296. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108297. int sixsize=7;
  108298. static int six[7]={17,177,170,242,169,19,148};
  108299. static int sixB[7]={136,141,85,79,149,200,41};
  108300. /* Test read/write together */
  108301. /* Later we test against pregenerated bitstreams */
  108302. oggpack_writeinit(&o);
  108303. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108304. cliptest(testbuffer1,test1size,0,one,onesize);
  108305. fprintf(stderr,"ok.");
  108306. fprintf(stderr,"\nNull bit call (LSb): ");
  108307. cliptest(testbuffer3,test3size,0,two,twosize);
  108308. fprintf(stderr,"ok.");
  108309. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108310. cliptest(testbuffer2,test2size,0,three,threesize);
  108311. fprintf(stderr,"ok.");
  108312. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108313. oggpack_reset(&o);
  108314. for(i=0;i<test2size;i++)
  108315. oggpack_write(&o,large[i],32);
  108316. buffer=oggpack_get_buffer(&o);
  108317. bytes=oggpack_bytes(&o);
  108318. oggpack_readinit(&r,buffer,bytes);
  108319. for(i=0;i<test2size;i++){
  108320. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108321. if(oggpack_look(&r,32)!=large[i]){
  108322. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108323. oggpack_look(&r,32),large[i]);
  108324. report("read incorrect value!\n");
  108325. }
  108326. oggpack_adv(&r,32);
  108327. }
  108328. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108329. fprintf(stderr,"ok.");
  108330. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108331. cliptest(testbuffer1,test1size,7,four,foursize);
  108332. fprintf(stderr,"ok.");
  108333. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108334. cliptest(testbuffer2,test2size,17,five,fivesize);
  108335. fprintf(stderr,"ok.");
  108336. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108337. cliptest(testbuffer3,test3size,1,six,sixsize);
  108338. fprintf(stderr,"ok.");
  108339. fprintf(stderr,"\nTesting read past end (LSb): ");
  108340. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108341. for(i=0;i<64;i++){
  108342. if(oggpack_read(&r,1)!=0){
  108343. fprintf(stderr,"failed; got -1 prematurely.\n");
  108344. exit(1);
  108345. }
  108346. }
  108347. if(oggpack_look(&r,1)!=-1 ||
  108348. oggpack_read(&r,1)!=-1){
  108349. fprintf(stderr,"failed; read past end without -1.\n");
  108350. exit(1);
  108351. }
  108352. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108353. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108354. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108355. exit(1);
  108356. }
  108357. if(oggpack_look(&r,18)!=0 ||
  108358. oggpack_look(&r,18)!=0){
  108359. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108360. exit(1);
  108361. }
  108362. if(oggpack_look(&r,19)!=-1 ||
  108363. oggpack_look(&r,19)!=-1){
  108364. fprintf(stderr,"failed; read past end without -1.\n");
  108365. exit(1);
  108366. }
  108367. if(oggpack_look(&r,32)!=-1 ||
  108368. oggpack_look(&r,32)!=-1){
  108369. fprintf(stderr,"failed; read past end without -1.\n");
  108370. exit(1);
  108371. }
  108372. oggpack_writeclear(&o);
  108373. fprintf(stderr,"ok.\n");
  108374. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108375. /* Test read/write together */
  108376. /* Later we test against pregenerated bitstreams */
  108377. oggpackB_writeinit(&o);
  108378. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108379. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108380. fprintf(stderr,"ok.");
  108381. fprintf(stderr,"\nNull bit call (MSb): ");
  108382. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108383. fprintf(stderr,"ok.");
  108384. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108385. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108386. fprintf(stderr,"ok.");
  108387. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108388. oggpackB_reset(&o);
  108389. for(i=0;i<test2size;i++)
  108390. oggpackB_write(&o,large[i],32);
  108391. buffer=oggpackB_get_buffer(&o);
  108392. bytes=oggpackB_bytes(&o);
  108393. oggpackB_readinit(&r,buffer,bytes);
  108394. for(i=0;i<test2size;i++){
  108395. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108396. if(oggpackB_look(&r,32)!=large[i]){
  108397. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108398. oggpackB_look(&r,32),large[i]);
  108399. report("read incorrect value!\n");
  108400. }
  108401. oggpackB_adv(&r,32);
  108402. }
  108403. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108404. fprintf(stderr,"ok.");
  108405. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108406. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108407. fprintf(stderr,"ok.");
  108408. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108409. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108410. fprintf(stderr,"ok.");
  108411. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108412. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108413. fprintf(stderr,"ok.");
  108414. fprintf(stderr,"\nTesting read past end (MSb): ");
  108415. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108416. for(i=0;i<64;i++){
  108417. if(oggpackB_read(&r,1)!=0){
  108418. fprintf(stderr,"failed; got -1 prematurely.\n");
  108419. exit(1);
  108420. }
  108421. }
  108422. if(oggpackB_look(&r,1)!=-1 ||
  108423. oggpackB_read(&r,1)!=-1){
  108424. fprintf(stderr,"failed; read past end without -1.\n");
  108425. exit(1);
  108426. }
  108427. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108428. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108429. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108430. exit(1);
  108431. }
  108432. if(oggpackB_look(&r,18)!=0 ||
  108433. oggpackB_look(&r,18)!=0){
  108434. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108435. exit(1);
  108436. }
  108437. if(oggpackB_look(&r,19)!=-1 ||
  108438. oggpackB_look(&r,19)!=-1){
  108439. fprintf(stderr,"failed; read past end without -1.\n");
  108440. exit(1);
  108441. }
  108442. if(oggpackB_look(&r,32)!=-1 ||
  108443. oggpackB_look(&r,32)!=-1){
  108444. fprintf(stderr,"failed; read past end without -1.\n");
  108445. exit(1);
  108446. }
  108447. oggpackB_writeclear(&o);
  108448. fprintf(stderr,"ok.\n\n");
  108449. return(0);
  108450. }
  108451. #endif /* _V_SELFTEST */
  108452. #undef BUFFER_INCREMENT
  108453. #endif
  108454. /*** End of inlined file: bitwise.c ***/
  108455. /*** Start of inlined file: framing.c ***/
  108456. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108457. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108458. // tasks..
  108459. #if JUCE_MSVC
  108460. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108461. #endif
  108462. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108463. #if JUCE_USE_OGGVORBIS
  108464. #include <stdlib.h>
  108465. #include <string.h>
  108466. /* A complete description of Ogg framing exists in docs/framing.html */
  108467. int ogg_page_version(ogg_page *og){
  108468. return((int)(og->header[4]));
  108469. }
  108470. int ogg_page_continued(ogg_page *og){
  108471. return((int)(og->header[5]&0x01));
  108472. }
  108473. int ogg_page_bos(ogg_page *og){
  108474. return((int)(og->header[5]&0x02));
  108475. }
  108476. int ogg_page_eos(ogg_page *og){
  108477. return((int)(og->header[5]&0x04));
  108478. }
  108479. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108480. unsigned char *page=og->header;
  108481. ogg_int64_t granulepos=page[13]&(0xff);
  108482. granulepos= (granulepos<<8)|(page[12]&0xff);
  108483. granulepos= (granulepos<<8)|(page[11]&0xff);
  108484. granulepos= (granulepos<<8)|(page[10]&0xff);
  108485. granulepos= (granulepos<<8)|(page[9]&0xff);
  108486. granulepos= (granulepos<<8)|(page[8]&0xff);
  108487. granulepos= (granulepos<<8)|(page[7]&0xff);
  108488. granulepos= (granulepos<<8)|(page[6]&0xff);
  108489. return(granulepos);
  108490. }
  108491. int ogg_page_serialno(ogg_page *og){
  108492. return(og->header[14] |
  108493. (og->header[15]<<8) |
  108494. (og->header[16]<<16) |
  108495. (og->header[17]<<24));
  108496. }
  108497. long ogg_page_pageno(ogg_page *og){
  108498. return(og->header[18] |
  108499. (og->header[19]<<8) |
  108500. (og->header[20]<<16) |
  108501. (og->header[21]<<24));
  108502. }
  108503. /* returns the number of packets that are completed on this page (if
  108504. the leading packet is begun on a previous page, but ends on this
  108505. page, it's counted */
  108506. /* NOTE:
  108507. If a page consists of a packet begun on a previous page, and a new
  108508. packet begun (but not completed) on this page, the return will be:
  108509. ogg_page_packets(page) ==1,
  108510. ogg_page_continued(page) !=0
  108511. If a page happens to be a single packet that was begun on a
  108512. previous page, and spans to the next page (in the case of a three or
  108513. more page packet), the return will be:
  108514. ogg_page_packets(page) ==0,
  108515. ogg_page_continued(page) !=0
  108516. */
  108517. int ogg_page_packets(ogg_page *og){
  108518. int i,n=og->header[26],count=0;
  108519. for(i=0;i<n;i++)
  108520. if(og->header[27+i]<255)count++;
  108521. return(count);
  108522. }
  108523. #if 0
  108524. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108525. use the static init below) */
  108526. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108527. int i;
  108528. unsigned long r;
  108529. r = index << 24;
  108530. for (i=0; i<8; i++)
  108531. if (r & 0x80000000UL)
  108532. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108533. polynomial, although we use an
  108534. unreflected alg and an init/final
  108535. of 0, not 0xffffffff */
  108536. else
  108537. r<<=1;
  108538. return (r & 0xffffffffUL);
  108539. }
  108540. #endif
  108541. static const ogg_uint32_t crc_lookup[256]={
  108542. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108543. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108544. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108545. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108546. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108547. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108548. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108549. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108550. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108551. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108552. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108553. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108554. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108555. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108556. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108557. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108558. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108559. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108560. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108561. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108562. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108563. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108564. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108565. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108566. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108567. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108568. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108569. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108570. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108571. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108572. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108573. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108574. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108575. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108576. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108577. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108578. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108579. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108580. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108581. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108582. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108583. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108584. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108585. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108586. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108587. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108588. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108589. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108590. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108591. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108592. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108593. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108594. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108595. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108596. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108597. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108598. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108599. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108600. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108601. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108602. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108603. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108604. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108605. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108606. /* init the encode/decode logical stream state */
  108607. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108608. if(os){
  108609. memset(os,0,sizeof(*os));
  108610. os->body_storage=16*1024;
  108611. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108612. os->lacing_storage=1024;
  108613. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108614. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108615. os->serialno=serialno;
  108616. return(0);
  108617. }
  108618. return(-1);
  108619. }
  108620. /* _clear does not free os, only the non-flat storage within */
  108621. int ogg_stream_clear(ogg_stream_state *os){
  108622. if(os){
  108623. if(os->body_data)_ogg_free(os->body_data);
  108624. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108625. if(os->granule_vals)_ogg_free(os->granule_vals);
  108626. memset(os,0,sizeof(*os));
  108627. }
  108628. return(0);
  108629. }
  108630. int ogg_stream_destroy(ogg_stream_state *os){
  108631. if(os){
  108632. ogg_stream_clear(os);
  108633. _ogg_free(os);
  108634. }
  108635. return(0);
  108636. }
  108637. /* Helpers for ogg_stream_encode; this keeps the structure and
  108638. what's happening fairly clear */
  108639. static void _os_body_expand(ogg_stream_state *os,int needed){
  108640. if(os->body_storage<=os->body_fill+needed){
  108641. os->body_storage+=(needed+1024);
  108642. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108643. }
  108644. }
  108645. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108646. if(os->lacing_storage<=os->lacing_fill+needed){
  108647. os->lacing_storage+=(needed+32);
  108648. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108649. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108650. }
  108651. }
  108652. /* checksum the page */
  108653. /* Direct table CRC; note that this will be faster in the future if we
  108654. perform the checksum silmultaneously with other copies */
  108655. void ogg_page_checksum_set(ogg_page *og){
  108656. if(og){
  108657. ogg_uint32_t crc_reg=0;
  108658. int i;
  108659. /* safety; needed for API behavior, but not framing code */
  108660. og->header[22]=0;
  108661. og->header[23]=0;
  108662. og->header[24]=0;
  108663. og->header[25]=0;
  108664. for(i=0;i<og->header_len;i++)
  108665. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108666. for(i=0;i<og->body_len;i++)
  108667. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108668. og->header[22]=(unsigned char)(crc_reg&0xff);
  108669. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108670. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108671. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108672. }
  108673. }
  108674. /* submit data to the internal buffer of the framing engine */
  108675. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108676. int lacing_vals=op->bytes/255+1,i;
  108677. if(os->body_returned){
  108678. /* advance packet data according to the body_returned pointer. We
  108679. had to keep it around to return a pointer into the buffer last
  108680. call */
  108681. os->body_fill-=os->body_returned;
  108682. if(os->body_fill)
  108683. memmove(os->body_data,os->body_data+os->body_returned,
  108684. os->body_fill);
  108685. os->body_returned=0;
  108686. }
  108687. /* make sure we have the buffer storage */
  108688. _os_body_expand(os,op->bytes);
  108689. _os_lacing_expand(os,lacing_vals);
  108690. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108691. the liability of overly clean abstraction for the time being. It
  108692. will actually be fairly easy to eliminate the extra copy in the
  108693. future */
  108694. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108695. os->body_fill+=op->bytes;
  108696. /* Store lacing vals for this packet */
  108697. for(i=0;i<lacing_vals-1;i++){
  108698. os->lacing_vals[os->lacing_fill+i]=255;
  108699. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108700. }
  108701. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108702. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108703. /* flag the first segment as the beginning of the packet */
  108704. os->lacing_vals[os->lacing_fill]|= 0x100;
  108705. os->lacing_fill+=lacing_vals;
  108706. /* for the sake of completeness */
  108707. os->packetno++;
  108708. if(op->e_o_s)os->e_o_s=1;
  108709. return(0);
  108710. }
  108711. /* This will flush remaining packets into a page (returning nonzero),
  108712. even if there is not enough data to trigger a flush normally
  108713. (undersized page). If there are no packets or partial packets to
  108714. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108715. try to flush a normal sized page like ogg_stream_pageout; a call to
  108716. ogg_stream_flush does not guarantee that all packets have flushed.
  108717. Only a return value of 0 from ogg_stream_flush indicates all packet
  108718. data is flushed into pages.
  108719. since ogg_stream_flush will flush the last page in a stream even if
  108720. it's undersized, you almost certainly want to use ogg_stream_pageout
  108721. (and *not* ogg_stream_flush) unless you specifically need to flush
  108722. an page regardless of size in the middle of a stream. */
  108723. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108724. int i;
  108725. int vals=0;
  108726. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108727. int bytes=0;
  108728. long acc=0;
  108729. ogg_int64_t granule_pos=-1;
  108730. if(maxvals==0)return(0);
  108731. /* construct a page */
  108732. /* decide how many segments to include */
  108733. /* If this is the initial header case, the first page must only include
  108734. the initial header packet */
  108735. if(os->b_o_s==0){ /* 'initial header page' case */
  108736. granule_pos=0;
  108737. for(vals=0;vals<maxvals;vals++){
  108738. if((os->lacing_vals[vals]&0x0ff)<255){
  108739. vals++;
  108740. break;
  108741. }
  108742. }
  108743. }else{
  108744. for(vals=0;vals<maxvals;vals++){
  108745. if(acc>4096)break;
  108746. acc+=os->lacing_vals[vals]&0x0ff;
  108747. if((os->lacing_vals[vals]&0xff)<255)
  108748. granule_pos=os->granule_vals[vals];
  108749. }
  108750. }
  108751. /* construct the header in temp storage */
  108752. memcpy(os->header,"OggS",4);
  108753. /* stream structure version */
  108754. os->header[4]=0x00;
  108755. /* continued packet flag? */
  108756. os->header[5]=0x00;
  108757. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108758. /* first page flag? */
  108759. if(os->b_o_s==0)os->header[5]|=0x02;
  108760. /* last page flag? */
  108761. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108762. os->b_o_s=1;
  108763. /* 64 bits of PCM position */
  108764. for(i=6;i<14;i++){
  108765. os->header[i]=(unsigned char)(granule_pos&0xff);
  108766. granule_pos>>=8;
  108767. }
  108768. /* 32 bits of stream serial number */
  108769. {
  108770. long serialno=os->serialno;
  108771. for(i=14;i<18;i++){
  108772. os->header[i]=(unsigned char)(serialno&0xff);
  108773. serialno>>=8;
  108774. }
  108775. }
  108776. /* 32 bits of page counter (we have both counter and page header
  108777. because this val can roll over) */
  108778. if(os->pageno==-1)os->pageno=0; /* because someone called
  108779. stream_reset; this would be a
  108780. strange thing to do in an
  108781. encode stream, but it has
  108782. plausible uses */
  108783. {
  108784. long pageno=os->pageno++;
  108785. for(i=18;i<22;i++){
  108786. os->header[i]=(unsigned char)(pageno&0xff);
  108787. pageno>>=8;
  108788. }
  108789. }
  108790. /* zero for computation; filled in later */
  108791. os->header[22]=0;
  108792. os->header[23]=0;
  108793. os->header[24]=0;
  108794. os->header[25]=0;
  108795. /* segment table */
  108796. os->header[26]=(unsigned char)(vals&0xff);
  108797. for(i=0;i<vals;i++)
  108798. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108799. /* set pointers in the ogg_page struct */
  108800. og->header=os->header;
  108801. og->header_len=os->header_fill=vals+27;
  108802. og->body=os->body_data+os->body_returned;
  108803. og->body_len=bytes;
  108804. /* advance the lacing data and set the body_returned pointer */
  108805. os->lacing_fill-=vals;
  108806. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108807. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108808. os->body_returned+=bytes;
  108809. /* calculate the checksum */
  108810. ogg_page_checksum_set(og);
  108811. /* done */
  108812. return(1);
  108813. }
  108814. /* This constructs pages from buffered packet segments. The pointers
  108815. returned are to static buffers; do not free. The returned buffers are
  108816. good only until the next call (using the same ogg_stream_state) */
  108817. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108818. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108819. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108820. os->lacing_fill>=255 || /* 'segment table full' case */
  108821. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108822. return(ogg_stream_flush(os,og));
  108823. }
  108824. /* not enough data to construct a page and not end of stream */
  108825. return(0);
  108826. }
  108827. int ogg_stream_eos(ogg_stream_state *os){
  108828. return os->e_o_s;
  108829. }
  108830. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108831. /* This has two layers to place more of the multi-serialno and paging
  108832. control in the application's hands. First, we expose a data buffer
  108833. using ogg_sync_buffer(). The app either copies into the
  108834. buffer, or passes it directly to read(), etc. We then call
  108835. ogg_sync_wrote() to tell how many bytes we just added.
  108836. Pages are returned (pointers into the buffer in ogg_sync_state)
  108837. by ogg_sync_pageout(). The page is then submitted to
  108838. ogg_stream_pagein() along with the appropriate
  108839. ogg_stream_state* (ie, matching serialno). We then get raw
  108840. packets out calling ogg_stream_packetout() with a
  108841. ogg_stream_state. */
  108842. /* initialize the struct to a known state */
  108843. int ogg_sync_init(ogg_sync_state *oy){
  108844. if(oy){
  108845. memset(oy,0,sizeof(*oy));
  108846. }
  108847. return(0);
  108848. }
  108849. /* clear non-flat storage within */
  108850. int ogg_sync_clear(ogg_sync_state *oy){
  108851. if(oy){
  108852. if(oy->data)_ogg_free(oy->data);
  108853. ogg_sync_init(oy);
  108854. }
  108855. return(0);
  108856. }
  108857. int ogg_sync_destroy(ogg_sync_state *oy){
  108858. if(oy){
  108859. ogg_sync_clear(oy);
  108860. _ogg_free(oy);
  108861. }
  108862. return(0);
  108863. }
  108864. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108865. /* first, clear out any space that has been previously returned */
  108866. if(oy->returned){
  108867. oy->fill-=oy->returned;
  108868. if(oy->fill>0)
  108869. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108870. oy->returned=0;
  108871. }
  108872. if(size>oy->storage-oy->fill){
  108873. /* We need to extend the internal buffer */
  108874. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108875. if(oy->data)
  108876. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108877. else
  108878. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108879. oy->storage=newsize;
  108880. }
  108881. /* expose a segment at least as large as requested at the fill mark */
  108882. return((char *)oy->data+oy->fill);
  108883. }
  108884. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108885. if(oy->fill+bytes>oy->storage)return(-1);
  108886. oy->fill+=bytes;
  108887. return(0);
  108888. }
  108889. /* sync the stream. This is meant to be useful for finding page
  108890. boundaries.
  108891. return values for this:
  108892. -n) skipped n bytes
  108893. 0) page not ready; more data (no bytes skipped)
  108894. n) page synced at current location; page length n bytes
  108895. */
  108896. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108897. unsigned char *page=oy->data+oy->returned;
  108898. unsigned char *next;
  108899. long bytes=oy->fill-oy->returned;
  108900. if(oy->headerbytes==0){
  108901. int headerbytes,i;
  108902. if(bytes<27)return(0); /* not enough for a header */
  108903. /* verify capture pattern */
  108904. if(memcmp(page,"OggS",4))goto sync_fail;
  108905. headerbytes=page[26]+27;
  108906. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108907. /* count up body length in the segment table */
  108908. for(i=0;i<page[26];i++)
  108909. oy->bodybytes+=page[27+i];
  108910. oy->headerbytes=headerbytes;
  108911. }
  108912. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108913. /* The whole test page is buffered. Verify the checksum */
  108914. {
  108915. /* Grab the checksum bytes, set the header field to zero */
  108916. char chksum[4];
  108917. ogg_page log;
  108918. memcpy(chksum,page+22,4);
  108919. memset(page+22,0,4);
  108920. /* set up a temp page struct and recompute the checksum */
  108921. log.header=page;
  108922. log.header_len=oy->headerbytes;
  108923. log.body=page+oy->headerbytes;
  108924. log.body_len=oy->bodybytes;
  108925. ogg_page_checksum_set(&log);
  108926. /* Compare */
  108927. if(memcmp(chksum,page+22,4)){
  108928. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108929. at all) */
  108930. /* replace the computed checksum with the one actually read in */
  108931. memcpy(page+22,chksum,4);
  108932. /* Bad checksum. Lose sync */
  108933. goto sync_fail;
  108934. }
  108935. }
  108936. /* yes, have a whole page all ready to go */
  108937. {
  108938. unsigned char *page=oy->data+oy->returned;
  108939. long bytes;
  108940. if(og){
  108941. og->header=page;
  108942. og->header_len=oy->headerbytes;
  108943. og->body=page+oy->headerbytes;
  108944. og->body_len=oy->bodybytes;
  108945. }
  108946. oy->unsynced=0;
  108947. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108948. oy->headerbytes=0;
  108949. oy->bodybytes=0;
  108950. return(bytes);
  108951. }
  108952. sync_fail:
  108953. oy->headerbytes=0;
  108954. oy->bodybytes=0;
  108955. /* search for possible capture */
  108956. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108957. if(!next)
  108958. next=oy->data+oy->fill;
  108959. oy->returned=next-oy->data;
  108960. return(-(next-page));
  108961. }
  108962. /* sync the stream and get a page. Keep trying until we find a page.
  108963. Supress 'sync errors' after reporting the first.
  108964. return values:
  108965. -1) recapture (hole in data)
  108966. 0) need more data
  108967. 1) page returned
  108968. Returns pointers into buffered data; invalidated by next call to
  108969. _stream, _clear, _init, or _buffer */
  108970. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108971. /* all we need to do is verify a page at the head of the stream
  108972. buffer. If it doesn't verify, we look for the next potential
  108973. frame */
  108974. for(;;){
  108975. long ret=ogg_sync_pageseek(oy,og);
  108976. if(ret>0){
  108977. /* have a page */
  108978. return(1);
  108979. }
  108980. if(ret==0){
  108981. /* need more data */
  108982. return(0);
  108983. }
  108984. /* head did not start a synced page... skipped some bytes */
  108985. if(!oy->unsynced){
  108986. oy->unsynced=1;
  108987. return(-1);
  108988. }
  108989. /* loop. keep looking */
  108990. }
  108991. }
  108992. /* add the incoming page to the stream state; we decompose the page
  108993. into packet segments here as well. */
  108994. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108995. unsigned char *header=og->header;
  108996. unsigned char *body=og->body;
  108997. long bodysize=og->body_len;
  108998. int segptr=0;
  108999. int version=ogg_page_version(og);
  109000. int continued=ogg_page_continued(og);
  109001. int bos=ogg_page_bos(og);
  109002. int eos=ogg_page_eos(og);
  109003. ogg_int64_t granulepos=ogg_page_granulepos(og);
  109004. int serialno=ogg_page_serialno(og);
  109005. long pageno=ogg_page_pageno(og);
  109006. int segments=header[26];
  109007. /* clean up 'returned data' */
  109008. {
  109009. long lr=os->lacing_returned;
  109010. long br=os->body_returned;
  109011. /* body data */
  109012. if(br){
  109013. os->body_fill-=br;
  109014. if(os->body_fill)
  109015. memmove(os->body_data,os->body_data+br,os->body_fill);
  109016. os->body_returned=0;
  109017. }
  109018. if(lr){
  109019. /* segment table */
  109020. if(os->lacing_fill-lr){
  109021. memmove(os->lacing_vals,os->lacing_vals+lr,
  109022. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  109023. memmove(os->granule_vals,os->granule_vals+lr,
  109024. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  109025. }
  109026. os->lacing_fill-=lr;
  109027. os->lacing_packet-=lr;
  109028. os->lacing_returned=0;
  109029. }
  109030. }
  109031. /* check the serial number */
  109032. if(serialno!=os->serialno)return(-1);
  109033. if(version>0)return(-1);
  109034. _os_lacing_expand(os,segments+1);
  109035. /* are we in sequence? */
  109036. if(pageno!=os->pageno){
  109037. int i;
  109038. /* unroll previous partial packet (if any) */
  109039. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109040. os->body_fill-=os->lacing_vals[i]&0xff;
  109041. os->lacing_fill=os->lacing_packet;
  109042. /* make a note of dropped data in segment table */
  109043. if(os->pageno!=-1){
  109044. os->lacing_vals[os->lacing_fill++]=0x400;
  109045. os->lacing_packet++;
  109046. }
  109047. }
  109048. /* are we a 'continued packet' page? If so, we may need to skip
  109049. some segments */
  109050. if(continued){
  109051. if(os->lacing_fill<1 ||
  109052. os->lacing_vals[os->lacing_fill-1]==0x400){
  109053. bos=0;
  109054. for(;segptr<segments;segptr++){
  109055. int val=header[27+segptr];
  109056. body+=val;
  109057. bodysize-=val;
  109058. if(val<255){
  109059. segptr++;
  109060. break;
  109061. }
  109062. }
  109063. }
  109064. }
  109065. if(bodysize){
  109066. _os_body_expand(os,bodysize);
  109067. memcpy(os->body_data+os->body_fill,body,bodysize);
  109068. os->body_fill+=bodysize;
  109069. }
  109070. {
  109071. int saved=-1;
  109072. while(segptr<segments){
  109073. int val=header[27+segptr];
  109074. os->lacing_vals[os->lacing_fill]=val;
  109075. os->granule_vals[os->lacing_fill]=-1;
  109076. if(bos){
  109077. os->lacing_vals[os->lacing_fill]|=0x100;
  109078. bos=0;
  109079. }
  109080. if(val<255)saved=os->lacing_fill;
  109081. os->lacing_fill++;
  109082. segptr++;
  109083. if(val<255)os->lacing_packet=os->lacing_fill;
  109084. }
  109085. /* set the granulepos on the last granuleval of the last full packet */
  109086. if(saved!=-1){
  109087. os->granule_vals[saved]=granulepos;
  109088. }
  109089. }
  109090. if(eos){
  109091. os->e_o_s=1;
  109092. if(os->lacing_fill>0)
  109093. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109094. }
  109095. os->pageno=pageno+1;
  109096. return(0);
  109097. }
  109098. /* clear things to an initial state. Good to call, eg, before seeking */
  109099. int ogg_sync_reset(ogg_sync_state *oy){
  109100. oy->fill=0;
  109101. oy->returned=0;
  109102. oy->unsynced=0;
  109103. oy->headerbytes=0;
  109104. oy->bodybytes=0;
  109105. return(0);
  109106. }
  109107. int ogg_stream_reset(ogg_stream_state *os){
  109108. os->body_fill=0;
  109109. os->body_returned=0;
  109110. os->lacing_fill=0;
  109111. os->lacing_packet=0;
  109112. os->lacing_returned=0;
  109113. os->header_fill=0;
  109114. os->e_o_s=0;
  109115. os->b_o_s=0;
  109116. os->pageno=-1;
  109117. os->packetno=0;
  109118. os->granulepos=0;
  109119. return(0);
  109120. }
  109121. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109122. ogg_stream_reset(os);
  109123. os->serialno=serialno;
  109124. return(0);
  109125. }
  109126. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109127. /* The last part of decode. We have the stream broken into packet
  109128. segments. Now we need to group them into packets (or return the
  109129. out of sync markers) */
  109130. int ptr=os->lacing_returned;
  109131. if(os->lacing_packet<=ptr)return(0);
  109132. if(os->lacing_vals[ptr]&0x400){
  109133. /* we need to tell the codec there's a gap; it might need to
  109134. handle previous packet dependencies. */
  109135. os->lacing_returned++;
  109136. os->packetno++;
  109137. return(-1);
  109138. }
  109139. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109140. to ask if there's a whole packet
  109141. waiting */
  109142. /* Gather the whole packet. We'll have no holes or a partial packet */
  109143. {
  109144. int size=os->lacing_vals[ptr]&0xff;
  109145. int bytes=size;
  109146. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109147. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109148. while(size==255){
  109149. int val=os->lacing_vals[++ptr];
  109150. size=val&0xff;
  109151. if(val&0x200)eos=0x200;
  109152. bytes+=size;
  109153. }
  109154. if(op){
  109155. op->e_o_s=eos;
  109156. op->b_o_s=bos;
  109157. op->packet=os->body_data+os->body_returned;
  109158. op->packetno=os->packetno;
  109159. op->granulepos=os->granule_vals[ptr];
  109160. op->bytes=bytes;
  109161. }
  109162. if(adv){
  109163. os->body_returned+=bytes;
  109164. os->lacing_returned=ptr+1;
  109165. os->packetno++;
  109166. }
  109167. }
  109168. return(1);
  109169. }
  109170. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109171. return _packetout(os,op,1);
  109172. }
  109173. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109174. return _packetout(os,op,0);
  109175. }
  109176. void ogg_packet_clear(ogg_packet *op) {
  109177. _ogg_free(op->packet);
  109178. memset(op, 0, sizeof(*op));
  109179. }
  109180. #ifdef _V_SELFTEST
  109181. #include <stdio.h>
  109182. ogg_stream_state os_en, os_de;
  109183. ogg_sync_state oy;
  109184. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109185. long j;
  109186. static int sequence=0;
  109187. static int lastno=0;
  109188. if(op->bytes!=len){
  109189. fprintf(stderr,"incorrect packet length!\n");
  109190. exit(1);
  109191. }
  109192. if(op->granulepos!=pos){
  109193. fprintf(stderr,"incorrect packet position!\n");
  109194. exit(1);
  109195. }
  109196. /* packet number just follows sequence/gap; adjust the input number
  109197. for that */
  109198. if(no==0){
  109199. sequence=0;
  109200. }else{
  109201. sequence++;
  109202. if(no>lastno+1)
  109203. sequence++;
  109204. }
  109205. lastno=no;
  109206. if(op->packetno!=sequence){
  109207. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109208. (long)(op->packetno),sequence);
  109209. exit(1);
  109210. }
  109211. /* Test data */
  109212. for(j=0;j<op->bytes;j++)
  109213. if(op->packet[j]!=((j+no)&0xff)){
  109214. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109215. j,op->packet[j],(j+no)&0xff);
  109216. exit(1);
  109217. }
  109218. }
  109219. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109220. long j;
  109221. /* Test data */
  109222. for(j=0;j<og->body_len;j++)
  109223. if(og->body[j]!=data[j]){
  109224. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109225. j,data[j],og->body[j]);
  109226. exit(1);
  109227. }
  109228. /* Test header */
  109229. for(j=0;j<og->header_len;j++){
  109230. if(og->header[j]!=header[j]){
  109231. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109232. for(j=0;j<header[26]+27;j++)
  109233. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109234. fprintf(stderr,"\n");
  109235. exit(1);
  109236. }
  109237. }
  109238. if(og->header_len!=header[26]+27){
  109239. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109240. og->header_len,header[26]+27);
  109241. exit(1);
  109242. }
  109243. }
  109244. void print_header(ogg_page *og){
  109245. int j;
  109246. fprintf(stderr,"\nHEADER:\n");
  109247. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109248. og->header[0],og->header[1],og->header[2],og->header[3],
  109249. (int)og->header[4],(int)og->header[5]);
  109250. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109251. (og->header[9]<<24)|(og->header[8]<<16)|
  109252. (og->header[7]<<8)|og->header[6],
  109253. (og->header[17]<<24)|(og->header[16]<<16)|
  109254. (og->header[15]<<8)|og->header[14],
  109255. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109256. (og->header[19]<<8)|og->header[18]);
  109257. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109258. (int)og->header[22],(int)og->header[23],
  109259. (int)og->header[24],(int)og->header[25],
  109260. (int)og->header[26]);
  109261. for(j=27;j<og->header_len;j++)
  109262. fprintf(stderr,"%d ",(int)og->header[j]);
  109263. fprintf(stderr,")\n\n");
  109264. }
  109265. void copy_page(ogg_page *og){
  109266. unsigned char *temp=_ogg_malloc(og->header_len);
  109267. memcpy(temp,og->header,og->header_len);
  109268. og->header=temp;
  109269. temp=_ogg_malloc(og->body_len);
  109270. memcpy(temp,og->body,og->body_len);
  109271. og->body=temp;
  109272. }
  109273. void free_page(ogg_page *og){
  109274. _ogg_free (og->header);
  109275. _ogg_free (og->body);
  109276. }
  109277. void error(void){
  109278. fprintf(stderr,"error!\n");
  109279. exit(1);
  109280. }
  109281. /* 17 only */
  109282. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109283. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109284. 0x01,0x02,0x03,0x04,0,0,0,0,
  109285. 0x15,0xed,0xec,0x91,
  109286. 1,
  109287. 17};
  109288. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109289. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109290. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109291. 0x01,0x02,0x03,0x04,0,0,0,0,
  109292. 0x59,0x10,0x6c,0x2c,
  109293. 1,
  109294. 17};
  109295. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109296. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109297. 0x01,0x02,0x03,0x04,1,0,0,0,
  109298. 0x89,0x33,0x85,0xce,
  109299. 13,
  109300. 254,255,0,255,1,255,245,255,255,0,
  109301. 255,255,90};
  109302. /* nil packets; beginning,middle,end */
  109303. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109304. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109305. 0x01,0x02,0x03,0x04,0,0,0,0,
  109306. 0xff,0x7b,0x23,0x17,
  109307. 1,
  109308. 0};
  109309. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109310. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109311. 0x01,0x02,0x03,0x04,1,0,0,0,
  109312. 0x5c,0x3f,0x66,0xcb,
  109313. 17,
  109314. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109315. 255,255,90,0};
  109316. /* large initial packet */
  109317. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109318. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109319. 0x01,0x02,0x03,0x04,0,0,0,0,
  109320. 0x01,0x27,0x31,0xaa,
  109321. 18,
  109322. 255,255,255,255,255,255,255,255,
  109323. 255,255,255,255,255,255,255,255,255,10};
  109324. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109325. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109326. 0x01,0x02,0x03,0x04,1,0,0,0,
  109327. 0x7f,0x4e,0x8a,0xd2,
  109328. 4,
  109329. 255,4,255,0};
  109330. /* continuing packet test */
  109331. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109332. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109333. 0x01,0x02,0x03,0x04,0,0,0,0,
  109334. 0xff,0x7b,0x23,0x17,
  109335. 1,
  109336. 0};
  109337. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109338. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109339. 0x01,0x02,0x03,0x04,1,0,0,0,
  109340. 0x54,0x05,0x51,0xc8,
  109341. 17,
  109342. 255,255,255,255,255,255,255,255,
  109343. 255,255,255,255,255,255,255,255,255};
  109344. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109345. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109346. 0x01,0x02,0x03,0x04,2,0,0,0,
  109347. 0xc8,0xc3,0xcb,0xed,
  109348. 5,
  109349. 10,255,4,255,0};
  109350. /* page with the 255 segment limit */
  109351. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109352. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109353. 0x01,0x02,0x03,0x04,0,0,0,0,
  109354. 0xff,0x7b,0x23,0x17,
  109355. 1,
  109356. 0};
  109357. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109358. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109359. 0x01,0x02,0x03,0x04,1,0,0,0,
  109360. 0xed,0x2a,0x2e,0xa7,
  109361. 255,
  109362. 10,10,10,10,10,10,10,10,
  109363. 10,10,10,10,10,10,10,10,
  109364. 10,10,10,10,10,10,10,10,
  109365. 10,10,10,10,10,10,10,10,
  109366. 10,10,10,10,10,10,10,10,
  109367. 10,10,10,10,10,10,10,10,
  109368. 10,10,10,10,10,10,10,10,
  109369. 10,10,10,10,10,10,10,10,
  109370. 10,10,10,10,10,10,10,10,
  109371. 10,10,10,10,10,10,10,10,
  109372. 10,10,10,10,10,10,10,10,
  109373. 10,10,10,10,10,10,10,10,
  109374. 10,10,10,10,10,10,10,10,
  109375. 10,10,10,10,10,10,10,10,
  109376. 10,10,10,10,10,10,10,10,
  109377. 10,10,10,10,10,10,10,10,
  109378. 10,10,10,10,10,10,10,10,
  109379. 10,10,10,10,10,10,10,10,
  109380. 10,10,10,10,10,10,10,10,
  109381. 10,10,10,10,10,10,10,10,
  109382. 10,10,10,10,10,10,10,10,
  109383. 10,10,10,10,10,10,10,10,
  109384. 10,10,10,10,10,10,10,10,
  109385. 10,10,10,10,10,10,10,10,
  109386. 10,10,10,10,10,10,10,10,
  109387. 10,10,10,10,10,10,10,10,
  109388. 10,10,10,10,10,10,10,10,
  109389. 10,10,10,10,10,10,10,10,
  109390. 10,10,10,10,10,10,10,10,
  109391. 10,10,10,10,10,10,10,10,
  109392. 10,10,10,10,10,10,10,10,
  109393. 10,10,10,10,10,10,10};
  109394. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109395. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109396. 0x01,0x02,0x03,0x04,2,0,0,0,
  109397. 0x6c,0x3b,0x82,0x3d,
  109398. 1,
  109399. 50};
  109400. /* packet that overspans over an entire page */
  109401. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109402. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109403. 0x01,0x02,0x03,0x04,0,0,0,0,
  109404. 0xff,0x7b,0x23,0x17,
  109405. 1,
  109406. 0};
  109407. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109408. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109409. 0x01,0x02,0x03,0x04,1,0,0,0,
  109410. 0x3c,0xd9,0x4d,0x3f,
  109411. 17,
  109412. 100,255,255,255,255,255,255,255,255,
  109413. 255,255,255,255,255,255,255,255};
  109414. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109415. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109416. 0x01,0x02,0x03,0x04,2,0,0,0,
  109417. 0x01,0xd2,0xe5,0xe5,
  109418. 17,
  109419. 255,255,255,255,255,255,255,255,
  109420. 255,255,255,255,255,255,255,255,255};
  109421. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109422. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109423. 0x01,0x02,0x03,0x04,3,0,0,0,
  109424. 0xef,0xdd,0x88,0xde,
  109425. 7,
  109426. 255,255,75,255,4,255,0};
  109427. /* packet that overspans over an entire page */
  109428. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109429. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109430. 0x01,0x02,0x03,0x04,0,0,0,0,
  109431. 0xff,0x7b,0x23,0x17,
  109432. 1,
  109433. 0};
  109434. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109435. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109436. 0x01,0x02,0x03,0x04,1,0,0,0,
  109437. 0x3c,0xd9,0x4d,0x3f,
  109438. 17,
  109439. 100,255,255,255,255,255,255,255,255,
  109440. 255,255,255,255,255,255,255,255};
  109441. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109442. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109443. 0x01,0x02,0x03,0x04,2,0,0,0,
  109444. 0xd4,0xe0,0x60,0xe5,
  109445. 1,0};
  109446. void test_pack(const int *pl, const int **headers, int byteskip,
  109447. int pageskip, int packetskip){
  109448. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109449. long inptr=0;
  109450. long outptr=0;
  109451. long deptr=0;
  109452. long depacket=0;
  109453. long granule_pos=7,pageno=0;
  109454. int i,j,packets,pageout=pageskip;
  109455. int eosflag=0;
  109456. int bosflag=0;
  109457. int byteskipcount=0;
  109458. ogg_stream_reset(&os_en);
  109459. ogg_stream_reset(&os_de);
  109460. ogg_sync_reset(&oy);
  109461. for(packets=0;packets<packetskip;packets++)
  109462. depacket+=pl[packets];
  109463. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109464. for(i=0;i<packets;i++){
  109465. /* construct a test packet */
  109466. ogg_packet op;
  109467. int len=pl[i];
  109468. op.packet=data+inptr;
  109469. op.bytes=len;
  109470. op.e_o_s=(pl[i+1]<0?1:0);
  109471. op.granulepos=granule_pos;
  109472. granule_pos+=1024;
  109473. for(j=0;j<len;j++)data[inptr++]=i+j;
  109474. /* submit the test packet */
  109475. ogg_stream_packetin(&os_en,&op);
  109476. /* retrieve any finished pages */
  109477. {
  109478. ogg_page og;
  109479. while(ogg_stream_pageout(&os_en,&og)){
  109480. /* We have a page. Check it carefully */
  109481. fprintf(stderr,"%ld, ",pageno);
  109482. if(headers[pageno]==NULL){
  109483. fprintf(stderr,"coded too many pages!\n");
  109484. exit(1);
  109485. }
  109486. check_page(data+outptr,headers[pageno],&og);
  109487. outptr+=og.body_len;
  109488. pageno++;
  109489. if(pageskip){
  109490. bosflag=1;
  109491. pageskip--;
  109492. deptr+=og.body_len;
  109493. }
  109494. /* have a complete page; submit it to sync/decode */
  109495. {
  109496. ogg_page og_de;
  109497. ogg_packet op_de,op_de2;
  109498. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109499. char *next=buf;
  109500. byteskipcount+=og.header_len;
  109501. if(byteskipcount>byteskip){
  109502. memcpy(next,og.header,byteskipcount-byteskip);
  109503. next+=byteskipcount-byteskip;
  109504. byteskipcount=byteskip;
  109505. }
  109506. byteskipcount+=og.body_len;
  109507. if(byteskipcount>byteskip){
  109508. memcpy(next,og.body,byteskipcount-byteskip);
  109509. next+=byteskipcount-byteskip;
  109510. byteskipcount=byteskip;
  109511. }
  109512. ogg_sync_wrote(&oy,next-buf);
  109513. while(1){
  109514. int ret=ogg_sync_pageout(&oy,&og_de);
  109515. if(ret==0)break;
  109516. if(ret<0)continue;
  109517. /* got a page. Happy happy. Verify that it's good. */
  109518. fprintf(stderr,"(%ld), ",pageout);
  109519. check_page(data+deptr,headers[pageout],&og_de);
  109520. deptr+=og_de.body_len;
  109521. pageout++;
  109522. /* submit it to deconstitution */
  109523. ogg_stream_pagein(&os_de,&og_de);
  109524. /* packets out? */
  109525. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109526. ogg_stream_packetpeek(&os_de,NULL);
  109527. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109528. /* verify peek and out match */
  109529. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109530. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109531. depacket);
  109532. exit(1);
  109533. }
  109534. /* verify the packet! */
  109535. /* check data */
  109536. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109537. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109538. depacket);
  109539. exit(1);
  109540. }
  109541. /* check bos flag */
  109542. if(bosflag==0 && op_de.b_o_s==0){
  109543. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109544. exit(1);
  109545. }
  109546. if(bosflag && op_de.b_o_s){
  109547. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109548. exit(1);
  109549. }
  109550. bosflag=1;
  109551. depacket+=op_de.bytes;
  109552. /* check eos flag */
  109553. if(eosflag){
  109554. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109555. exit(1);
  109556. }
  109557. if(op_de.e_o_s)eosflag=1;
  109558. /* check granulepos flag */
  109559. if(op_de.granulepos!=-1){
  109560. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109561. }
  109562. }
  109563. }
  109564. }
  109565. }
  109566. }
  109567. }
  109568. _ogg_free(data);
  109569. if(headers[pageno]!=NULL){
  109570. fprintf(stderr,"did not write last page!\n");
  109571. exit(1);
  109572. }
  109573. if(headers[pageout]!=NULL){
  109574. fprintf(stderr,"did not decode last page!\n");
  109575. exit(1);
  109576. }
  109577. if(inptr!=outptr){
  109578. fprintf(stderr,"encoded page data incomplete!\n");
  109579. exit(1);
  109580. }
  109581. if(inptr!=deptr){
  109582. fprintf(stderr,"decoded page data incomplete!\n");
  109583. exit(1);
  109584. }
  109585. if(inptr!=depacket){
  109586. fprintf(stderr,"decoded packet data incomplete!\n");
  109587. exit(1);
  109588. }
  109589. if(!eosflag){
  109590. fprintf(stderr,"Never got a packet with EOS set!\n");
  109591. exit(1);
  109592. }
  109593. fprintf(stderr,"ok.\n");
  109594. }
  109595. int main(void){
  109596. ogg_stream_init(&os_en,0x04030201);
  109597. ogg_stream_init(&os_de,0x04030201);
  109598. ogg_sync_init(&oy);
  109599. /* Exercise each code path in the framing code. Also verify that
  109600. the checksums are working. */
  109601. {
  109602. /* 17 only */
  109603. const int packets[]={17, -1};
  109604. const int *headret[]={head1_0,NULL};
  109605. fprintf(stderr,"testing single page encoding... ");
  109606. test_pack(packets,headret,0,0,0);
  109607. }
  109608. {
  109609. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109610. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109611. const int *headret[]={head1_1,head2_1,NULL};
  109612. fprintf(stderr,"testing basic page encoding... ");
  109613. test_pack(packets,headret,0,0,0);
  109614. }
  109615. {
  109616. /* nil packets; beginning,middle,end */
  109617. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109618. const int *headret[]={head1_2,head2_2,NULL};
  109619. fprintf(stderr,"testing basic nil packets... ");
  109620. test_pack(packets,headret,0,0,0);
  109621. }
  109622. {
  109623. /* large initial packet */
  109624. const int packets[]={4345,259,255,-1};
  109625. const int *headret[]={head1_3,head2_3,NULL};
  109626. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109627. test_pack(packets,headret,0,0,0);
  109628. }
  109629. {
  109630. /* continuing packet test */
  109631. const int packets[]={0,4345,259,255,-1};
  109632. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109633. fprintf(stderr,"testing single packet page span... ");
  109634. test_pack(packets,headret,0,0,0);
  109635. }
  109636. /* page with the 255 segment limit */
  109637. {
  109638. const int packets[]={0,10,10,10,10,10,10,10,10,
  109639. 10,10,10,10,10,10,10,10,
  109640. 10,10,10,10,10,10,10,10,
  109641. 10,10,10,10,10,10,10,10,
  109642. 10,10,10,10,10,10,10,10,
  109643. 10,10,10,10,10,10,10,10,
  109644. 10,10,10,10,10,10,10,10,
  109645. 10,10,10,10,10,10,10,10,
  109646. 10,10,10,10,10,10,10,10,
  109647. 10,10,10,10,10,10,10,10,
  109648. 10,10,10,10,10,10,10,10,
  109649. 10,10,10,10,10,10,10,10,
  109650. 10,10,10,10,10,10,10,10,
  109651. 10,10,10,10,10,10,10,10,
  109652. 10,10,10,10,10,10,10,10,
  109653. 10,10,10,10,10,10,10,10,
  109654. 10,10,10,10,10,10,10,10,
  109655. 10,10,10,10,10,10,10,10,
  109656. 10,10,10,10,10,10,10,10,
  109657. 10,10,10,10,10,10,10,10,
  109658. 10,10,10,10,10,10,10,10,
  109659. 10,10,10,10,10,10,10,10,
  109660. 10,10,10,10,10,10,10,10,
  109661. 10,10,10,10,10,10,10,10,
  109662. 10,10,10,10,10,10,10,10,
  109663. 10,10,10,10,10,10,10,10,
  109664. 10,10,10,10,10,10,10,10,
  109665. 10,10,10,10,10,10,10,10,
  109666. 10,10,10,10,10,10,10,10,
  109667. 10,10,10,10,10,10,10,10,
  109668. 10,10,10,10,10,10,10,10,
  109669. 10,10,10,10,10,10,10,50,-1};
  109670. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109671. fprintf(stderr,"testing max packet segments... ");
  109672. test_pack(packets,headret,0,0,0);
  109673. }
  109674. {
  109675. /* packet that overspans over an entire page */
  109676. const int packets[]={0,100,9000,259,255,-1};
  109677. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109678. fprintf(stderr,"testing very large packets... ");
  109679. test_pack(packets,headret,0,0,0);
  109680. }
  109681. {
  109682. /* test for the libogg 1.1.1 resync in large continuation bug
  109683. found by Josh Coalson) */
  109684. const int packets[]={0,100,9000,259,255,-1};
  109685. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109686. fprintf(stderr,"testing continuation resync in very large packets... ");
  109687. test_pack(packets,headret,100,2,3);
  109688. }
  109689. {
  109690. /* term only page. why not? */
  109691. const int packets[]={0,100,4080,-1};
  109692. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109693. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109694. test_pack(packets,headret,0,0,0);
  109695. }
  109696. {
  109697. /* build a bunch of pages for testing */
  109698. unsigned char *data=_ogg_malloc(1024*1024);
  109699. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109700. int inptr=0,i,j;
  109701. ogg_page og[5];
  109702. ogg_stream_reset(&os_en);
  109703. for(i=0;pl[i]!=-1;i++){
  109704. ogg_packet op;
  109705. int len=pl[i];
  109706. op.packet=data+inptr;
  109707. op.bytes=len;
  109708. op.e_o_s=(pl[i+1]<0?1:0);
  109709. op.granulepos=(i+1)*1000;
  109710. for(j=0;j<len;j++)data[inptr++]=i+j;
  109711. ogg_stream_packetin(&os_en,&op);
  109712. }
  109713. _ogg_free(data);
  109714. /* retrieve finished pages */
  109715. for(i=0;i<5;i++){
  109716. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109717. fprintf(stderr,"Too few pages output building sync tests!\n");
  109718. exit(1);
  109719. }
  109720. copy_page(&og[i]);
  109721. }
  109722. /* Test lost pages on pagein/packetout: no rollback */
  109723. {
  109724. ogg_page temp;
  109725. ogg_packet test;
  109726. fprintf(stderr,"Testing loss of pages... ");
  109727. ogg_sync_reset(&oy);
  109728. ogg_stream_reset(&os_de);
  109729. for(i=0;i<5;i++){
  109730. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109731. og[i].header_len);
  109732. ogg_sync_wrote(&oy,og[i].header_len);
  109733. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109734. ogg_sync_wrote(&oy,og[i].body_len);
  109735. }
  109736. ogg_sync_pageout(&oy,&temp);
  109737. ogg_stream_pagein(&os_de,&temp);
  109738. ogg_sync_pageout(&oy,&temp);
  109739. ogg_stream_pagein(&os_de,&temp);
  109740. ogg_sync_pageout(&oy,&temp);
  109741. /* skip */
  109742. ogg_sync_pageout(&oy,&temp);
  109743. ogg_stream_pagein(&os_de,&temp);
  109744. /* do we get the expected results/packets? */
  109745. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109746. checkpacket(&test,0,0,0);
  109747. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109748. checkpacket(&test,100,1,-1);
  109749. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109750. checkpacket(&test,4079,2,3000);
  109751. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109752. fprintf(stderr,"Error: loss of page did not return error\n");
  109753. exit(1);
  109754. }
  109755. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109756. checkpacket(&test,76,5,-1);
  109757. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109758. checkpacket(&test,34,6,-1);
  109759. fprintf(stderr,"ok.\n");
  109760. }
  109761. /* Test lost pages on pagein/packetout: rollback with continuation */
  109762. {
  109763. ogg_page temp;
  109764. ogg_packet test;
  109765. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109766. ogg_sync_reset(&oy);
  109767. ogg_stream_reset(&os_de);
  109768. for(i=0;i<5;i++){
  109769. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109770. og[i].header_len);
  109771. ogg_sync_wrote(&oy,og[i].header_len);
  109772. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109773. ogg_sync_wrote(&oy,og[i].body_len);
  109774. }
  109775. ogg_sync_pageout(&oy,&temp);
  109776. ogg_stream_pagein(&os_de,&temp);
  109777. ogg_sync_pageout(&oy,&temp);
  109778. ogg_stream_pagein(&os_de,&temp);
  109779. ogg_sync_pageout(&oy,&temp);
  109780. ogg_stream_pagein(&os_de,&temp);
  109781. ogg_sync_pageout(&oy,&temp);
  109782. /* skip */
  109783. ogg_sync_pageout(&oy,&temp);
  109784. ogg_stream_pagein(&os_de,&temp);
  109785. /* do we get the expected results/packets? */
  109786. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109787. checkpacket(&test,0,0,0);
  109788. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109789. checkpacket(&test,100,1,-1);
  109790. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109791. checkpacket(&test,4079,2,3000);
  109792. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109793. checkpacket(&test,2956,3,4000);
  109794. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109795. fprintf(stderr,"Error: loss of page did not return error\n");
  109796. exit(1);
  109797. }
  109798. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109799. checkpacket(&test,300,13,14000);
  109800. fprintf(stderr,"ok.\n");
  109801. }
  109802. /* the rest only test sync */
  109803. {
  109804. ogg_page og_de;
  109805. /* Test fractional page inputs: incomplete capture */
  109806. fprintf(stderr,"Testing sync on partial inputs... ");
  109807. ogg_sync_reset(&oy);
  109808. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109809. 3);
  109810. ogg_sync_wrote(&oy,3);
  109811. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109812. /* Test fractional page inputs: incomplete fixed header */
  109813. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109814. 20);
  109815. ogg_sync_wrote(&oy,20);
  109816. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109817. /* Test fractional page inputs: incomplete header */
  109818. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109819. 5);
  109820. ogg_sync_wrote(&oy,5);
  109821. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109822. /* Test fractional page inputs: incomplete body */
  109823. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109824. og[1].header_len-28);
  109825. ogg_sync_wrote(&oy,og[1].header_len-28);
  109826. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109827. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109828. ogg_sync_wrote(&oy,1000);
  109829. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109830. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109831. og[1].body_len-1000);
  109832. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109833. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109834. fprintf(stderr,"ok.\n");
  109835. }
  109836. /* Test fractional page inputs: page + incomplete capture */
  109837. {
  109838. ogg_page og_de;
  109839. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109840. ogg_sync_reset(&oy);
  109841. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109842. og[1].header_len);
  109843. ogg_sync_wrote(&oy,og[1].header_len);
  109844. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109845. og[1].body_len);
  109846. ogg_sync_wrote(&oy,og[1].body_len);
  109847. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109848. 20);
  109849. ogg_sync_wrote(&oy,20);
  109850. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109851. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109852. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109853. og[1].header_len-20);
  109854. ogg_sync_wrote(&oy,og[1].header_len-20);
  109855. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109856. og[1].body_len);
  109857. ogg_sync_wrote(&oy,og[1].body_len);
  109858. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109859. fprintf(stderr,"ok.\n");
  109860. }
  109861. /* Test recapture: garbage + page */
  109862. {
  109863. ogg_page og_de;
  109864. fprintf(stderr,"Testing search for capture... ");
  109865. ogg_sync_reset(&oy);
  109866. /* 'garbage' */
  109867. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109868. og[1].body_len);
  109869. ogg_sync_wrote(&oy,og[1].body_len);
  109870. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109871. og[1].header_len);
  109872. ogg_sync_wrote(&oy,og[1].header_len);
  109873. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109874. og[1].body_len);
  109875. ogg_sync_wrote(&oy,og[1].body_len);
  109876. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109877. 20);
  109878. ogg_sync_wrote(&oy,20);
  109879. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109880. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109881. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109882. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109883. og[2].header_len-20);
  109884. ogg_sync_wrote(&oy,og[2].header_len-20);
  109885. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109886. og[2].body_len);
  109887. ogg_sync_wrote(&oy,og[2].body_len);
  109888. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109889. fprintf(stderr,"ok.\n");
  109890. }
  109891. /* Test recapture: page + garbage + page */
  109892. {
  109893. ogg_page og_de;
  109894. fprintf(stderr,"Testing recapture... ");
  109895. ogg_sync_reset(&oy);
  109896. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109897. og[1].header_len);
  109898. ogg_sync_wrote(&oy,og[1].header_len);
  109899. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109900. og[1].body_len);
  109901. ogg_sync_wrote(&oy,og[1].body_len);
  109902. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109903. og[2].header_len);
  109904. ogg_sync_wrote(&oy,og[2].header_len);
  109905. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109906. og[2].header_len);
  109907. ogg_sync_wrote(&oy,og[2].header_len);
  109908. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109909. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109910. og[2].body_len-5);
  109911. ogg_sync_wrote(&oy,og[2].body_len-5);
  109912. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109913. og[3].header_len);
  109914. ogg_sync_wrote(&oy,og[3].header_len);
  109915. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109916. og[3].body_len);
  109917. ogg_sync_wrote(&oy,og[3].body_len);
  109918. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109919. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109920. fprintf(stderr,"ok.\n");
  109921. }
  109922. /* Free page data that was previously copied */
  109923. {
  109924. for(i=0;i<5;i++){
  109925. free_page(&og[i]);
  109926. }
  109927. }
  109928. }
  109929. return(0);
  109930. }
  109931. #endif
  109932. #endif
  109933. /*** End of inlined file: framing.c ***/
  109934. /*** Start of inlined file: analysis.c ***/
  109935. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109936. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109937. // tasks..
  109938. #if JUCE_MSVC
  109939. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109940. #endif
  109941. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109942. #if JUCE_USE_OGGVORBIS
  109943. #include <stdio.h>
  109944. #include <string.h>
  109945. #include <math.h>
  109946. /*** Start of inlined file: codec_internal.h ***/
  109947. #ifndef _V_CODECI_H_
  109948. #define _V_CODECI_H_
  109949. /*** Start of inlined file: envelope.h ***/
  109950. #ifndef _V_ENVELOPE_
  109951. #define _V_ENVELOPE_
  109952. /*** Start of inlined file: mdct.h ***/
  109953. #ifndef _OGG_mdct_H_
  109954. #define _OGG_mdct_H_
  109955. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109956. #ifdef MDCT_INTEGERIZED
  109957. #define DATA_TYPE int
  109958. #define REG_TYPE register int
  109959. #define TRIGBITS 14
  109960. #define cPI3_8 6270
  109961. #define cPI2_8 11585
  109962. #define cPI1_8 15137
  109963. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109964. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109965. #define HALVE(x) ((x)>>1)
  109966. #else
  109967. #define DATA_TYPE float
  109968. #define REG_TYPE float
  109969. #define cPI3_8 .38268343236508977175F
  109970. #define cPI2_8 .70710678118654752441F
  109971. #define cPI1_8 .92387953251128675613F
  109972. #define FLOAT_CONV(x) (x)
  109973. #define MULT_NORM(x) (x)
  109974. #define HALVE(x) ((x)*.5f)
  109975. #endif
  109976. typedef struct {
  109977. int n;
  109978. int log2n;
  109979. DATA_TYPE *trig;
  109980. int *bitrev;
  109981. DATA_TYPE scale;
  109982. } mdct_lookup;
  109983. extern void mdct_init(mdct_lookup *lookup,int n);
  109984. extern void mdct_clear(mdct_lookup *l);
  109985. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109986. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109987. #endif
  109988. /*** End of inlined file: mdct.h ***/
  109989. #define VE_PRE 16
  109990. #define VE_WIN 4
  109991. #define VE_POST 2
  109992. #define VE_AMP (VE_PRE+VE_POST-1)
  109993. #define VE_BANDS 7
  109994. #define VE_NEARDC 15
  109995. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109996. #define VE_MAXSTRETCH 12 /* one-third full block */
  109997. typedef struct {
  109998. float ampbuf[VE_AMP];
  109999. int ampptr;
  110000. float nearDC[VE_NEARDC];
  110001. float nearDC_acc;
  110002. float nearDC_partialacc;
  110003. int nearptr;
  110004. } envelope_filter_state;
  110005. typedef struct {
  110006. int begin;
  110007. int end;
  110008. float *window;
  110009. float total;
  110010. } envelope_band;
  110011. typedef struct {
  110012. int ch;
  110013. int winlength;
  110014. int searchstep;
  110015. float minenergy;
  110016. mdct_lookup mdct;
  110017. float *mdct_win;
  110018. envelope_band band[VE_BANDS];
  110019. envelope_filter_state *filter;
  110020. int stretch;
  110021. int *mark;
  110022. long storage;
  110023. long current;
  110024. long curmark;
  110025. long cursor;
  110026. } envelope_lookup;
  110027. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110028. extern void _ve_envelope_clear(envelope_lookup *e);
  110029. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110030. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110031. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110032. #endif
  110033. /*** End of inlined file: envelope.h ***/
  110034. /*** Start of inlined file: codebook.h ***/
  110035. #ifndef _V_CODEBOOK_H_
  110036. #define _V_CODEBOOK_H_
  110037. /* This structure encapsulates huffman and VQ style encoding books; it
  110038. doesn't do anything specific to either.
  110039. valuelist/quantlist are nonNULL (and q_* significant) only if
  110040. there's entry->value mapping to be done.
  110041. If encode-side mapping must be done (and thus the entry needs to be
  110042. hunted), the auxiliary encode pointer will point to a decision
  110043. tree. This is true of both VQ and huffman, but is mostly useful
  110044. with VQ.
  110045. */
  110046. typedef struct static_codebook{
  110047. long dim; /* codebook dimensions (elements per vector) */
  110048. long entries; /* codebook entries */
  110049. long *lengthlist; /* codeword lengths in bits */
  110050. /* mapping ***************************************************************/
  110051. int maptype; /* 0=none
  110052. 1=implicitly populated values from map column
  110053. 2=listed arbitrary values */
  110054. /* The below does a linear, single monotonic sequence mapping. */
  110055. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110056. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110057. int q_quant; /* bits: 0 < quant <= 16 */
  110058. int q_sequencep; /* bitflag */
  110059. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110060. map == 2: list of dim*entries quantized entry vals
  110061. */
  110062. /* encode helpers ********************************************************/
  110063. struct encode_aux_nearestmatch *nearest_tree;
  110064. struct encode_aux_threshmatch *thresh_tree;
  110065. struct encode_aux_pigeonhole *pigeon_tree;
  110066. int allocedp;
  110067. } static_codebook;
  110068. /* this structures an arbitrary trained book to quickly find the
  110069. nearest cell match */
  110070. typedef struct encode_aux_nearestmatch{
  110071. /* pre-calculated partitioning tree */
  110072. long *ptr0;
  110073. long *ptr1;
  110074. long *p; /* decision points (each is an entry) */
  110075. long *q; /* decision points (each is an entry) */
  110076. long aux; /* number of tree entries */
  110077. long alloc;
  110078. } encode_aux_nearestmatch;
  110079. /* assumes a maptype of 1; encode side only, so that's OK */
  110080. typedef struct encode_aux_threshmatch{
  110081. float *quantthresh;
  110082. long *quantmap;
  110083. int quantvals;
  110084. int threshvals;
  110085. } encode_aux_threshmatch;
  110086. typedef struct encode_aux_pigeonhole{
  110087. float min;
  110088. float del;
  110089. int mapentries;
  110090. int quantvals;
  110091. long *pigeonmap;
  110092. long fittotal;
  110093. long *fitlist;
  110094. long *fitmap;
  110095. long *fitlength;
  110096. } encode_aux_pigeonhole;
  110097. typedef struct codebook{
  110098. long dim; /* codebook dimensions (elements per vector) */
  110099. long entries; /* codebook entries */
  110100. long used_entries; /* populated codebook entries */
  110101. const static_codebook *c;
  110102. /* for encode, the below are entry-ordered, fully populated */
  110103. /* for decode, the below are ordered by bitreversed codeword and only
  110104. used entries are populated */
  110105. float *valuelist; /* list of dim*entries actual entry values */
  110106. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110107. int *dec_index; /* only used if sparseness collapsed */
  110108. char *dec_codelengths;
  110109. ogg_uint32_t *dec_firsttable;
  110110. int dec_firsttablen;
  110111. int dec_maxlength;
  110112. } codebook;
  110113. extern void vorbis_staticbook_clear(static_codebook *b);
  110114. extern void vorbis_staticbook_destroy(static_codebook *b);
  110115. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110116. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110117. extern void vorbis_book_clear(codebook *b);
  110118. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110119. extern float *_book_logdist(const static_codebook *b,float *vals);
  110120. extern float _float32_unpack(long val);
  110121. extern long _float32_pack(float val);
  110122. extern int _best(codebook *book, float *a, int step);
  110123. extern int _ilog(unsigned int v);
  110124. extern long _book_maptype1_quantvals(const static_codebook *b);
  110125. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110126. extern long vorbis_book_codeword(codebook *book,int entry);
  110127. extern long vorbis_book_codelen(codebook *book,int entry);
  110128. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110129. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110130. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110131. extern int vorbis_book_errorv(codebook *book, float *a);
  110132. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110133. oggpack_buffer *b);
  110134. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110135. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110136. oggpack_buffer *b,int n);
  110137. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110138. oggpack_buffer *b,int n);
  110139. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110140. oggpack_buffer *b,int n);
  110141. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110142. long off,int ch,
  110143. oggpack_buffer *b,int n);
  110144. #endif
  110145. /*** End of inlined file: codebook.h ***/
  110146. #define BLOCKTYPE_IMPULSE 0
  110147. #define BLOCKTYPE_PADDING 1
  110148. #define BLOCKTYPE_TRANSITION 0
  110149. #define BLOCKTYPE_LONG 1
  110150. #define PACKETBLOBS 15
  110151. typedef struct vorbis_block_internal{
  110152. float **pcmdelay; /* this is a pointer into local storage */
  110153. float ampmax;
  110154. int blocktype;
  110155. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110156. blob [PACKETBLOBS/2] points to
  110157. the oggpack_buffer in the
  110158. main vorbis_block */
  110159. } vorbis_block_internal;
  110160. typedef void vorbis_look_floor;
  110161. typedef void vorbis_look_residue;
  110162. typedef void vorbis_look_transform;
  110163. /* mode ************************************************************/
  110164. typedef struct {
  110165. int blockflag;
  110166. int windowtype;
  110167. int transformtype;
  110168. int mapping;
  110169. } vorbis_info_mode;
  110170. typedef void vorbis_info_floor;
  110171. typedef void vorbis_info_residue;
  110172. typedef void vorbis_info_mapping;
  110173. /*** Start of inlined file: psy.h ***/
  110174. #ifndef _V_PSY_H_
  110175. #define _V_PSY_H_
  110176. /*** Start of inlined file: smallft.h ***/
  110177. #ifndef _V_SMFT_H_
  110178. #define _V_SMFT_H_
  110179. typedef struct {
  110180. int n;
  110181. float *trigcache;
  110182. int *splitcache;
  110183. } drft_lookup;
  110184. extern void drft_forward(drft_lookup *l,float *data);
  110185. extern void drft_backward(drft_lookup *l,float *data);
  110186. extern void drft_init(drft_lookup *l,int n);
  110187. extern void drft_clear(drft_lookup *l);
  110188. #endif
  110189. /*** End of inlined file: smallft.h ***/
  110190. /*** Start of inlined file: backends.h ***/
  110191. /* this is exposed up here because we need it for static modes.
  110192. Lookups for each backend aren't exposed because there's no reason
  110193. to do so */
  110194. #ifndef _vorbis_backend_h_
  110195. #define _vorbis_backend_h_
  110196. /* this would all be simpler/shorter with templates, but.... */
  110197. /* Floor backend generic *****************************************/
  110198. typedef struct{
  110199. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110200. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110201. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110202. void (*free_info) (vorbis_info_floor *);
  110203. void (*free_look) (vorbis_look_floor *);
  110204. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110205. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110206. void *buffer,float *);
  110207. } vorbis_func_floor;
  110208. typedef struct{
  110209. int order;
  110210. long rate;
  110211. long barkmap;
  110212. int ampbits;
  110213. int ampdB;
  110214. int numbooks; /* <= 16 */
  110215. int books[16];
  110216. float lessthan; /* encode-only config setting hacks for libvorbis */
  110217. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110218. } vorbis_info_floor0;
  110219. #define VIF_POSIT 63
  110220. #define VIF_CLASS 16
  110221. #define VIF_PARTS 31
  110222. typedef struct{
  110223. int partitions; /* 0 to 31 */
  110224. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110225. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110226. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110227. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110228. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110229. int mult; /* 1 2 3 or 4 */
  110230. int postlist[VIF_POSIT+2]; /* first two implicit */
  110231. /* encode side analysis parameters */
  110232. float maxover;
  110233. float maxunder;
  110234. float maxerr;
  110235. float twofitweight;
  110236. float twofitatten;
  110237. int n;
  110238. } vorbis_info_floor1;
  110239. /* Residue backend generic *****************************************/
  110240. typedef struct{
  110241. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110242. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110243. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110244. vorbis_info_residue *);
  110245. void (*free_info) (vorbis_info_residue *);
  110246. void (*free_look) (vorbis_look_residue *);
  110247. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110248. float **,int *,int);
  110249. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110250. vorbis_look_residue *,
  110251. float **,float **,int *,int,long **);
  110252. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110253. float **,int *,int);
  110254. } vorbis_func_residue;
  110255. typedef struct vorbis_info_residue0{
  110256. /* block-partitioned VQ coded straight residue */
  110257. long begin;
  110258. long end;
  110259. /* first stage (lossless partitioning) */
  110260. int grouping; /* group n vectors per partition */
  110261. int partitions; /* possible codebooks for a partition */
  110262. int groupbook; /* huffbook for partitioning */
  110263. int secondstages[64]; /* expanded out to pointers in lookup */
  110264. int booklist[256]; /* list of second stage books */
  110265. float classmetric1[64];
  110266. float classmetric2[64];
  110267. } vorbis_info_residue0;
  110268. /* Mapping backend generic *****************************************/
  110269. typedef struct{
  110270. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110271. oggpack_buffer *);
  110272. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110273. void (*free_info) (vorbis_info_mapping *);
  110274. int (*forward) (struct vorbis_block *vb);
  110275. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110276. } vorbis_func_mapping;
  110277. typedef struct vorbis_info_mapping0{
  110278. int submaps; /* <= 16 */
  110279. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110280. int floorsubmap[16]; /* [mux] submap to floors */
  110281. int residuesubmap[16]; /* [mux] submap to residue */
  110282. int coupling_steps;
  110283. int coupling_mag[256];
  110284. int coupling_ang[256];
  110285. } vorbis_info_mapping0;
  110286. #endif
  110287. /*** End of inlined file: backends.h ***/
  110288. #ifndef EHMER_MAX
  110289. #define EHMER_MAX 56
  110290. #endif
  110291. /* psychoacoustic setup ********************************************/
  110292. #define P_BANDS 17 /* 62Hz to 16kHz */
  110293. #define P_LEVELS 8 /* 30dB to 100dB */
  110294. #define P_LEVEL_0 30. /* 30 dB */
  110295. #define P_NOISECURVES 3
  110296. #define NOISE_COMPAND_LEVELS 40
  110297. typedef struct vorbis_info_psy{
  110298. int blockflag;
  110299. float ath_adjatt;
  110300. float ath_maxatt;
  110301. float tone_masteratt[P_NOISECURVES];
  110302. float tone_centerboost;
  110303. float tone_decay;
  110304. float tone_abs_limit;
  110305. float toneatt[P_BANDS];
  110306. int noisemaskp;
  110307. float noisemaxsupp;
  110308. float noisewindowlo;
  110309. float noisewindowhi;
  110310. int noisewindowlomin;
  110311. int noisewindowhimin;
  110312. int noisewindowfixed;
  110313. float noiseoff[P_NOISECURVES][P_BANDS];
  110314. float noisecompand[NOISE_COMPAND_LEVELS];
  110315. float max_curve_dB;
  110316. int normal_channel_p;
  110317. int normal_point_p;
  110318. int normal_start;
  110319. int normal_partition;
  110320. double normal_thresh;
  110321. } vorbis_info_psy;
  110322. typedef struct{
  110323. int eighth_octave_lines;
  110324. /* for block long/short tuning; encode only */
  110325. float preecho_thresh[VE_BANDS];
  110326. float postecho_thresh[VE_BANDS];
  110327. float stretch_penalty;
  110328. float preecho_minenergy;
  110329. float ampmax_att_per_sec;
  110330. /* channel coupling config */
  110331. int coupling_pkHz[PACKETBLOBS];
  110332. int coupling_pointlimit[2][PACKETBLOBS];
  110333. int coupling_prepointamp[PACKETBLOBS];
  110334. int coupling_postpointamp[PACKETBLOBS];
  110335. int sliding_lowpass[2][PACKETBLOBS];
  110336. } vorbis_info_psy_global;
  110337. typedef struct {
  110338. float ampmax;
  110339. int channels;
  110340. vorbis_info_psy_global *gi;
  110341. int coupling_pointlimit[2][P_NOISECURVES];
  110342. } vorbis_look_psy_global;
  110343. typedef struct {
  110344. int n;
  110345. struct vorbis_info_psy *vi;
  110346. float ***tonecurves;
  110347. float **noiseoffset;
  110348. float *ath;
  110349. long *octave; /* in n.ocshift format */
  110350. long *bark;
  110351. long firstoc;
  110352. long shiftoc;
  110353. int eighth_octave_lines; /* power of two, please */
  110354. int total_octave_lines;
  110355. long rate; /* cache it */
  110356. float m_val; /* Masking compensation value */
  110357. } vorbis_look_psy;
  110358. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110359. vorbis_info_psy_global *gi,int n,long rate);
  110360. extern void _vp_psy_clear(vorbis_look_psy *p);
  110361. extern void *_vi_psy_dup(void *source);
  110362. extern void _vi_psy_free(vorbis_info_psy *i);
  110363. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110364. extern void _vp_remove_floor(vorbis_look_psy *p,
  110365. float *mdct,
  110366. int *icodedflr,
  110367. float *residue,
  110368. int sliding_lowpass);
  110369. extern void _vp_noisemask(vorbis_look_psy *p,
  110370. float *logmdct,
  110371. float *logmask);
  110372. extern void _vp_tonemask(vorbis_look_psy *p,
  110373. float *logfft,
  110374. float *logmask,
  110375. float global_specmax,
  110376. float local_specmax);
  110377. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110378. float *noise,
  110379. float *tone,
  110380. int offset_select,
  110381. float *logmask,
  110382. float *mdct,
  110383. float *logmdct);
  110384. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110385. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110386. vorbis_info_psy_global *g,
  110387. vorbis_look_psy *p,
  110388. vorbis_info_mapping0 *vi,
  110389. float **mdct);
  110390. extern void _vp_couple(int blobno,
  110391. vorbis_info_psy_global *g,
  110392. vorbis_look_psy *p,
  110393. vorbis_info_mapping0 *vi,
  110394. float **res,
  110395. float **mag_memo,
  110396. int **mag_sort,
  110397. int **ifloor,
  110398. int *nonzero,
  110399. int sliding_lowpass);
  110400. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110401. float *in,float *out,int *sortedindex);
  110402. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110403. float *magnitudes,int *sortedindex);
  110404. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110405. vorbis_look_psy *p,
  110406. vorbis_info_mapping0 *vi,
  110407. float **mags);
  110408. extern void hf_reduction(vorbis_info_psy_global *g,
  110409. vorbis_look_psy *p,
  110410. vorbis_info_mapping0 *vi,
  110411. float **mdct);
  110412. #endif
  110413. /*** End of inlined file: psy.h ***/
  110414. /*** Start of inlined file: bitrate.h ***/
  110415. #ifndef _V_BITRATE_H_
  110416. #define _V_BITRATE_H_
  110417. /*** Start of inlined file: os.h ***/
  110418. #ifndef _OS_H
  110419. #define _OS_H
  110420. /********************************************************************
  110421. * *
  110422. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110423. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110424. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110425. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110426. * *
  110427. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110428. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110429. * *
  110430. ********************************************************************
  110431. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110432. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110433. ********************************************************************/
  110434. #ifdef HAVE_CONFIG_H
  110435. #include "config.h"
  110436. #endif
  110437. #include <math.h>
  110438. /*** Start of inlined file: misc.h ***/
  110439. #ifndef _V_RANDOM_H_
  110440. #define _V_RANDOM_H_
  110441. extern int analysis_noisy;
  110442. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110443. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110444. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110445. ogg_int64_t off);
  110446. #ifdef DEBUG_MALLOC
  110447. #define _VDBG_GRAPHFILE "malloc.m"
  110448. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110449. extern void _VDBG_free(void *ptr,char *file,long line);
  110450. #ifndef MISC_C
  110451. #undef _ogg_malloc
  110452. #undef _ogg_calloc
  110453. #undef _ogg_realloc
  110454. #undef _ogg_free
  110455. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110456. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110457. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110458. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110459. #endif
  110460. #endif
  110461. #endif
  110462. /*** End of inlined file: misc.h ***/
  110463. #ifndef _V_IFDEFJAIL_H_
  110464. # define _V_IFDEFJAIL_H_
  110465. # ifdef __GNUC__
  110466. # define STIN static __inline__
  110467. # elif _WIN32
  110468. # define STIN static __inline
  110469. # else
  110470. # define STIN static
  110471. # endif
  110472. #ifdef DJGPP
  110473. # define rint(x) (floor((x)+0.5f))
  110474. #endif
  110475. #ifndef M_PI
  110476. # define M_PI (3.1415926536f)
  110477. #endif
  110478. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110479. # include <malloc.h>
  110480. # define rint(x) (floor((x)+0.5f))
  110481. # define NO_FLOAT_MATH_LIB
  110482. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110483. #endif
  110484. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110485. void *_alloca(size_t size);
  110486. # define alloca _alloca
  110487. #endif
  110488. #ifndef FAST_HYPOT
  110489. # define FAST_HYPOT hypot
  110490. #endif
  110491. #endif
  110492. #ifdef HAVE_ALLOCA_H
  110493. # include <alloca.h>
  110494. #endif
  110495. #ifdef USE_MEMORY_H
  110496. # include <memory.h>
  110497. #endif
  110498. #ifndef min
  110499. # define min(x,y) ((x)>(y)?(y):(x))
  110500. #endif
  110501. #ifndef max
  110502. # define max(x,y) ((x)<(y)?(y):(x))
  110503. #endif
  110504. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110505. # define VORBIS_FPU_CONTROL
  110506. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110507. Because of encapsulation constraints (GCC can't see inside the asm
  110508. block and so we end up doing stupid things like a store/load that
  110509. is collectively a noop), we do it this way */
  110510. /* we must set up the fpu before this works!! */
  110511. typedef ogg_int16_t vorbis_fpu_control;
  110512. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110513. ogg_int16_t ret;
  110514. ogg_int16_t temp;
  110515. __asm__ __volatile__("fnstcw %0\n\t"
  110516. "movw %0,%%dx\n\t"
  110517. "orw $62463,%%dx\n\t"
  110518. "movw %%dx,%1\n\t"
  110519. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110520. *fpu=ret;
  110521. }
  110522. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110523. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110524. }
  110525. /* assumes the FPU is in round mode! */
  110526. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110527. we get extra fst/fld to
  110528. truncate precision */
  110529. int i;
  110530. __asm__("fistl %0": "=m"(i) : "t"(f));
  110531. return(i);
  110532. }
  110533. #endif
  110534. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110535. # define VORBIS_FPU_CONTROL
  110536. typedef ogg_int16_t vorbis_fpu_control;
  110537. static __inline int vorbis_ftoi(double f){
  110538. int i;
  110539. __asm{
  110540. fld f
  110541. fistp i
  110542. }
  110543. return i;
  110544. }
  110545. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110546. }
  110547. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110548. }
  110549. #endif
  110550. #ifndef VORBIS_FPU_CONTROL
  110551. typedef int vorbis_fpu_control;
  110552. static int vorbis_ftoi(double f){
  110553. return (int)(f+.5);
  110554. }
  110555. /* We don't have special code for this compiler/arch, so do it the slow way */
  110556. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110557. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110558. #endif
  110559. #endif /* _OS_H */
  110560. /*** End of inlined file: os.h ***/
  110561. /* encode side bitrate tracking */
  110562. typedef struct bitrate_manager_state {
  110563. int managed;
  110564. long avg_reservoir;
  110565. long minmax_reservoir;
  110566. long avg_bitsper;
  110567. long min_bitsper;
  110568. long max_bitsper;
  110569. long short_per_long;
  110570. double avgfloat;
  110571. vorbis_block *vb;
  110572. int choice;
  110573. } bitrate_manager_state;
  110574. typedef struct bitrate_manager_info{
  110575. long avg_rate;
  110576. long min_rate;
  110577. long max_rate;
  110578. long reservoir_bits;
  110579. double reservoir_bias;
  110580. double slew_damp;
  110581. } bitrate_manager_info;
  110582. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110583. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110584. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110585. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110586. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110587. #endif
  110588. /*** End of inlined file: bitrate.h ***/
  110589. static int ilog(unsigned int v){
  110590. int ret=0;
  110591. while(v){
  110592. ret++;
  110593. v>>=1;
  110594. }
  110595. return(ret);
  110596. }
  110597. static int ilog2(unsigned int v){
  110598. int ret=0;
  110599. if(v)--v;
  110600. while(v){
  110601. ret++;
  110602. v>>=1;
  110603. }
  110604. return(ret);
  110605. }
  110606. typedef struct private_state {
  110607. /* local lookup storage */
  110608. envelope_lookup *ve; /* envelope lookup */
  110609. int window[2];
  110610. vorbis_look_transform **transform[2]; /* block, type */
  110611. drft_lookup fft_look[2];
  110612. int modebits;
  110613. vorbis_look_floor **flr;
  110614. vorbis_look_residue **residue;
  110615. vorbis_look_psy *psy;
  110616. vorbis_look_psy_global *psy_g_look;
  110617. /* local storage, only used on the encoding side. This way the
  110618. application does not need to worry about freeing some packets'
  110619. memory and not others'; packet storage is always tracked.
  110620. Cleared next call to a _dsp_ function */
  110621. unsigned char *header;
  110622. unsigned char *header1;
  110623. unsigned char *header2;
  110624. bitrate_manager_state bms;
  110625. ogg_int64_t sample_count;
  110626. } private_state;
  110627. /* codec_setup_info contains all the setup information specific to the
  110628. specific compression/decompression mode in progress (eg,
  110629. psychoacoustic settings, channel setup, options, codebook
  110630. etc).
  110631. *********************************************************************/
  110632. /*** Start of inlined file: highlevel.h ***/
  110633. typedef struct highlevel_byblocktype {
  110634. double tone_mask_setting;
  110635. double tone_peaklimit_setting;
  110636. double noise_bias_setting;
  110637. double noise_compand_setting;
  110638. } highlevel_byblocktype;
  110639. typedef struct highlevel_encode_setup {
  110640. void *setup;
  110641. int set_in_stone;
  110642. double base_setting;
  110643. double long_setting;
  110644. double short_setting;
  110645. double impulse_noisetune;
  110646. int managed;
  110647. long bitrate_min;
  110648. long bitrate_av;
  110649. double bitrate_av_damp;
  110650. long bitrate_max;
  110651. long bitrate_reservoir;
  110652. double bitrate_reservoir_bias;
  110653. int impulse_block_p;
  110654. int noise_normalize_p;
  110655. double stereo_point_setting;
  110656. double lowpass_kHz;
  110657. double ath_floating_dB;
  110658. double ath_absolute_dB;
  110659. double amplitude_track_dBpersec;
  110660. double trigger_setting;
  110661. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110662. } highlevel_encode_setup;
  110663. /*** End of inlined file: highlevel.h ***/
  110664. typedef struct codec_setup_info {
  110665. /* Vorbis supports only short and long blocks, but allows the
  110666. encoder to choose the sizes */
  110667. long blocksizes[2];
  110668. /* modes are the primary means of supporting on-the-fly different
  110669. blocksizes, different channel mappings (LR or M/A),
  110670. different residue backends, etc. Each mode consists of a
  110671. blocksize flag and a mapping (along with the mapping setup */
  110672. int modes;
  110673. int maps;
  110674. int floors;
  110675. int residues;
  110676. int books;
  110677. int psys; /* encode only */
  110678. vorbis_info_mode *mode_param[64];
  110679. int map_type[64];
  110680. vorbis_info_mapping *map_param[64];
  110681. int floor_type[64];
  110682. vorbis_info_floor *floor_param[64];
  110683. int residue_type[64];
  110684. vorbis_info_residue *residue_param[64];
  110685. static_codebook *book_param[256];
  110686. codebook *fullbooks;
  110687. vorbis_info_psy *psy_param[4]; /* encode only */
  110688. vorbis_info_psy_global psy_g_param;
  110689. bitrate_manager_info bi;
  110690. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110691. highly redundant structure, but
  110692. improves clarity of program flow. */
  110693. int halfrate_flag; /* painless downsample for decode */
  110694. } codec_setup_info;
  110695. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110696. extern void _vp_global_free(vorbis_look_psy_global *look);
  110697. #endif
  110698. /*** End of inlined file: codec_internal.h ***/
  110699. /*** Start of inlined file: registry.h ***/
  110700. #ifndef _V_REG_H_
  110701. #define _V_REG_H_
  110702. #define VI_TRANSFORMB 1
  110703. #define VI_WINDOWB 1
  110704. #define VI_TIMEB 1
  110705. #define VI_FLOORB 2
  110706. #define VI_RESB 3
  110707. #define VI_MAPB 1
  110708. extern vorbis_func_floor *_floor_P[];
  110709. extern vorbis_func_residue *_residue_P[];
  110710. extern vorbis_func_mapping *_mapping_P[];
  110711. #endif
  110712. /*** End of inlined file: registry.h ***/
  110713. /*** Start of inlined file: scales.h ***/
  110714. #ifndef _V_SCALES_H_
  110715. #define _V_SCALES_H_
  110716. #include <math.h>
  110717. /* 20log10(x) */
  110718. #define VORBIS_IEEE_FLOAT32 1
  110719. #ifdef VORBIS_IEEE_FLOAT32
  110720. static float unitnorm(float x){
  110721. union {
  110722. ogg_uint32_t i;
  110723. float f;
  110724. } ix;
  110725. ix.f = x;
  110726. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110727. return ix.f;
  110728. }
  110729. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110730. static float todB(const float *x){
  110731. union {
  110732. ogg_uint32_t i;
  110733. float f;
  110734. } ix;
  110735. ix.f = *x;
  110736. ix.i = ix.i&0x7fffffff;
  110737. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110738. }
  110739. #define todB_nn(x) todB(x)
  110740. #else
  110741. static float unitnorm(float x){
  110742. if(x<0)return(-1.f);
  110743. return(1.f);
  110744. }
  110745. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110746. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110747. #endif
  110748. #define fromdB(x) (exp((x)*.11512925f))
  110749. /* The bark scale equations are approximations, since the original
  110750. table was somewhat hand rolled. The below are chosen to have the
  110751. best possible fit to the rolled tables, thus their somewhat odd
  110752. appearance (these are more accurate and over a longer range than
  110753. the oft-quoted bark equations found in the texts I have). The
  110754. approximations are valid from 0 - 30kHz (nyquist) or so.
  110755. all f in Hz, z in Bark */
  110756. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110757. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110758. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110759. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110760. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110761. 0.0 */
  110762. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110763. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110764. #endif
  110765. /*** End of inlined file: scales.h ***/
  110766. int analysis_noisy=1;
  110767. /* decides between modes, dispatches to the appropriate mapping. */
  110768. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110769. int ret,i;
  110770. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110771. vb->glue_bits=0;
  110772. vb->time_bits=0;
  110773. vb->floor_bits=0;
  110774. vb->res_bits=0;
  110775. /* first things first. Make sure encode is ready */
  110776. for(i=0;i<PACKETBLOBS;i++)
  110777. oggpack_reset(vbi->packetblob[i]);
  110778. /* we only have one mapping type (0), and we let the mapping code
  110779. itself figure out what soft mode to use. This allows easier
  110780. bitrate management */
  110781. if((ret=_mapping_P[0]->forward(vb)))
  110782. return(ret);
  110783. if(op){
  110784. if(vorbis_bitrate_managed(vb))
  110785. /* The app is using a bitmanaged mode... but not using the
  110786. bitrate management interface. */
  110787. return(OV_EINVAL);
  110788. op->packet=oggpack_get_buffer(&vb->opb);
  110789. op->bytes=oggpack_bytes(&vb->opb);
  110790. op->b_o_s=0;
  110791. op->e_o_s=vb->eofflag;
  110792. op->granulepos=vb->granulepos;
  110793. op->packetno=vb->sequence; /* for sake of completeness */
  110794. }
  110795. return(0);
  110796. }
  110797. /* there was no great place to put this.... */
  110798. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110799. int j;
  110800. FILE *of;
  110801. char buffer[80];
  110802. /* if(i==5870){*/
  110803. sprintf(buffer,"%s_%d.m",base,i);
  110804. of=fopen(buffer,"w");
  110805. if(!of)perror("failed to open data dump file");
  110806. for(j=0;j<n;j++){
  110807. if(bark){
  110808. float b=toBARK((4000.f*j/n)+.25);
  110809. fprintf(of,"%f ",b);
  110810. }else
  110811. if(off!=0)
  110812. fprintf(of,"%f ",(double)(j+off)/8000.);
  110813. else
  110814. fprintf(of,"%f ",(double)j);
  110815. if(dB){
  110816. float val;
  110817. if(v[j]==0.)
  110818. val=-140.;
  110819. else
  110820. val=todB(v+j);
  110821. fprintf(of,"%f\n",val);
  110822. }else{
  110823. fprintf(of,"%f\n",v[j]);
  110824. }
  110825. }
  110826. fclose(of);
  110827. /* } */
  110828. }
  110829. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110830. ogg_int64_t off){
  110831. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110832. }
  110833. #endif
  110834. /*** End of inlined file: analysis.c ***/
  110835. /*** Start of inlined file: bitrate.c ***/
  110836. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110837. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110838. // tasks..
  110839. #if JUCE_MSVC
  110840. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110841. #endif
  110842. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110843. #if JUCE_USE_OGGVORBIS
  110844. #include <stdlib.h>
  110845. #include <string.h>
  110846. #include <math.h>
  110847. /* compute bitrate tracking setup */
  110848. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110849. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110850. bitrate_manager_info *bi=&ci->bi;
  110851. memset(bm,0,sizeof(*bm));
  110852. if(bi && (bi->reservoir_bits>0)){
  110853. long ratesamples=vi->rate;
  110854. int halfsamples=ci->blocksizes[0]>>1;
  110855. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110856. bm->managed=1;
  110857. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110858. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110859. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110860. bm->avgfloat=PACKETBLOBS/2;
  110861. /* not a necessary fix, but one that leads to a more balanced
  110862. typical initialization */
  110863. {
  110864. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110865. bm->minmax_reservoir=desired_fill;
  110866. bm->avg_reservoir=desired_fill;
  110867. }
  110868. }
  110869. }
  110870. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110871. memset(bm,0,sizeof(*bm));
  110872. return;
  110873. }
  110874. int vorbis_bitrate_managed(vorbis_block *vb){
  110875. vorbis_dsp_state *vd=vb->vd;
  110876. private_state *b=(private_state*)vd->backend_state;
  110877. bitrate_manager_state *bm=&b->bms;
  110878. if(bm && bm->managed)return(1);
  110879. return(0);
  110880. }
  110881. /* finish taking in the block we just processed */
  110882. int vorbis_bitrate_addblock(vorbis_block *vb){
  110883. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110884. vorbis_dsp_state *vd=vb->vd;
  110885. private_state *b=(private_state*)vd->backend_state;
  110886. bitrate_manager_state *bm=&b->bms;
  110887. vorbis_info *vi=vd->vi;
  110888. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110889. bitrate_manager_info *bi=&ci->bi;
  110890. int choice=rint(bm->avgfloat);
  110891. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110892. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110893. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110894. int samples=ci->blocksizes[vb->W]>>1;
  110895. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110896. if(!bm->managed){
  110897. /* not a bitrate managed stream, but for API simplicity, we'll
  110898. buffer the packet to keep the code path clean */
  110899. if(bm->vb)return(-1); /* one has been submitted without
  110900. being claimed */
  110901. bm->vb=vb;
  110902. return(0);
  110903. }
  110904. bm->vb=vb;
  110905. /* look ahead for avg floater */
  110906. if(bm->avg_bitsper>0){
  110907. double slew=0.;
  110908. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110909. double slewlimit= 15./bi->slew_damp;
  110910. /* choosing a new floater:
  110911. if we're over target, we slew down
  110912. if we're under target, we slew up
  110913. choose slew as follows: look through packetblobs of this frame
  110914. and set slew as the first in the appropriate direction that
  110915. gives us the slew we want. This may mean no slew if delta is
  110916. already favorable.
  110917. Then limit slew to slew max */
  110918. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110919. while(choice>0 && this_bits>avg_target_bits &&
  110920. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110921. choice--;
  110922. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110923. }
  110924. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110925. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110926. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110927. choice++;
  110928. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110929. }
  110930. }
  110931. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110932. if(slew<-slewlimit)slew=-slewlimit;
  110933. if(slew>slewlimit)slew=slewlimit;
  110934. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110935. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110936. }
  110937. /* enforce min(if used) on the current floater (if used) */
  110938. if(bm->min_bitsper>0){
  110939. /* do we need to force the bitrate up? */
  110940. if(this_bits<min_target_bits){
  110941. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110942. choice++;
  110943. if(choice>=PACKETBLOBS)break;
  110944. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110945. }
  110946. }
  110947. }
  110948. /* enforce max (if used) on the current floater (if used) */
  110949. if(bm->max_bitsper>0){
  110950. /* do we need to force the bitrate down? */
  110951. if(this_bits>max_target_bits){
  110952. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110953. choice--;
  110954. if(choice<0)break;
  110955. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110956. }
  110957. }
  110958. }
  110959. /* Choice of packetblobs now made based on floater, and min/max
  110960. requirements. Now boundary check extreme choices */
  110961. if(choice<0){
  110962. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110963. frame will need to be truncated */
  110964. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110965. bm->choice=choice=0;
  110966. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110967. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110968. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110969. }
  110970. }else{
  110971. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110972. if(choice>=PACKETBLOBS)
  110973. choice=PACKETBLOBS-1;
  110974. bm->choice=choice;
  110975. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110976. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110977. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110978. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110979. }
  110980. /* now we have the final packet and the final packet size. Update statistics */
  110981. /* min and max reservoir */
  110982. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110983. if(max_target_bits>0 && this_bits>max_target_bits){
  110984. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110985. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110986. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110987. }else{
  110988. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110989. if(bm->minmax_reservoir>desired_fill){
  110990. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110991. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110992. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110993. }else{
  110994. bm->minmax_reservoir=desired_fill;
  110995. }
  110996. }else{
  110997. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110998. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110999. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  111000. }else{
  111001. bm->minmax_reservoir=desired_fill;
  111002. }
  111003. }
  111004. }
  111005. }
  111006. /* avg reservoir */
  111007. if(bm->avg_bitsper>0){
  111008. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111009. bm->avg_reservoir+=this_bits-avg_target_bits;
  111010. }
  111011. return(0);
  111012. }
  111013. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  111014. private_state *b=(private_state*)vd->backend_state;
  111015. bitrate_manager_state *bm=&b->bms;
  111016. vorbis_block *vb=bm->vb;
  111017. int choice=PACKETBLOBS/2;
  111018. if(!vb)return 0;
  111019. if(op){
  111020. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111021. if(vorbis_bitrate_managed(vb))
  111022. choice=bm->choice;
  111023. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  111024. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  111025. op->b_o_s=0;
  111026. op->e_o_s=vb->eofflag;
  111027. op->granulepos=vb->granulepos;
  111028. op->packetno=vb->sequence; /* for sake of completeness */
  111029. }
  111030. bm->vb=0;
  111031. return(1);
  111032. }
  111033. #endif
  111034. /*** End of inlined file: bitrate.c ***/
  111035. /*** Start of inlined file: block.c ***/
  111036. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111037. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111038. // tasks..
  111039. #if JUCE_MSVC
  111040. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111041. #endif
  111042. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111043. #if JUCE_USE_OGGVORBIS
  111044. #include <stdio.h>
  111045. #include <stdlib.h>
  111046. #include <string.h>
  111047. /*** Start of inlined file: window.h ***/
  111048. #ifndef _V_WINDOW_
  111049. #define _V_WINDOW_
  111050. extern float *_vorbis_window_get(int n);
  111051. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111052. int lW,int W,int nW);
  111053. #endif
  111054. /*** End of inlined file: window.h ***/
  111055. /*** Start of inlined file: lpc.h ***/
  111056. #ifndef _V_LPC_H_
  111057. #define _V_LPC_H_
  111058. /* simple linear scale LPC code */
  111059. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111060. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111061. float *data,long n);
  111062. #endif
  111063. /*** End of inlined file: lpc.h ***/
  111064. /* pcm accumulator examples (not exhaustive):
  111065. <-------------- lW ---------------->
  111066. <--------------- W ---------------->
  111067. : .....|..... _______________ |
  111068. : .''' | '''_--- | |\ |
  111069. :.....''' |_____--- '''......| | \_______|
  111070. :.................|__________________|_______|__|______|
  111071. |<------ Sl ------>| > Sr < |endW
  111072. |beginSl |endSl | |endSr
  111073. |beginW |endlW |beginSr
  111074. |< lW >|
  111075. <--------------- W ---------------->
  111076. | | .. ______________ |
  111077. | | ' `/ | ---_ |
  111078. |___.'___/`. | ---_____|
  111079. |_______|__|_______|_________________|
  111080. | >|Sl|< |<------ Sr ----->|endW
  111081. | | |endSl |beginSr |endSr
  111082. |beginW | |endlW
  111083. mult[0] |beginSl mult[n]
  111084. <-------------- lW ----------------->
  111085. |<--W-->|
  111086. : .............. ___ | |
  111087. : .''' |`/ \ | |
  111088. :.....''' |/`....\|...|
  111089. :.........................|___|___|___|
  111090. |Sl |Sr |endW
  111091. | | |endSr
  111092. | |beginSr
  111093. | |endSl
  111094. |beginSl
  111095. |beginW
  111096. */
  111097. /* block abstraction setup *********************************************/
  111098. #ifndef WORD_ALIGN
  111099. #define WORD_ALIGN 8
  111100. #endif
  111101. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111102. int i;
  111103. memset(vb,0,sizeof(*vb));
  111104. vb->vd=v;
  111105. vb->localalloc=0;
  111106. vb->localstore=NULL;
  111107. if(v->analysisp){
  111108. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111109. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111110. vbi->ampmax=-9999;
  111111. for(i=0;i<PACKETBLOBS;i++){
  111112. if(i==PACKETBLOBS/2){
  111113. vbi->packetblob[i]=&vb->opb;
  111114. }else{
  111115. vbi->packetblob[i]=
  111116. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111117. }
  111118. oggpack_writeinit(vbi->packetblob[i]);
  111119. }
  111120. }
  111121. return(0);
  111122. }
  111123. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111124. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111125. if(bytes+vb->localtop>vb->localalloc){
  111126. /* can't just _ogg_realloc... there are outstanding pointers */
  111127. if(vb->localstore){
  111128. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111129. vb->totaluse+=vb->localtop;
  111130. link->next=vb->reap;
  111131. link->ptr=vb->localstore;
  111132. vb->reap=link;
  111133. }
  111134. /* highly conservative */
  111135. vb->localalloc=bytes;
  111136. vb->localstore=_ogg_malloc(vb->localalloc);
  111137. vb->localtop=0;
  111138. }
  111139. {
  111140. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111141. vb->localtop+=bytes;
  111142. return ret;
  111143. }
  111144. }
  111145. /* reap the chain, pull the ripcord */
  111146. void _vorbis_block_ripcord(vorbis_block *vb){
  111147. /* reap the chain */
  111148. struct alloc_chain *reap=vb->reap;
  111149. while(reap){
  111150. struct alloc_chain *next=reap->next;
  111151. _ogg_free(reap->ptr);
  111152. memset(reap,0,sizeof(*reap));
  111153. _ogg_free(reap);
  111154. reap=next;
  111155. }
  111156. /* consolidate storage */
  111157. if(vb->totaluse){
  111158. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111159. vb->localalloc+=vb->totaluse;
  111160. vb->totaluse=0;
  111161. }
  111162. /* pull the ripcord */
  111163. vb->localtop=0;
  111164. vb->reap=NULL;
  111165. }
  111166. int vorbis_block_clear(vorbis_block *vb){
  111167. int i;
  111168. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111169. _vorbis_block_ripcord(vb);
  111170. if(vb->localstore)_ogg_free(vb->localstore);
  111171. if(vbi){
  111172. for(i=0;i<PACKETBLOBS;i++){
  111173. oggpack_writeclear(vbi->packetblob[i]);
  111174. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111175. }
  111176. _ogg_free(vbi);
  111177. }
  111178. memset(vb,0,sizeof(*vb));
  111179. return(0);
  111180. }
  111181. /* Analysis side code, but directly related to blocking. Thus it's
  111182. here and not in analysis.c (which is for analysis transforms only).
  111183. The init is here because some of it is shared */
  111184. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111185. int i;
  111186. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111187. private_state *b=NULL;
  111188. int hs;
  111189. if(ci==NULL) return 1;
  111190. hs=ci->halfrate_flag;
  111191. memset(v,0,sizeof(*v));
  111192. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111193. v->vi=vi;
  111194. b->modebits=ilog2(ci->modes);
  111195. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111196. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111197. /* MDCT is tranform 0 */
  111198. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111199. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111200. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111201. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111202. /* Vorbis I uses only window type 0 */
  111203. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111204. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111205. if(encp){ /* encode/decode differ here */
  111206. /* analysis always needs an fft */
  111207. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111208. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111209. /* finish the codebooks */
  111210. if(!ci->fullbooks){
  111211. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111212. for(i=0;i<ci->books;i++)
  111213. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111214. }
  111215. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111216. for(i=0;i<ci->psys;i++){
  111217. _vp_psy_init(b->psy+i,
  111218. ci->psy_param[i],
  111219. &ci->psy_g_param,
  111220. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111221. vi->rate);
  111222. }
  111223. v->analysisp=1;
  111224. }else{
  111225. /* finish the codebooks */
  111226. if(!ci->fullbooks){
  111227. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111228. for(i=0;i<ci->books;i++){
  111229. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111230. /* decode codebooks are now standalone after init */
  111231. vorbis_staticbook_destroy(ci->book_param[i]);
  111232. ci->book_param[i]=NULL;
  111233. }
  111234. }
  111235. }
  111236. /* initialize the storage vectors. blocksize[1] is small for encode,
  111237. but the correct size for decode */
  111238. v->pcm_storage=ci->blocksizes[1];
  111239. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111240. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111241. {
  111242. int i;
  111243. for(i=0;i<vi->channels;i++)
  111244. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111245. }
  111246. /* all 1 (large block) or 0 (small block) */
  111247. /* explicitly set for the sake of clarity */
  111248. v->lW=0; /* previous window size */
  111249. v->W=0; /* current window size */
  111250. /* all vector indexes */
  111251. v->centerW=ci->blocksizes[1]/2;
  111252. v->pcm_current=v->centerW;
  111253. /* initialize all the backend lookups */
  111254. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111255. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111256. for(i=0;i<ci->floors;i++)
  111257. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111258. look(v,ci->floor_param[i]);
  111259. for(i=0;i<ci->residues;i++)
  111260. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111261. look(v,ci->residue_param[i]);
  111262. return 0;
  111263. }
  111264. /* arbitrary settings and spec-mandated numbers get filled in here */
  111265. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111266. private_state *b=NULL;
  111267. if(_vds_shared_init(v,vi,1))return 1;
  111268. b=(private_state*)v->backend_state;
  111269. b->psy_g_look=_vp_global_look(vi);
  111270. /* Initialize the envelope state storage */
  111271. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111272. _ve_envelope_init(b->ve,vi);
  111273. vorbis_bitrate_init(vi,&b->bms);
  111274. /* compressed audio packets start after the headers
  111275. with sequence number 3 */
  111276. v->sequence=3;
  111277. return(0);
  111278. }
  111279. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111280. int i;
  111281. if(v){
  111282. vorbis_info *vi=v->vi;
  111283. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111284. private_state *b=(private_state*)v->backend_state;
  111285. if(b){
  111286. if(b->ve){
  111287. _ve_envelope_clear(b->ve);
  111288. _ogg_free(b->ve);
  111289. }
  111290. if(b->transform[0]){
  111291. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111292. _ogg_free(b->transform[0][0]);
  111293. _ogg_free(b->transform[0]);
  111294. }
  111295. if(b->transform[1]){
  111296. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111297. _ogg_free(b->transform[1][0]);
  111298. _ogg_free(b->transform[1]);
  111299. }
  111300. if(b->flr){
  111301. for(i=0;i<ci->floors;i++)
  111302. _floor_P[ci->floor_type[i]]->
  111303. free_look(b->flr[i]);
  111304. _ogg_free(b->flr);
  111305. }
  111306. if(b->residue){
  111307. for(i=0;i<ci->residues;i++)
  111308. _residue_P[ci->residue_type[i]]->
  111309. free_look(b->residue[i]);
  111310. _ogg_free(b->residue);
  111311. }
  111312. if(b->psy){
  111313. for(i=0;i<ci->psys;i++)
  111314. _vp_psy_clear(b->psy+i);
  111315. _ogg_free(b->psy);
  111316. }
  111317. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111318. vorbis_bitrate_clear(&b->bms);
  111319. drft_clear(&b->fft_look[0]);
  111320. drft_clear(&b->fft_look[1]);
  111321. }
  111322. if(v->pcm){
  111323. for(i=0;i<vi->channels;i++)
  111324. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111325. _ogg_free(v->pcm);
  111326. if(v->pcmret)_ogg_free(v->pcmret);
  111327. }
  111328. if(b){
  111329. /* free header, header1, header2 */
  111330. if(b->header)_ogg_free(b->header);
  111331. if(b->header1)_ogg_free(b->header1);
  111332. if(b->header2)_ogg_free(b->header2);
  111333. _ogg_free(b);
  111334. }
  111335. memset(v,0,sizeof(*v));
  111336. }
  111337. }
  111338. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111339. int i;
  111340. vorbis_info *vi=v->vi;
  111341. private_state *b=(private_state*)v->backend_state;
  111342. /* free header, header1, header2 */
  111343. if(b->header)_ogg_free(b->header);b->header=NULL;
  111344. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111345. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111346. /* Do we have enough storage space for the requested buffer? If not,
  111347. expand the PCM (and envelope) storage */
  111348. if(v->pcm_current+vals>=v->pcm_storage){
  111349. v->pcm_storage=v->pcm_current+vals*2;
  111350. for(i=0;i<vi->channels;i++){
  111351. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111352. }
  111353. }
  111354. for(i=0;i<vi->channels;i++)
  111355. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111356. return(v->pcmret);
  111357. }
  111358. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111359. int i;
  111360. int order=32;
  111361. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111362. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111363. long j;
  111364. v->preextrapolate=1;
  111365. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111366. for(i=0;i<v->vi->channels;i++){
  111367. /* need to run the extrapolation in reverse! */
  111368. for(j=0;j<v->pcm_current;j++)
  111369. work[j]=v->pcm[i][v->pcm_current-j-1];
  111370. /* prime as above */
  111371. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111372. /* run the predictor filter */
  111373. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111374. order,
  111375. work+v->pcm_current-v->centerW,
  111376. v->centerW);
  111377. for(j=0;j<v->pcm_current;j++)
  111378. v->pcm[i][v->pcm_current-j-1]=work[j];
  111379. }
  111380. }
  111381. }
  111382. /* call with val<=0 to set eof */
  111383. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111384. vorbis_info *vi=v->vi;
  111385. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111386. if(vals<=0){
  111387. int order=32;
  111388. int i;
  111389. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111390. /* if it wasn't done earlier (very short sample) */
  111391. if(!v->preextrapolate)
  111392. _preextrapolate_helper(v);
  111393. /* We're encoding the end of the stream. Just make sure we have
  111394. [at least] a few full blocks of zeroes at the end. */
  111395. /* actually, we don't want zeroes; that could drop a large
  111396. amplitude off a cliff, creating spread spectrum noise that will
  111397. suck to encode. Extrapolate for the sake of cleanliness. */
  111398. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111399. v->eofflag=v->pcm_current;
  111400. v->pcm_current+=ci->blocksizes[1]*3;
  111401. for(i=0;i<vi->channels;i++){
  111402. if(v->eofflag>order*2){
  111403. /* extrapolate with LPC to fill in */
  111404. long n;
  111405. /* make a predictor filter */
  111406. n=v->eofflag;
  111407. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111408. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111409. /* run the predictor filter */
  111410. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111411. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111412. }else{
  111413. /* not enough data to extrapolate (unlikely to happen due to
  111414. guarding the overlap, but bulletproof in case that
  111415. assumtion goes away). zeroes will do. */
  111416. memset(v->pcm[i]+v->eofflag,0,
  111417. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111418. }
  111419. }
  111420. }else{
  111421. if(v->pcm_current+vals>v->pcm_storage)
  111422. return(OV_EINVAL);
  111423. v->pcm_current+=vals;
  111424. /* we may want to reverse extrapolate the beginning of a stream
  111425. too... in case we're beginning on a cliff! */
  111426. /* clumsy, but simple. It only runs once, so simple is good. */
  111427. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111428. _preextrapolate_helper(v);
  111429. }
  111430. return(0);
  111431. }
  111432. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111433. the next block on which to continue analysis */
  111434. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111435. int i;
  111436. vorbis_info *vi=v->vi;
  111437. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111438. private_state *b=(private_state*)v->backend_state;
  111439. vorbis_look_psy_global *g=b->psy_g_look;
  111440. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111441. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111442. /* check to see if we're started... */
  111443. if(!v->preextrapolate)return(0);
  111444. /* check to see if we're done... */
  111445. if(v->eofflag==-1)return(0);
  111446. /* By our invariant, we have lW, W and centerW set. Search for
  111447. the next boundary so we can determine nW (the next window size)
  111448. which lets us compute the shape of the current block's window */
  111449. /* we do an envelope search even on a single blocksize; we may still
  111450. be throwing more bits at impulses, and envelope search handles
  111451. marking impulses too. */
  111452. {
  111453. long bp=_ve_envelope_search(v);
  111454. if(bp==-1){
  111455. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111456. full long block */
  111457. v->nW=0;
  111458. }else{
  111459. if(ci->blocksizes[0]==ci->blocksizes[1])
  111460. v->nW=0;
  111461. else
  111462. v->nW=bp;
  111463. }
  111464. }
  111465. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111466. {
  111467. /* center of next block + next block maximum right side. */
  111468. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111469. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111470. although this check is
  111471. less strict that the
  111472. _ve_envelope_search,
  111473. the search is not run
  111474. if we only use one
  111475. block size */
  111476. }
  111477. /* fill in the block. Note that for a short window, lW and nW are *short*
  111478. regardless of actual settings in the stream */
  111479. _vorbis_block_ripcord(vb);
  111480. vb->lW=v->lW;
  111481. vb->W=v->W;
  111482. vb->nW=v->nW;
  111483. if(v->W){
  111484. if(!v->lW || !v->nW){
  111485. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111486. /*fprintf(stderr,"-");*/
  111487. }else{
  111488. vbi->blocktype=BLOCKTYPE_LONG;
  111489. /*fprintf(stderr,"_");*/
  111490. }
  111491. }else{
  111492. if(_ve_envelope_mark(v)){
  111493. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111494. /*fprintf(stderr,"|");*/
  111495. }else{
  111496. vbi->blocktype=BLOCKTYPE_PADDING;
  111497. /*fprintf(stderr,".");*/
  111498. }
  111499. }
  111500. vb->vd=v;
  111501. vb->sequence=v->sequence++;
  111502. vb->granulepos=v->granulepos;
  111503. vb->pcmend=ci->blocksizes[v->W];
  111504. /* copy the vectors; this uses the local storage in vb */
  111505. /* this tracks 'strongest peak' for later psychoacoustics */
  111506. /* moved to the global psy state; clean this mess up */
  111507. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111508. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111509. vbi->ampmax=g->ampmax;
  111510. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111511. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111512. for(i=0;i<vi->channels;i++){
  111513. vbi->pcmdelay[i]=
  111514. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111515. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111516. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111517. /* before we added the delay
  111518. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111519. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111520. */
  111521. }
  111522. /* handle eof detection: eof==0 means that we've not yet received EOF
  111523. eof>0 marks the last 'real' sample in pcm[]
  111524. eof<0 'no more to do'; doesn't get here */
  111525. if(v->eofflag){
  111526. if(v->centerW>=v->eofflag){
  111527. v->eofflag=-1;
  111528. vb->eofflag=1;
  111529. return(1);
  111530. }
  111531. }
  111532. /* advance storage vectors and clean up */
  111533. {
  111534. int new_centerNext=ci->blocksizes[1]/2;
  111535. int movementW=centerNext-new_centerNext;
  111536. if(movementW>0){
  111537. _ve_envelope_shift(b->ve,movementW);
  111538. v->pcm_current-=movementW;
  111539. for(i=0;i<vi->channels;i++)
  111540. memmove(v->pcm[i],v->pcm[i]+movementW,
  111541. v->pcm_current*sizeof(*v->pcm[i]));
  111542. v->lW=v->W;
  111543. v->W=v->nW;
  111544. v->centerW=new_centerNext;
  111545. if(v->eofflag){
  111546. v->eofflag-=movementW;
  111547. if(v->eofflag<=0)v->eofflag=-1;
  111548. /* do not add padding to end of stream! */
  111549. if(v->centerW>=v->eofflag){
  111550. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111551. }else{
  111552. v->granulepos+=movementW;
  111553. }
  111554. }else{
  111555. v->granulepos+=movementW;
  111556. }
  111557. }
  111558. }
  111559. /* done */
  111560. return(1);
  111561. }
  111562. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111563. vorbis_info *vi=v->vi;
  111564. codec_setup_info *ci;
  111565. int hs;
  111566. if(!v->backend_state)return -1;
  111567. if(!vi)return -1;
  111568. ci=(codec_setup_info*) vi->codec_setup;
  111569. if(!ci)return -1;
  111570. hs=ci->halfrate_flag;
  111571. v->centerW=ci->blocksizes[1]>>(hs+1);
  111572. v->pcm_current=v->centerW>>hs;
  111573. v->pcm_returned=-1;
  111574. v->granulepos=-1;
  111575. v->sequence=-1;
  111576. v->eofflag=0;
  111577. ((private_state *)(v->backend_state))->sample_count=-1;
  111578. return(0);
  111579. }
  111580. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111581. if(_vds_shared_init(v,vi,0)) return 1;
  111582. vorbis_synthesis_restart(v);
  111583. return 0;
  111584. }
  111585. /* Unlike in analysis, the window is only partially applied for each
  111586. block. The time domain envelope is not yet handled at the point of
  111587. calling (as it relies on the previous block). */
  111588. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111589. vorbis_info *vi=v->vi;
  111590. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111591. private_state *b=(private_state*)v->backend_state;
  111592. int hs=ci->halfrate_flag;
  111593. int i,j;
  111594. if(!vb)return(OV_EINVAL);
  111595. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111596. v->lW=v->W;
  111597. v->W=vb->W;
  111598. v->nW=-1;
  111599. if((v->sequence==-1)||
  111600. (v->sequence+1 != vb->sequence)){
  111601. v->granulepos=-1; /* out of sequence; lose count */
  111602. b->sample_count=-1;
  111603. }
  111604. v->sequence=vb->sequence;
  111605. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111606. was called on block */
  111607. int n=ci->blocksizes[v->W]>>(hs+1);
  111608. int n0=ci->blocksizes[0]>>(hs+1);
  111609. int n1=ci->blocksizes[1]>>(hs+1);
  111610. int thisCenter;
  111611. int prevCenter;
  111612. v->glue_bits+=vb->glue_bits;
  111613. v->time_bits+=vb->time_bits;
  111614. v->floor_bits+=vb->floor_bits;
  111615. v->res_bits+=vb->res_bits;
  111616. if(v->centerW){
  111617. thisCenter=n1;
  111618. prevCenter=0;
  111619. }else{
  111620. thisCenter=0;
  111621. prevCenter=n1;
  111622. }
  111623. /* v->pcm is now used like a two-stage double buffer. We don't want
  111624. to have to constantly shift *or* adjust memory usage. Don't
  111625. accept a new block until the old is shifted out */
  111626. for(j=0;j<vi->channels;j++){
  111627. /* the overlap/add section */
  111628. if(v->lW){
  111629. if(v->W){
  111630. /* large/large */
  111631. float *w=_vorbis_window_get(b->window[1]-hs);
  111632. float *pcm=v->pcm[j]+prevCenter;
  111633. float *p=vb->pcm[j];
  111634. for(i=0;i<n1;i++)
  111635. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111636. }else{
  111637. /* large/small */
  111638. float *w=_vorbis_window_get(b->window[0]-hs);
  111639. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111640. float *p=vb->pcm[j];
  111641. for(i=0;i<n0;i++)
  111642. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111643. }
  111644. }else{
  111645. if(v->W){
  111646. /* small/large */
  111647. float *w=_vorbis_window_get(b->window[0]-hs);
  111648. float *pcm=v->pcm[j]+prevCenter;
  111649. float *p=vb->pcm[j]+n1/2-n0/2;
  111650. for(i=0;i<n0;i++)
  111651. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111652. for(;i<n1/2+n0/2;i++)
  111653. pcm[i]=p[i];
  111654. }else{
  111655. /* small/small */
  111656. float *w=_vorbis_window_get(b->window[0]-hs);
  111657. float *pcm=v->pcm[j]+prevCenter;
  111658. float *p=vb->pcm[j];
  111659. for(i=0;i<n0;i++)
  111660. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111661. }
  111662. }
  111663. /* the copy section */
  111664. {
  111665. float *pcm=v->pcm[j]+thisCenter;
  111666. float *p=vb->pcm[j]+n;
  111667. for(i=0;i<n;i++)
  111668. pcm[i]=p[i];
  111669. }
  111670. }
  111671. if(v->centerW)
  111672. v->centerW=0;
  111673. else
  111674. v->centerW=n1;
  111675. /* deal with initial packet state; we do this using the explicit
  111676. pcm_returned==-1 flag otherwise we're sensitive to first block
  111677. being short or long */
  111678. if(v->pcm_returned==-1){
  111679. v->pcm_returned=thisCenter;
  111680. v->pcm_current=thisCenter;
  111681. }else{
  111682. v->pcm_returned=prevCenter;
  111683. v->pcm_current=prevCenter+
  111684. ((ci->blocksizes[v->lW]/4+
  111685. ci->blocksizes[v->W]/4)>>hs);
  111686. }
  111687. }
  111688. /* track the frame number... This is for convenience, but also
  111689. making sure our last packet doesn't end with added padding. If
  111690. the last packet is partial, the number of samples we'll have to
  111691. return will be past the vb->granulepos.
  111692. This is not foolproof! It will be confused if we begin
  111693. decoding at the last page after a seek or hole. In that case,
  111694. we don't have a starting point to judge where the last frame
  111695. is. For this reason, vorbisfile will always try to make sure
  111696. it reads the last two marked pages in proper sequence */
  111697. if(b->sample_count==-1){
  111698. b->sample_count=0;
  111699. }else{
  111700. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111701. }
  111702. if(v->granulepos==-1){
  111703. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111704. v->granulepos=vb->granulepos;
  111705. /* is this a short page? */
  111706. if(b->sample_count>v->granulepos){
  111707. /* corner case; if this is both the first and last audio page,
  111708. then spec says the end is cut, not beginning */
  111709. if(vb->eofflag){
  111710. /* trim the end */
  111711. /* no preceeding granulepos; assume we started at zero (we'd
  111712. have to in a short single-page stream) */
  111713. /* granulepos could be -1 due to a seek, but that would result
  111714. in a long count, not short count */
  111715. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111716. }else{
  111717. /* trim the beginning */
  111718. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111719. if(v->pcm_returned>v->pcm_current)
  111720. v->pcm_returned=v->pcm_current;
  111721. }
  111722. }
  111723. }
  111724. }else{
  111725. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111726. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111727. if(v->granulepos>vb->granulepos){
  111728. long extra=v->granulepos-vb->granulepos;
  111729. if(extra)
  111730. if(vb->eofflag){
  111731. /* partial last frame. Strip the extra samples off */
  111732. v->pcm_current-=extra>>hs;
  111733. } /* else {Shouldn't happen *unless* the bitstream is out of
  111734. spec. Either way, believe the bitstream } */
  111735. } /* else {Shouldn't happen *unless* the bitstream is out of
  111736. spec. Either way, believe the bitstream } */
  111737. v->granulepos=vb->granulepos;
  111738. }
  111739. }
  111740. /* Update, cleanup */
  111741. if(vb->eofflag)v->eofflag=1;
  111742. return(0);
  111743. }
  111744. /* pcm==NULL indicates we just want the pending samples, no more */
  111745. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111746. vorbis_info *vi=v->vi;
  111747. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111748. if(pcm){
  111749. int i;
  111750. for(i=0;i<vi->channels;i++)
  111751. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111752. *pcm=v->pcmret;
  111753. }
  111754. return(v->pcm_current-v->pcm_returned);
  111755. }
  111756. return(0);
  111757. }
  111758. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111759. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111760. v->pcm_returned+=n;
  111761. return(0);
  111762. }
  111763. /* intended for use with a specific vorbisfile feature; we want access
  111764. to the [usually synthetic/postextrapolated] buffer and lapping at
  111765. the end of a decode cycle, specifically, a half-short-block worth.
  111766. This funtion works like pcmout above, except it will also expose
  111767. this implicit buffer data not normally decoded. */
  111768. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111769. vorbis_info *vi=v->vi;
  111770. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111771. int hs=ci->halfrate_flag;
  111772. int n=ci->blocksizes[v->W]>>(hs+1);
  111773. int n0=ci->blocksizes[0]>>(hs+1);
  111774. int n1=ci->blocksizes[1]>>(hs+1);
  111775. int i,j;
  111776. if(v->pcm_returned<0)return 0;
  111777. /* our returned data ends at pcm_returned; because the synthesis pcm
  111778. buffer is a two-fragment ring, that means our data block may be
  111779. fragmented by buffering, wrapping or a short block not filling
  111780. out a buffer. To simplify things, we unfragment if it's at all
  111781. possibly needed. Otherwise, we'd need to call lapout more than
  111782. once as well as hold additional dsp state. Opt for
  111783. simplicity. */
  111784. /* centerW was advanced by blockin; it would be the center of the
  111785. *next* block */
  111786. if(v->centerW==n1){
  111787. /* the data buffer wraps; swap the halves */
  111788. /* slow, sure, small */
  111789. for(j=0;j<vi->channels;j++){
  111790. float *p=v->pcm[j];
  111791. for(i=0;i<n1;i++){
  111792. float temp=p[i];
  111793. p[i]=p[i+n1];
  111794. p[i+n1]=temp;
  111795. }
  111796. }
  111797. v->pcm_current-=n1;
  111798. v->pcm_returned-=n1;
  111799. v->centerW=0;
  111800. }
  111801. /* solidify buffer into contiguous space */
  111802. if((v->lW^v->W)==1){
  111803. /* long/short or short/long */
  111804. for(j=0;j<vi->channels;j++){
  111805. float *s=v->pcm[j];
  111806. float *d=v->pcm[j]+(n1-n0)/2;
  111807. for(i=(n1+n0)/2-1;i>=0;--i)
  111808. d[i]=s[i];
  111809. }
  111810. v->pcm_returned+=(n1-n0)/2;
  111811. v->pcm_current+=(n1-n0)/2;
  111812. }else{
  111813. if(v->lW==0){
  111814. /* short/short */
  111815. for(j=0;j<vi->channels;j++){
  111816. float *s=v->pcm[j];
  111817. float *d=v->pcm[j]+n1-n0;
  111818. for(i=n0-1;i>=0;--i)
  111819. d[i]=s[i];
  111820. }
  111821. v->pcm_returned+=n1-n0;
  111822. v->pcm_current+=n1-n0;
  111823. }
  111824. }
  111825. if(pcm){
  111826. int i;
  111827. for(i=0;i<vi->channels;i++)
  111828. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111829. *pcm=v->pcmret;
  111830. }
  111831. return(n1+n-v->pcm_returned);
  111832. }
  111833. float *vorbis_window(vorbis_dsp_state *v,int W){
  111834. vorbis_info *vi=v->vi;
  111835. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111836. int hs=ci->halfrate_flag;
  111837. private_state *b=(private_state*)v->backend_state;
  111838. if(b->window[W]-1<0)return NULL;
  111839. return _vorbis_window_get(b->window[W]-hs);
  111840. }
  111841. #endif
  111842. /*** End of inlined file: block.c ***/
  111843. /*** Start of inlined file: codebook.c ***/
  111844. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111845. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111846. // tasks..
  111847. #if JUCE_MSVC
  111848. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111849. #endif
  111850. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111851. #if JUCE_USE_OGGVORBIS
  111852. #include <stdlib.h>
  111853. #include <string.h>
  111854. #include <math.h>
  111855. /* packs the given codebook into the bitstream **************************/
  111856. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111857. long i,j;
  111858. int ordered=0;
  111859. /* first the basic parameters */
  111860. oggpack_write(opb,0x564342,24);
  111861. oggpack_write(opb,c->dim,16);
  111862. oggpack_write(opb,c->entries,24);
  111863. /* pack the codewords. There are two packings; length ordered and
  111864. length random. Decide between the two now. */
  111865. for(i=1;i<c->entries;i++)
  111866. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111867. if(i==c->entries)ordered=1;
  111868. if(ordered){
  111869. /* length ordered. We only need to say how many codewords of
  111870. each length. The actual codewords are generated
  111871. deterministically */
  111872. long count=0;
  111873. oggpack_write(opb,1,1); /* ordered */
  111874. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111875. for(i=1;i<c->entries;i++){
  111876. long thisx=c->lengthlist[i];
  111877. long last=c->lengthlist[i-1];
  111878. if(thisx>last){
  111879. for(j=last;j<thisx;j++){
  111880. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111881. count=i;
  111882. }
  111883. }
  111884. }
  111885. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111886. }else{
  111887. /* length random. Again, we don't code the codeword itself, just
  111888. the length. This time, though, we have to encode each length */
  111889. oggpack_write(opb,0,1); /* unordered */
  111890. /* algortihmic mapping has use for 'unused entries', which we tag
  111891. here. The algorithmic mapping happens as usual, but the unused
  111892. entry has no codeword. */
  111893. for(i=0;i<c->entries;i++)
  111894. if(c->lengthlist[i]==0)break;
  111895. if(i==c->entries){
  111896. oggpack_write(opb,0,1); /* no unused entries */
  111897. for(i=0;i<c->entries;i++)
  111898. oggpack_write(opb,c->lengthlist[i]-1,5);
  111899. }else{
  111900. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111901. for(i=0;i<c->entries;i++){
  111902. if(c->lengthlist[i]==0){
  111903. oggpack_write(opb,0,1);
  111904. }else{
  111905. oggpack_write(opb,1,1);
  111906. oggpack_write(opb,c->lengthlist[i]-1,5);
  111907. }
  111908. }
  111909. }
  111910. }
  111911. /* is the entry number the desired return value, or do we have a
  111912. mapping? If we have a mapping, what type? */
  111913. oggpack_write(opb,c->maptype,4);
  111914. switch(c->maptype){
  111915. case 0:
  111916. /* no mapping */
  111917. break;
  111918. case 1:case 2:
  111919. /* implicitly populated value mapping */
  111920. /* explicitly populated value mapping */
  111921. if(!c->quantlist){
  111922. /* no quantlist? error */
  111923. return(-1);
  111924. }
  111925. /* values that define the dequantization */
  111926. oggpack_write(opb,c->q_min,32);
  111927. oggpack_write(opb,c->q_delta,32);
  111928. oggpack_write(opb,c->q_quant-1,4);
  111929. oggpack_write(opb,c->q_sequencep,1);
  111930. {
  111931. int quantvals;
  111932. switch(c->maptype){
  111933. case 1:
  111934. /* a single column of (c->entries/c->dim) quantized values for
  111935. building a full value list algorithmically (square lattice) */
  111936. quantvals=_book_maptype1_quantvals(c);
  111937. break;
  111938. case 2:
  111939. /* every value (c->entries*c->dim total) specified explicitly */
  111940. quantvals=c->entries*c->dim;
  111941. break;
  111942. default: /* NOT_REACHABLE */
  111943. quantvals=-1;
  111944. }
  111945. /* quantized values */
  111946. for(i=0;i<quantvals;i++)
  111947. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111948. }
  111949. break;
  111950. default:
  111951. /* error case; we don't have any other map types now */
  111952. return(-1);
  111953. }
  111954. return(0);
  111955. }
  111956. /* unpacks a codebook from the packet buffer into the codebook struct,
  111957. readies the codebook auxiliary structures for decode *************/
  111958. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111959. long i,j;
  111960. memset(s,0,sizeof(*s));
  111961. s->allocedp=1;
  111962. /* make sure alignment is correct */
  111963. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111964. /* first the basic parameters */
  111965. s->dim=oggpack_read(opb,16);
  111966. s->entries=oggpack_read(opb,24);
  111967. if(s->entries==-1)goto _eofout;
  111968. /* codeword ordering.... length ordered or unordered? */
  111969. switch((int)oggpack_read(opb,1)){
  111970. case 0:
  111971. /* unordered */
  111972. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111973. /* allocated but unused entries? */
  111974. if(oggpack_read(opb,1)){
  111975. /* yes, unused entries */
  111976. for(i=0;i<s->entries;i++){
  111977. if(oggpack_read(opb,1)){
  111978. long num=oggpack_read(opb,5);
  111979. if(num==-1)goto _eofout;
  111980. s->lengthlist[i]=num+1;
  111981. }else
  111982. s->lengthlist[i]=0;
  111983. }
  111984. }else{
  111985. /* all entries used; no tagging */
  111986. for(i=0;i<s->entries;i++){
  111987. long num=oggpack_read(opb,5);
  111988. if(num==-1)goto _eofout;
  111989. s->lengthlist[i]=num+1;
  111990. }
  111991. }
  111992. break;
  111993. case 1:
  111994. /* ordered */
  111995. {
  111996. long length=oggpack_read(opb,5)+1;
  111997. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111998. for(i=0;i<s->entries;){
  111999. long num=oggpack_read(opb,_ilog(s->entries-i));
  112000. if(num==-1)goto _eofout;
  112001. for(j=0;j<num && i<s->entries;j++,i++)
  112002. s->lengthlist[i]=length;
  112003. length++;
  112004. }
  112005. }
  112006. break;
  112007. default:
  112008. /* EOF */
  112009. return(-1);
  112010. }
  112011. /* Do we have a mapping to unpack? */
  112012. switch((s->maptype=oggpack_read(opb,4))){
  112013. case 0:
  112014. /* no mapping */
  112015. break;
  112016. case 1: case 2:
  112017. /* implicitly populated value mapping */
  112018. /* explicitly populated value mapping */
  112019. s->q_min=oggpack_read(opb,32);
  112020. s->q_delta=oggpack_read(opb,32);
  112021. s->q_quant=oggpack_read(opb,4)+1;
  112022. s->q_sequencep=oggpack_read(opb,1);
  112023. {
  112024. int quantvals=0;
  112025. switch(s->maptype){
  112026. case 1:
  112027. quantvals=_book_maptype1_quantvals(s);
  112028. break;
  112029. case 2:
  112030. quantvals=s->entries*s->dim;
  112031. break;
  112032. }
  112033. /* quantized values */
  112034. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112035. for(i=0;i<quantvals;i++)
  112036. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112037. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112038. }
  112039. break;
  112040. default:
  112041. goto _errout;
  112042. }
  112043. /* all set */
  112044. return(0);
  112045. _errout:
  112046. _eofout:
  112047. vorbis_staticbook_clear(s);
  112048. return(-1);
  112049. }
  112050. /* returns the number of bits ************************************************/
  112051. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112052. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112053. return(book->c->lengthlist[a]);
  112054. }
  112055. /* One the encode side, our vector writers are each designed for a
  112056. specific purpose, and the encoder is not flexible without modification:
  112057. The LSP vector coder uses a single stage nearest-match with no
  112058. interleave, so no step and no error return. This is specced by floor0
  112059. and doesn't change.
  112060. Residue0 encoding interleaves, uses multiple stages, and each stage
  112061. peels of a specific amount of resolution from a lattice (thus we want
  112062. to match by threshold, not nearest match). Residue doesn't *have* to
  112063. be encoded that way, but to change it, one will need to add more
  112064. infrastructure on the encode side (decode side is specced and simpler) */
  112065. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112066. /* returns entry number and *modifies a* to the quantization value *****/
  112067. int vorbis_book_errorv(codebook *book,float *a){
  112068. int dim=book->dim,k;
  112069. int best=_best(book,a,1);
  112070. for(k=0;k<dim;k++)
  112071. a[k]=(book->valuelist+best*dim)[k];
  112072. return(best);
  112073. }
  112074. /* returns the number of bits and *modifies a* to the quantization value *****/
  112075. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112076. int k,dim=book->dim;
  112077. for(k=0;k<dim;k++)
  112078. a[k]=(book->valuelist+best*dim)[k];
  112079. return(vorbis_book_encode(book,best,b));
  112080. }
  112081. /* the 'eliminate the decode tree' optimization actually requires the
  112082. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112083. (and one of the first places where carefully thought out design
  112084. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112085. to an MSb bitpacker), but not actually the huge hit it appears to
  112086. be. The first-stage decode table catches most words so that
  112087. bitreverse is not in the main execution path. */
  112088. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112089. int read=book->dec_maxlength;
  112090. long lo,hi;
  112091. long lok = oggpack_look(b,book->dec_firsttablen);
  112092. if (lok >= 0) {
  112093. long entry = book->dec_firsttable[lok];
  112094. if(entry&0x80000000UL){
  112095. lo=(entry>>15)&0x7fff;
  112096. hi=book->used_entries-(entry&0x7fff);
  112097. }else{
  112098. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112099. return(entry-1);
  112100. }
  112101. }else{
  112102. lo=0;
  112103. hi=book->used_entries;
  112104. }
  112105. lok = oggpack_look(b, read);
  112106. while(lok<0 && read>1)
  112107. lok = oggpack_look(b, --read);
  112108. if(lok<0)return -1;
  112109. /* bisect search for the codeword in the ordered list */
  112110. {
  112111. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112112. while(hi-lo>1){
  112113. long p=(hi-lo)>>1;
  112114. long test=book->codelist[lo+p]>testword;
  112115. lo+=p&(test-1);
  112116. hi-=p&(-test);
  112117. }
  112118. if(book->dec_codelengths[lo]<=read){
  112119. oggpack_adv(b, book->dec_codelengths[lo]);
  112120. return(lo);
  112121. }
  112122. }
  112123. oggpack_adv(b, read);
  112124. return(-1);
  112125. }
  112126. /* Decode side is specced and easier, because we don't need to find
  112127. matches using different criteria; we simply read and map. There are
  112128. two things we need to do 'depending':
  112129. We may need to support interleave. We don't really, but it's
  112130. convenient to do it here rather than rebuild the vector later.
  112131. Cascades may be additive or multiplicitive; this is not inherent in
  112132. the codebook, but set in the code using the codebook. Like
  112133. interleaving, it's easiest to do it here.
  112134. addmul==0 -> declarative (set the value)
  112135. addmul==1 -> additive
  112136. addmul==2 -> multiplicitive */
  112137. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112138. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112139. long packed_entry=decode_packed_entry_number(book,b);
  112140. if(packed_entry>=0)
  112141. return(book->dec_index[packed_entry]);
  112142. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112143. return(packed_entry);
  112144. }
  112145. /* returns 0 on OK or -1 on eof *************************************/
  112146. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112147. int step=n/book->dim;
  112148. long *entry = (long*)alloca(sizeof(*entry)*step);
  112149. float **t = (float**)alloca(sizeof(*t)*step);
  112150. int i,j,o;
  112151. for (i = 0; i < step; i++) {
  112152. entry[i]=decode_packed_entry_number(book,b);
  112153. if(entry[i]==-1)return(-1);
  112154. t[i] = book->valuelist+entry[i]*book->dim;
  112155. }
  112156. for(i=0,o=0;i<book->dim;i++,o+=step)
  112157. for (j=0;j<step;j++)
  112158. a[o+j]+=t[j][i];
  112159. return(0);
  112160. }
  112161. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112162. int i,j,entry;
  112163. float *t;
  112164. if(book->dim>8){
  112165. for(i=0;i<n;){
  112166. entry = decode_packed_entry_number(book,b);
  112167. if(entry==-1)return(-1);
  112168. t = book->valuelist+entry*book->dim;
  112169. for (j=0;j<book->dim;)
  112170. a[i++]+=t[j++];
  112171. }
  112172. }else{
  112173. for(i=0;i<n;){
  112174. entry = decode_packed_entry_number(book,b);
  112175. if(entry==-1)return(-1);
  112176. t = book->valuelist+entry*book->dim;
  112177. j=0;
  112178. switch((int)book->dim){
  112179. case 8:
  112180. a[i++]+=t[j++];
  112181. case 7:
  112182. a[i++]+=t[j++];
  112183. case 6:
  112184. a[i++]+=t[j++];
  112185. case 5:
  112186. a[i++]+=t[j++];
  112187. case 4:
  112188. a[i++]+=t[j++];
  112189. case 3:
  112190. a[i++]+=t[j++];
  112191. case 2:
  112192. a[i++]+=t[j++];
  112193. case 1:
  112194. a[i++]+=t[j++];
  112195. case 0:
  112196. break;
  112197. }
  112198. }
  112199. }
  112200. return(0);
  112201. }
  112202. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112203. int i,j,entry;
  112204. float *t;
  112205. for(i=0;i<n;){
  112206. entry = decode_packed_entry_number(book,b);
  112207. if(entry==-1)return(-1);
  112208. t = book->valuelist+entry*book->dim;
  112209. for (j=0;j<book->dim;)
  112210. a[i++]=t[j++];
  112211. }
  112212. return(0);
  112213. }
  112214. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112215. oggpack_buffer *b,int n){
  112216. long i,j,entry;
  112217. int chptr=0;
  112218. for(i=offset/ch;i<(offset+n)/ch;){
  112219. entry = decode_packed_entry_number(book,b);
  112220. if(entry==-1)return(-1);
  112221. {
  112222. const float *t = book->valuelist+entry*book->dim;
  112223. for (j=0;j<book->dim;j++){
  112224. a[chptr++][i]+=t[j];
  112225. if(chptr==ch){
  112226. chptr=0;
  112227. i++;
  112228. }
  112229. }
  112230. }
  112231. }
  112232. return(0);
  112233. }
  112234. #ifdef _V_SELFTEST
  112235. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112236. number of vectors through (keeping track of the quantized values),
  112237. and decode using the unpacked book. quantized version of in should
  112238. exactly equal out */
  112239. #include <stdio.h>
  112240. #include "vorbis/book/lsp20_0.vqh"
  112241. #include "vorbis/book/res0a_13.vqh"
  112242. #define TESTSIZE 40
  112243. float test1[TESTSIZE]={
  112244. 0.105939f,
  112245. 0.215373f,
  112246. 0.429117f,
  112247. 0.587974f,
  112248. 0.181173f,
  112249. 0.296583f,
  112250. 0.515707f,
  112251. 0.715261f,
  112252. 0.162327f,
  112253. 0.263834f,
  112254. 0.342876f,
  112255. 0.406025f,
  112256. 0.103571f,
  112257. 0.223561f,
  112258. 0.368513f,
  112259. 0.540313f,
  112260. 0.136672f,
  112261. 0.395882f,
  112262. 0.587183f,
  112263. 0.652476f,
  112264. 0.114338f,
  112265. 0.417300f,
  112266. 0.525486f,
  112267. 0.698679f,
  112268. 0.147492f,
  112269. 0.324481f,
  112270. 0.643089f,
  112271. 0.757582f,
  112272. 0.139556f,
  112273. 0.215795f,
  112274. 0.324559f,
  112275. 0.399387f,
  112276. 0.120236f,
  112277. 0.267420f,
  112278. 0.446940f,
  112279. 0.608760f,
  112280. 0.115587f,
  112281. 0.287234f,
  112282. 0.571081f,
  112283. 0.708603f,
  112284. };
  112285. float test3[TESTSIZE]={
  112286. 0,1,-2,3,4,-5,6,7,8,9,
  112287. 8,-2,7,-1,4,6,8,3,1,-9,
  112288. 10,11,12,13,14,15,26,17,18,19,
  112289. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112290. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112291. &_vq_book_res0a_13,NULL};
  112292. float *testvec[]={test1,test3};
  112293. int main(){
  112294. oggpack_buffer write;
  112295. oggpack_buffer read;
  112296. long ptr=0,i;
  112297. oggpack_writeinit(&write);
  112298. fprintf(stderr,"Testing codebook abstraction...:\n");
  112299. while(testlist[ptr]){
  112300. codebook c;
  112301. static_codebook s;
  112302. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112303. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112304. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112305. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112306. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112307. /* pack the codebook, write the testvector */
  112308. oggpack_reset(&write);
  112309. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112310. we can write */
  112311. vorbis_staticbook_pack(testlist[ptr],&write);
  112312. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112313. for(i=0;i<TESTSIZE;i+=c.dim){
  112314. int best=_best(&c,qv+i,1);
  112315. vorbis_book_encodev(&c,best,qv+i,&write);
  112316. }
  112317. vorbis_book_clear(&c);
  112318. fprintf(stderr,"OK.\n");
  112319. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112320. /* transfer the write data to a read buffer and unpack/read */
  112321. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112322. if(vorbis_staticbook_unpack(&read,&s)){
  112323. fprintf(stderr,"Error unpacking codebook.\n");
  112324. exit(1);
  112325. }
  112326. if(vorbis_book_init_decode(&c,&s)){
  112327. fprintf(stderr,"Error initializing codebook.\n");
  112328. exit(1);
  112329. }
  112330. for(i=0;i<TESTSIZE;i+=c.dim)
  112331. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112332. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112333. exit(1);
  112334. }
  112335. for(i=0;i<TESTSIZE;i++)
  112336. if(fabs(qv[i]-iv[i])>.000001){
  112337. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112338. iv[i],qv[i],i);
  112339. exit(1);
  112340. }
  112341. fprintf(stderr,"OK\n");
  112342. ptr++;
  112343. }
  112344. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112345. exit(0);
  112346. }
  112347. #endif
  112348. #endif
  112349. /*** End of inlined file: codebook.c ***/
  112350. /*** Start of inlined file: envelope.c ***/
  112351. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112352. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112353. // tasks..
  112354. #if JUCE_MSVC
  112355. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112356. #endif
  112357. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112358. #if JUCE_USE_OGGVORBIS
  112359. #include <stdlib.h>
  112360. #include <string.h>
  112361. #include <stdio.h>
  112362. #include <math.h>
  112363. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112364. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112365. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112366. int ch=vi->channels;
  112367. int i,j;
  112368. int n=e->winlength=128;
  112369. e->searchstep=64; /* not random */
  112370. e->minenergy=gi->preecho_minenergy;
  112371. e->ch=ch;
  112372. e->storage=128;
  112373. e->cursor=ci->blocksizes[1]/2;
  112374. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112375. mdct_init(&e->mdct,n);
  112376. for(i=0;i<n;i++){
  112377. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112378. e->mdct_win[i]*=e->mdct_win[i];
  112379. }
  112380. /* magic follows */
  112381. e->band[0].begin=2; e->band[0].end=4;
  112382. e->band[1].begin=4; e->band[1].end=5;
  112383. e->band[2].begin=6; e->band[2].end=6;
  112384. e->band[3].begin=9; e->band[3].end=8;
  112385. e->band[4].begin=13; e->band[4].end=8;
  112386. e->band[5].begin=17; e->band[5].end=8;
  112387. e->band[6].begin=22; e->band[6].end=8;
  112388. for(j=0;j<VE_BANDS;j++){
  112389. n=e->band[j].end;
  112390. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112391. for(i=0;i<n;i++){
  112392. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112393. e->band[j].total+=e->band[j].window[i];
  112394. }
  112395. e->band[j].total=1./e->band[j].total;
  112396. }
  112397. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112398. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112399. }
  112400. void _ve_envelope_clear(envelope_lookup *e){
  112401. int i;
  112402. mdct_clear(&e->mdct);
  112403. for(i=0;i<VE_BANDS;i++)
  112404. _ogg_free(e->band[i].window);
  112405. _ogg_free(e->mdct_win);
  112406. _ogg_free(e->filter);
  112407. _ogg_free(e->mark);
  112408. memset(e,0,sizeof(*e));
  112409. }
  112410. /* fairly straight threshhold-by-band based until we find something
  112411. that works better and isn't patented. */
  112412. static int _ve_amp(envelope_lookup *ve,
  112413. vorbis_info_psy_global *gi,
  112414. float *data,
  112415. envelope_band *bands,
  112416. envelope_filter_state *filters,
  112417. long pos){
  112418. long n=ve->winlength;
  112419. int ret=0;
  112420. long i,j;
  112421. float decay;
  112422. /* we want to have a 'minimum bar' for energy, else we're just
  112423. basing blocks on quantization noise that outweighs the signal
  112424. itself (for low power signals) */
  112425. float minV=ve->minenergy;
  112426. float *vec=(float*) alloca(n*sizeof(*vec));
  112427. /* stretch is used to gradually lengthen the number of windows
  112428. considered prevoius-to-potential-trigger */
  112429. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112430. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112431. if(penalty<0.f)penalty=0.f;
  112432. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112433. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112434. totalshift+pos*ve->searchstep);*/
  112435. /* window and transform */
  112436. for(i=0;i<n;i++)
  112437. vec[i]=data[i]*ve->mdct_win[i];
  112438. mdct_forward(&ve->mdct,vec,vec);
  112439. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112440. /* near-DC spreading function; this has nothing to do with
  112441. psychoacoustics, just sidelobe leakage and window size */
  112442. {
  112443. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112444. int ptr=filters->nearptr;
  112445. /* the accumulation is regularly refreshed from scratch to avoid
  112446. floating point creep */
  112447. if(ptr==0){
  112448. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112449. filters->nearDC_partialacc=temp;
  112450. }else{
  112451. decay=filters->nearDC_acc+=temp;
  112452. filters->nearDC_partialacc+=temp;
  112453. }
  112454. filters->nearDC_acc-=filters->nearDC[ptr];
  112455. filters->nearDC[ptr]=temp;
  112456. decay*=(1./(VE_NEARDC+1));
  112457. filters->nearptr++;
  112458. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112459. decay=todB(&decay)*.5-15.f;
  112460. }
  112461. /* perform spreading and limiting, also smooth the spectrum. yes,
  112462. the MDCT results in all real coefficients, but it still *behaves*
  112463. like real/imaginary pairs */
  112464. for(i=0;i<n/2;i+=2){
  112465. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112466. val=todB(&val)*.5f;
  112467. if(val<decay)val=decay;
  112468. if(val<minV)val=minV;
  112469. vec[i>>1]=val;
  112470. decay-=8.;
  112471. }
  112472. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112473. /* perform preecho/postecho triggering by band */
  112474. for(j=0;j<VE_BANDS;j++){
  112475. float acc=0.;
  112476. float valmax,valmin;
  112477. /* accumulate amplitude */
  112478. for(i=0;i<bands[j].end;i++)
  112479. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112480. acc*=bands[j].total;
  112481. /* convert amplitude to delta */
  112482. {
  112483. int p,thisx=filters[j].ampptr;
  112484. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112485. p=thisx;
  112486. p--;
  112487. if(p<0)p+=VE_AMP;
  112488. postmax=max(acc,filters[j].ampbuf[p]);
  112489. postmin=min(acc,filters[j].ampbuf[p]);
  112490. for(i=0;i<stretch;i++){
  112491. p--;
  112492. if(p<0)p+=VE_AMP;
  112493. premax=max(premax,filters[j].ampbuf[p]);
  112494. premin=min(premin,filters[j].ampbuf[p]);
  112495. }
  112496. valmin=postmin-premin;
  112497. valmax=postmax-premax;
  112498. /*filters[j].markers[pos]=valmax;*/
  112499. filters[j].ampbuf[thisx]=acc;
  112500. filters[j].ampptr++;
  112501. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112502. }
  112503. /* look at min/max, decide trigger */
  112504. if(valmax>gi->preecho_thresh[j]+penalty){
  112505. ret|=1;
  112506. ret|=4;
  112507. }
  112508. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112509. }
  112510. return(ret);
  112511. }
  112512. #if 0
  112513. static int seq=0;
  112514. static ogg_int64_t totalshift=-1024;
  112515. #endif
  112516. long _ve_envelope_search(vorbis_dsp_state *v){
  112517. vorbis_info *vi=v->vi;
  112518. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112519. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112520. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112521. long i,j;
  112522. int first=ve->current/ve->searchstep;
  112523. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112524. if(first<0)first=0;
  112525. /* make sure we have enough storage to match the PCM */
  112526. if(last+VE_WIN+VE_POST>ve->storage){
  112527. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112528. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112529. }
  112530. for(j=first;j<last;j++){
  112531. int ret=0;
  112532. ve->stretch++;
  112533. if(ve->stretch>VE_MAXSTRETCH*2)
  112534. ve->stretch=VE_MAXSTRETCH*2;
  112535. for(i=0;i<ve->ch;i++){
  112536. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112537. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112538. }
  112539. ve->mark[j+VE_POST]=0;
  112540. if(ret&1){
  112541. ve->mark[j]=1;
  112542. ve->mark[j+1]=1;
  112543. }
  112544. if(ret&2){
  112545. ve->mark[j]=1;
  112546. if(j>0)ve->mark[j-1]=1;
  112547. }
  112548. if(ret&4)ve->stretch=-1;
  112549. }
  112550. ve->current=last*ve->searchstep;
  112551. {
  112552. long centerW=v->centerW;
  112553. long testW=
  112554. centerW+
  112555. ci->blocksizes[v->W]/4+
  112556. ci->blocksizes[1]/2+
  112557. ci->blocksizes[0]/4;
  112558. j=ve->cursor;
  112559. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112560. working back one window */
  112561. if(j>=testW)return(1);
  112562. ve->cursor=j;
  112563. if(ve->mark[j/ve->searchstep]){
  112564. if(j>centerW){
  112565. #if 0
  112566. if(j>ve->curmark){
  112567. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112568. int l,m;
  112569. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112570. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112571. seq,
  112572. (totalshift+ve->cursor)/44100.,
  112573. (totalshift+j)/44100.);
  112574. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112575. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112576. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112577. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112578. for(m=0;m<VE_BANDS;m++){
  112579. char buf[80];
  112580. sprintf(buf,"delL%d",m);
  112581. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112582. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112583. }
  112584. for(m=0;m<VE_BANDS;m++){
  112585. char buf[80];
  112586. sprintf(buf,"delR%d",m);
  112587. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112588. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112589. }
  112590. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112591. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112592. seq++;
  112593. }
  112594. #endif
  112595. ve->curmark=j;
  112596. if(j>=testW)return(1);
  112597. return(0);
  112598. }
  112599. }
  112600. j+=ve->searchstep;
  112601. }
  112602. }
  112603. return(-1);
  112604. }
  112605. int _ve_envelope_mark(vorbis_dsp_state *v){
  112606. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112607. vorbis_info *vi=v->vi;
  112608. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112609. long centerW=v->centerW;
  112610. long beginW=centerW-ci->blocksizes[v->W]/4;
  112611. long endW=centerW+ci->blocksizes[v->W]/4;
  112612. if(v->W){
  112613. beginW-=ci->blocksizes[v->lW]/4;
  112614. endW+=ci->blocksizes[v->nW]/4;
  112615. }else{
  112616. beginW-=ci->blocksizes[0]/4;
  112617. endW+=ci->blocksizes[0]/4;
  112618. }
  112619. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112620. {
  112621. long first=beginW/ve->searchstep;
  112622. long last=endW/ve->searchstep;
  112623. long i;
  112624. for(i=first;i<last;i++)
  112625. if(ve->mark[i])return(1);
  112626. }
  112627. return(0);
  112628. }
  112629. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112630. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112631. ahead of ve->current */
  112632. int smallshift=shift/e->searchstep;
  112633. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112634. #if 0
  112635. for(i=0;i<VE_BANDS*e->ch;i++)
  112636. memmove(e->filter[i].markers,
  112637. e->filter[i].markers+smallshift,
  112638. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112639. totalshift+=shift;
  112640. #endif
  112641. e->current-=shift;
  112642. if(e->curmark>=0)
  112643. e->curmark-=shift;
  112644. e->cursor-=shift;
  112645. }
  112646. #endif
  112647. /*** End of inlined file: envelope.c ***/
  112648. /*** Start of inlined file: floor0.c ***/
  112649. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112650. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112651. // tasks..
  112652. #if JUCE_MSVC
  112653. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112654. #endif
  112655. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112656. #if JUCE_USE_OGGVORBIS
  112657. #include <stdlib.h>
  112658. #include <string.h>
  112659. #include <math.h>
  112660. /*** Start of inlined file: lsp.h ***/
  112661. #ifndef _V_LSP_H_
  112662. #define _V_LSP_H_
  112663. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112664. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112665. float *lsp,int m,
  112666. float amp,float ampoffset);
  112667. #endif
  112668. /*** End of inlined file: lsp.h ***/
  112669. #include <stdio.h>
  112670. typedef struct {
  112671. int ln;
  112672. int m;
  112673. int **linearmap;
  112674. int n[2];
  112675. vorbis_info_floor0 *vi;
  112676. long bits;
  112677. long frames;
  112678. } vorbis_look_floor0;
  112679. /***********************************************/
  112680. static void floor0_free_info(vorbis_info_floor *i){
  112681. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112682. if(info){
  112683. memset(info,0,sizeof(*info));
  112684. _ogg_free(info);
  112685. }
  112686. }
  112687. static void floor0_free_look(vorbis_look_floor *i){
  112688. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112689. if(look){
  112690. if(look->linearmap){
  112691. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112692. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112693. _ogg_free(look->linearmap);
  112694. }
  112695. memset(look,0,sizeof(*look));
  112696. _ogg_free(look);
  112697. }
  112698. }
  112699. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112700. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112701. int j;
  112702. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112703. info->order=oggpack_read(opb,8);
  112704. info->rate=oggpack_read(opb,16);
  112705. info->barkmap=oggpack_read(opb,16);
  112706. info->ampbits=oggpack_read(opb,6);
  112707. info->ampdB=oggpack_read(opb,8);
  112708. info->numbooks=oggpack_read(opb,4)+1;
  112709. if(info->order<1)goto err_out;
  112710. if(info->rate<1)goto err_out;
  112711. if(info->barkmap<1)goto err_out;
  112712. if(info->numbooks<1)goto err_out;
  112713. for(j=0;j<info->numbooks;j++){
  112714. info->books[j]=oggpack_read(opb,8);
  112715. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112716. }
  112717. return(info);
  112718. err_out:
  112719. floor0_free_info(info);
  112720. return(NULL);
  112721. }
  112722. /* initialize Bark scale and normalization lookups. We could do this
  112723. with static tables, but Vorbis allows a number of possible
  112724. combinations, so it's best to do it computationally.
  112725. The below is authoritative in terms of defining scale mapping.
  112726. Note that the scale depends on the sampling rate as well as the
  112727. linear block and mapping sizes */
  112728. static void floor0_map_lazy_init(vorbis_block *vb,
  112729. vorbis_info_floor *infoX,
  112730. vorbis_look_floor0 *look){
  112731. if(!look->linearmap[vb->W]){
  112732. vorbis_dsp_state *vd=vb->vd;
  112733. vorbis_info *vi=vd->vi;
  112734. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112735. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112736. int W=vb->W;
  112737. int n=ci->blocksizes[W]/2,j;
  112738. /* we choose a scaling constant so that:
  112739. floor(bark(rate/2-1)*C)=mapped-1
  112740. floor(bark(rate/2)*C)=mapped */
  112741. float scale=look->ln/toBARK(info->rate/2.f);
  112742. /* the mapping from a linear scale to a smaller bark scale is
  112743. straightforward. We do *not* make sure that the linear mapping
  112744. does not skip bark-scale bins; the decoder simply skips them and
  112745. the encoder may do what it wishes in filling them. They're
  112746. necessary in some mapping combinations to keep the scale spacing
  112747. accurate */
  112748. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112749. for(j=0;j<n;j++){
  112750. int val=floor( toBARK((info->rate/2.f)/n*j)
  112751. *scale); /* bark numbers represent band edges */
  112752. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112753. look->linearmap[W][j]=val;
  112754. }
  112755. look->linearmap[W][j]=-1;
  112756. look->n[W]=n;
  112757. }
  112758. }
  112759. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112760. vorbis_info_floor *i){
  112761. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112762. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112763. look->m=info->order;
  112764. look->ln=info->barkmap;
  112765. look->vi=info;
  112766. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112767. return look;
  112768. }
  112769. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112770. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112771. vorbis_info_floor0 *info=look->vi;
  112772. int j,k;
  112773. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112774. if(ampraw>0){ /* also handles the -1 out of data case */
  112775. long maxval=(1<<info->ampbits)-1;
  112776. float amp=(float)ampraw/maxval*info->ampdB;
  112777. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112778. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112779. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112780. codebook *b=ci->fullbooks+info->books[booknum];
  112781. float last=0.f;
  112782. /* the additional b->dim is a guard against any possible stack
  112783. smash; b->dim is provably more than we can overflow the
  112784. vector */
  112785. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112786. for(j=0;j<look->m;j+=b->dim)
  112787. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112788. for(j=0;j<look->m;){
  112789. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112790. last=lsp[j-1];
  112791. }
  112792. lsp[look->m]=amp;
  112793. return(lsp);
  112794. }
  112795. }
  112796. eop:
  112797. return(NULL);
  112798. }
  112799. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112800. void *memo,float *out){
  112801. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112802. vorbis_info_floor0 *info=look->vi;
  112803. floor0_map_lazy_init(vb,info,look);
  112804. if(memo){
  112805. float *lsp=(float *)memo;
  112806. float amp=lsp[look->m];
  112807. /* take the coefficients back to a spectral envelope curve */
  112808. vorbis_lsp_to_curve(out,
  112809. look->linearmap[vb->W],
  112810. look->n[vb->W],
  112811. look->ln,
  112812. lsp,look->m,amp,(float)info->ampdB);
  112813. return(1);
  112814. }
  112815. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112816. return(0);
  112817. }
  112818. /* export hooks */
  112819. vorbis_func_floor floor0_exportbundle={
  112820. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112821. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112822. };
  112823. #endif
  112824. /*** End of inlined file: floor0.c ***/
  112825. /*** Start of inlined file: floor1.c ***/
  112826. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112827. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112828. // tasks..
  112829. #if JUCE_MSVC
  112830. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112831. #endif
  112832. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112833. #if JUCE_USE_OGGVORBIS
  112834. #include <stdlib.h>
  112835. #include <string.h>
  112836. #include <math.h>
  112837. #include <stdio.h>
  112838. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112839. typedef struct {
  112840. int sorted_index[VIF_POSIT+2];
  112841. int forward_index[VIF_POSIT+2];
  112842. int reverse_index[VIF_POSIT+2];
  112843. int hineighbor[VIF_POSIT];
  112844. int loneighbor[VIF_POSIT];
  112845. int posts;
  112846. int n;
  112847. int quant_q;
  112848. vorbis_info_floor1 *vi;
  112849. long phrasebits;
  112850. long postbits;
  112851. long frames;
  112852. } vorbis_look_floor1;
  112853. typedef struct lsfit_acc{
  112854. long x0;
  112855. long x1;
  112856. long xa;
  112857. long ya;
  112858. long x2a;
  112859. long y2a;
  112860. long xya;
  112861. long an;
  112862. } lsfit_acc;
  112863. /***********************************************/
  112864. static void floor1_free_info(vorbis_info_floor *i){
  112865. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112866. if(info){
  112867. memset(info,0,sizeof(*info));
  112868. _ogg_free(info);
  112869. }
  112870. }
  112871. static void floor1_free_look(vorbis_look_floor *i){
  112872. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112873. if(look){
  112874. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112875. (float)look->phrasebits/look->frames,
  112876. (float)look->postbits/look->frames,
  112877. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112878. memset(look,0,sizeof(*look));
  112879. _ogg_free(look);
  112880. }
  112881. }
  112882. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112883. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112884. int j,k;
  112885. int count=0;
  112886. int rangebits;
  112887. int maxposit=info->postlist[1];
  112888. int maxclass=-1;
  112889. /* save out partitions */
  112890. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112891. for(j=0;j<info->partitions;j++){
  112892. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112893. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112894. }
  112895. /* save out partition classes */
  112896. for(j=0;j<maxclass+1;j++){
  112897. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112898. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112899. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112900. for(k=0;k<(1<<info->class_subs[j]);k++)
  112901. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112902. }
  112903. /* save out the post list */
  112904. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112905. oggpack_write(opb,ilog2(maxposit),4);
  112906. rangebits=ilog2(maxposit);
  112907. for(j=0,k=0;j<info->partitions;j++){
  112908. count+=info->class_dim[info->partitionclass[j]];
  112909. for(;k<count;k++)
  112910. oggpack_write(opb,info->postlist[k+2],rangebits);
  112911. }
  112912. }
  112913. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112914. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112915. int j,k,count=0,maxclass=-1,rangebits;
  112916. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112917. /* read partitions */
  112918. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112919. for(j=0;j<info->partitions;j++){
  112920. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112921. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112922. }
  112923. /* read partition classes */
  112924. for(j=0;j<maxclass+1;j++){
  112925. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112926. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112927. if(info->class_subs[j]<0)
  112928. goto err_out;
  112929. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112930. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112931. goto err_out;
  112932. for(k=0;k<(1<<info->class_subs[j]);k++){
  112933. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112934. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112935. goto err_out;
  112936. }
  112937. }
  112938. /* read the post list */
  112939. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112940. rangebits=oggpack_read(opb,4);
  112941. for(j=0,k=0;j<info->partitions;j++){
  112942. count+=info->class_dim[info->partitionclass[j]];
  112943. for(;k<count;k++){
  112944. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112945. if(t<0 || t>=(1<<rangebits))
  112946. goto err_out;
  112947. }
  112948. }
  112949. info->postlist[0]=0;
  112950. info->postlist[1]=1<<rangebits;
  112951. return(info);
  112952. err_out:
  112953. floor1_free_info(info);
  112954. return(NULL);
  112955. }
  112956. static int JUCE_CDECL icomp(const void *a,const void *b){
  112957. return(**(int **)a-**(int **)b);
  112958. }
  112959. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112960. vorbis_info_floor *in){
  112961. int *sortpointer[VIF_POSIT+2];
  112962. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112963. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112964. int i,j,n=0;
  112965. look->vi=info;
  112966. look->n=info->postlist[1];
  112967. /* we drop each position value in-between already decoded values,
  112968. and use linear interpolation to predict each new value past the
  112969. edges. The positions are read in the order of the position
  112970. list... we precompute the bounding positions in the lookup. Of
  112971. course, the neighbors can change (if a position is declined), but
  112972. this is an initial mapping */
  112973. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112974. n+=2;
  112975. look->posts=n;
  112976. /* also store a sorted position index */
  112977. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112978. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112979. /* points from sort order back to range number */
  112980. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112981. /* points from range order to sorted position */
  112982. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112983. /* we actually need the post values too */
  112984. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112985. /* quantize values to multiplier spec */
  112986. switch(info->mult){
  112987. case 1: /* 1024 -> 256 */
  112988. look->quant_q=256;
  112989. break;
  112990. case 2: /* 1024 -> 128 */
  112991. look->quant_q=128;
  112992. break;
  112993. case 3: /* 1024 -> 86 */
  112994. look->quant_q=86;
  112995. break;
  112996. case 4: /* 1024 -> 64 */
  112997. look->quant_q=64;
  112998. break;
  112999. }
  113000. /* discover our neighbors for decode where we don't use fit flags
  113001. (that would push the neighbors outward) */
  113002. for(i=0;i<n-2;i++){
  113003. int lo=0;
  113004. int hi=1;
  113005. int lx=0;
  113006. int hx=look->n;
  113007. int currentx=info->postlist[i+2];
  113008. for(j=0;j<i+2;j++){
  113009. int x=info->postlist[j];
  113010. if(x>lx && x<currentx){
  113011. lo=j;
  113012. lx=x;
  113013. }
  113014. if(x<hx && x>currentx){
  113015. hi=j;
  113016. hx=x;
  113017. }
  113018. }
  113019. look->loneighbor[i]=lo;
  113020. look->hineighbor[i]=hi;
  113021. }
  113022. return(look);
  113023. }
  113024. static int render_point(int x0,int x1,int y0,int y1,int x){
  113025. y0&=0x7fff; /* mask off flag */
  113026. y1&=0x7fff;
  113027. {
  113028. int dy=y1-y0;
  113029. int adx=x1-x0;
  113030. int ady=abs(dy);
  113031. int err=ady*(x-x0);
  113032. int off=err/adx;
  113033. if(dy<0)return(y0-off);
  113034. return(y0+off);
  113035. }
  113036. }
  113037. static int vorbis_dBquant(const float *x){
  113038. int i= *x*7.3142857f+1023.5f;
  113039. if(i>1023)return(1023);
  113040. if(i<0)return(0);
  113041. return i;
  113042. }
  113043. static float FLOOR1_fromdB_LOOKUP[256]={
  113044. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113045. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113046. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113047. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113048. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113049. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113050. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113051. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113052. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113053. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113054. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113055. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113056. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113057. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113058. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113059. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113060. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113061. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113062. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113063. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113064. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113065. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113066. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113067. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113068. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113069. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113070. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113071. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113072. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113073. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113074. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113075. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113076. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113077. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113078. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113079. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113080. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113081. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113082. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113083. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113084. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113085. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113086. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113087. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113088. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113089. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113090. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113091. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113092. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113093. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113094. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113095. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113096. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113097. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113098. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113099. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113100. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113101. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113102. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113103. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113104. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113105. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113106. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113107. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113108. };
  113109. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113110. int dy=y1-y0;
  113111. int adx=x1-x0;
  113112. int ady=abs(dy);
  113113. int base=dy/adx;
  113114. int sy=(dy<0?base-1:base+1);
  113115. int x=x0;
  113116. int y=y0;
  113117. int err=0;
  113118. ady-=abs(base*adx);
  113119. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113120. while(++x<x1){
  113121. err=err+ady;
  113122. if(err>=adx){
  113123. err-=adx;
  113124. y+=sy;
  113125. }else{
  113126. y+=base;
  113127. }
  113128. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113129. }
  113130. }
  113131. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113132. int dy=y1-y0;
  113133. int adx=x1-x0;
  113134. int ady=abs(dy);
  113135. int base=dy/adx;
  113136. int sy=(dy<0?base-1:base+1);
  113137. int x=x0;
  113138. int y=y0;
  113139. int err=0;
  113140. ady-=abs(base*adx);
  113141. d[x]=y;
  113142. while(++x<x1){
  113143. err=err+ady;
  113144. if(err>=adx){
  113145. err-=adx;
  113146. y+=sy;
  113147. }else{
  113148. y+=base;
  113149. }
  113150. d[x]=y;
  113151. }
  113152. }
  113153. /* the floor has already been filtered to only include relevant sections */
  113154. static int accumulate_fit(const float *flr,const float *mdct,
  113155. int x0, int x1,lsfit_acc *a,
  113156. int n,vorbis_info_floor1 *info){
  113157. long i;
  113158. 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;
  113159. memset(a,0,sizeof(*a));
  113160. a->x0=x0;
  113161. a->x1=x1;
  113162. if(x1>=n)x1=n-1;
  113163. for(i=x0;i<=x1;i++){
  113164. int quantized=vorbis_dBquant(flr+i);
  113165. if(quantized){
  113166. if(mdct[i]+info->twofitatten>=flr[i]){
  113167. xa += i;
  113168. ya += quantized;
  113169. x2a += i*i;
  113170. y2a += quantized*quantized;
  113171. xya += i*quantized;
  113172. na++;
  113173. }else{
  113174. xb += i;
  113175. yb += quantized;
  113176. x2b += i*i;
  113177. y2b += quantized*quantized;
  113178. xyb += i*quantized;
  113179. nb++;
  113180. }
  113181. }
  113182. }
  113183. xb+=xa;
  113184. yb+=ya;
  113185. x2b+=x2a;
  113186. y2b+=y2a;
  113187. xyb+=xya;
  113188. nb+=na;
  113189. /* weight toward the actually used frequencies if we meet the threshhold */
  113190. {
  113191. int weight=nb*info->twofitweight/(na+1);
  113192. a->xa=xa*weight+xb;
  113193. a->ya=ya*weight+yb;
  113194. a->x2a=x2a*weight+x2b;
  113195. a->y2a=y2a*weight+y2b;
  113196. a->xya=xya*weight+xyb;
  113197. a->an=na*weight+nb;
  113198. }
  113199. return(na);
  113200. }
  113201. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113202. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113203. long x0=a[0].x0;
  113204. long x1=a[fits-1].x1;
  113205. for(i=0;i<fits;i++){
  113206. x+=a[i].xa;
  113207. y+=a[i].ya;
  113208. x2+=a[i].x2a;
  113209. y2+=a[i].y2a;
  113210. xy+=a[i].xya;
  113211. an+=a[i].an;
  113212. }
  113213. if(*y0>=0){
  113214. x+= x0;
  113215. y+= *y0;
  113216. x2+= x0 * x0;
  113217. y2+= *y0 * *y0;
  113218. xy+= *y0 * x0;
  113219. an++;
  113220. }
  113221. if(*y1>=0){
  113222. x+= x1;
  113223. y+= *y1;
  113224. x2+= x1 * x1;
  113225. y2+= *y1 * *y1;
  113226. xy+= *y1 * x1;
  113227. an++;
  113228. }
  113229. if(an){
  113230. /* need 64 bit multiplies, which C doesn't give portably as int */
  113231. double fx=x;
  113232. double fy=y;
  113233. double fx2=x2;
  113234. double fxy=xy;
  113235. double denom=1./(an*fx2-fx*fx);
  113236. double a=(fy*fx2-fxy*fx)*denom;
  113237. double b=(an*fxy-fx*fy)*denom;
  113238. *y0=rint(a+b*x0);
  113239. *y1=rint(a+b*x1);
  113240. /* limit to our range! */
  113241. if(*y0>1023)*y0=1023;
  113242. if(*y1>1023)*y1=1023;
  113243. if(*y0<0)*y0=0;
  113244. if(*y1<0)*y1=0;
  113245. }else{
  113246. *y0=0;
  113247. *y1=0;
  113248. }
  113249. }
  113250. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113251. long y=0;
  113252. int i;
  113253. for(i=0;i<fits && y==0;i++)
  113254. y+=a[i].ya;
  113255. *y0=*y1=y;
  113256. }*/
  113257. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113258. const float *mdct,
  113259. vorbis_info_floor1 *info){
  113260. int dy=y1-y0;
  113261. int adx=x1-x0;
  113262. int ady=abs(dy);
  113263. int base=dy/adx;
  113264. int sy=(dy<0?base-1:base+1);
  113265. int x=x0;
  113266. int y=y0;
  113267. int err=0;
  113268. int val=vorbis_dBquant(mask+x);
  113269. int mse=0;
  113270. int n=0;
  113271. ady-=abs(base*adx);
  113272. mse=(y-val);
  113273. mse*=mse;
  113274. n++;
  113275. if(mdct[x]+info->twofitatten>=mask[x]){
  113276. if(y+info->maxover<val)return(1);
  113277. if(y-info->maxunder>val)return(1);
  113278. }
  113279. while(++x<x1){
  113280. err=err+ady;
  113281. if(err>=adx){
  113282. err-=adx;
  113283. y+=sy;
  113284. }else{
  113285. y+=base;
  113286. }
  113287. val=vorbis_dBquant(mask+x);
  113288. mse+=((y-val)*(y-val));
  113289. n++;
  113290. if(mdct[x]+info->twofitatten>=mask[x]){
  113291. if(val){
  113292. if(y+info->maxover<val)return(1);
  113293. if(y-info->maxunder>val)return(1);
  113294. }
  113295. }
  113296. }
  113297. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113298. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113299. if(mse/n>info->maxerr)return(1);
  113300. return(0);
  113301. }
  113302. static int post_Y(int *A,int *B,int pos){
  113303. if(A[pos]<0)
  113304. return B[pos];
  113305. if(B[pos]<0)
  113306. return A[pos];
  113307. return (A[pos]+B[pos])>>1;
  113308. }
  113309. int *floor1_fit(vorbis_block *vb,void *look_,
  113310. const float *logmdct, /* in */
  113311. const float *logmask){
  113312. long i,j;
  113313. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113314. vorbis_info_floor1 *info=look->vi;
  113315. long n=look->n;
  113316. long posts=look->posts;
  113317. long nonzero=0;
  113318. lsfit_acc fits[VIF_POSIT+1];
  113319. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113320. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113321. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113322. int hineighbor[VIF_POSIT+2];
  113323. int *output=NULL;
  113324. int memo[VIF_POSIT+2];
  113325. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113326. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113327. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113328. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113329. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113330. /* quantize the relevant floor points and collect them into line fit
  113331. structures (one per minimal division) at the same time */
  113332. if(posts==0){
  113333. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113334. }else{
  113335. for(i=0;i<posts-1;i++)
  113336. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113337. look->sorted_index[i+1],fits+i,
  113338. n,info);
  113339. }
  113340. if(nonzero){
  113341. /* start by fitting the implicit base case.... */
  113342. int y0=-200;
  113343. int y1=-200;
  113344. fit_line(fits,posts-1,&y0,&y1);
  113345. fit_valueA[0]=y0;
  113346. fit_valueB[0]=y0;
  113347. fit_valueB[1]=y1;
  113348. fit_valueA[1]=y1;
  113349. /* Non degenerate case */
  113350. /* start progressive splitting. This is a greedy, non-optimal
  113351. algorithm, but simple and close enough to the best
  113352. answer. */
  113353. for(i=2;i<posts;i++){
  113354. int sortpos=look->reverse_index[i];
  113355. int ln=loneighbor[sortpos];
  113356. int hn=hineighbor[sortpos];
  113357. /* eliminate repeat searches of a particular range with a memo */
  113358. if(memo[ln]!=hn){
  113359. /* haven't performed this error search yet */
  113360. int lsortpos=look->reverse_index[ln];
  113361. int hsortpos=look->reverse_index[hn];
  113362. memo[ln]=hn;
  113363. {
  113364. /* A note: we want to bound/minimize *local*, not global, error */
  113365. int lx=info->postlist[ln];
  113366. int hx=info->postlist[hn];
  113367. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113368. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113369. if(ly==-1 || hy==-1){
  113370. exit(1);
  113371. }
  113372. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113373. /* outside error bounds/begin search area. Split it. */
  113374. int ly0=-200;
  113375. int ly1=-200;
  113376. int hy0=-200;
  113377. int hy1=-200;
  113378. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113379. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113380. /* store new edge values */
  113381. fit_valueB[ln]=ly0;
  113382. if(ln==0)fit_valueA[ln]=ly0;
  113383. fit_valueA[i]=ly1;
  113384. fit_valueB[i]=hy0;
  113385. fit_valueA[hn]=hy1;
  113386. if(hn==1)fit_valueB[hn]=hy1;
  113387. if(ly1>=0 || hy0>=0){
  113388. /* store new neighbor values */
  113389. for(j=sortpos-1;j>=0;j--)
  113390. if(hineighbor[j]==hn)
  113391. hineighbor[j]=i;
  113392. else
  113393. break;
  113394. for(j=sortpos+1;j<posts;j++)
  113395. if(loneighbor[j]==ln)
  113396. loneighbor[j]=i;
  113397. else
  113398. break;
  113399. }
  113400. }else{
  113401. fit_valueA[i]=-200;
  113402. fit_valueB[i]=-200;
  113403. }
  113404. }
  113405. }
  113406. }
  113407. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113408. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113409. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113410. /* fill in posts marked as not using a fit; we will zero
  113411. back out to 'unused' when encoding them so long as curve
  113412. interpolation doesn't force them into use */
  113413. for(i=2;i<posts;i++){
  113414. int ln=look->loneighbor[i-2];
  113415. int hn=look->hineighbor[i-2];
  113416. int x0=info->postlist[ln];
  113417. int x1=info->postlist[hn];
  113418. int y0=output[ln];
  113419. int y1=output[hn];
  113420. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113421. int vx=post_Y(fit_valueA,fit_valueB,i);
  113422. if(vx>=0 && predicted!=vx){
  113423. output[i]=vx;
  113424. }else{
  113425. output[i]= predicted|0x8000;
  113426. }
  113427. }
  113428. }
  113429. return(output);
  113430. }
  113431. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113432. int *A,int *B,
  113433. int del){
  113434. long i;
  113435. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113436. long posts=look->posts;
  113437. int *output=NULL;
  113438. if(A && B){
  113439. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113440. for(i=0;i<posts;i++){
  113441. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113442. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113443. }
  113444. }
  113445. return(output);
  113446. }
  113447. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113448. void*look_,
  113449. int *post,int *ilogmask){
  113450. long i,j;
  113451. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113452. vorbis_info_floor1 *info=look->vi;
  113453. long posts=look->posts;
  113454. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113455. int out[VIF_POSIT+2];
  113456. static_codebook **sbooks=ci->book_param;
  113457. codebook *books=ci->fullbooks;
  113458. static long seq=0;
  113459. /* quantize values to multiplier spec */
  113460. if(post){
  113461. for(i=0;i<posts;i++){
  113462. int val=post[i]&0x7fff;
  113463. switch(info->mult){
  113464. case 1: /* 1024 -> 256 */
  113465. val>>=2;
  113466. break;
  113467. case 2: /* 1024 -> 128 */
  113468. val>>=3;
  113469. break;
  113470. case 3: /* 1024 -> 86 */
  113471. val/=12;
  113472. break;
  113473. case 4: /* 1024 -> 64 */
  113474. val>>=4;
  113475. break;
  113476. }
  113477. post[i]=val | (post[i]&0x8000);
  113478. }
  113479. out[0]=post[0];
  113480. out[1]=post[1];
  113481. /* find prediction values for each post and subtract them */
  113482. for(i=2;i<posts;i++){
  113483. int ln=look->loneighbor[i-2];
  113484. int hn=look->hineighbor[i-2];
  113485. int x0=info->postlist[ln];
  113486. int x1=info->postlist[hn];
  113487. int y0=post[ln];
  113488. int y1=post[hn];
  113489. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113490. if((post[i]&0x8000) || (predicted==post[i])){
  113491. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113492. in interpolation */
  113493. out[i]=0;
  113494. }else{
  113495. int headroom=(look->quant_q-predicted<predicted?
  113496. look->quant_q-predicted:predicted);
  113497. int val=post[i]-predicted;
  113498. /* at this point the 'deviation' value is in the range +/- max
  113499. range, but the real, unique range can always be mapped to
  113500. only [0-maxrange). So we want to wrap the deviation into
  113501. this limited range, but do it in the way that least screws
  113502. an essentially gaussian probability distribution. */
  113503. if(val<0)
  113504. if(val<-headroom)
  113505. val=headroom-val-1;
  113506. else
  113507. val=-1-(val<<1);
  113508. else
  113509. if(val>=headroom)
  113510. val= val+headroom;
  113511. else
  113512. val<<=1;
  113513. out[i]=val;
  113514. post[ln]&=0x7fff;
  113515. post[hn]&=0x7fff;
  113516. }
  113517. }
  113518. /* we have everything we need. pack it out */
  113519. /* mark nontrivial floor */
  113520. oggpack_write(opb,1,1);
  113521. /* beginning/end post */
  113522. look->frames++;
  113523. look->postbits+=ilog(look->quant_q-1)*2;
  113524. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113525. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113526. /* partition by partition */
  113527. for(i=0,j=2;i<info->partitions;i++){
  113528. int classx=info->partitionclass[i];
  113529. int cdim=info->class_dim[classx];
  113530. int csubbits=info->class_subs[classx];
  113531. int csub=1<<csubbits;
  113532. int bookas[8]={0,0,0,0,0,0,0,0};
  113533. int cval=0;
  113534. int cshift=0;
  113535. int k,l;
  113536. /* generate the partition's first stage cascade value */
  113537. if(csubbits){
  113538. int maxval[8];
  113539. for(k=0;k<csub;k++){
  113540. int booknum=info->class_subbook[classx][k];
  113541. if(booknum<0){
  113542. maxval[k]=1;
  113543. }else{
  113544. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113545. }
  113546. }
  113547. for(k=0;k<cdim;k++){
  113548. for(l=0;l<csub;l++){
  113549. int val=out[j+k];
  113550. if(val<maxval[l]){
  113551. bookas[k]=l;
  113552. break;
  113553. }
  113554. }
  113555. cval|= bookas[k]<<cshift;
  113556. cshift+=csubbits;
  113557. }
  113558. /* write it */
  113559. look->phrasebits+=
  113560. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113561. #ifdef TRAIN_FLOOR1
  113562. {
  113563. FILE *of;
  113564. char buffer[80];
  113565. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113566. vb->pcmend/2,posts-2,class);
  113567. of=fopen(buffer,"a");
  113568. fprintf(of,"%d\n",cval);
  113569. fclose(of);
  113570. }
  113571. #endif
  113572. }
  113573. /* write post values */
  113574. for(k=0;k<cdim;k++){
  113575. int book=info->class_subbook[classx][bookas[k]];
  113576. if(book>=0){
  113577. /* hack to allow training with 'bad' books */
  113578. if(out[j+k]<(books+book)->entries)
  113579. look->postbits+=vorbis_book_encode(books+book,
  113580. out[j+k],opb);
  113581. /*else
  113582. fprintf(stderr,"+!");*/
  113583. #ifdef TRAIN_FLOOR1
  113584. {
  113585. FILE *of;
  113586. char buffer[80];
  113587. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113588. vb->pcmend/2,posts-2,class,bookas[k]);
  113589. of=fopen(buffer,"a");
  113590. fprintf(of,"%d\n",out[j+k]);
  113591. fclose(of);
  113592. }
  113593. #endif
  113594. }
  113595. }
  113596. j+=cdim;
  113597. }
  113598. {
  113599. /* generate quantized floor equivalent to what we'd unpack in decode */
  113600. /* render the lines */
  113601. int hx=0;
  113602. int lx=0;
  113603. int ly=post[0]*info->mult;
  113604. for(j=1;j<look->posts;j++){
  113605. int current=look->forward_index[j];
  113606. int hy=post[current]&0x7fff;
  113607. if(hy==post[current]){
  113608. hy*=info->mult;
  113609. hx=info->postlist[current];
  113610. render_line0(lx,hx,ly,hy,ilogmask);
  113611. lx=hx;
  113612. ly=hy;
  113613. }
  113614. }
  113615. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113616. seq++;
  113617. return(1);
  113618. }
  113619. }else{
  113620. oggpack_write(opb,0,1);
  113621. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113622. seq++;
  113623. return(0);
  113624. }
  113625. }
  113626. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113627. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113628. vorbis_info_floor1 *info=look->vi;
  113629. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113630. int i,j,k;
  113631. codebook *books=ci->fullbooks;
  113632. /* unpack wrapped/predicted values from stream */
  113633. if(oggpack_read(&vb->opb,1)==1){
  113634. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113635. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113636. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113637. /* partition by partition */
  113638. for(i=0,j=2;i<info->partitions;i++){
  113639. int classx=info->partitionclass[i];
  113640. int cdim=info->class_dim[classx];
  113641. int csubbits=info->class_subs[classx];
  113642. int csub=1<<csubbits;
  113643. int cval=0;
  113644. /* decode the partition's first stage cascade value */
  113645. if(csubbits){
  113646. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113647. if(cval==-1)goto eop;
  113648. }
  113649. for(k=0;k<cdim;k++){
  113650. int book=info->class_subbook[classx][cval&(csub-1)];
  113651. cval>>=csubbits;
  113652. if(book>=0){
  113653. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113654. goto eop;
  113655. }else{
  113656. fit_value[j+k]=0;
  113657. }
  113658. }
  113659. j+=cdim;
  113660. }
  113661. /* unwrap positive values and reconsitute via linear interpolation */
  113662. for(i=2;i<look->posts;i++){
  113663. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113664. info->postlist[look->hineighbor[i-2]],
  113665. fit_value[look->loneighbor[i-2]],
  113666. fit_value[look->hineighbor[i-2]],
  113667. info->postlist[i]);
  113668. int hiroom=look->quant_q-predicted;
  113669. int loroom=predicted;
  113670. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113671. int val=fit_value[i];
  113672. if(val){
  113673. if(val>=room){
  113674. if(hiroom>loroom){
  113675. val = val-loroom;
  113676. }else{
  113677. val = -1-(val-hiroom);
  113678. }
  113679. }else{
  113680. if(val&1){
  113681. val= -((val+1)>>1);
  113682. }else{
  113683. val>>=1;
  113684. }
  113685. }
  113686. fit_value[i]=val+predicted;
  113687. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113688. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113689. }else{
  113690. fit_value[i]=predicted|0x8000;
  113691. }
  113692. }
  113693. return(fit_value);
  113694. }
  113695. eop:
  113696. return(NULL);
  113697. }
  113698. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113699. float *out){
  113700. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113701. vorbis_info_floor1 *info=look->vi;
  113702. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113703. int n=ci->blocksizes[vb->W]/2;
  113704. int j;
  113705. if(memo){
  113706. /* render the lines */
  113707. int *fit_value=(int *)memo;
  113708. int hx=0;
  113709. int lx=0;
  113710. int ly=fit_value[0]*info->mult;
  113711. for(j=1;j<look->posts;j++){
  113712. int current=look->forward_index[j];
  113713. int hy=fit_value[current]&0x7fff;
  113714. if(hy==fit_value[current]){
  113715. hy*=info->mult;
  113716. hx=info->postlist[current];
  113717. render_line(lx,hx,ly,hy,out);
  113718. lx=hx;
  113719. ly=hy;
  113720. }
  113721. }
  113722. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113723. return(1);
  113724. }
  113725. memset(out,0,sizeof(*out)*n);
  113726. return(0);
  113727. }
  113728. /* export hooks */
  113729. vorbis_func_floor floor1_exportbundle={
  113730. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113731. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113732. };
  113733. #endif
  113734. /*** End of inlined file: floor1.c ***/
  113735. /*** Start of inlined file: info.c ***/
  113736. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113737. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113738. // tasks..
  113739. #if JUCE_MSVC
  113740. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113741. #endif
  113742. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113743. #if JUCE_USE_OGGVORBIS
  113744. /* general handling of the header and the vorbis_info structure (and
  113745. substructures) */
  113746. #include <stdlib.h>
  113747. #include <string.h>
  113748. #include <ctype.h>
  113749. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113750. while(bytes--){
  113751. oggpack_write(o,*s++,8);
  113752. }
  113753. }
  113754. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113755. while(bytes--){
  113756. *buf++=oggpack_read(o,8);
  113757. }
  113758. }
  113759. void vorbis_comment_init(vorbis_comment *vc){
  113760. memset(vc,0,sizeof(*vc));
  113761. }
  113762. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113763. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113764. (vc->comments+2)*sizeof(*vc->user_comments));
  113765. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113766. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113767. vc->comment_lengths[vc->comments]=strlen(comment);
  113768. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113769. strcpy(vc->user_comments[vc->comments], comment);
  113770. vc->comments++;
  113771. vc->user_comments[vc->comments]=NULL;
  113772. }
  113773. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113774. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113775. strcpy(comment, tag);
  113776. strcat(comment, "=");
  113777. strcat(comment, contents);
  113778. vorbis_comment_add(vc, comment);
  113779. }
  113780. /* This is more or less the same as strncasecmp - but that doesn't exist
  113781. * everywhere, and this is a fairly trivial function, so we include it */
  113782. static int tagcompare(const char *s1, const char *s2, int n){
  113783. int c=0;
  113784. while(c < n){
  113785. if(toupper(s1[c]) != toupper(s2[c]))
  113786. return !0;
  113787. c++;
  113788. }
  113789. return 0;
  113790. }
  113791. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113792. long i;
  113793. int found = 0;
  113794. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113795. char *fulltag = (char*)alloca(taglen+ 1);
  113796. strcpy(fulltag, tag);
  113797. strcat(fulltag, "=");
  113798. for(i=0;i<vc->comments;i++){
  113799. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113800. if(count == found)
  113801. /* We return a pointer to the data, not a copy */
  113802. return vc->user_comments[i] + taglen;
  113803. else
  113804. found++;
  113805. }
  113806. }
  113807. return NULL; /* didn't find anything */
  113808. }
  113809. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113810. int i,count=0;
  113811. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113812. char *fulltag = (char*)alloca(taglen+1);
  113813. strcpy(fulltag,tag);
  113814. strcat(fulltag, "=");
  113815. for(i=0;i<vc->comments;i++){
  113816. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113817. count++;
  113818. }
  113819. return count;
  113820. }
  113821. void vorbis_comment_clear(vorbis_comment *vc){
  113822. if(vc){
  113823. long i;
  113824. for(i=0;i<vc->comments;i++)
  113825. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113826. if(vc->user_comments)_ogg_free(vc->user_comments);
  113827. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113828. if(vc->vendor)_ogg_free(vc->vendor);
  113829. }
  113830. memset(vc,0,sizeof(*vc));
  113831. }
  113832. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113833. They may be equal, but short will never ge greater than long */
  113834. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113835. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113836. return ci ? ci->blocksizes[zo] : -1;
  113837. }
  113838. /* used by synthesis, which has a full, alloced vi */
  113839. void vorbis_info_init(vorbis_info *vi){
  113840. memset(vi,0,sizeof(*vi));
  113841. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113842. }
  113843. void vorbis_info_clear(vorbis_info *vi){
  113844. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113845. int i;
  113846. if(ci){
  113847. for(i=0;i<ci->modes;i++)
  113848. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113849. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113850. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113851. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113852. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113853. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113854. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113855. for(i=0;i<ci->books;i++){
  113856. if(ci->book_param[i]){
  113857. /* knows if the book was not alloced */
  113858. vorbis_staticbook_destroy(ci->book_param[i]);
  113859. }
  113860. if(ci->fullbooks)
  113861. vorbis_book_clear(ci->fullbooks+i);
  113862. }
  113863. if(ci->fullbooks)
  113864. _ogg_free(ci->fullbooks);
  113865. for(i=0;i<ci->psys;i++)
  113866. _vi_psy_free(ci->psy_param[i]);
  113867. _ogg_free(ci);
  113868. }
  113869. memset(vi,0,sizeof(*vi));
  113870. }
  113871. /* Header packing/unpacking ********************************************/
  113872. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113873. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113874. if(!ci)return(OV_EFAULT);
  113875. vi->version=oggpack_read(opb,32);
  113876. if(vi->version!=0)return(OV_EVERSION);
  113877. vi->channels=oggpack_read(opb,8);
  113878. vi->rate=oggpack_read(opb,32);
  113879. vi->bitrate_upper=oggpack_read(opb,32);
  113880. vi->bitrate_nominal=oggpack_read(opb,32);
  113881. vi->bitrate_lower=oggpack_read(opb,32);
  113882. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113883. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113884. if(vi->rate<1)goto err_out;
  113885. if(vi->channels<1)goto err_out;
  113886. if(ci->blocksizes[0]<8)goto err_out;
  113887. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113888. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113889. return(0);
  113890. err_out:
  113891. vorbis_info_clear(vi);
  113892. return(OV_EBADHEADER);
  113893. }
  113894. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113895. int i;
  113896. int vendorlen=oggpack_read(opb,32);
  113897. if(vendorlen<0)goto err_out;
  113898. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113899. _v_readstring(opb,vc->vendor,vendorlen);
  113900. vc->comments=oggpack_read(opb,32);
  113901. if(vc->comments<0)goto err_out;
  113902. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113903. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113904. for(i=0;i<vc->comments;i++){
  113905. int len=oggpack_read(opb,32);
  113906. if(len<0)goto err_out;
  113907. vc->comment_lengths[i]=len;
  113908. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113909. _v_readstring(opb,vc->user_comments[i],len);
  113910. }
  113911. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113912. return(0);
  113913. err_out:
  113914. vorbis_comment_clear(vc);
  113915. return(OV_EBADHEADER);
  113916. }
  113917. /* all of the real encoding details are here. The modes, books,
  113918. everything */
  113919. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113920. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113921. int i;
  113922. if(!ci)return(OV_EFAULT);
  113923. /* codebooks */
  113924. ci->books=oggpack_read(opb,8)+1;
  113925. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113926. for(i=0;i<ci->books;i++){
  113927. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113928. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113929. }
  113930. /* time backend settings; hooks are unused */
  113931. {
  113932. int times=oggpack_read(opb,6)+1;
  113933. for(i=0;i<times;i++){
  113934. int test=oggpack_read(opb,16);
  113935. if(test<0 || test>=VI_TIMEB)goto err_out;
  113936. }
  113937. }
  113938. /* floor backend settings */
  113939. ci->floors=oggpack_read(opb,6)+1;
  113940. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113941. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113942. for(i=0;i<ci->floors;i++){
  113943. ci->floor_type[i]=oggpack_read(opb,16);
  113944. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113945. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113946. if(!ci->floor_param[i])goto err_out;
  113947. }
  113948. /* residue backend settings */
  113949. ci->residues=oggpack_read(opb,6)+1;
  113950. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113951. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113952. for(i=0;i<ci->residues;i++){
  113953. ci->residue_type[i]=oggpack_read(opb,16);
  113954. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113955. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113956. if(!ci->residue_param[i])goto err_out;
  113957. }
  113958. /* map backend settings */
  113959. ci->maps=oggpack_read(opb,6)+1;
  113960. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113961. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113962. for(i=0;i<ci->maps;i++){
  113963. ci->map_type[i]=oggpack_read(opb,16);
  113964. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113965. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113966. if(!ci->map_param[i])goto err_out;
  113967. }
  113968. /* mode settings */
  113969. ci->modes=oggpack_read(opb,6)+1;
  113970. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113971. for(i=0;i<ci->modes;i++){
  113972. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113973. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113974. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113975. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113976. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113977. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113978. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113979. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113980. }
  113981. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113982. return(0);
  113983. err_out:
  113984. vorbis_info_clear(vi);
  113985. return(OV_EBADHEADER);
  113986. }
  113987. /* The Vorbis header is in three packets; the initial small packet in
  113988. the first page that identifies basic parameters, a second packet
  113989. with bitstream comments and a third packet that holds the
  113990. codebook. */
  113991. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113992. oggpack_buffer opb;
  113993. if(op){
  113994. oggpack_readinit(&opb,op->packet,op->bytes);
  113995. /* Which of the three types of header is this? */
  113996. /* Also verify header-ness, vorbis */
  113997. {
  113998. char buffer[6];
  113999. int packtype=oggpack_read(&opb,8);
  114000. memset(buffer,0,6);
  114001. _v_readstring(&opb,buffer,6);
  114002. if(memcmp(buffer,"vorbis",6)){
  114003. /* not a vorbis header */
  114004. return(OV_ENOTVORBIS);
  114005. }
  114006. switch(packtype){
  114007. case 0x01: /* least significant *bit* is read first */
  114008. if(!op->b_o_s){
  114009. /* Not the initial packet */
  114010. return(OV_EBADHEADER);
  114011. }
  114012. if(vi->rate!=0){
  114013. /* previously initialized info header */
  114014. return(OV_EBADHEADER);
  114015. }
  114016. return(_vorbis_unpack_info(vi,&opb));
  114017. case 0x03: /* least significant *bit* is read first */
  114018. if(vi->rate==0){
  114019. /* um... we didn't get the initial header */
  114020. return(OV_EBADHEADER);
  114021. }
  114022. return(_vorbis_unpack_comment(vc,&opb));
  114023. case 0x05: /* least significant *bit* is read first */
  114024. if(vi->rate==0 || vc->vendor==NULL){
  114025. /* um... we didn;t get the initial header or comments yet */
  114026. return(OV_EBADHEADER);
  114027. }
  114028. return(_vorbis_unpack_books(vi,&opb));
  114029. default:
  114030. /* Not a valid vorbis header type */
  114031. return(OV_EBADHEADER);
  114032. break;
  114033. }
  114034. }
  114035. }
  114036. return(OV_EBADHEADER);
  114037. }
  114038. /* pack side **********************************************************/
  114039. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114040. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114041. if(!ci)return(OV_EFAULT);
  114042. /* preamble */
  114043. oggpack_write(opb,0x01,8);
  114044. _v_writestring(opb,"vorbis", 6);
  114045. /* basic information about the stream */
  114046. oggpack_write(opb,0x00,32);
  114047. oggpack_write(opb,vi->channels,8);
  114048. oggpack_write(opb,vi->rate,32);
  114049. oggpack_write(opb,vi->bitrate_upper,32);
  114050. oggpack_write(opb,vi->bitrate_nominal,32);
  114051. oggpack_write(opb,vi->bitrate_lower,32);
  114052. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114053. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114054. oggpack_write(opb,1,1);
  114055. return(0);
  114056. }
  114057. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114058. char temp[]="Xiph.Org libVorbis I 20050304";
  114059. int bytes = strlen(temp);
  114060. /* preamble */
  114061. oggpack_write(opb,0x03,8);
  114062. _v_writestring(opb,"vorbis", 6);
  114063. /* vendor */
  114064. oggpack_write(opb,bytes,32);
  114065. _v_writestring(opb,temp, bytes);
  114066. /* comments */
  114067. oggpack_write(opb,vc->comments,32);
  114068. if(vc->comments){
  114069. int i;
  114070. for(i=0;i<vc->comments;i++){
  114071. if(vc->user_comments[i]){
  114072. oggpack_write(opb,vc->comment_lengths[i],32);
  114073. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114074. }else{
  114075. oggpack_write(opb,0,32);
  114076. }
  114077. }
  114078. }
  114079. oggpack_write(opb,1,1);
  114080. return(0);
  114081. }
  114082. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114083. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114084. int i;
  114085. if(!ci)return(OV_EFAULT);
  114086. oggpack_write(opb,0x05,8);
  114087. _v_writestring(opb,"vorbis", 6);
  114088. /* books */
  114089. oggpack_write(opb,ci->books-1,8);
  114090. for(i=0;i<ci->books;i++)
  114091. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114092. /* times; hook placeholders */
  114093. oggpack_write(opb,0,6);
  114094. oggpack_write(opb,0,16);
  114095. /* floors */
  114096. oggpack_write(opb,ci->floors-1,6);
  114097. for(i=0;i<ci->floors;i++){
  114098. oggpack_write(opb,ci->floor_type[i],16);
  114099. if(_floor_P[ci->floor_type[i]]->pack)
  114100. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114101. else
  114102. goto err_out;
  114103. }
  114104. /* residues */
  114105. oggpack_write(opb,ci->residues-1,6);
  114106. for(i=0;i<ci->residues;i++){
  114107. oggpack_write(opb,ci->residue_type[i],16);
  114108. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114109. }
  114110. /* maps */
  114111. oggpack_write(opb,ci->maps-1,6);
  114112. for(i=0;i<ci->maps;i++){
  114113. oggpack_write(opb,ci->map_type[i],16);
  114114. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114115. }
  114116. /* modes */
  114117. oggpack_write(opb,ci->modes-1,6);
  114118. for(i=0;i<ci->modes;i++){
  114119. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114120. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114121. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114122. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114123. }
  114124. oggpack_write(opb,1,1);
  114125. return(0);
  114126. err_out:
  114127. return(-1);
  114128. }
  114129. int vorbis_commentheader_out(vorbis_comment *vc,
  114130. ogg_packet *op){
  114131. oggpack_buffer opb;
  114132. oggpack_writeinit(&opb);
  114133. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114134. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114135. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114136. op->bytes=oggpack_bytes(&opb);
  114137. op->b_o_s=0;
  114138. op->e_o_s=0;
  114139. op->granulepos=0;
  114140. op->packetno=1;
  114141. return 0;
  114142. }
  114143. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114144. vorbis_comment *vc,
  114145. ogg_packet *op,
  114146. ogg_packet *op_comm,
  114147. ogg_packet *op_code){
  114148. int ret=OV_EIMPL;
  114149. vorbis_info *vi=v->vi;
  114150. oggpack_buffer opb;
  114151. private_state *b=(private_state*)v->backend_state;
  114152. if(!b){
  114153. ret=OV_EFAULT;
  114154. goto err_out;
  114155. }
  114156. /* first header packet **********************************************/
  114157. oggpack_writeinit(&opb);
  114158. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114159. /* build the packet */
  114160. if(b->header)_ogg_free(b->header);
  114161. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114162. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114163. op->packet=b->header;
  114164. op->bytes=oggpack_bytes(&opb);
  114165. op->b_o_s=1;
  114166. op->e_o_s=0;
  114167. op->granulepos=0;
  114168. op->packetno=0;
  114169. /* second header packet (comments) **********************************/
  114170. oggpack_reset(&opb);
  114171. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114172. if(b->header1)_ogg_free(b->header1);
  114173. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114174. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114175. op_comm->packet=b->header1;
  114176. op_comm->bytes=oggpack_bytes(&opb);
  114177. op_comm->b_o_s=0;
  114178. op_comm->e_o_s=0;
  114179. op_comm->granulepos=0;
  114180. op_comm->packetno=1;
  114181. /* third header packet (modes/codebooks) ****************************/
  114182. oggpack_reset(&opb);
  114183. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114184. if(b->header2)_ogg_free(b->header2);
  114185. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114186. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114187. op_code->packet=b->header2;
  114188. op_code->bytes=oggpack_bytes(&opb);
  114189. op_code->b_o_s=0;
  114190. op_code->e_o_s=0;
  114191. op_code->granulepos=0;
  114192. op_code->packetno=2;
  114193. oggpack_writeclear(&opb);
  114194. return(0);
  114195. err_out:
  114196. oggpack_writeclear(&opb);
  114197. memset(op,0,sizeof(*op));
  114198. memset(op_comm,0,sizeof(*op_comm));
  114199. memset(op_code,0,sizeof(*op_code));
  114200. if(b->header)_ogg_free(b->header);
  114201. if(b->header1)_ogg_free(b->header1);
  114202. if(b->header2)_ogg_free(b->header2);
  114203. b->header=NULL;
  114204. b->header1=NULL;
  114205. b->header2=NULL;
  114206. return(ret);
  114207. }
  114208. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114209. if(granulepos>=0)
  114210. return((double)granulepos/v->vi->rate);
  114211. return(-1);
  114212. }
  114213. #endif
  114214. /*** End of inlined file: info.c ***/
  114215. /*** Start of inlined file: lpc.c ***/
  114216. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114217. are derived from code written by Jutta Degener and Carsten Bormann;
  114218. thus we include their copyright below. The entirety of this file
  114219. is freely redistributable on the condition that both of these
  114220. copyright notices are preserved without modification. */
  114221. /* Preserved Copyright: *********************************************/
  114222. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114223. Technische Universita"t Berlin
  114224. Any use of this software is permitted provided that this notice is not
  114225. removed and that neither the authors nor the Technische Universita"t
  114226. Berlin are deemed to have made any representations as to the
  114227. suitability of this software for any purpose nor are held responsible
  114228. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114229. THIS SOFTWARE.
  114230. As a matter of courtesy, the authors request to be informed about uses
  114231. this software has found, about bugs in this software, and about any
  114232. improvements that may be of general interest.
  114233. Berlin, 28.11.1994
  114234. Jutta Degener
  114235. Carsten Bormann
  114236. *********************************************************************/
  114237. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114238. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114239. // tasks..
  114240. #if JUCE_MSVC
  114241. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114242. #endif
  114243. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114244. #if JUCE_USE_OGGVORBIS
  114245. #include <stdlib.h>
  114246. #include <string.h>
  114247. #include <math.h>
  114248. /* Autocorrelation LPC coeff generation algorithm invented by
  114249. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114250. /* Input : n elements of time doamin data
  114251. Output: m lpc coefficients, excitation energy */
  114252. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114253. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114254. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114255. double error;
  114256. int i,j;
  114257. /* autocorrelation, p+1 lag coefficients */
  114258. j=m+1;
  114259. while(j--){
  114260. double d=0; /* double needed for accumulator depth */
  114261. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114262. aut[j]=d;
  114263. }
  114264. /* Generate lpc coefficients from autocorr values */
  114265. error=aut[0];
  114266. for(i=0;i<m;i++){
  114267. double r= -aut[i+1];
  114268. if(error==0){
  114269. memset(lpci,0,m*sizeof(*lpci));
  114270. return 0;
  114271. }
  114272. /* Sum up this iteration's reflection coefficient; note that in
  114273. Vorbis we don't save it. If anyone wants to recycle this code
  114274. and needs reflection coefficients, save the results of 'r' from
  114275. each iteration. */
  114276. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114277. r/=error;
  114278. /* Update LPC coefficients and total error */
  114279. lpc[i]=r;
  114280. for(j=0;j<i/2;j++){
  114281. double tmp=lpc[j];
  114282. lpc[j]+=r*lpc[i-1-j];
  114283. lpc[i-1-j]+=r*tmp;
  114284. }
  114285. if(i%2)lpc[j]+=lpc[j]*r;
  114286. error*=1.f-r*r;
  114287. }
  114288. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114289. /* we need the error value to know how big an impulse to hit the
  114290. filter with later */
  114291. return error;
  114292. }
  114293. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114294. float *data,long n){
  114295. /* in: coeff[0...m-1] LPC coefficients
  114296. prime[0...m-1] initial values (allocated size of n+m-1)
  114297. out: data[0...n-1] data samples */
  114298. long i,j,o,p;
  114299. float y;
  114300. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114301. if(!prime)
  114302. for(i=0;i<m;i++)
  114303. work[i]=0.f;
  114304. else
  114305. for(i=0;i<m;i++)
  114306. work[i]=prime[i];
  114307. for(i=0;i<n;i++){
  114308. y=0;
  114309. o=i;
  114310. p=m;
  114311. for(j=0;j<m;j++)
  114312. y-=work[o++]*coeff[--p];
  114313. data[i]=work[o]=y;
  114314. }
  114315. }
  114316. #endif
  114317. /*** End of inlined file: lpc.c ***/
  114318. /*** Start of inlined file: lsp.c ***/
  114319. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114320. an iterative root polisher (CACM algorithm 283). It *is* possible
  114321. to confuse this algorithm into not converging; that should only
  114322. happen with absurdly closely spaced roots (very sharp peaks in the
  114323. LPC f response) which in turn should be impossible in our use of
  114324. the code. If this *does* happen anyway, it's a bug in the floor
  114325. finder; find the cause of the confusion (probably a single bin
  114326. spike or accidental near-float-limit resolution problems) and
  114327. correct it. */
  114328. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114329. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114330. // tasks..
  114331. #if JUCE_MSVC
  114332. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114333. #endif
  114334. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114335. #if JUCE_USE_OGGVORBIS
  114336. #include <math.h>
  114337. #include <string.h>
  114338. #include <stdlib.h>
  114339. /*** Start of inlined file: lookup.h ***/
  114340. #ifndef _V_LOOKUP_H_
  114341. #ifdef FLOAT_LOOKUP
  114342. extern float vorbis_coslook(float a);
  114343. extern float vorbis_invsqlook(float a);
  114344. extern float vorbis_invsq2explook(int a);
  114345. extern float vorbis_fromdBlook(float a);
  114346. #endif
  114347. #ifdef INT_LOOKUP
  114348. extern long vorbis_invsqlook_i(long a,long e);
  114349. extern long vorbis_coslook_i(long a);
  114350. extern float vorbis_fromdBlook_i(long a);
  114351. #endif
  114352. #endif
  114353. /*** End of inlined file: lookup.h ***/
  114354. /* three possible LSP to f curve functions; the exact computation
  114355. (float), a lookup based float implementation, and an integer
  114356. implementation. The float lookup is likely the optimal choice on
  114357. any machine with an FPU. The integer implementation is *not* fixed
  114358. point (due to the need for a large dynamic range and thus a
  114359. seperately tracked exponent) and thus much more complex than the
  114360. relatively simple float implementations. It's mostly for future
  114361. work on a fully fixed point implementation for processors like the
  114362. ARM family. */
  114363. /* undefine both for the 'old' but more precise implementation */
  114364. #define FLOAT_LOOKUP
  114365. #undef INT_LOOKUP
  114366. #ifdef FLOAT_LOOKUP
  114367. /*** Start of inlined file: lookup.c ***/
  114368. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114369. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114370. // tasks..
  114371. #if JUCE_MSVC
  114372. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114373. #endif
  114374. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114375. #if JUCE_USE_OGGVORBIS
  114376. #include <math.h>
  114377. /*** Start of inlined file: lookup.h ***/
  114378. #ifndef _V_LOOKUP_H_
  114379. #ifdef FLOAT_LOOKUP
  114380. extern float vorbis_coslook(float a);
  114381. extern float vorbis_invsqlook(float a);
  114382. extern float vorbis_invsq2explook(int a);
  114383. extern float vorbis_fromdBlook(float a);
  114384. #endif
  114385. #ifdef INT_LOOKUP
  114386. extern long vorbis_invsqlook_i(long a,long e);
  114387. extern long vorbis_coslook_i(long a);
  114388. extern float vorbis_fromdBlook_i(long a);
  114389. #endif
  114390. #endif
  114391. /*** End of inlined file: lookup.h ***/
  114392. /*** Start of inlined file: lookup_data.h ***/
  114393. #ifndef _V_LOOKUP_DATA_H_
  114394. #ifdef FLOAT_LOOKUP
  114395. #define COS_LOOKUP_SZ 128
  114396. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114397. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114398. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114399. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114400. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114401. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114402. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114403. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114404. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114405. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114406. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114407. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114408. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114409. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114410. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114411. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114412. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114413. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114414. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114415. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114416. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114417. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114418. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114419. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114420. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114421. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114422. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114423. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114424. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114425. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114426. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114427. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114428. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114429. -1.0000000000000f,
  114430. };
  114431. #define INVSQ_LOOKUP_SZ 32
  114432. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114433. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114434. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114435. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114436. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114437. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114438. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114439. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114440. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114441. 1.000000000000f,
  114442. };
  114443. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114444. #define INVSQ2EXP_LOOKUP_MAX 32
  114445. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114446. INVSQ2EXP_LOOKUP_MIN+1]={
  114447. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114448. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114449. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114450. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114451. 256.f, 181.019336f, 128.f, 90.50966799f,
  114452. 64.f, 45.254834f, 32.f, 22.627417f,
  114453. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114454. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114455. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114456. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114457. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114458. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114459. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114460. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114461. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114462. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114463. 1.525878906e-05f,
  114464. };
  114465. #endif
  114466. #define FROMdB_LOOKUP_SZ 35
  114467. #define FROMdB2_LOOKUP_SZ 32
  114468. #define FROMdB_SHIFT 5
  114469. #define FROMdB2_SHIFT 3
  114470. #define FROMdB2_MASK 31
  114471. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114472. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114473. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114474. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114475. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114476. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114477. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114478. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114479. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114480. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114481. };
  114482. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114483. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114484. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114485. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114486. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114487. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114488. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114489. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114490. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114491. };
  114492. #ifdef INT_LOOKUP
  114493. #define INVSQ_LOOKUP_I_SHIFT 10
  114494. #define INVSQ_LOOKUP_I_MASK 1023
  114495. static long INVSQ_LOOKUP_I[64+1]={
  114496. 92682l, 91966l, 91267l, 90583l,
  114497. 89915l, 89261l, 88621l, 87995l,
  114498. 87381l, 86781l, 86192l, 85616l,
  114499. 85051l, 84497l, 83953l, 83420l,
  114500. 82897l, 82384l, 81880l, 81385l,
  114501. 80899l, 80422l, 79953l, 79492l,
  114502. 79039l, 78594l, 78156l, 77726l,
  114503. 77302l, 76885l, 76475l, 76072l,
  114504. 75674l, 75283l, 74898l, 74519l,
  114505. 74146l, 73778l, 73415l, 73058l,
  114506. 72706l, 72359l, 72016l, 71679l,
  114507. 71347l, 71019l, 70695l, 70376l,
  114508. 70061l, 69750l, 69444l, 69141l,
  114509. 68842l, 68548l, 68256l, 67969l,
  114510. 67685l, 67405l, 67128l, 66855l,
  114511. 66585l, 66318l, 66054l, 65794l,
  114512. 65536l,
  114513. };
  114514. #define COS_LOOKUP_I_SHIFT 9
  114515. #define COS_LOOKUP_I_MASK 511
  114516. #define COS_LOOKUP_I_SZ 128
  114517. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114518. 16384l, 16379l, 16364l, 16340l,
  114519. 16305l, 16261l, 16207l, 16143l,
  114520. 16069l, 15986l, 15893l, 15791l,
  114521. 15679l, 15557l, 15426l, 15286l,
  114522. 15137l, 14978l, 14811l, 14635l,
  114523. 14449l, 14256l, 14053l, 13842l,
  114524. 13623l, 13395l, 13160l, 12916l,
  114525. 12665l, 12406l, 12140l, 11866l,
  114526. 11585l, 11297l, 11003l, 10702l,
  114527. 10394l, 10080l, 9760l, 9434l,
  114528. 9102l, 8765l, 8423l, 8076l,
  114529. 7723l, 7366l, 7005l, 6639l,
  114530. 6270l, 5897l, 5520l, 5139l,
  114531. 4756l, 4370l, 3981l, 3590l,
  114532. 3196l, 2801l, 2404l, 2006l,
  114533. 1606l, 1205l, 804l, 402l,
  114534. 0l, -401l, -803l, -1204l,
  114535. -1605l, -2005l, -2403l, -2800l,
  114536. -3195l, -3589l, -3980l, -4369l,
  114537. -4755l, -5138l, -5519l, -5896l,
  114538. -6269l, -6638l, -7004l, -7365l,
  114539. -7722l, -8075l, -8422l, -8764l,
  114540. -9101l, -9433l, -9759l, -10079l,
  114541. -10393l, -10701l, -11002l, -11296l,
  114542. -11584l, -11865l, -12139l, -12405l,
  114543. -12664l, -12915l, -13159l, -13394l,
  114544. -13622l, -13841l, -14052l, -14255l,
  114545. -14448l, -14634l, -14810l, -14977l,
  114546. -15136l, -15285l, -15425l, -15556l,
  114547. -15678l, -15790l, -15892l, -15985l,
  114548. -16068l, -16142l, -16206l, -16260l,
  114549. -16304l, -16339l, -16363l, -16378l,
  114550. -16383l,
  114551. };
  114552. #endif
  114553. #endif
  114554. /*** End of inlined file: lookup_data.h ***/
  114555. #ifdef FLOAT_LOOKUP
  114556. /* interpolated lookup based cos function, domain 0 to PI only */
  114557. float vorbis_coslook(float a){
  114558. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114559. int i=vorbis_ftoi(d-.5);
  114560. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114561. }
  114562. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114563. float vorbis_invsqlook(float a){
  114564. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114565. int i=vorbis_ftoi(d-.5f);
  114566. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114567. }
  114568. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114569. float vorbis_invsq2explook(int a){
  114570. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114571. }
  114572. #include <stdio.h>
  114573. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114574. float vorbis_fromdBlook(float a){
  114575. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114576. return (i<0)?1.f:
  114577. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114578. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114579. }
  114580. #endif
  114581. #ifdef INT_LOOKUP
  114582. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114583. 16.16 format
  114584. returns in m.8 format */
  114585. long vorbis_invsqlook_i(long a,long e){
  114586. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114587. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114588. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114589. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114590. d)>>16); /* result 1.16 */
  114591. e+=32;
  114592. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114593. e=(e>>1)-8;
  114594. return(val>>e);
  114595. }
  114596. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114597. /* a is in n.12 format */
  114598. float vorbis_fromdBlook_i(long a){
  114599. int i=(-a)>>(12-FROMdB2_SHIFT);
  114600. return (i<0)?1.f:
  114601. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114602. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114603. }
  114604. /* interpolated lookup based cos function, domain 0 to PI only */
  114605. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114606. long vorbis_coslook_i(long a){
  114607. int i=a>>COS_LOOKUP_I_SHIFT;
  114608. int d=a&COS_LOOKUP_I_MASK;
  114609. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114610. COS_LOOKUP_I_SHIFT);
  114611. }
  114612. #endif
  114613. #endif
  114614. /*** End of inlined file: lookup.c ***/
  114615. /* catch this in the build system; we #include for
  114616. compilers (like gcc) that can't inline across
  114617. modules */
  114618. /* side effect: changes *lsp to cosines of lsp */
  114619. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114620. float amp,float ampoffset){
  114621. int i;
  114622. float wdel=M_PI/ln;
  114623. vorbis_fpu_control fpu;
  114624. (void) fpu; // to avoid an unused variable warning
  114625. vorbis_fpu_setround(&fpu);
  114626. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114627. i=0;
  114628. while(i<n){
  114629. int k=map[i];
  114630. int qexp;
  114631. float p=.7071067812f;
  114632. float q=.7071067812f;
  114633. float w=vorbis_coslook(wdel*k);
  114634. float *ftmp=lsp;
  114635. int c=m>>1;
  114636. do{
  114637. q*=ftmp[0]-w;
  114638. p*=ftmp[1]-w;
  114639. ftmp+=2;
  114640. }while(--c);
  114641. if(m&1){
  114642. /* odd order filter; slightly assymetric */
  114643. /* the last coefficient */
  114644. q*=ftmp[0]-w;
  114645. q*=q;
  114646. p*=p*(1.f-w*w);
  114647. }else{
  114648. /* even order filter; still symmetric */
  114649. q*=q*(1.f+w);
  114650. p*=p*(1.f-w);
  114651. }
  114652. q=frexp(p+q,&qexp);
  114653. q=vorbis_fromdBlook(amp*
  114654. vorbis_invsqlook(q)*
  114655. vorbis_invsq2explook(qexp+m)-
  114656. ampoffset);
  114657. do{
  114658. curve[i++]*=q;
  114659. }while(map[i]==k);
  114660. }
  114661. vorbis_fpu_restore(fpu);
  114662. }
  114663. #else
  114664. #ifdef INT_LOOKUP
  114665. /*** Start of inlined file: lookup.c ***/
  114666. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114667. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114668. // tasks..
  114669. #if JUCE_MSVC
  114670. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114671. #endif
  114672. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114673. #if JUCE_USE_OGGVORBIS
  114674. #include <math.h>
  114675. /*** Start of inlined file: lookup.h ***/
  114676. #ifndef _V_LOOKUP_H_
  114677. #ifdef FLOAT_LOOKUP
  114678. extern float vorbis_coslook(float a);
  114679. extern float vorbis_invsqlook(float a);
  114680. extern float vorbis_invsq2explook(int a);
  114681. extern float vorbis_fromdBlook(float a);
  114682. #endif
  114683. #ifdef INT_LOOKUP
  114684. extern long vorbis_invsqlook_i(long a,long e);
  114685. extern long vorbis_coslook_i(long a);
  114686. extern float vorbis_fromdBlook_i(long a);
  114687. #endif
  114688. #endif
  114689. /*** End of inlined file: lookup.h ***/
  114690. /*** Start of inlined file: lookup_data.h ***/
  114691. #ifndef _V_LOOKUP_DATA_H_
  114692. #ifdef FLOAT_LOOKUP
  114693. #define COS_LOOKUP_SZ 128
  114694. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114695. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114696. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114697. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114698. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114699. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114700. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114701. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114702. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114703. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114704. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114705. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114706. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114707. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114708. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114709. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114710. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114711. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114712. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114713. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114714. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114715. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114716. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114717. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114718. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114719. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114720. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114721. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114722. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114723. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114724. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114725. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114726. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114727. -1.0000000000000f,
  114728. };
  114729. #define INVSQ_LOOKUP_SZ 32
  114730. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114731. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114732. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114733. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114734. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114735. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114736. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114737. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114738. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114739. 1.000000000000f,
  114740. };
  114741. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114742. #define INVSQ2EXP_LOOKUP_MAX 32
  114743. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114744. INVSQ2EXP_LOOKUP_MIN+1]={
  114745. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114746. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114747. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114748. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114749. 256.f, 181.019336f, 128.f, 90.50966799f,
  114750. 64.f, 45.254834f, 32.f, 22.627417f,
  114751. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114752. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114753. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114754. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114755. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114756. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114757. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114758. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114759. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114760. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114761. 1.525878906e-05f,
  114762. };
  114763. #endif
  114764. #define FROMdB_LOOKUP_SZ 35
  114765. #define FROMdB2_LOOKUP_SZ 32
  114766. #define FROMdB_SHIFT 5
  114767. #define FROMdB2_SHIFT 3
  114768. #define FROMdB2_MASK 31
  114769. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114770. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114771. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114772. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114773. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114774. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114775. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114776. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114777. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114778. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114779. };
  114780. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114781. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114782. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114783. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114784. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114785. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114786. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114787. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114788. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114789. };
  114790. #ifdef INT_LOOKUP
  114791. #define INVSQ_LOOKUP_I_SHIFT 10
  114792. #define INVSQ_LOOKUP_I_MASK 1023
  114793. static long INVSQ_LOOKUP_I[64+1]={
  114794. 92682l, 91966l, 91267l, 90583l,
  114795. 89915l, 89261l, 88621l, 87995l,
  114796. 87381l, 86781l, 86192l, 85616l,
  114797. 85051l, 84497l, 83953l, 83420l,
  114798. 82897l, 82384l, 81880l, 81385l,
  114799. 80899l, 80422l, 79953l, 79492l,
  114800. 79039l, 78594l, 78156l, 77726l,
  114801. 77302l, 76885l, 76475l, 76072l,
  114802. 75674l, 75283l, 74898l, 74519l,
  114803. 74146l, 73778l, 73415l, 73058l,
  114804. 72706l, 72359l, 72016l, 71679l,
  114805. 71347l, 71019l, 70695l, 70376l,
  114806. 70061l, 69750l, 69444l, 69141l,
  114807. 68842l, 68548l, 68256l, 67969l,
  114808. 67685l, 67405l, 67128l, 66855l,
  114809. 66585l, 66318l, 66054l, 65794l,
  114810. 65536l,
  114811. };
  114812. #define COS_LOOKUP_I_SHIFT 9
  114813. #define COS_LOOKUP_I_MASK 511
  114814. #define COS_LOOKUP_I_SZ 128
  114815. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114816. 16384l, 16379l, 16364l, 16340l,
  114817. 16305l, 16261l, 16207l, 16143l,
  114818. 16069l, 15986l, 15893l, 15791l,
  114819. 15679l, 15557l, 15426l, 15286l,
  114820. 15137l, 14978l, 14811l, 14635l,
  114821. 14449l, 14256l, 14053l, 13842l,
  114822. 13623l, 13395l, 13160l, 12916l,
  114823. 12665l, 12406l, 12140l, 11866l,
  114824. 11585l, 11297l, 11003l, 10702l,
  114825. 10394l, 10080l, 9760l, 9434l,
  114826. 9102l, 8765l, 8423l, 8076l,
  114827. 7723l, 7366l, 7005l, 6639l,
  114828. 6270l, 5897l, 5520l, 5139l,
  114829. 4756l, 4370l, 3981l, 3590l,
  114830. 3196l, 2801l, 2404l, 2006l,
  114831. 1606l, 1205l, 804l, 402l,
  114832. 0l, -401l, -803l, -1204l,
  114833. -1605l, -2005l, -2403l, -2800l,
  114834. -3195l, -3589l, -3980l, -4369l,
  114835. -4755l, -5138l, -5519l, -5896l,
  114836. -6269l, -6638l, -7004l, -7365l,
  114837. -7722l, -8075l, -8422l, -8764l,
  114838. -9101l, -9433l, -9759l, -10079l,
  114839. -10393l, -10701l, -11002l, -11296l,
  114840. -11584l, -11865l, -12139l, -12405l,
  114841. -12664l, -12915l, -13159l, -13394l,
  114842. -13622l, -13841l, -14052l, -14255l,
  114843. -14448l, -14634l, -14810l, -14977l,
  114844. -15136l, -15285l, -15425l, -15556l,
  114845. -15678l, -15790l, -15892l, -15985l,
  114846. -16068l, -16142l, -16206l, -16260l,
  114847. -16304l, -16339l, -16363l, -16378l,
  114848. -16383l,
  114849. };
  114850. #endif
  114851. #endif
  114852. /*** End of inlined file: lookup_data.h ***/
  114853. #ifdef FLOAT_LOOKUP
  114854. /* interpolated lookup based cos function, domain 0 to PI only */
  114855. float vorbis_coslook(float a){
  114856. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114857. int i=vorbis_ftoi(d-.5);
  114858. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114859. }
  114860. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114861. float vorbis_invsqlook(float a){
  114862. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114863. int i=vorbis_ftoi(d-.5f);
  114864. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114865. }
  114866. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114867. float vorbis_invsq2explook(int a){
  114868. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114869. }
  114870. #include <stdio.h>
  114871. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114872. float vorbis_fromdBlook(float a){
  114873. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114874. return (i<0)?1.f:
  114875. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114876. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114877. }
  114878. #endif
  114879. #ifdef INT_LOOKUP
  114880. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114881. 16.16 format
  114882. returns in m.8 format */
  114883. long vorbis_invsqlook_i(long a,long e){
  114884. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114885. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114886. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114887. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114888. d)>>16); /* result 1.16 */
  114889. e+=32;
  114890. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114891. e=(e>>1)-8;
  114892. return(val>>e);
  114893. }
  114894. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114895. /* a is in n.12 format */
  114896. float vorbis_fromdBlook_i(long a){
  114897. int i=(-a)>>(12-FROMdB2_SHIFT);
  114898. return (i<0)?1.f:
  114899. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114900. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114901. }
  114902. /* interpolated lookup based cos function, domain 0 to PI only */
  114903. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114904. long vorbis_coslook_i(long a){
  114905. int i=a>>COS_LOOKUP_I_SHIFT;
  114906. int d=a&COS_LOOKUP_I_MASK;
  114907. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114908. COS_LOOKUP_I_SHIFT);
  114909. }
  114910. #endif
  114911. #endif
  114912. /*** End of inlined file: lookup.c ***/
  114913. /* catch this in the build system; we #include for
  114914. compilers (like gcc) that can't inline across
  114915. modules */
  114916. static int MLOOP_1[64]={
  114917. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114918. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114919. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114920. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114921. };
  114922. static int MLOOP_2[64]={
  114923. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114924. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114925. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114926. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114927. };
  114928. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114929. /* side effect: changes *lsp to cosines of lsp */
  114930. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114931. float amp,float ampoffset){
  114932. /* 0 <= m < 256 */
  114933. /* set up for using all int later */
  114934. int i;
  114935. int ampoffseti=rint(ampoffset*4096.f);
  114936. int ampi=rint(amp*16.f);
  114937. long *ilsp=alloca(m*sizeof(*ilsp));
  114938. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114939. i=0;
  114940. while(i<n){
  114941. int j,k=map[i];
  114942. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114943. unsigned long qi=46341;
  114944. int qexp=0,shift;
  114945. long wi=vorbis_coslook_i(k*65536/ln);
  114946. qi*=labs(ilsp[0]-wi);
  114947. pi*=labs(ilsp[1]-wi);
  114948. for(j=3;j<m;j+=2){
  114949. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114950. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114951. shift=MLOOP_3[(pi|qi)>>16];
  114952. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114953. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114954. qexp+=shift;
  114955. }
  114956. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114957. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114958. shift=MLOOP_3[(pi|qi)>>16];
  114959. /* pi,qi normalized collectively, both tracked using qexp */
  114960. if(m&1){
  114961. /* odd order filter; slightly assymetric */
  114962. /* the last coefficient */
  114963. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114964. pi=(pi>>shift)<<14;
  114965. qexp+=shift;
  114966. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114967. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114968. shift=MLOOP_3[(pi|qi)>>16];
  114969. pi>>=shift;
  114970. qi>>=shift;
  114971. qexp+=shift-14*((m+1)>>1);
  114972. pi=((pi*pi)>>16);
  114973. qi=((qi*qi)>>16);
  114974. qexp=qexp*2+m;
  114975. pi*=(1<<14)-((wi*wi)>>14);
  114976. qi+=pi>>14;
  114977. }else{
  114978. /* even order filter; still symmetric */
  114979. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114980. worth tracking step by step */
  114981. pi>>=shift;
  114982. qi>>=shift;
  114983. qexp+=shift-7*m;
  114984. pi=((pi*pi)>>16);
  114985. qi=((qi*qi)>>16);
  114986. qexp=qexp*2+m;
  114987. pi*=(1<<14)-wi;
  114988. qi*=(1<<14)+wi;
  114989. qi=(qi+pi)>>14;
  114990. }
  114991. /* we've let the normalization drift because it wasn't important;
  114992. however, for the lookup, things must be normalized again. We
  114993. need at most one right shift or a number of left shifts */
  114994. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114995. qi>>=1; qexp++;
  114996. }else
  114997. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114998. qi<<=1; qexp--;
  114999. }
  115000. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  115001. vorbis_invsqlook_i(qi,qexp)-
  115002. /* m.8, m+n<=8 */
  115003. ampoffseti); /* 8.12[0] */
  115004. curve[i]*=amp;
  115005. while(map[++i]==k)curve[i]*=amp;
  115006. }
  115007. }
  115008. #else
  115009. /* old, nonoptimized but simple version for any poor sap who needs to
  115010. figure out what the hell this code does, or wants the other
  115011. fraction of a dB precision */
  115012. /* side effect: changes *lsp to cosines of lsp */
  115013. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115014. float amp,float ampoffset){
  115015. int i;
  115016. float wdel=M_PI/ln;
  115017. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  115018. i=0;
  115019. while(i<n){
  115020. int j,k=map[i];
  115021. float p=.5f;
  115022. float q=.5f;
  115023. float w=2.f*cos(wdel*k);
  115024. for(j=1;j<m;j+=2){
  115025. q *= w-lsp[j-1];
  115026. p *= w-lsp[j];
  115027. }
  115028. if(j==m){
  115029. /* odd order filter; slightly assymetric */
  115030. /* the last coefficient */
  115031. q*=w-lsp[j-1];
  115032. p*=p*(4.f-w*w);
  115033. q*=q;
  115034. }else{
  115035. /* even order filter; still symmetric */
  115036. p*=p*(2.f-w);
  115037. q*=q*(2.f+w);
  115038. }
  115039. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115040. curve[i]*=q;
  115041. while(map[++i]==k)curve[i]*=q;
  115042. }
  115043. }
  115044. #endif
  115045. #endif
  115046. static void cheby(float *g, int ord) {
  115047. int i, j;
  115048. g[0] *= .5f;
  115049. for(i=2; i<= ord; i++) {
  115050. for(j=ord; j >= i; j--) {
  115051. g[j-2] -= g[j];
  115052. g[j] += g[j];
  115053. }
  115054. }
  115055. }
  115056. static int JUCE_CDECL comp(const void *a,const void *b){
  115057. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115058. }
  115059. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115060. but there are root sets for which it gets into limit cycles
  115061. (exacerbated by zero suppression) and fails. We can't afford to
  115062. fail, even if the failure is 1 in 100,000,000, so we now use
  115063. Laguerre and later polish with Newton-Raphson (which can then
  115064. afford to fail) */
  115065. #define EPSILON 10e-7
  115066. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115067. int i,m;
  115068. double lastdelta=0.f;
  115069. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115070. for(i=0;i<=ord;i++)defl[i]=a[i];
  115071. for(m=ord;m>0;m--){
  115072. double newx=0.f,delta;
  115073. /* iterate a root */
  115074. while(1){
  115075. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115076. /* eval the polynomial and its first two derivatives */
  115077. for(i=m;i>0;i--){
  115078. ppp = newx*ppp + pp;
  115079. pp = newx*pp + p;
  115080. p = newx*p + defl[i-1];
  115081. }
  115082. /* Laguerre's method */
  115083. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115084. if(denom<0)
  115085. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115086. if(pp>0){
  115087. denom = pp + sqrt(denom);
  115088. if(denom<EPSILON)denom=EPSILON;
  115089. }else{
  115090. denom = pp - sqrt(denom);
  115091. if(denom>-(EPSILON))denom=-(EPSILON);
  115092. }
  115093. delta = m*p/denom;
  115094. newx -= delta;
  115095. if(delta<0.f)delta*=-1;
  115096. if(fabs(delta/newx)<10e-12)break;
  115097. lastdelta=delta;
  115098. }
  115099. r[m-1]=newx;
  115100. /* forward deflation */
  115101. for(i=m;i>0;i--)
  115102. defl[i-1]+=newx*defl[i];
  115103. defl++;
  115104. }
  115105. return(0);
  115106. }
  115107. /* for spit-and-polish only */
  115108. static int Newton_Raphson(float *a,int ord,float *r){
  115109. int i, k, count=0;
  115110. double error=1.f;
  115111. double *root=(double*)alloca(ord*sizeof(*root));
  115112. for(i=0; i<ord;i++) root[i] = r[i];
  115113. while(error>1e-20){
  115114. error=0;
  115115. for(i=0; i<ord; i++) { /* Update each point. */
  115116. double pp=0.,delta;
  115117. double rooti=root[i];
  115118. double p=a[ord];
  115119. for(k=ord-1; k>= 0; k--) {
  115120. pp= pp* rooti + p;
  115121. p = p * rooti + a[k];
  115122. }
  115123. delta = p/pp;
  115124. root[i] -= delta;
  115125. error+= delta*delta;
  115126. }
  115127. if(count>40)return(-1);
  115128. count++;
  115129. }
  115130. /* Replaced the original bubble sort with a real sort. With your
  115131. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115132. for(i=0; i<ord;i++) r[i] = root[i];
  115133. return(0);
  115134. }
  115135. /* Convert lpc coefficients to lsp coefficients */
  115136. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115137. int order2=(m+1)>>1;
  115138. int g1_order,g2_order;
  115139. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115140. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115141. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115142. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115143. int i;
  115144. /* even and odd are slightly different base cases */
  115145. g1_order=(m+1)>>1;
  115146. g2_order=(m) >>1;
  115147. /* Compute the lengths of the x polynomials. */
  115148. /* Compute the first half of K & R F1 & F2 polynomials. */
  115149. /* Compute half of the symmetric and antisymmetric polynomials. */
  115150. /* Remove the roots at +1 and -1. */
  115151. g1[g1_order] = 1.f;
  115152. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115153. g2[g2_order] = 1.f;
  115154. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115155. if(g1_order>g2_order){
  115156. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115157. }else{
  115158. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115159. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115160. }
  115161. /* Convert into polynomials in cos(alpha) */
  115162. cheby(g1,g1_order);
  115163. cheby(g2,g2_order);
  115164. /* Find the roots of the 2 even polynomials.*/
  115165. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115166. Laguerre_With_Deflation(g2,g2_order,g2r))
  115167. return(-1);
  115168. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115169. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115170. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115171. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115172. for(i=0;i<g1_order;i++)
  115173. lsp[i*2] = acos(g1r[i]);
  115174. for(i=0;i<g2_order;i++)
  115175. lsp[i*2+1] = acos(g2r[i]);
  115176. return(0);
  115177. }
  115178. #endif
  115179. /*** End of inlined file: lsp.c ***/
  115180. /*** Start of inlined file: mapping0.c ***/
  115181. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115182. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115183. // tasks..
  115184. #if JUCE_MSVC
  115185. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115186. #endif
  115187. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115188. #if JUCE_USE_OGGVORBIS
  115189. #include <stdlib.h>
  115190. #include <stdio.h>
  115191. #include <string.h>
  115192. #include <math.h>
  115193. /* simplistic, wasteful way of doing this (unique lookup for each
  115194. mode/submapping); there should be a central repository for
  115195. identical lookups. That will require minor work, so I'm putting it
  115196. off as low priority.
  115197. Why a lookup for each backend in a given mode? Because the
  115198. blocksize is set by the mode, and low backend lookups may require
  115199. parameters from other areas of the mode/mapping */
  115200. static void mapping0_free_info(vorbis_info_mapping *i){
  115201. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115202. if(info){
  115203. memset(info,0,sizeof(*info));
  115204. _ogg_free(info);
  115205. }
  115206. }
  115207. static int ilog3(unsigned int v){
  115208. int ret=0;
  115209. if(v)--v;
  115210. while(v){
  115211. ret++;
  115212. v>>=1;
  115213. }
  115214. return(ret);
  115215. }
  115216. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115217. oggpack_buffer *opb){
  115218. int i;
  115219. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115220. /* another 'we meant to do it this way' hack... up to beta 4, we
  115221. packed 4 binary zeros here to signify one submapping in use. We
  115222. now redefine that to mean four bitflags that indicate use of
  115223. deeper features; bit0:submappings, bit1:coupling,
  115224. bit2,3:reserved. This is backward compatable with all actual uses
  115225. of the beta code. */
  115226. if(info->submaps>1){
  115227. oggpack_write(opb,1,1);
  115228. oggpack_write(opb,info->submaps-1,4);
  115229. }else
  115230. oggpack_write(opb,0,1);
  115231. if(info->coupling_steps>0){
  115232. oggpack_write(opb,1,1);
  115233. oggpack_write(opb,info->coupling_steps-1,8);
  115234. for(i=0;i<info->coupling_steps;i++){
  115235. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115236. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115237. }
  115238. }else
  115239. oggpack_write(opb,0,1);
  115240. oggpack_write(opb,0,2); /* 2,3:reserved */
  115241. /* we don't write the channel submappings if we only have one... */
  115242. if(info->submaps>1){
  115243. for(i=0;i<vi->channels;i++)
  115244. oggpack_write(opb,info->chmuxlist[i],4);
  115245. }
  115246. for(i=0;i<info->submaps;i++){
  115247. oggpack_write(opb,0,8); /* time submap unused */
  115248. oggpack_write(opb,info->floorsubmap[i],8);
  115249. oggpack_write(opb,info->residuesubmap[i],8);
  115250. }
  115251. }
  115252. /* also responsible for range checking */
  115253. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115254. int i;
  115255. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115256. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115257. memset(info,0,sizeof(*info));
  115258. if(oggpack_read(opb,1))
  115259. info->submaps=oggpack_read(opb,4)+1;
  115260. else
  115261. info->submaps=1;
  115262. if(oggpack_read(opb,1)){
  115263. info->coupling_steps=oggpack_read(opb,8)+1;
  115264. for(i=0;i<info->coupling_steps;i++){
  115265. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115266. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115267. if(testM<0 ||
  115268. testA<0 ||
  115269. testM==testA ||
  115270. testM>=vi->channels ||
  115271. testA>=vi->channels) goto err_out;
  115272. }
  115273. }
  115274. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115275. if(info->submaps>1){
  115276. for(i=0;i<vi->channels;i++){
  115277. info->chmuxlist[i]=oggpack_read(opb,4);
  115278. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115279. }
  115280. }
  115281. for(i=0;i<info->submaps;i++){
  115282. oggpack_read(opb,8); /* time submap unused */
  115283. info->floorsubmap[i]=oggpack_read(opb,8);
  115284. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115285. info->residuesubmap[i]=oggpack_read(opb,8);
  115286. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115287. }
  115288. return info;
  115289. err_out:
  115290. mapping0_free_info(info);
  115291. return(NULL);
  115292. }
  115293. #if 0
  115294. static long seq=0;
  115295. static ogg_int64_t total=0;
  115296. static float FLOOR1_fromdB_LOOKUP[256]={
  115297. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115298. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115299. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115300. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115301. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115302. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115303. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115304. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115305. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115306. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115307. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115308. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115309. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115310. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115311. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115312. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115313. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115314. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115315. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115316. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115317. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115318. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115319. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115320. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115321. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115322. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115323. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115324. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115325. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115326. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115327. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115328. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115329. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115330. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115331. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115332. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115333. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115334. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115335. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115336. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115337. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115338. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115339. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115340. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115341. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115342. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115343. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115344. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115345. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115346. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115347. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115348. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115349. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115350. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115351. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115352. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115353. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115354. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115355. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115356. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115357. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115358. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115359. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115360. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115361. };
  115362. #endif
  115363. extern int *floor1_fit(vorbis_block *vb,void *look,
  115364. const float *logmdct, /* in */
  115365. const float *logmask);
  115366. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115367. int *A,int *B,
  115368. int del);
  115369. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115370. void*look,
  115371. int *post,int *ilogmask);
  115372. static int mapping0_forward(vorbis_block *vb){
  115373. vorbis_dsp_state *vd=vb->vd;
  115374. vorbis_info *vi=vd->vi;
  115375. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115376. private_state *b=(private_state*)vb->vd->backend_state;
  115377. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115378. int n=vb->pcmend;
  115379. int i,j,k;
  115380. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115381. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115382. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115383. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115384. float global_ampmax=vbi->ampmax;
  115385. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115386. int blocktype=vbi->blocktype;
  115387. int modenumber=vb->W;
  115388. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115389. vorbis_look_psy *psy_look=
  115390. b->psy+blocktype+(vb->W?2:0);
  115391. vb->mode=modenumber;
  115392. for(i=0;i<vi->channels;i++){
  115393. float scale=4.f/n;
  115394. float scale_dB;
  115395. float *pcm =vb->pcm[i];
  115396. float *logfft =pcm;
  115397. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115398. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115399. todB estimation used on IEEE 754
  115400. compliant machines had a bug that
  115401. returned dB values about a third
  115402. of a decibel too high. The bug
  115403. was harmless because tunings
  115404. implicitly took that into
  115405. account. However, fixing the bug
  115406. in the estimator requires
  115407. changing all the tunings as well.
  115408. For now, it's easier to sync
  115409. things back up here, and
  115410. recalibrate the tunings in the
  115411. next major model upgrade. */
  115412. #if 0
  115413. if(vi->channels==2)
  115414. if(i==0)
  115415. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115416. else
  115417. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115418. #endif
  115419. /* window the PCM data */
  115420. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115421. #if 0
  115422. if(vi->channels==2)
  115423. if(i==0)
  115424. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115425. else
  115426. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115427. #endif
  115428. /* transform the PCM data */
  115429. /* only MDCT right now.... */
  115430. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115431. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115432. drft_forward(&b->fft_look[vb->W],pcm);
  115433. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115434. original todB estimation used on
  115435. IEEE 754 compliant machines had a
  115436. bug that returned dB values about
  115437. a third of a decibel too high.
  115438. The bug was harmless because
  115439. tunings implicitly took that into
  115440. account. However, fixing the bug
  115441. in the estimator requires
  115442. changing all the tunings as well.
  115443. For now, it's easier to sync
  115444. things back up here, and
  115445. recalibrate the tunings in the
  115446. next major model upgrade. */
  115447. local_ampmax[i]=logfft[0];
  115448. for(j=1;j<n-1;j+=2){
  115449. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115450. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115451. .345 is a hack; the original todB
  115452. estimation used on IEEE 754
  115453. compliant machines had a bug that
  115454. returned dB values about a third
  115455. of a decibel too high. The bug
  115456. was harmless because tunings
  115457. implicitly took that into
  115458. account. However, fixing the bug
  115459. in the estimator requires
  115460. changing all the tunings as well.
  115461. For now, it's easier to sync
  115462. things back up here, and
  115463. recalibrate the tunings in the
  115464. next major model upgrade. */
  115465. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115466. }
  115467. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115468. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115469. #if 0
  115470. if(vi->channels==2){
  115471. if(i==0){
  115472. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115473. }else{
  115474. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115475. }
  115476. }
  115477. #endif
  115478. }
  115479. {
  115480. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115481. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115482. for(i=0;i<vi->channels;i++){
  115483. /* the encoder setup assumes that all the modes used by any
  115484. specific bitrate tweaking use the same floor */
  115485. int submap=info->chmuxlist[i];
  115486. /* the following makes things clearer to *me* anyway */
  115487. float *mdct =gmdct[i];
  115488. float *logfft =vb->pcm[i];
  115489. float *logmdct =logfft+n/2;
  115490. float *logmask =logfft;
  115491. vb->mode=modenumber;
  115492. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115493. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115494. for(j=0;j<n/2;j++)
  115495. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115496. todB estimation used on IEEE 754
  115497. compliant machines had a bug that
  115498. returned dB values about a third
  115499. of a decibel too high. The bug
  115500. was harmless because tunings
  115501. implicitly took that into
  115502. account. However, fixing the bug
  115503. in the estimator requires
  115504. changing all the tunings as well.
  115505. For now, it's easier to sync
  115506. things back up here, and
  115507. recalibrate the tunings in the
  115508. next major model upgrade. */
  115509. #if 0
  115510. if(vi->channels==2){
  115511. if(i==0)
  115512. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115513. else
  115514. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115515. }else{
  115516. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115517. }
  115518. #endif
  115519. /* first step; noise masking. Not only does 'noise masking'
  115520. give us curves from which we can decide how much resolution
  115521. to give noise parts of the spectrum, it also implicitly hands
  115522. us a tonality estimate (the larger the value in the
  115523. 'noise_depth' vector, the more tonal that area is) */
  115524. _vp_noisemask(psy_look,
  115525. logmdct,
  115526. noise); /* noise does not have by-frequency offset
  115527. bias applied yet */
  115528. #if 0
  115529. if(vi->channels==2){
  115530. if(i==0)
  115531. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115532. else
  115533. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115534. }
  115535. #endif
  115536. /* second step: 'all the other crap'; all the stuff that isn't
  115537. computed/fit for bitrate management goes in the second psy
  115538. vector. This includes tone masking, peak limiting and ATH */
  115539. _vp_tonemask(psy_look,
  115540. logfft,
  115541. tone,
  115542. global_ampmax,
  115543. local_ampmax[i]);
  115544. #if 0
  115545. if(vi->channels==2){
  115546. if(i==0)
  115547. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115548. else
  115549. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115550. }
  115551. #endif
  115552. /* third step; we offset the noise vectors, overlay tone
  115553. masking. We then do a floor1-specific line fit. If we're
  115554. performing bitrate management, the line fit is performed
  115555. multiple times for up/down tweakage on demand. */
  115556. #if 0
  115557. {
  115558. float aotuv[psy_look->n];
  115559. #endif
  115560. _vp_offset_and_mix(psy_look,
  115561. noise,
  115562. tone,
  115563. 1,
  115564. logmask,
  115565. mdct,
  115566. logmdct);
  115567. #if 0
  115568. if(vi->channels==2){
  115569. if(i==0)
  115570. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115571. else
  115572. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115573. }
  115574. }
  115575. #endif
  115576. #if 0
  115577. if(vi->channels==2){
  115578. if(i==0)
  115579. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115580. else
  115581. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115582. }
  115583. #endif
  115584. /* this algorithm is hardwired to floor 1 for now; abort out if
  115585. we're *not* floor1. This won't happen unless someone has
  115586. broken the encode setup lib. Guard it anyway. */
  115587. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115588. floor_posts[i][PACKETBLOBS/2]=
  115589. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115590. logmdct,
  115591. logmask);
  115592. /* are we managing bitrate? If so, perform two more fits for
  115593. later rate tweaking (fits represent hi/lo) */
  115594. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115595. /* higher rate by way of lower noise curve */
  115596. _vp_offset_and_mix(psy_look,
  115597. noise,
  115598. tone,
  115599. 2,
  115600. logmask,
  115601. mdct,
  115602. logmdct);
  115603. #if 0
  115604. if(vi->channels==2){
  115605. if(i==0)
  115606. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115607. else
  115608. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115609. }
  115610. #endif
  115611. floor_posts[i][PACKETBLOBS-1]=
  115612. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115613. logmdct,
  115614. logmask);
  115615. /* lower rate by way of higher noise curve */
  115616. _vp_offset_and_mix(psy_look,
  115617. noise,
  115618. tone,
  115619. 0,
  115620. logmask,
  115621. mdct,
  115622. logmdct);
  115623. #if 0
  115624. if(vi->channels==2)
  115625. if(i==0)
  115626. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115627. else
  115628. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115629. #endif
  115630. floor_posts[i][0]=
  115631. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115632. logmdct,
  115633. logmask);
  115634. /* we also interpolate a range of intermediate curves for
  115635. intermediate rates */
  115636. for(k=1;k<PACKETBLOBS/2;k++)
  115637. floor_posts[i][k]=
  115638. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115639. floor_posts[i][0],
  115640. floor_posts[i][PACKETBLOBS/2],
  115641. k*65536/(PACKETBLOBS/2));
  115642. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115643. floor_posts[i][k]=
  115644. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115645. floor_posts[i][PACKETBLOBS/2],
  115646. floor_posts[i][PACKETBLOBS-1],
  115647. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115648. }
  115649. }
  115650. }
  115651. vbi->ampmax=global_ampmax;
  115652. /*
  115653. the next phases are performed once for vbr-only and PACKETBLOB
  115654. times for bitrate managed modes.
  115655. 1) encode actual mode being used
  115656. 2) encode the floor for each channel, compute coded mask curve/res
  115657. 3) normalize and couple.
  115658. 4) encode residue
  115659. 5) save packet bytes to the packetblob vector
  115660. */
  115661. /* iterate over the many masking curve fits we've created */
  115662. {
  115663. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115664. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115665. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115666. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115667. float **mag_memo;
  115668. int **mag_sort;
  115669. if(info->coupling_steps){
  115670. mag_memo=_vp_quantize_couple_memo(vb,
  115671. &ci->psy_g_param,
  115672. psy_look,
  115673. info,
  115674. gmdct);
  115675. mag_sort=_vp_quantize_couple_sort(vb,
  115676. psy_look,
  115677. info,
  115678. mag_memo);
  115679. hf_reduction(&ci->psy_g_param,
  115680. psy_look,
  115681. info,
  115682. mag_memo);
  115683. }
  115684. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115685. if(psy_look->vi->normal_channel_p){
  115686. for(i=0;i<vi->channels;i++){
  115687. float *mdct =gmdct[i];
  115688. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115689. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115690. }
  115691. }
  115692. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115693. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115694. k++){
  115695. oggpack_buffer *opb=vbi->packetblob[k];
  115696. /* start out our new packet blob with packet type and mode */
  115697. /* Encode the packet type */
  115698. oggpack_write(opb,0,1);
  115699. /* Encode the modenumber */
  115700. /* Encode frame mode, pre,post windowsize, then dispatch */
  115701. oggpack_write(opb,modenumber,b->modebits);
  115702. if(vb->W){
  115703. oggpack_write(opb,vb->lW,1);
  115704. oggpack_write(opb,vb->nW,1);
  115705. }
  115706. /* encode floor, compute masking curve, sep out residue */
  115707. for(i=0;i<vi->channels;i++){
  115708. int submap=info->chmuxlist[i];
  115709. float *mdct =gmdct[i];
  115710. float *res =vb->pcm[i];
  115711. int *ilogmask=ilogmaskch[i]=
  115712. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115713. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115714. floor_posts[i][k],
  115715. ilogmask);
  115716. #if 0
  115717. {
  115718. char buf[80];
  115719. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115720. float work[n/2];
  115721. for(j=0;j<n/2;j++)
  115722. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115723. _analysis_output(buf,seq,work,n/2,1,1,0);
  115724. }
  115725. #endif
  115726. _vp_remove_floor(psy_look,
  115727. mdct,
  115728. ilogmask,
  115729. res,
  115730. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115731. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115732. #if 0
  115733. {
  115734. char buf[80];
  115735. float work[n/2];
  115736. for(j=0;j<n/2;j++)
  115737. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115738. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115739. _analysis_output(buf,seq,work,n/2,1,1,0);
  115740. }
  115741. #endif
  115742. }
  115743. /* our iteration is now based on masking curve, not prequant and
  115744. coupling. Only one prequant/coupling step */
  115745. /* quantize/couple */
  115746. /* incomplete implementation that assumes the tree is all depth
  115747. one, or no tree at all */
  115748. if(info->coupling_steps){
  115749. _vp_couple(k,
  115750. &ci->psy_g_param,
  115751. psy_look,
  115752. info,
  115753. vb->pcm,
  115754. mag_memo,
  115755. mag_sort,
  115756. ilogmaskch,
  115757. nonzero,
  115758. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115759. }
  115760. /* classify and encode by submap */
  115761. for(i=0;i<info->submaps;i++){
  115762. int ch_in_bundle=0;
  115763. long **classifications;
  115764. int resnum=info->residuesubmap[i];
  115765. for(j=0;j<vi->channels;j++){
  115766. if(info->chmuxlist[j]==i){
  115767. zerobundle[ch_in_bundle]=0;
  115768. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115769. res_bundle[ch_in_bundle]=vb->pcm[j];
  115770. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115771. }
  115772. }
  115773. classifications=_residue_P[ci->residue_type[resnum]]->
  115774. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115775. _residue_P[ci->residue_type[resnum]]->
  115776. forward(opb,vb,b->residue[resnum],
  115777. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115778. }
  115779. /* ok, done encoding. Next protopacket. */
  115780. }
  115781. }
  115782. #if 0
  115783. seq++;
  115784. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115785. #endif
  115786. return(0);
  115787. }
  115788. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115789. vorbis_dsp_state *vd=vb->vd;
  115790. vorbis_info *vi=vd->vi;
  115791. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115792. private_state *b=(private_state*)vd->backend_state;
  115793. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115794. int i,j;
  115795. long n=vb->pcmend=ci->blocksizes[vb->W];
  115796. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115797. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115798. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115799. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115800. /* recover the spectral envelope; store it in the PCM vector for now */
  115801. for(i=0;i<vi->channels;i++){
  115802. int submap=info->chmuxlist[i];
  115803. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115804. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115805. if(floormemo[i])
  115806. nonzero[i]=1;
  115807. else
  115808. nonzero[i]=0;
  115809. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115810. }
  115811. /* channel coupling can 'dirty' the nonzero listing */
  115812. for(i=0;i<info->coupling_steps;i++){
  115813. if(nonzero[info->coupling_mag[i]] ||
  115814. nonzero[info->coupling_ang[i]]){
  115815. nonzero[info->coupling_mag[i]]=1;
  115816. nonzero[info->coupling_ang[i]]=1;
  115817. }
  115818. }
  115819. /* recover the residue into our working vectors */
  115820. for(i=0;i<info->submaps;i++){
  115821. int ch_in_bundle=0;
  115822. for(j=0;j<vi->channels;j++){
  115823. if(info->chmuxlist[j]==i){
  115824. if(nonzero[j])
  115825. zerobundle[ch_in_bundle]=1;
  115826. else
  115827. zerobundle[ch_in_bundle]=0;
  115828. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115829. }
  115830. }
  115831. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115832. inverse(vb,b->residue[info->residuesubmap[i]],
  115833. pcmbundle,zerobundle,ch_in_bundle);
  115834. }
  115835. /* channel coupling */
  115836. for(i=info->coupling_steps-1;i>=0;i--){
  115837. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115838. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115839. for(j=0;j<n/2;j++){
  115840. float mag=pcmM[j];
  115841. float ang=pcmA[j];
  115842. if(mag>0)
  115843. if(ang>0){
  115844. pcmM[j]=mag;
  115845. pcmA[j]=mag-ang;
  115846. }else{
  115847. pcmA[j]=mag;
  115848. pcmM[j]=mag+ang;
  115849. }
  115850. else
  115851. if(ang>0){
  115852. pcmM[j]=mag;
  115853. pcmA[j]=mag+ang;
  115854. }else{
  115855. pcmA[j]=mag;
  115856. pcmM[j]=mag-ang;
  115857. }
  115858. }
  115859. }
  115860. /* compute and apply spectral envelope */
  115861. for(i=0;i<vi->channels;i++){
  115862. float *pcm=vb->pcm[i];
  115863. int submap=info->chmuxlist[i];
  115864. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115865. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115866. floormemo[i],pcm);
  115867. }
  115868. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115869. /* only MDCT right now.... */
  115870. for(i=0;i<vi->channels;i++){
  115871. float *pcm=vb->pcm[i];
  115872. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115873. }
  115874. /* all done! */
  115875. return(0);
  115876. }
  115877. /* export hooks */
  115878. vorbis_func_mapping mapping0_exportbundle={
  115879. &mapping0_pack,
  115880. &mapping0_unpack,
  115881. &mapping0_free_info,
  115882. &mapping0_forward,
  115883. &mapping0_inverse
  115884. };
  115885. #endif
  115886. /*** End of inlined file: mapping0.c ***/
  115887. /*** Start of inlined file: mdct.c ***/
  115888. /* this can also be run as an integer transform by uncommenting a
  115889. define in mdct.h; the integerization is a first pass and although
  115890. it's likely stable for Vorbis, the dynamic range is constrained and
  115891. roundoff isn't done (so it's noisy). Consider it functional, but
  115892. only a starting point. There's no point on a machine with an FPU */
  115893. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115894. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115895. // tasks..
  115896. #if JUCE_MSVC
  115897. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115898. #endif
  115899. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115900. #if JUCE_USE_OGGVORBIS
  115901. #include <stdio.h>
  115902. #include <stdlib.h>
  115903. #include <string.h>
  115904. #include <math.h>
  115905. /* build lookups for trig functions; also pre-figure scaling and
  115906. some window function algebra. */
  115907. void mdct_init(mdct_lookup *lookup,int n){
  115908. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115909. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115910. int i;
  115911. int n2=n>>1;
  115912. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115913. lookup->n=n;
  115914. lookup->trig=T;
  115915. lookup->bitrev=bitrev;
  115916. /* trig lookups... */
  115917. for(i=0;i<n/4;i++){
  115918. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115919. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115920. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115921. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115922. }
  115923. for(i=0;i<n/8;i++){
  115924. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115925. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115926. }
  115927. /* bitreverse lookup... */
  115928. {
  115929. int mask=(1<<(log2n-1))-1,i,j;
  115930. int msb=1<<(log2n-2);
  115931. for(i=0;i<n/8;i++){
  115932. int acc=0;
  115933. for(j=0;msb>>j;j++)
  115934. if((msb>>j)&i)acc|=1<<j;
  115935. bitrev[i*2]=((~acc)&mask)-1;
  115936. bitrev[i*2+1]=acc;
  115937. }
  115938. }
  115939. lookup->scale=FLOAT_CONV(4.f/n);
  115940. }
  115941. /* 8 point butterfly (in place, 4 register) */
  115942. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115943. REG_TYPE r0 = x[6] + x[2];
  115944. REG_TYPE r1 = x[6] - x[2];
  115945. REG_TYPE r2 = x[4] + x[0];
  115946. REG_TYPE r3 = x[4] - x[0];
  115947. x[6] = r0 + r2;
  115948. x[4] = r0 - r2;
  115949. r0 = x[5] - x[1];
  115950. r2 = x[7] - x[3];
  115951. x[0] = r1 + r0;
  115952. x[2] = r1 - r0;
  115953. r0 = x[5] + x[1];
  115954. r1 = x[7] + x[3];
  115955. x[3] = r2 + r3;
  115956. x[1] = r2 - r3;
  115957. x[7] = r1 + r0;
  115958. x[5] = r1 - r0;
  115959. }
  115960. /* 16 point butterfly (in place, 4 register) */
  115961. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115962. REG_TYPE r0 = x[1] - x[9];
  115963. REG_TYPE r1 = x[0] - x[8];
  115964. x[8] += x[0];
  115965. x[9] += x[1];
  115966. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115967. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115968. r0 = x[3] - x[11];
  115969. r1 = x[10] - x[2];
  115970. x[10] += x[2];
  115971. x[11] += x[3];
  115972. x[2] = r0;
  115973. x[3] = r1;
  115974. r0 = x[12] - x[4];
  115975. r1 = x[13] - x[5];
  115976. x[12] += x[4];
  115977. x[13] += x[5];
  115978. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115979. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115980. r0 = x[14] - x[6];
  115981. r1 = x[15] - x[7];
  115982. x[14] += x[6];
  115983. x[15] += x[7];
  115984. x[6] = r0;
  115985. x[7] = r1;
  115986. mdct_butterfly_8(x);
  115987. mdct_butterfly_8(x+8);
  115988. }
  115989. /* 32 point butterfly (in place, 4 register) */
  115990. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115991. REG_TYPE r0 = x[30] - x[14];
  115992. REG_TYPE r1 = x[31] - x[15];
  115993. x[30] += x[14];
  115994. x[31] += x[15];
  115995. x[14] = r0;
  115996. x[15] = r1;
  115997. r0 = x[28] - x[12];
  115998. r1 = x[29] - x[13];
  115999. x[28] += x[12];
  116000. x[29] += x[13];
  116001. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  116002. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  116003. r0 = x[26] - x[10];
  116004. r1 = x[27] - x[11];
  116005. x[26] += x[10];
  116006. x[27] += x[11];
  116007. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  116008. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  116009. r0 = x[24] - x[8];
  116010. r1 = x[25] - x[9];
  116011. x[24] += x[8];
  116012. x[25] += x[9];
  116013. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  116014. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116015. r0 = x[22] - x[6];
  116016. r1 = x[7] - x[23];
  116017. x[22] += x[6];
  116018. x[23] += x[7];
  116019. x[6] = r1;
  116020. x[7] = r0;
  116021. r0 = x[4] - x[20];
  116022. r1 = x[5] - x[21];
  116023. x[20] += x[4];
  116024. x[21] += x[5];
  116025. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116026. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116027. r0 = x[2] - x[18];
  116028. r1 = x[3] - x[19];
  116029. x[18] += x[2];
  116030. x[19] += x[3];
  116031. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116032. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116033. r0 = x[0] - x[16];
  116034. r1 = x[1] - x[17];
  116035. x[16] += x[0];
  116036. x[17] += x[1];
  116037. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116038. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116039. mdct_butterfly_16(x);
  116040. mdct_butterfly_16(x+16);
  116041. }
  116042. /* N point first stage butterfly (in place, 2 register) */
  116043. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116044. DATA_TYPE *x,
  116045. int points){
  116046. DATA_TYPE *x1 = x + points - 8;
  116047. DATA_TYPE *x2 = x + (points>>1) - 8;
  116048. REG_TYPE r0;
  116049. REG_TYPE r1;
  116050. do{
  116051. r0 = x1[6] - x2[6];
  116052. r1 = x1[7] - x2[7];
  116053. x1[6] += x2[6];
  116054. x1[7] += x2[7];
  116055. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116056. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116057. r0 = x1[4] - x2[4];
  116058. r1 = x1[5] - x2[5];
  116059. x1[4] += x2[4];
  116060. x1[5] += x2[5];
  116061. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116062. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116063. r0 = x1[2] - x2[2];
  116064. r1 = x1[3] - x2[3];
  116065. x1[2] += x2[2];
  116066. x1[3] += x2[3];
  116067. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116068. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116069. r0 = x1[0] - x2[0];
  116070. r1 = x1[1] - x2[1];
  116071. x1[0] += x2[0];
  116072. x1[1] += x2[1];
  116073. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116074. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116075. x1-=8;
  116076. x2-=8;
  116077. T+=16;
  116078. }while(x2>=x);
  116079. }
  116080. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116081. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116082. DATA_TYPE *x,
  116083. int points,
  116084. int trigint){
  116085. DATA_TYPE *x1 = x + points - 8;
  116086. DATA_TYPE *x2 = x + (points>>1) - 8;
  116087. REG_TYPE r0;
  116088. REG_TYPE r1;
  116089. do{
  116090. r0 = x1[6] - x2[6];
  116091. r1 = x1[7] - x2[7];
  116092. x1[6] += x2[6];
  116093. x1[7] += x2[7];
  116094. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116095. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116096. T+=trigint;
  116097. r0 = x1[4] - x2[4];
  116098. r1 = x1[5] - x2[5];
  116099. x1[4] += x2[4];
  116100. x1[5] += x2[5];
  116101. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116102. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116103. T+=trigint;
  116104. r0 = x1[2] - x2[2];
  116105. r1 = x1[3] - x2[3];
  116106. x1[2] += x2[2];
  116107. x1[3] += x2[3];
  116108. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116109. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116110. T+=trigint;
  116111. r0 = x1[0] - x2[0];
  116112. r1 = x1[1] - x2[1];
  116113. x1[0] += x2[0];
  116114. x1[1] += x2[1];
  116115. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116116. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116117. T+=trigint;
  116118. x1-=8;
  116119. x2-=8;
  116120. }while(x2>=x);
  116121. }
  116122. STIN void mdct_butterflies(mdct_lookup *init,
  116123. DATA_TYPE *x,
  116124. int points){
  116125. DATA_TYPE *T=init->trig;
  116126. int stages=init->log2n-5;
  116127. int i,j;
  116128. if(--stages>0){
  116129. mdct_butterfly_first(T,x,points);
  116130. }
  116131. for(i=1;--stages>0;i++){
  116132. for(j=0;j<(1<<i);j++)
  116133. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116134. }
  116135. for(j=0;j<points;j+=32)
  116136. mdct_butterfly_32(x+j);
  116137. }
  116138. void mdct_clear(mdct_lookup *l){
  116139. if(l){
  116140. if(l->trig)_ogg_free(l->trig);
  116141. if(l->bitrev)_ogg_free(l->bitrev);
  116142. memset(l,0,sizeof(*l));
  116143. }
  116144. }
  116145. STIN void mdct_bitreverse(mdct_lookup *init,
  116146. DATA_TYPE *x){
  116147. int n = init->n;
  116148. int *bit = init->bitrev;
  116149. DATA_TYPE *w0 = x;
  116150. DATA_TYPE *w1 = x = w0+(n>>1);
  116151. DATA_TYPE *T = init->trig+n;
  116152. do{
  116153. DATA_TYPE *x0 = x+bit[0];
  116154. DATA_TYPE *x1 = x+bit[1];
  116155. REG_TYPE r0 = x0[1] - x1[1];
  116156. REG_TYPE r1 = x0[0] + x1[0];
  116157. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116158. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116159. w1 -= 4;
  116160. r0 = HALVE(x0[1] + x1[1]);
  116161. r1 = HALVE(x0[0] - x1[0]);
  116162. w0[0] = r0 + r2;
  116163. w1[2] = r0 - r2;
  116164. w0[1] = r1 + r3;
  116165. w1[3] = r3 - r1;
  116166. x0 = x+bit[2];
  116167. x1 = x+bit[3];
  116168. r0 = x0[1] - x1[1];
  116169. r1 = x0[0] + x1[0];
  116170. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116171. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116172. r0 = HALVE(x0[1] + x1[1]);
  116173. r1 = HALVE(x0[0] - x1[0]);
  116174. w0[2] = r0 + r2;
  116175. w1[0] = r0 - r2;
  116176. w0[3] = r1 + r3;
  116177. w1[1] = r3 - r1;
  116178. T += 4;
  116179. bit += 4;
  116180. w0 += 4;
  116181. }while(w0<w1);
  116182. }
  116183. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116184. int n=init->n;
  116185. int n2=n>>1;
  116186. int n4=n>>2;
  116187. /* rotate */
  116188. DATA_TYPE *iX = in+n2-7;
  116189. DATA_TYPE *oX = out+n2+n4;
  116190. DATA_TYPE *T = init->trig+n4;
  116191. do{
  116192. oX -= 4;
  116193. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116194. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116195. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116196. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116197. iX -= 8;
  116198. T += 4;
  116199. }while(iX>=in);
  116200. iX = in+n2-8;
  116201. oX = out+n2+n4;
  116202. T = init->trig+n4;
  116203. do{
  116204. T -= 4;
  116205. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116206. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116207. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116208. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116209. iX -= 8;
  116210. oX += 4;
  116211. }while(iX>=in);
  116212. mdct_butterflies(init,out+n2,n2);
  116213. mdct_bitreverse(init,out);
  116214. /* roatate + window */
  116215. {
  116216. DATA_TYPE *oX1=out+n2+n4;
  116217. DATA_TYPE *oX2=out+n2+n4;
  116218. DATA_TYPE *iX =out;
  116219. T =init->trig+n2;
  116220. do{
  116221. oX1-=4;
  116222. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116223. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116224. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116225. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116226. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116227. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116228. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116229. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116230. oX2+=4;
  116231. iX += 8;
  116232. T += 8;
  116233. }while(iX<oX1);
  116234. iX=out+n2+n4;
  116235. oX1=out+n4;
  116236. oX2=oX1;
  116237. do{
  116238. oX1-=4;
  116239. iX-=4;
  116240. oX2[0] = -(oX1[3] = iX[3]);
  116241. oX2[1] = -(oX1[2] = iX[2]);
  116242. oX2[2] = -(oX1[1] = iX[1]);
  116243. oX2[3] = -(oX1[0] = iX[0]);
  116244. oX2+=4;
  116245. }while(oX2<iX);
  116246. iX=out+n2+n4;
  116247. oX1=out+n2+n4;
  116248. oX2=out+n2;
  116249. do{
  116250. oX1-=4;
  116251. oX1[0]= iX[3];
  116252. oX1[1]= iX[2];
  116253. oX1[2]= iX[1];
  116254. oX1[3]= iX[0];
  116255. iX+=4;
  116256. }while(oX1>oX2);
  116257. }
  116258. }
  116259. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116260. int n=init->n;
  116261. int n2=n>>1;
  116262. int n4=n>>2;
  116263. int n8=n>>3;
  116264. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116265. DATA_TYPE *w2=w+n2;
  116266. /* rotate */
  116267. /* window + rotate + step 1 */
  116268. REG_TYPE r0;
  116269. REG_TYPE r1;
  116270. DATA_TYPE *x0=in+n2+n4;
  116271. DATA_TYPE *x1=x0+1;
  116272. DATA_TYPE *T=init->trig+n2;
  116273. int i=0;
  116274. for(i=0;i<n8;i+=2){
  116275. x0 -=4;
  116276. T-=2;
  116277. r0= x0[2] + x1[0];
  116278. r1= x0[0] + x1[2];
  116279. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116280. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116281. x1 +=4;
  116282. }
  116283. x1=in+1;
  116284. for(;i<n2-n8;i+=2){
  116285. T-=2;
  116286. x0 -=4;
  116287. r0= x0[2] - x1[0];
  116288. r1= x0[0] - x1[2];
  116289. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116290. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116291. x1 +=4;
  116292. }
  116293. x0=in+n;
  116294. for(;i<n2;i+=2){
  116295. T-=2;
  116296. x0 -=4;
  116297. r0= -x0[2] - x1[0];
  116298. r1= -x0[0] - x1[2];
  116299. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116300. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116301. x1 +=4;
  116302. }
  116303. mdct_butterflies(init,w+n2,n2);
  116304. mdct_bitreverse(init,w);
  116305. /* roatate + window */
  116306. T=init->trig+n2;
  116307. x0=out+n2;
  116308. for(i=0;i<n4;i++){
  116309. x0--;
  116310. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116311. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116312. w+=2;
  116313. T+=2;
  116314. }
  116315. }
  116316. #endif
  116317. /*** End of inlined file: mdct.c ***/
  116318. /*** Start of inlined file: psy.c ***/
  116319. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116320. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116321. // tasks..
  116322. #if JUCE_MSVC
  116323. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116324. #endif
  116325. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116326. #if JUCE_USE_OGGVORBIS
  116327. #include <stdlib.h>
  116328. #include <math.h>
  116329. #include <string.h>
  116330. /*** Start of inlined file: masking.h ***/
  116331. #ifndef _V_MASKING_H_
  116332. #define _V_MASKING_H_
  116333. /* more detailed ATH; the bass if flat to save stressing the floor
  116334. overly for only a bin or two of savings. */
  116335. #define MAX_ATH 88
  116336. static float ATH[]={
  116337. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116338. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116339. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116340. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116341. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116342. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116343. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116344. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116345. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116346. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116347. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116348. };
  116349. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116350. replaced by an empirically collected data set. The previously
  116351. published values were, far too often, simply on crack. */
  116352. #define EHMER_OFFSET 16
  116353. #define EHMER_MAX 56
  116354. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116355. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116356. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116357. for collection of these curves) */
  116358. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116359. /* 62.5 Hz */
  116360. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116361. -60, -60, -60, -60, -62, -62, -65, -73,
  116362. -69, -68, -68, -67, -70, -70, -72, -74,
  116363. -75, -79, -79, -80, -83, -88, -93, -100,
  116364. -110, -999, -999, -999, -999, -999, -999, -999,
  116365. -999, -999, -999, -999, -999, -999, -999, -999,
  116366. -999, -999, -999, -999, -999, -999, -999, -999},
  116367. { -48, -48, -48, -48, -48, -48, -48, -48,
  116368. -48, -48, -48, -48, -48, -53, -61, -66,
  116369. -66, -68, -67, -70, -76, -76, -72, -73,
  116370. -75, -76, -78, -79, -83, -88, -93, -100,
  116371. -110, -999, -999, -999, -999, -999, -999, -999,
  116372. -999, -999, -999, -999, -999, -999, -999, -999,
  116373. -999, -999, -999, -999, -999, -999, -999, -999},
  116374. { -37, -37, -37, -37, -37, -37, -37, -37,
  116375. -38, -40, -42, -46, -48, -53, -55, -62,
  116376. -65, -58, -56, -56, -61, -60, -65, -67,
  116377. -69, -71, -77, -77, -78, -80, -82, -84,
  116378. -88, -93, -98, -106, -112, -999, -999, -999,
  116379. -999, -999, -999, -999, -999, -999, -999, -999,
  116380. -999, -999, -999, -999, -999, -999, -999, -999},
  116381. { -25, -25, -25, -25, -25, -25, -25, -25,
  116382. -25, -26, -27, -29, -32, -38, -48, -52,
  116383. -52, -50, -48, -48, -51, -52, -54, -60,
  116384. -67, -67, -66, -68, -69, -73, -73, -76,
  116385. -80, -81, -81, -85, -85, -86, -88, -93,
  116386. -100, -110, -999, -999, -999, -999, -999, -999,
  116387. -999, -999, -999, -999, -999, -999, -999, -999},
  116388. { -16, -16, -16, -16, -16, -16, -16, -16,
  116389. -17, -19, -20, -22, -26, -28, -31, -40,
  116390. -47, -39, -39, -40, -42, -43, -47, -51,
  116391. -57, -52, -55, -55, -60, -58, -62, -63,
  116392. -70, -67, -69, -72, -73, -77, -80, -82,
  116393. -83, -87, -90, -94, -98, -104, -115, -999,
  116394. -999, -999, -999, -999, -999, -999, -999, -999},
  116395. { -8, -8, -8, -8, -8, -8, -8, -8,
  116396. -8, -8, -10, -11, -15, -19, -25, -30,
  116397. -34, -31, -30, -31, -29, -32, -35, -42,
  116398. -48, -42, -44, -46, -50, -50, -51, -52,
  116399. -59, -54, -55, -55, -58, -62, -63, -66,
  116400. -72, -73, -76, -75, -78, -80, -80, -81,
  116401. -84, -88, -90, -94, -98, -101, -106, -110}},
  116402. /* 88Hz */
  116403. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116404. -66, -66, -66, -66, -66, -67, -67, -67,
  116405. -76, -72, -71, -74, -76, -76, -75, -78,
  116406. -79, -79, -81, -83, -86, -89, -93, -97,
  116407. -100, -105, -110, -999, -999, -999, -999, -999,
  116408. -999, -999, -999, -999, -999, -999, -999, -999,
  116409. -999, -999, -999, -999, -999, -999, -999, -999},
  116410. { -47, -47, -47, -47, -47, -47, -47, -47,
  116411. -47, -47, -47, -48, -51, -55, -59, -66,
  116412. -66, -66, -67, -66, -68, -69, -70, -74,
  116413. -79, -77, -77, -78, -80, -81, -82, -84,
  116414. -86, -88, -91, -95, -100, -108, -116, -999,
  116415. -999, -999, -999, -999, -999, -999, -999, -999,
  116416. -999, -999, -999, -999, -999, -999, -999, -999},
  116417. { -36, -36, -36, -36, -36, -36, -36, -36,
  116418. -36, -37, -37, -41, -44, -48, -51, -58,
  116419. -62, -60, -57, -59, -59, -60, -63, -65,
  116420. -72, -71, -70, -72, -74, -77, -76, -78,
  116421. -81, -81, -80, -83, -86, -91, -96, -100,
  116422. -105, -110, -999, -999, -999, -999, -999, -999,
  116423. -999, -999, -999, -999, -999, -999, -999, -999},
  116424. { -28, -28, -28, -28, -28, -28, -28, -28,
  116425. -28, -30, -32, -32, -33, -35, -41, -49,
  116426. -50, -49, -47, -48, -48, -52, -51, -57,
  116427. -65, -61, -59, -61, -64, -69, -70, -74,
  116428. -77, -77, -78, -81, -84, -85, -87, -90,
  116429. -92, -96, -100, -107, -112, -999, -999, -999,
  116430. -999, -999, -999, -999, -999, -999, -999, -999},
  116431. { -19, -19, -19, -19, -19, -19, -19, -19,
  116432. -20, -21, -23, -27, -30, -35, -36, -41,
  116433. -46, -44, -42, -40, -41, -41, -43, -48,
  116434. -55, -53, -52, -53, -56, -59, -58, -60,
  116435. -67, -66, -69, -71, -72, -75, -79, -81,
  116436. -84, -87, -90, -93, -97, -101, -107, -114,
  116437. -999, -999, -999, -999, -999, -999, -999, -999},
  116438. { -9, -9, -9, -9, -9, -9, -9, -9,
  116439. -11, -12, -12, -15, -16, -20, -23, -30,
  116440. -37, -34, -33, -34, -31, -32, -32, -38,
  116441. -47, -44, -41, -40, -47, -49, -46, -46,
  116442. -58, -50, -50, -54, -58, -62, -64, -67,
  116443. -67, -70, -72, -76, -79, -83, -87, -91,
  116444. -96, -100, -104, -110, -999, -999, -999, -999}},
  116445. /* 125 Hz */
  116446. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116447. -62, -62, -63, -64, -66, -67, -66, -68,
  116448. -75, -72, -76, -75, -76, -78, -79, -82,
  116449. -84, -85, -90, -94, -101, -110, -999, -999,
  116450. -999, -999, -999, -999, -999, -999, -999, -999,
  116451. -999, -999, -999, -999, -999, -999, -999, -999,
  116452. -999, -999, -999, -999, -999, -999, -999, -999},
  116453. { -59, -59, -59, -59, -59, -59, -59, -59,
  116454. -59, -59, -59, -60, -60, -61, -63, -66,
  116455. -71, -68, -70, -70, -71, -72, -72, -75,
  116456. -81, -78, -79, -82, -83, -86, -90, -97,
  116457. -103, -113, -999, -999, -999, -999, -999, -999,
  116458. -999, -999, -999, -999, -999, -999, -999, -999,
  116459. -999, -999, -999, -999, -999, -999, -999, -999},
  116460. { -53, -53, -53, -53, -53, -53, -53, -53,
  116461. -53, -54, -55, -57, -56, -57, -55, -61,
  116462. -65, -60, -60, -62, -63, -63, -66, -68,
  116463. -74, -73, -75, -75, -78, -80, -80, -82,
  116464. -85, -90, -96, -101, -108, -999, -999, -999,
  116465. -999, -999, -999, -999, -999, -999, -999, -999,
  116466. -999, -999, -999, -999, -999, -999, -999, -999},
  116467. { -46, -46, -46, -46, -46, -46, -46, -46,
  116468. -46, -46, -47, -47, -47, -47, -48, -51,
  116469. -57, -51, -49, -50, -51, -53, -54, -59,
  116470. -66, -60, -62, -67, -67, -70, -72, -75,
  116471. -76, -78, -81, -85, -88, -94, -97, -104,
  116472. -112, -999, -999, -999, -999, -999, -999, -999,
  116473. -999, -999, -999, -999, -999, -999, -999, -999},
  116474. { -36, -36, -36, -36, -36, -36, -36, -36,
  116475. -39, -41, -42, -42, -39, -38, -41, -43,
  116476. -52, -44, -40, -39, -37, -37, -40, -47,
  116477. -54, -50, -48, -50, -55, -61, -59, -62,
  116478. -66, -66, -66, -69, -69, -73, -74, -74,
  116479. -75, -77, -79, -82, -87, -91, -95, -100,
  116480. -108, -115, -999, -999, -999, -999, -999, -999},
  116481. { -28, -26, -24, -22, -20, -20, -23, -29,
  116482. -30, -31, -28, -27, -28, -28, -28, -35,
  116483. -40, -33, -32, -29, -30, -30, -30, -37,
  116484. -45, -41, -37, -38, -45, -47, -47, -48,
  116485. -53, -49, -48, -50, -49, -49, -51, -52,
  116486. -58, -56, -57, -56, -60, -61, -62, -70,
  116487. -72, -74, -78, -83, -88, -93, -100, -106}},
  116488. /* 177 Hz */
  116489. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116490. -999, -110, -105, -100, -95, -91, -87, -83,
  116491. -80, -78, -76, -78, -78, -81, -83, -85,
  116492. -86, -85, -86, -87, -90, -97, -107, -999,
  116493. -999, -999, -999, -999, -999, -999, -999, -999,
  116494. -999, -999, -999, -999, -999, -999, -999, -999,
  116495. -999, -999, -999, -999, -999, -999, -999, -999},
  116496. {-999, -999, -999, -110, -105, -100, -95, -90,
  116497. -85, -81, -77, -73, -70, -67, -67, -68,
  116498. -75, -73, -70, -69, -70, -72, -75, -79,
  116499. -84, -83, -84, -86, -88, -89, -89, -93,
  116500. -98, -105, -112, -999, -999, -999, -999, -999,
  116501. -999, -999, -999, -999, -999, -999, -999, -999,
  116502. -999, -999, -999, -999, -999, -999, -999, -999},
  116503. {-105, -100, -95, -90, -85, -80, -76, -71,
  116504. -68, -68, -65, -63, -63, -62, -62, -64,
  116505. -65, -64, -61, -62, -63, -64, -66, -68,
  116506. -73, -73, -74, -75, -76, -81, -83, -85,
  116507. -88, -89, -92, -95, -100, -108, -999, -999,
  116508. -999, -999, -999, -999, -999, -999, -999, -999,
  116509. -999, -999, -999, -999, -999, -999, -999, -999},
  116510. { -80, -75, -71, -68, -65, -63, -62, -61,
  116511. -61, -61, -61, -59, -56, -57, -53, -50,
  116512. -58, -52, -50, -50, -52, -53, -54, -58,
  116513. -67, -63, -67, -68, -72, -75, -78, -80,
  116514. -81, -81, -82, -85, -89, -90, -93, -97,
  116515. -101, -107, -114, -999, -999, -999, -999, -999,
  116516. -999, -999, -999, -999, -999, -999, -999, -999},
  116517. { -65, -61, -59, -57, -56, -55, -55, -56,
  116518. -56, -57, -55, -53, -52, -47, -44, -44,
  116519. -50, -44, -41, -39, -39, -42, -40, -46,
  116520. -51, -49, -50, -53, -54, -63, -60, -61,
  116521. -62, -66, -66, -66, -70, -73, -74, -75,
  116522. -76, -75, -79, -85, -89, -91, -96, -102,
  116523. -110, -999, -999, -999, -999, -999, -999, -999},
  116524. { -52, -50, -49, -49, -48, -48, -48, -49,
  116525. -50, -50, -49, -46, -43, -39, -35, -33,
  116526. -38, -36, -32, -29, -32, -32, -32, -35,
  116527. -44, -39, -38, -38, -46, -50, -45, -46,
  116528. -53, -50, -50, -50, -54, -54, -53, -53,
  116529. -56, -57, -59, -66, -70, -72, -74, -79,
  116530. -83, -85, -90, -97, -114, -999, -999, -999}},
  116531. /* 250 Hz */
  116532. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116533. -100, -95, -90, -86, -80, -75, -75, -79,
  116534. -80, -79, -80, -81, -82, -88, -95, -103,
  116535. -110, -999, -999, -999, -999, -999, -999, -999,
  116536. -999, -999, -999, -999, -999, -999, -999, -999,
  116537. -999, -999, -999, -999, -999, -999, -999, -999,
  116538. -999, -999, -999, -999, -999, -999, -999, -999},
  116539. {-999, -999, -999, -999, -108, -103, -98, -93,
  116540. -88, -83, -79, -78, -75, -71, -67, -68,
  116541. -73, -73, -72, -73, -75, -77, -80, -82,
  116542. -88, -93, -100, -107, -114, -999, -999, -999,
  116543. -999, -999, -999, -999, -999, -999, -999, -999,
  116544. -999, -999, -999, -999, -999, -999, -999, -999,
  116545. -999, -999, -999, -999, -999, -999, -999, -999},
  116546. {-999, -999, -999, -110, -105, -101, -96, -90,
  116547. -86, -81, -77, -73, -69, -66, -61, -62,
  116548. -66, -64, -62, -65, -66, -70, -72, -76,
  116549. -81, -80, -84, -90, -95, -102, -110, -999,
  116550. -999, -999, -999, -999, -999, -999, -999, -999,
  116551. -999, -999, -999, -999, -999, -999, -999, -999,
  116552. -999, -999, -999, -999, -999, -999, -999, -999},
  116553. {-999, -999, -999, -107, -103, -97, -92, -88,
  116554. -83, -79, -74, -70, -66, -59, -53, -58,
  116555. -62, -55, -54, -54, -54, -58, -61, -62,
  116556. -72, -70, -72, -75, -78, -80, -81, -80,
  116557. -83, -83, -88, -93, -100, -107, -115, -999,
  116558. -999, -999, -999, -999, -999, -999, -999, -999,
  116559. -999, -999, -999, -999, -999, -999, -999, -999},
  116560. {-999, -999, -999, -105, -100, -95, -90, -85,
  116561. -80, -75, -70, -66, -62, -56, -48, -44,
  116562. -48, -46, -46, -43, -46, -48, -48, -51,
  116563. -58, -58, -59, -60, -62, -62, -61, -61,
  116564. -65, -64, -65, -68, -70, -74, -75, -78,
  116565. -81, -86, -95, -110, -999, -999, -999, -999,
  116566. -999, -999, -999, -999, -999, -999, -999, -999},
  116567. {-999, -999, -105, -100, -95, -90, -85, -80,
  116568. -75, -70, -65, -61, -55, -49, -39, -33,
  116569. -40, -35, -32, -38, -40, -33, -35, -37,
  116570. -46, -41, -45, -44, -46, -42, -45, -46,
  116571. -52, -50, -50, -50, -54, -54, -55, -57,
  116572. -62, -64, -66, -68, -70, -76, -81, -90,
  116573. -100, -110, -999, -999, -999, -999, -999, -999}},
  116574. /* 354 hz */
  116575. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116576. -105, -98, -90, -85, -82, -83, -80, -78,
  116577. -84, -79, -80, -83, -87, -89, -91, -93,
  116578. -99, -106, -117, -999, -999, -999, -999, -999,
  116579. -999, -999, -999, -999, -999, -999, -999, -999,
  116580. -999, -999, -999, -999, -999, -999, -999, -999,
  116581. -999, -999, -999, -999, -999, -999, -999, -999},
  116582. {-999, -999, -999, -999, -999, -999, -999, -999,
  116583. -105, -98, -90, -85, -80, -75, -70, -68,
  116584. -74, -72, -74, -77, -80, -82, -85, -87,
  116585. -92, -89, -91, -95, -100, -106, -112, -999,
  116586. -999, -999, -999, -999, -999, -999, -999, -999,
  116587. -999, -999, -999, -999, -999, -999, -999, -999,
  116588. -999, -999, -999, -999, -999, -999, -999, -999},
  116589. {-999, -999, -999, -999, -999, -999, -999, -999,
  116590. -105, -98, -90, -83, -75, -71, -63, -64,
  116591. -67, -62, -64, -67, -70, -73, -77, -81,
  116592. -84, -83, -85, -89, -90, -93, -98, -104,
  116593. -109, -114, -999, -999, -999, -999, -999, -999,
  116594. -999, -999, -999, -999, -999, -999, -999, -999,
  116595. -999, -999, -999, -999, -999, -999, -999, -999},
  116596. {-999, -999, -999, -999, -999, -999, -999, -999,
  116597. -103, -96, -88, -81, -75, -68, -58, -54,
  116598. -56, -54, -56, -56, -58, -60, -63, -66,
  116599. -74, -69, -72, -72, -75, -74, -77, -81,
  116600. -81, -82, -84, -87, -93, -96, -99, -104,
  116601. -110, -999, -999, -999, -999, -999, -999, -999,
  116602. -999, -999, -999, -999, -999, -999, -999, -999},
  116603. {-999, -999, -999, -999, -999, -108, -102, -96,
  116604. -91, -85, -80, -74, -68, -60, -51, -46,
  116605. -48, -46, -43, -45, -47, -47, -49, -48,
  116606. -56, -53, -55, -58, -57, -63, -58, -60,
  116607. -66, -64, -67, -70, -70, -74, -77, -84,
  116608. -86, -89, -91, -93, -94, -101, -109, -118,
  116609. -999, -999, -999, -999, -999, -999, -999, -999},
  116610. {-999, -999, -999, -108, -103, -98, -93, -88,
  116611. -83, -78, -73, -68, -60, -53, -44, -35,
  116612. -38, -38, -34, -34, -36, -40, -41, -44,
  116613. -51, -45, -46, -47, -46, -54, -50, -49,
  116614. -50, -50, -50, -51, -54, -57, -58, -60,
  116615. -66, -66, -66, -64, -65, -68, -77, -82,
  116616. -87, -95, -110, -999, -999, -999, -999, -999}},
  116617. /* 500 Hz */
  116618. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116619. -107, -102, -97, -92, -87, -83, -78, -75,
  116620. -82, -79, -83, -85, -89, -92, -95, -98,
  116621. -101, -105, -109, -113, -999, -999, -999, -999,
  116622. -999, -999, -999, -999, -999, -999, -999, -999,
  116623. -999, -999, -999, -999, -999, -999, -999, -999,
  116624. -999, -999, -999, -999, -999, -999, -999, -999},
  116625. {-999, -999, -999, -999, -999, -999, -999, -106,
  116626. -100, -95, -90, -86, -81, -78, -74, -69,
  116627. -74, -74, -76, -79, -83, -84, -86, -89,
  116628. -92, -97, -93, -100, -103, -107, -110, -999,
  116629. -999, -999, -999, -999, -999, -999, -999, -999,
  116630. -999, -999, -999, -999, -999, -999, -999, -999,
  116631. -999, -999, -999, -999, -999, -999, -999, -999},
  116632. {-999, -999, -999, -999, -999, -999, -106, -100,
  116633. -95, -90, -87, -83, -80, -75, -69, -60,
  116634. -66, -66, -68, -70, -74, -78, -79, -81,
  116635. -81, -83, -84, -87, -93, -96, -99, -103,
  116636. -107, -110, -999, -999, -999, -999, -999, -999,
  116637. -999, -999, -999, -999, -999, -999, -999, -999,
  116638. -999, -999, -999, -999, -999, -999, -999, -999},
  116639. {-999, -999, -999, -999, -999, -108, -103, -98,
  116640. -93, -89, -85, -82, -78, -71, -62, -55,
  116641. -58, -58, -54, -54, -55, -59, -61, -62,
  116642. -70, -66, -66, -67, -70, -72, -75, -78,
  116643. -84, -84, -84, -88, -91, -90, -95, -98,
  116644. -102, -103, -106, -110, -999, -999, -999, -999,
  116645. -999, -999, -999, -999, -999, -999, -999, -999},
  116646. {-999, -999, -999, -999, -108, -103, -98, -94,
  116647. -90, -87, -82, -79, -73, -67, -58, -47,
  116648. -50, -45, -41, -45, -48, -44, -44, -49,
  116649. -54, -51, -48, -47, -49, -50, -51, -57,
  116650. -58, -60, -63, -69, -70, -69, -71, -74,
  116651. -78, -82, -90, -95, -101, -105, -110, -999,
  116652. -999, -999, -999, -999, -999, -999, -999, -999},
  116653. {-999, -999, -999, -105, -101, -97, -93, -90,
  116654. -85, -80, -77, -72, -65, -56, -48, -37,
  116655. -40, -36, -34, -40, -50, -47, -38, -41,
  116656. -47, -38, -35, -39, -38, -43, -40, -45,
  116657. -50, -45, -44, -47, -50, -55, -48, -48,
  116658. -52, -66, -70, -76, -82, -90, -97, -105,
  116659. -110, -999, -999, -999, -999, -999, -999, -999}},
  116660. /* 707 Hz */
  116661. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116662. -999, -108, -103, -98, -93, -86, -79, -76,
  116663. -83, -81, -85, -87, -89, -93, -98, -102,
  116664. -107, -112, -999, -999, -999, -999, -999, -999,
  116665. -999, -999, -999, -999, -999, -999, -999, -999,
  116666. -999, -999, -999, -999, -999, -999, -999, -999,
  116667. -999, -999, -999, -999, -999, -999, -999, -999},
  116668. {-999, -999, -999, -999, -999, -999, -999, -999,
  116669. -999, -108, -103, -98, -93, -86, -79, -71,
  116670. -77, -74, -77, -79, -81, -84, -85, -90,
  116671. -92, -93, -92, -98, -101, -108, -112, -999,
  116672. -999, -999, -999, -999, -999, -999, -999, -999,
  116673. -999, -999, -999, -999, -999, -999, -999, -999,
  116674. -999, -999, -999, -999, -999, -999, -999, -999},
  116675. {-999, -999, -999, -999, -999, -999, -999, -999,
  116676. -108, -103, -98, -93, -87, -78, -68, -65,
  116677. -66, -62, -65, -67, -70, -73, -75, -78,
  116678. -82, -82, -83, -84, -91, -93, -98, -102,
  116679. -106, -110, -999, -999, -999, -999, -999, -999,
  116680. -999, -999, -999, -999, -999, -999, -999, -999,
  116681. -999, -999, -999, -999, -999, -999, -999, -999},
  116682. {-999, -999, -999, -999, -999, -999, -999, -999,
  116683. -105, -100, -95, -90, -82, -74, -62, -57,
  116684. -58, -56, -51, -52, -52, -54, -54, -58,
  116685. -66, -59, -60, -63, -66, -69, -73, -79,
  116686. -83, -84, -80, -81, -81, -82, -88, -92,
  116687. -98, -105, -113, -999, -999, -999, -999, -999,
  116688. -999, -999, -999, -999, -999, -999, -999, -999},
  116689. {-999, -999, -999, -999, -999, -999, -999, -107,
  116690. -102, -97, -92, -84, -79, -69, -57, -47,
  116691. -52, -47, -44, -45, -50, -52, -42, -42,
  116692. -53, -43, -43, -48, -51, -56, -55, -52,
  116693. -57, -59, -61, -62, -67, -71, -78, -83,
  116694. -86, -94, -98, -103, -110, -999, -999, -999,
  116695. -999, -999, -999, -999, -999, -999, -999, -999},
  116696. {-999, -999, -999, -999, -999, -999, -105, -100,
  116697. -95, -90, -84, -78, -70, -61, -51, -41,
  116698. -40, -38, -40, -46, -52, -51, -41, -40,
  116699. -46, -40, -38, -38, -41, -46, -41, -46,
  116700. -47, -43, -43, -45, -41, -45, -56, -67,
  116701. -68, -83, -87, -90, -95, -102, -107, -113,
  116702. -999, -999, -999, -999, -999, -999, -999, -999}},
  116703. /* 1000 Hz */
  116704. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116705. -999, -109, -105, -101, -96, -91, -84, -77,
  116706. -82, -82, -85, -89, -94, -100, -106, -110,
  116707. -999, -999, -999, -999, -999, -999, -999, -999,
  116708. -999, -999, -999, -999, -999, -999, -999, -999,
  116709. -999, -999, -999, -999, -999, -999, -999, -999,
  116710. -999, -999, -999, -999, -999, -999, -999, -999},
  116711. {-999, -999, -999, -999, -999, -999, -999, -999,
  116712. -999, -106, -103, -98, -92, -85, -80, -71,
  116713. -75, -72, -76, -80, -84, -86, -89, -93,
  116714. -100, -107, -113, -999, -999, -999, -999, -999,
  116715. -999, -999, -999, -999, -999, -999, -999, -999,
  116716. -999, -999, -999, -999, -999, -999, -999, -999,
  116717. -999, -999, -999, -999, -999, -999, -999, -999},
  116718. {-999, -999, -999, -999, -999, -999, -999, -107,
  116719. -104, -101, -97, -92, -88, -84, -80, -64,
  116720. -66, -63, -64, -66, -69, -73, -77, -83,
  116721. -83, -86, -91, -98, -104, -111, -999, -999,
  116722. -999, -999, -999, -999, -999, -999, -999, -999,
  116723. -999, -999, -999, -999, -999, -999, -999, -999,
  116724. -999, -999, -999, -999, -999, -999, -999, -999},
  116725. {-999, -999, -999, -999, -999, -999, -999, -107,
  116726. -104, -101, -97, -92, -90, -84, -74, -57,
  116727. -58, -52, -55, -54, -50, -52, -50, -52,
  116728. -63, -62, -69, -76, -77, -78, -78, -79,
  116729. -82, -88, -94, -100, -106, -111, -999, -999,
  116730. -999, -999, -999, -999, -999, -999, -999, -999,
  116731. -999, -999, -999, -999, -999, -999, -999, -999},
  116732. {-999, -999, -999, -999, -999, -999, -106, -102,
  116733. -98, -95, -90, -85, -83, -78, -70, -50,
  116734. -50, -41, -44, -49, -47, -50, -50, -44,
  116735. -55, -46, -47, -48, -48, -54, -49, -49,
  116736. -58, -62, -71, -81, -87, -92, -97, -102,
  116737. -108, -114, -999, -999, -999, -999, -999, -999,
  116738. -999, -999, -999, -999, -999, -999, -999, -999},
  116739. {-999, -999, -999, -999, -999, -999, -106, -102,
  116740. -98, -95, -90, -85, -83, -78, -70, -45,
  116741. -43, -41, -47, -50, -51, -50, -49, -45,
  116742. -47, -41, -44, -41, -39, -43, -38, -37,
  116743. -40, -41, -44, -50, -58, -65, -73, -79,
  116744. -85, -92, -97, -101, -105, -109, -113, -999,
  116745. -999, -999, -999, -999, -999, -999, -999, -999}},
  116746. /* 1414 Hz */
  116747. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116748. -999, -999, -999, -107, -100, -95, -87, -81,
  116749. -85, -83, -88, -93, -100, -107, -114, -999,
  116750. -999, -999, -999, -999, -999, -999, -999, -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, -999, -999, -999, -999, -999,
  116755. -999, -999, -107, -101, -95, -88, -83, -76,
  116756. -73, -72, -79, -84, -90, -95, -100, -105,
  116757. -110, -115, -999, -999, -999, -999, -999, -999,
  116758. -999, -999, -999, -999, -999, -999, -999, -999,
  116759. -999, -999, -999, -999, -999, -999, -999, -999,
  116760. -999, -999, -999, -999, -999, -999, -999, -999},
  116761. {-999, -999, -999, -999, -999, -999, -999, -999,
  116762. -999, -999, -104, -98, -92, -87, -81, -70,
  116763. -65, -62, -67, -71, -74, -80, -85, -91,
  116764. -95, -99, -103, -108, -111, -114, -999, -999,
  116765. -999, -999, -999, -999, -999, -999, -999, -999,
  116766. -999, -999, -999, -999, -999, -999, -999, -999,
  116767. -999, -999, -999, -999, -999, -999, -999, -999},
  116768. {-999, -999, -999, -999, -999, -999, -999, -999,
  116769. -999, -999, -103, -97, -90, -85, -76, -60,
  116770. -56, -54, -60, -62, -61, -56, -63, -65,
  116771. -73, -74, -77, -75, -78, -81, -86, -87,
  116772. -88, -91, -94, -98, -103, -110, -999, -999,
  116773. -999, -999, -999, -999, -999, -999, -999, -999,
  116774. -999, -999, -999, -999, -999, -999, -999, -999},
  116775. {-999, -999, -999, -999, -999, -999, -999, -105,
  116776. -100, -97, -92, -86, -81, -79, -70, -57,
  116777. -51, -47, -51, -58, -60, -56, -53, -50,
  116778. -58, -52, -50, -50, -53, -55, -64, -69,
  116779. -71, -85, -82, -78, -81, -85, -95, -102,
  116780. -112, -999, -999, -999, -999, -999, -999, -999,
  116781. -999, -999, -999, -999, -999, -999, -999, -999},
  116782. {-999, -999, -999, -999, -999, -999, -999, -105,
  116783. -100, -97, -92, -85, -83, -79, -72, -49,
  116784. -40, -43, -43, -54, -56, -51, -50, -40,
  116785. -43, -38, -36, -35, -37, -38, -37, -44,
  116786. -54, -60, -57, -60, -70, -75, -84, -92,
  116787. -103, -112, -999, -999, -999, -999, -999, -999,
  116788. -999, -999, -999, -999, -999, -999, -999, -999}},
  116789. /* 2000 Hz */
  116790. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116791. -999, -999, -999, -110, -102, -95, -89, -82,
  116792. -83, -84, -90, -92, -99, -107, -113, -999,
  116793. -999, -999, -999, -999, -999, -999, -999, -999,
  116794. -999, -999, -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. -999, -999, -107, -101, -95, -89, -83, -72,
  116799. -74, -78, -85, -88, -88, -90, -92, -98,
  116800. -105, -111, -999, -999, -999, -999, -999, -999,
  116801. -999, -999, -999, -999, -999, -999, -999, -999,
  116802. -999, -999, -999, -999, -999, -999, -999, -999,
  116803. -999, -999, -999, -999, -999, -999, -999, -999},
  116804. {-999, -999, -999, -999, -999, -999, -999, -999,
  116805. -999, -109, -103, -97, -93, -87, -81, -70,
  116806. -70, -67, -75, -73, -76, -79, -81, -83,
  116807. -88, -89, -97, -103, -110, -999, -999, -999,
  116808. -999, -999, -999, -999, -999, -999, -999, -999,
  116809. -999, -999, -999, -999, -999, -999, -999, -999,
  116810. -999, -999, -999, -999, -999, -999, -999, -999},
  116811. {-999, -999, -999, -999, -999, -999, -999, -999,
  116812. -999, -107, -100, -94, -88, -83, -75, -63,
  116813. -59, -59, -63, -66, -60, -62, -67, -67,
  116814. -77, -76, -81, -88, -86, -92, -96, -102,
  116815. -109, -116, -999, -999, -999, -999, -999, -999,
  116816. -999, -999, -999, -999, -999, -999, -999, -999,
  116817. -999, -999, -999, -999, -999, -999, -999, -999},
  116818. {-999, -999, -999, -999, -999, -999, -999, -999,
  116819. -999, -105, -98, -92, -86, -81, -73, -56,
  116820. -52, -47, -55, -60, -58, -52, -51, -45,
  116821. -49, -50, -53, -54, -61, -71, -70, -69,
  116822. -78, -79, -87, -90, -96, -104, -112, -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, -103, -96, -90, -86, -78, -70, -51,
  116827. -42, -47, -48, -55, -54, -54, -53, -42,
  116828. -35, -28, -33, -38, -37, -44, -47, -49,
  116829. -54, -63, -68, -78, -82, -89, -94, -99,
  116830. -104, -109, -114, -999, -999, -999, -999, -999,
  116831. -999, -999, -999, -999, -999, -999, -999, -999}},
  116832. /* 2828 Hz */
  116833. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116834. -999, -999, -999, -999, -110, -100, -90, -79,
  116835. -85, -81, -82, -82, -89, -94, -99, -103,
  116836. -109, -115, -999, -999, -999, -999, -999, -999,
  116837. -999, -999, -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, -999, -999, -999,
  116841. -999, -999, -999, -999, -105, -97, -85, -72,
  116842. -74, -70, -70, -70, -76, -85, -91, -93,
  116843. -97, -103, -109, -115, -999, -999, -999, -999,
  116844. -999, -999, -999, -999, -999, -999, -999, -999,
  116845. -999, -999, -999, -999, -999, -999, -999, -999,
  116846. -999, -999, -999, -999, -999, -999, -999, -999},
  116847. {-999, -999, -999, -999, -999, -999, -999, -999,
  116848. -999, -999, -999, -999, -112, -93, -81, -68,
  116849. -62, -60, -60, -57, -63, -70, -77, -82,
  116850. -90, -93, -98, -104, -109, -113, -999, -999,
  116851. -999, -999, -999, -999, -999, -999, -999, -999,
  116852. -999, -999, -999, -999, -999, -999, -999, -999,
  116853. -999, -999, -999, -999, -999, -999, -999, -999},
  116854. {-999, -999, -999, -999, -999, -999, -999, -999,
  116855. -999, -999, -999, -113, -100, -93, -84, -63,
  116856. -58, -48, -53, -54, -52, -52, -57, -64,
  116857. -66, -76, -83, -81, -85, -85, -90, -95,
  116858. -98, -101, -103, -106, -108, -111, -999, -999,
  116859. -999, -999, -999, -999, -999, -999, -999, -999,
  116860. -999, -999, -999, -999, -999, -999, -999, -999},
  116861. {-999, -999, -999, -999, -999, -999, -999, -999,
  116862. -999, -999, -999, -105, -95, -86, -74, -53,
  116863. -50, -38, -43, -49, -43, -42, -39, -39,
  116864. -46, -52, -57, -56, -72, -69, -74, -81,
  116865. -87, -92, -94, -97, -99, -102, -105, -108,
  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, -108, -99, -90, -76, -66, -45,
  116870. -43, -41, -44, -47, -43, -47, -40, -30,
  116871. -31, -31, -39, -33, -40, -41, -43, -53,
  116872. -59, -70, -73, -77, -79, -82, -84, -87,
  116873. -999, -999, -999, -999, -999, -999, -999, -999,
  116874. -999, -999, -999, -999, -999, -999, -999, -999}},
  116875. /* 4000 Hz */
  116876. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116877. -999, -999, -999, -999, -999, -110, -91, -76,
  116878. -75, -85, -93, -98, -104, -110, -999, -999,
  116879. -999, -999, -999, -999, -999, -999, -999, -999,
  116880. -999, -999, -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. -999, -999, -999, -999, -999, -110, -91, -70,
  116885. -70, -75, -86, -89, -94, -98, -101, -106,
  116886. -110, -999, -999, -999, -999, -999, -999, -999,
  116887. -999, -999, -999, -999, -999, -999, -999, -999,
  116888. -999, -999, -999, -999, -999, -999, -999, -999,
  116889. -999, -999, -999, -999, -999, -999, -999, -999},
  116890. {-999, -999, -999, -999, -999, -999, -999, -999,
  116891. -999, -999, -999, -999, -110, -95, -80, -60,
  116892. -65, -64, -74, -83, -88, -91, -95, -99,
  116893. -103, -107, -110, -999, -999, -999, -999, -999,
  116894. -999, -999, -999, -999, -999, -999, -999, -999,
  116895. -999, -999, -999, -999, -999, -999, -999, -999,
  116896. -999, -999, -999, -999, -999, -999, -999, -999},
  116897. {-999, -999, -999, -999, -999, -999, -999, -999,
  116898. -999, -999, -999, -999, -110, -95, -80, -58,
  116899. -55, -49, -66, -68, -71, -78, -78, -80,
  116900. -88, -85, -89, -97, -100, -105, -110, -999,
  116901. -999, -999, -999, -999, -999, -999, -999, -999,
  116902. -999, -999, -999, -999, -999, -999, -999, -999,
  116903. -999, -999, -999, -999, -999, -999, -999, -999},
  116904. {-999, -999, -999, -999, -999, -999, -999, -999,
  116905. -999, -999, -999, -999, -110, -95, -80, -53,
  116906. -52, -41, -59, -59, -49, -58, -56, -63,
  116907. -86, -79, -90, -93, -98, -103, -107, -112,
  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, -110, -97, -91, -73, -45,
  116913. -40, -33, -53, -61, -49, -54, -50, -50,
  116914. -60, -52, -67, -74, -81, -92, -96, -100,
  116915. -105, -110, -999, -999, -999, -999, -999, -999,
  116916. -999, -999, -999, -999, -999, -999, -999, -999,
  116917. -999, -999, -999, -999, -999, -999, -999, -999}},
  116918. /* 5657 Hz */
  116919. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116920. -999, -999, -999, -113, -106, -99, -92, -77,
  116921. -80, -88, -97, -106, -115, -999, -999, -999,
  116922. -999, -999, -999, -999, -999, -999, -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, -999,
  116927. -999, -999, -116, -109, -102, -95, -89, -74,
  116928. -72, -88, -87, -95, -102, -109, -116, -999,
  116929. -999, -999, -999, -999, -999, -999, -999, -999,
  116930. -999, -999, -999, -999, -999, -999, -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, -999, -999,
  116934. -999, -999, -116, -109, -102, -95, -89, -75,
  116935. -66, -74, -77, -78, -86, -87, -90, -96,
  116936. -105, -115, -999, -999, -999, -999, -999, -999,
  116937. -999, -999, -999, -999, -999, -999, -999, -999,
  116938. -999, -999, -999, -999, -999, -999, -999, -999,
  116939. -999, -999, -999, -999, -999, -999, -999, -999},
  116940. {-999, -999, -999, -999, -999, -999, -999, -999,
  116941. -999, -999, -115, -108, -101, -94, -88, -66,
  116942. -56, -61, -70, -65, -78, -72, -83, -84,
  116943. -93, -98, -105, -110, -999, -999, -999, -999,
  116944. -999, -999, -999, -999, -999, -999, -999, -999,
  116945. -999, -999, -999, -999, -999, -999, -999, -999,
  116946. -999, -999, -999, -999, -999, -999, -999, -999},
  116947. {-999, -999, -999, -999, -999, -999, -999, -999,
  116948. -999, -999, -110, -105, -95, -89, -82, -57,
  116949. -52, -52, -59, -56, -59, -58, -69, -67,
  116950. -88, -82, -82, -89, -94, -100, -108, -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, -110, -101, -96, -90, -83, -77, -54,
  116956. -43, -38, -50, -48, -52, -48, -42, -42,
  116957. -51, -52, -53, -59, -65, -71, -78, -85,
  116958. -95, -999, -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. /* 8000 Hz */
  116962. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -999, -999, -120, -105, -86, -68,
  116964. -78, -79, -90, -100, -110, -999, -999, -999,
  116965. -999, -999, -999, -999, -999, -999, -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, -999, -999, -120, -105, -86, -66,
  116971. -73, -77, -88, -96, -105, -115, -999, -999,
  116972. -999, -999, -999, -999, -999, -999, -999, -999,
  116973. -999, -999, -999, -999, -999, -999, -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, -999,
  116977. -999, -999, -999, -120, -105, -92, -80, -61,
  116978. -64, -68, -80, -87, -92, -100, -110, -999,
  116979. -999, -999, -999, -999, -999, -999, -999, -999,
  116980. -999, -999, -999, -999, -999, -999, -999, -999,
  116981. -999, -999, -999, -999, -999, -999, -999, -999,
  116982. -999, -999, -999, -999, -999, -999, -999, -999},
  116983. {-999, -999, -999, -999, -999, -999, -999, -999,
  116984. -999, -999, -999, -120, -104, -91, -79, -52,
  116985. -60, -54, -64, -69, -77, -80, -82, -84,
  116986. -85, -87, -88, -90, -999, -999, -999, -999,
  116987. -999, -999, -999, -999, -999, -999, -999, -999,
  116988. -999, -999, -999, -999, -999, -999, -999, -999,
  116989. -999, -999, -999, -999, -999, -999, -999, -999},
  116990. {-999, -999, -999, -999, -999, -999, -999, -999,
  116991. -999, -999, -999, -118, -100, -87, -77, -49,
  116992. -50, -44, -58, -61, -61, -67, -65, -62,
  116993. -62, -62, -65, -68, -999, -999, -999, -999,
  116994. -999, -999, -999, -999, -999, -999, -999, -999,
  116995. -999, -999, -999, -999, -999, -999, -999, -999,
  116996. -999, -999, -999, -999, -999, -999, -999, -999},
  116997. {-999, -999, -999, -999, -999, -999, -999, -999,
  116998. -999, -999, -999, -115, -98, -84, -62, -49,
  116999. -44, -38, -46, -49, -49, -46, -39, -37,
  117000. -39, -40, -42, -43, -999, -999, -999, -999,
  117001. -999, -999, -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. /* 11314 Hz */
  117005. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117006. -999, -999, -999, -999, -999, -110, -88, -74,
  117007. -77, -82, -82, -85, -90, -94, -99, -104,
  117008. -999, -999, -999, -999, -999, -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, -999, -999, -999, -999, -110, -88, -66,
  117014. -70, -81, -80, -81, -84, -88, -91, -93,
  117015. -999, -999, -999, -999, -999, -999, -999, -999,
  117016. -999, -999, -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, -999, -999, -999, -999, -110, -88, -61,
  117021. -63, -70, -71, -74, -77, -80, -83, -85,
  117022. -999, -999, -999, -999, -999, -999, -999, -999,
  117023. -999, -999, -999, -999, -999, -999, -999, -999,
  117024. -999, -999, -999, -999, -999, -999, -999, -999,
  117025. -999, -999, -999, -999, -999, -999, -999, -999},
  117026. {-999, -999, -999, -999, -999, -999, -999, -999,
  117027. -999, -999, -999, -999, -999, -110, -86, -62,
  117028. -63, -62, -62, -58, -52, -50, -50, -52,
  117029. -54, -999, -999, -999, -999, -999, -999, -999,
  117030. -999, -999, -999, -999, -999, -999, -999, -999,
  117031. -999, -999, -999, -999, -999, -999, -999, -999,
  117032. -999, -999, -999, -999, -999, -999, -999, -999},
  117033. {-999, -999, -999, -999, -999, -999, -999, -999,
  117034. -999, -999, -999, -999, -118, -108, -84, -53,
  117035. -50, -50, -50, -55, -47, -45, -40, -40,
  117036. -40, -999, -999, -999, -999, -999, -999, -999,
  117037. -999, -999, -999, -999, -999, -999, -999, -999,
  117038. -999, -999, -999, -999, -999, -999, -999, -999,
  117039. -999, -999, -999, -999, -999, -999, -999, -999},
  117040. {-999, -999, -999, -999, -999, -999, -999, -999,
  117041. -999, -999, -999, -999, -118, -100, -73, -43,
  117042. -37, -42, -43, -53, -38, -37, -35, -35,
  117043. -38, -999, -999, -999, -999, -999, -999, -999,
  117044. -999, -999, -999, -999, -999, -999, -999, -999,
  117045. -999, -999, -999, -999, -999, -999, -999, -999,
  117046. -999, -999, -999, -999, -999, -999, -999, -999}},
  117047. /* 16000 Hz */
  117048. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117049. -999, -999, -999, -110, -100, -91, -84, -74,
  117050. -80, -80, -80, -80, -80, -999, -999, -999,
  117051. -999, -999, -999, -999, -999, -999, -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, -110, -100, -91, -84, -74,
  117057. -68, -68, -68, -68, -68, -999, -999, -999,
  117058. -999, -999, -999, -999, -999, -999, -999, -999,
  117059. -999, -999, -999, -999, -999, -999, -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, -110, -100, -86, -78, -70,
  117064. -60, -45, -30, -21, -999, -999, -999, -999,
  117065. -999, -999, -999, -999, -999, -999, -999, -999,
  117066. -999, -999, -999, -999, -999, -999, -999, -999,
  117067. -999, -999, -999, -999, -999, -999, -999, -999,
  117068. -999, -999, -999, -999, -999, -999, -999, -999},
  117069. {-999, -999, -999, -999, -999, -999, -999, -999,
  117070. -999, -999, -999, -110, -100, -87, -78, -67,
  117071. -48, -38, -29, -21, -999, -999, -999, -999,
  117072. -999, -999, -999, -999, -999, -999, -999, -999,
  117073. -999, -999, -999, -999, -999, -999, -999, -999,
  117074. -999, -999, -999, -999, -999, -999, -999, -999,
  117075. -999, -999, -999, -999, -999, -999, -999, -999},
  117076. {-999, -999, -999, -999, -999, -999, -999, -999,
  117077. -999, -999, -999, -110, -100, -86, -69, -56,
  117078. -45, -35, -33, -29, -999, -999, -999, -999,
  117079. -999, -999, -999, -999, -999, -999, -999, -999,
  117080. -999, -999, -999, -999, -999, -999, -999, -999,
  117081. -999, -999, -999, -999, -999, -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, -110, -100, -83, -71, -48,
  117085. -27, -38, -37, -34, -999, -999, -999, -999,
  117086. -999, -999, -999, -999, -999, -999, -999, -999,
  117087. -999, -999, -999, -999, -999, -999, -999, -999,
  117088. -999, -999, -999, -999, -999, -999, -999, -999,
  117089. -999, -999, -999, -999, -999, -999, -999, -999}}
  117090. };
  117091. #endif
  117092. /*** End of inlined file: masking.h ***/
  117093. #define NEGINF -9999.f
  117094. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117095. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117096. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117097. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117098. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117099. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117100. look->channels=vi->channels;
  117101. look->ampmax=-9999.;
  117102. look->gi=gi;
  117103. return(look);
  117104. }
  117105. void _vp_global_free(vorbis_look_psy_global *look){
  117106. if(look){
  117107. memset(look,0,sizeof(*look));
  117108. _ogg_free(look);
  117109. }
  117110. }
  117111. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117112. if(i){
  117113. memset(i,0,sizeof(*i));
  117114. _ogg_free(i);
  117115. }
  117116. }
  117117. void _vi_psy_free(vorbis_info_psy *i){
  117118. if(i){
  117119. memset(i,0,sizeof(*i));
  117120. _ogg_free(i);
  117121. }
  117122. }
  117123. static void min_curve(float *c,
  117124. float *c2){
  117125. int i;
  117126. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117127. }
  117128. static void max_curve(float *c,
  117129. float *c2){
  117130. int i;
  117131. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117132. }
  117133. static void attenuate_curve(float *c,float att){
  117134. int i;
  117135. for(i=0;i<EHMER_MAX;i++)
  117136. c[i]+=att;
  117137. }
  117138. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117139. float center_boost, float center_decay_rate){
  117140. int i,j,k,m;
  117141. float ath[EHMER_MAX];
  117142. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117143. float athc[P_LEVELS][EHMER_MAX];
  117144. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117145. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117146. memset(workc,0,sizeof(workc));
  117147. for(i=0;i<P_BANDS;i++){
  117148. /* we add back in the ATH to avoid low level curves falling off to
  117149. -infinity and unnecessarily cutting off high level curves in the
  117150. curve limiting (last step). */
  117151. /* A half-band's settings must be valid over the whole band, and
  117152. it's better to mask too little than too much */
  117153. int ath_offset=i*4;
  117154. for(j=0;j<EHMER_MAX;j++){
  117155. float min=999.;
  117156. for(k=0;k<4;k++)
  117157. if(j+k+ath_offset<MAX_ATH){
  117158. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117159. }else{
  117160. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117161. }
  117162. ath[j]=min;
  117163. }
  117164. /* copy curves into working space, replicate the 50dB curve to 30
  117165. and 40, replicate the 100dB curve to 110 */
  117166. for(j=0;j<6;j++)
  117167. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117168. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117169. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117170. /* apply centered curve boost/decay */
  117171. for(j=0;j<P_LEVELS;j++){
  117172. for(k=0;k<EHMER_MAX;k++){
  117173. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117174. if(adj<0. && center_boost>0)adj=0.;
  117175. if(adj>0. && center_boost<0)adj=0.;
  117176. workc[i][j][k]+=adj;
  117177. }
  117178. }
  117179. /* normalize curves so the driving amplitude is 0dB */
  117180. /* make temp curves with the ATH overlayed */
  117181. for(j=0;j<P_LEVELS;j++){
  117182. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117183. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117184. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117185. max_curve(athc[j],workc[i][j]);
  117186. }
  117187. /* Now limit the louder curves.
  117188. the idea is this: We don't know what the playback attenuation
  117189. will be; 0dB SL moves every time the user twiddles the volume
  117190. knob. So that means we have to use a single 'most pessimal' curve
  117191. for all masking amplitudes, right? Wrong. The *loudest* sound
  117192. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117193. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117194. etc... */
  117195. for(j=1;j<P_LEVELS;j++){
  117196. min_curve(athc[j],athc[j-1]);
  117197. min_curve(workc[i][j],athc[j]);
  117198. }
  117199. }
  117200. for(i=0;i<P_BANDS;i++){
  117201. int hi_curve,lo_curve,bin;
  117202. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117203. /* low frequency curves are measured with greater resolution than
  117204. the MDCT/FFT will actually give us; we want the curve applied
  117205. to the tone data to be pessimistic and thus apply the minimum
  117206. masking possible for a given bin. That means that a single bin
  117207. could span more than one octave and that the curve will be a
  117208. composite of multiple octaves. It also may mean that a single
  117209. bin may span > an eighth of an octave and that the eighth
  117210. octave values may also be composited. */
  117211. /* which octave curves will we be compositing? */
  117212. bin=floor(fromOC(i*.5)/binHz);
  117213. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117214. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117215. if(lo_curve>i)lo_curve=i;
  117216. if(lo_curve<0)lo_curve=0;
  117217. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117218. for(m=0;m<P_LEVELS;m++){
  117219. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117220. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117221. /* render the curve into bins, then pull values back into curve.
  117222. The point is that any inherent subsampling aliasing results in
  117223. a safe minimum */
  117224. for(k=lo_curve;k<=hi_curve;k++){
  117225. int l=0;
  117226. for(j=0;j<EHMER_MAX;j++){
  117227. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117228. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117229. if(lo_bin<0)lo_bin=0;
  117230. if(lo_bin>n)lo_bin=n;
  117231. if(lo_bin<l)l=lo_bin;
  117232. if(hi_bin<0)hi_bin=0;
  117233. if(hi_bin>n)hi_bin=n;
  117234. for(;l<hi_bin && l<n;l++)
  117235. if(brute_buffer[l]>workc[k][m][j])
  117236. brute_buffer[l]=workc[k][m][j];
  117237. }
  117238. for(;l<n;l++)
  117239. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117240. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117241. }
  117242. /* be equally paranoid about being valid up to next half ocatve */
  117243. if(i+1<P_BANDS){
  117244. int l=0;
  117245. k=i+1;
  117246. for(j=0;j<EHMER_MAX;j++){
  117247. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117248. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117249. if(lo_bin<0)lo_bin=0;
  117250. if(lo_bin>n)lo_bin=n;
  117251. if(lo_bin<l)l=lo_bin;
  117252. if(hi_bin<0)hi_bin=0;
  117253. if(hi_bin>n)hi_bin=n;
  117254. for(;l<hi_bin && l<n;l++)
  117255. if(brute_buffer[l]>workc[k][m][j])
  117256. brute_buffer[l]=workc[k][m][j];
  117257. }
  117258. for(;l<n;l++)
  117259. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117260. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117261. }
  117262. for(j=0;j<EHMER_MAX;j++){
  117263. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117264. if(bin<0){
  117265. ret[i][m][j+2]=-999.;
  117266. }else{
  117267. if(bin>=n){
  117268. ret[i][m][j+2]=-999.;
  117269. }else{
  117270. ret[i][m][j+2]=brute_buffer[bin];
  117271. }
  117272. }
  117273. }
  117274. /* add fenceposts */
  117275. for(j=0;j<EHMER_OFFSET;j++)
  117276. if(ret[i][m][j+2]>-200.f)break;
  117277. ret[i][m][0]=j;
  117278. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117279. if(ret[i][m][j+2]>-200.f)
  117280. break;
  117281. ret[i][m][1]=j;
  117282. }
  117283. }
  117284. return(ret);
  117285. }
  117286. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117287. vorbis_info_psy_global *gi,int n,long rate){
  117288. long i,j,lo=-99,hi=1;
  117289. long maxoc;
  117290. memset(p,0,sizeof(*p));
  117291. p->eighth_octave_lines=gi->eighth_octave_lines;
  117292. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117293. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117294. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117295. p->total_octave_lines=maxoc-p->firstoc+1;
  117296. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117297. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117298. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117299. p->vi=vi;
  117300. p->n=n;
  117301. p->rate=rate;
  117302. /* AoTuV HF weighting */
  117303. p->m_val = 1.;
  117304. if(rate < 26000) p->m_val = 0;
  117305. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117306. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117307. /* set up the lookups for a given blocksize and sample rate */
  117308. for(i=0,j=0;i<MAX_ATH-1;i++){
  117309. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117310. float base=ATH[i];
  117311. if(j<endpos){
  117312. float delta=(ATH[i+1]-base)/(endpos-j);
  117313. for(;j<endpos && j<n;j++){
  117314. p->ath[j]=base+100.;
  117315. base+=delta;
  117316. }
  117317. }
  117318. }
  117319. for(i=0;i<n;i++){
  117320. float bark=toBARK(rate/(2*n)*i);
  117321. for(;lo+vi->noisewindowlomin<i &&
  117322. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117323. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117324. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117325. p->bark[i]=((lo-1)<<16)+(hi-1);
  117326. }
  117327. for(i=0;i<n;i++)
  117328. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117329. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117330. vi->tone_centerboost,vi->tone_decay);
  117331. /* set up rolling noise median */
  117332. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117333. for(i=0;i<P_NOISECURVES;i++)
  117334. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117335. for(i=0;i<n;i++){
  117336. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117337. int inthalfoc;
  117338. float del;
  117339. if(halfoc<0)halfoc=0;
  117340. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117341. inthalfoc=(int)halfoc;
  117342. del=halfoc-inthalfoc;
  117343. for(j=0;j<P_NOISECURVES;j++)
  117344. p->noiseoffset[j][i]=
  117345. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117346. p->vi->noiseoff[j][inthalfoc+1]*del;
  117347. }
  117348. #if 0
  117349. {
  117350. static int ls=0;
  117351. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117352. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117353. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117354. }
  117355. #endif
  117356. }
  117357. void _vp_psy_clear(vorbis_look_psy *p){
  117358. int i,j;
  117359. if(p){
  117360. if(p->ath)_ogg_free(p->ath);
  117361. if(p->octave)_ogg_free(p->octave);
  117362. if(p->bark)_ogg_free(p->bark);
  117363. if(p->tonecurves){
  117364. for(i=0;i<P_BANDS;i++){
  117365. for(j=0;j<P_LEVELS;j++){
  117366. _ogg_free(p->tonecurves[i][j]);
  117367. }
  117368. _ogg_free(p->tonecurves[i]);
  117369. }
  117370. _ogg_free(p->tonecurves);
  117371. }
  117372. if(p->noiseoffset){
  117373. for(i=0;i<P_NOISECURVES;i++){
  117374. _ogg_free(p->noiseoffset[i]);
  117375. }
  117376. _ogg_free(p->noiseoffset);
  117377. }
  117378. memset(p,0,sizeof(*p));
  117379. }
  117380. }
  117381. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117382. static void seed_curve(float *seed,
  117383. const float **curves,
  117384. float amp,
  117385. int oc, int n,
  117386. int linesper,float dBoffset){
  117387. int i,post1;
  117388. int seedptr;
  117389. const float *posts,*curve;
  117390. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117391. choice=max(choice,0);
  117392. choice=min(choice,P_LEVELS-1);
  117393. posts=curves[choice];
  117394. curve=posts+2;
  117395. post1=(int)posts[1];
  117396. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117397. for(i=posts[0];i<post1;i++){
  117398. if(seedptr>0){
  117399. float lin=amp+curve[i];
  117400. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117401. }
  117402. seedptr+=linesper;
  117403. if(seedptr>=n)break;
  117404. }
  117405. }
  117406. static void seed_loop(vorbis_look_psy *p,
  117407. const float ***curves,
  117408. const float *f,
  117409. const float *flr,
  117410. float *seed,
  117411. float specmax){
  117412. vorbis_info_psy *vi=p->vi;
  117413. long n=p->n,i;
  117414. float dBoffset=vi->max_curve_dB-specmax;
  117415. /* prime the working vector with peak values */
  117416. for(i=0;i<n;i++){
  117417. float max=f[i];
  117418. long oc=p->octave[i];
  117419. while(i+1<n && p->octave[i+1]==oc){
  117420. i++;
  117421. if(f[i]>max)max=f[i];
  117422. }
  117423. if(max+6.f>flr[i]){
  117424. oc=oc>>p->shiftoc;
  117425. if(oc>=P_BANDS)oc=P_BANDS-1;
  117426. if(oc<0)oc=0;
  117427. seed_curve(seed,
  117428. curves[oc],
  117429. max,
  117430. p->octave[i]-p->firstoc,
  117431. p->total_octave_lines,
  117432. p->eighth_octave_lines,
  117433. dBoffset);
  117434. }
  117435. }
  117436. }
  117437. static void seed_chase(float *seeds, int linesper, long n){
  117438. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117439. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117440. long stack=0;
  117441. long pos=0;
  117442. long i;
  117443. for(i=0;i<n;i++){
  117444. if(stack<2){
  117445. posstack[stack]=i;
  117446. ampstack[stack++]=seeds[i];
  117447. }else{
  117448. while(1){
  117449. if(seeds[i]<ampstack[stack-1]){
  117450. posstack[stack]=i;
  117451. ampstack[stack++]=seeds[i];
  117452. break;
  117453. }else{
  117454. if(i<posstack[stack-1]+linesper){
  117455. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117456. i<posstack[stack-2]+linesper){
  117457. /* we completely overlap, making stack-1 irrelevant. pop it */
  117458. stack--;
  117459. continue;
  117460. }
  117461. }
  117462. posstack[stack]=i;
  117463. ampstack[stack++]=seeds[i];
  117464. break;
  117465. }
  117466. }
  117467. }
  117468. }
  117469. /* the stack now contains only the positions that are relevant. Scan
  117470. 'em straight through */
  117471. for(i=0;i<stack;i++){
  117472. long endpos;
  117473. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117474. endpos=posstack[i+1];
  117475. }else{
  117476. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117477. discarded in short frames */
  117478. }
  117479. if(endpos>n)endpos=n;
  117480. for(;pos<endpos;pos++)
  117481. seeds[pos]=ampstack[i];
  117482. }
  117483. /* there. Linear time. I now remember this was on a problem set I
  117484. had in Grad Skool... I didn't solve it at the time ;-) */
  117485. }
  117486. /* bleaugh, this is more complicated than it needs to be */
  117487. #include<stdio.h>
  117488. static void max_seeds(vorbis_look_psy *p,
  117489. float *seed,
  117490. float *flr){
  117491. long n=p->total_octave_lines;
  117492. int linesper=p->eighth_octave_lines;
  117493. long linpos=0;
  117494. long pos;
  117495. seed_chase(seed,linesper,n); /* for masking */
  117496. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117497. while(linpos+1<p->n){
  117498. float minV=seed[pos];
  117499. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117500. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117501. while(pos+1<=end){
  117502. pos++;
  117503. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117504. minV=seed[pos];
  117505. }
  117506. end=pos+p->firstoc;
  117507. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117508. if(flr[linpos]<minV)flr[linpos]=minV;
  117509. }
  117510. {
  117511. float minV=seed[p->total_octave_lines-1];
  117512. for(;linpos<p->n;linpos++)
  117513. if(flr[linpos]<minV)flr[linpos]=minV;
  117514. }
  117515. }
  117516. static void bark_noise_hybridmp(int n,const long *b,
  117517. const float *f,
  117518. float *noise,
  117519. const float offset,
  117520. const int fixed){
  117521. float *N=(float*) alloca(n*sizeof(*N));
  117522. float *X=(float*) alloca(n*sizeof(*N));
  117523. float *XX=(float*) alloca(n*sizeof(*N));
  117524. float *Y=(float*) alloca(n*sizeof(*N));
  117525. float *XY=(float*) alloca(n*sizeof(*N));
  117526. float tN, tX, tXX, tY, tXY;
  117527. int i;
  117528. int lo, hi;
  117529. float R, A, B, D;
  117530. float w, x, y;
  117531. tN = tX = tXX = tY = tXY = 0.f;
  117532. y = f[0] + offset;
  117533. if (y < 1.f) y = 1.f;
  117534. w = y * y * .5;
  117535. tN += w;
  117536. tX += w;
  117537. tY += w * y;
  117538. N[0] = tN;
  117539. X[0] = tX;
  117540. XX[0] = tXX;
  117541. Y[0] = tY;
  117542. XY[0] = tXY;
  117543. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117544. y = f[i] + offset;
  117545. if (y < 1.f) y = 1.f;
  117546. w = y * y;
  117547. tN += w;
  117548. tX += w * x;
  117549. tXX += w * x * x;
  117550. tY += w * y;
  117551. tXY += w * x * y;
  117552. N[i] = tN;
  117553. X[i] = tX;
  117554. XX[i] = tXX;
  117555. Y[i] = tY;
  117556. XY[i] = tXY;
  117557. }
  117558. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117559. lo = b[i] >> 16;
  117560. if( lo>=0 ) break;
  117561. hi = b[i] & 0xffff;
  117562. tN = N[hi] + N[-lo];
  117563. tX = X[hi] - X[-lo];
  117564. tXX = XX[hi] + XX[-lo];
  117565. tY = Y[hi] + Y[-lo];
  117566. tXY = XY[hi] - XY[-lo];
  117567. A = tY * tXX - tX * tXY;
  117568. B = tN * tXY - tX * tY;
  117569. D = tN * tXX - tX * tX;
  117570. R = (A + x * B) / D;
  117571. if (R < 0.f)
  117572. R = 0.f;
  117573. noise[i] = R - offset;
  117574. }
  117575. for ( ;; i++, x += 1.f) {
  117576. lo = b[i] >> 16;
  117577. hi = b[i] & 0xffff;
  117578. if(hi>=n)break;
  117579. tN = N[hi] - N[lo];
  117580. tX = X[hi] - X[lo];
  117581. tXX = XX[hi] - XX[lo];
  117582. tY = Y[hi] - Y[lo];
  117583. tXY = XY[hi] - XY[lo];
  117584. A = tY * tXX - tX * tXY;
  117585. B = tN * tXY - tX * tY;
  117586. D = tN * tXX - tX * tX;
  117587. R = (A + x * B) / D;
  117588. if (R < 0.f) R = 0.f;
  117589. noise[i] = R - offset;
  117590. }
  117591. for ( ; i < n; i++, x += 1.f) {
  117592. R = (A + x * B) / D;
  117593. if (R < 0.f) R = 0.f;
  117594. noise[i] = R - offset;
  117595. }
  117596. if (fixed <= 0) return;
  117597. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117598. hi = i + fixed / 2;
  117599. lo = hi - fixed;
  117600. if(lo>=0)break;
  117601. tN = N[hi] + N[-lo];
  117602. tX = X[hi] - X[-lo];
  117603. tXX = XX[hi] + XX[-lo];
  117604. tY = Y[hi] + Y[-lo];
  117605. tXY = XY[hi] - XY[-lo];
  117606. A = tY * tXX - tX * tXY;
  117607. B = tN * tXY - tX * tY;
  117608. D = tN * tXX - tX * tX;
  117609. R = (A + x * B) / D;
  117610. if (R - offset < noise[i]) noise[i] = R - offset;
  117611. }
  117612. for ( ;; i++, x += 1.f) {
  117613. hi = i + fixed / 2;
  117614. lo = hi - fixed;
  117615. if(hi>=n)break;
  117616. tN = N[hi] - N[lo];
  117617. tX = X[hi] - X[lo];
  117618. tXX = XX[hi] - XX[lo];
  117619. tY = Y[hi] - Y[lo];
  117620. tXY = XY[hi] - XY[lo];
  117621. A = tY * tXX - tX * tXY;
  117622. B = tN * tXY - tX * tY;
  117623. D = tN * tXX - tX * tX;
  117624. R = (A + x * B) / D;
  117625. if (R - offset < noise[i]) noise[i] = R - offset;
  117626. }
  117627. for ( ; i < n; i++, x += 1.f) {
  117628. R = (A + x * B) / D;
  117629. if (R - offset < noise[i]) noise[i] = R - offset;
  117630. }
  117631. }
  117632. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117633. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117634. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117635. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117636. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117637. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117638. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117639. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117640. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117641. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117642. 973377.F, 913981.F, 858210.F, 805842.F,
  117643. 756669.F, 710497.F, 667142.F, 626433.F,
  117644. 588208.F, 552316.F, 518613.F, 486967.F,
  117645. 457252.F, 429351.F, 403152.F, 378551.F,
  117646. 355452.F, 333762.F, 313396.F, 294273.F,
  117647. 276316.F, 259455.F, 243623.F, 228757.F,
  117648. 214798.F, 201691.F, 189384.F, 177828.F,
  117649. 166977.F, 156788.F, 147221.F, 138237.F,
  117650. 129802.F, 121881.F, 114444.F, 107461.F,
  117651. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117652. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117653. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117654. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117655. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117656. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117657. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117658. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117659. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117660. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117661. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117662. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117663. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117664. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117665. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117666. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117667. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117668. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117669. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117670. 842.910F, 791.475F, 743.179F, 697.830F,
  117671. 655.249F, 615.265F, 577.722F, 542.469F,
  117672. 509.367F, 478.286F, 449.101F, 421.696F,
  117673. 395.964F, 371.803F, 349.115F, 327.812F,
  117674. 307.809F, 289.026F, 271.390F, 254.830F,
  117675. 239.280F, 224.679F, 210.969F, 198.096F,
  117676. 186.008F, 174.658F, 164.000F, 153.993F,
  117677. 144.596F, 135.773F, 127.488F, 119.708F,
  117678. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117679. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117680. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117681. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117682. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117683. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117684. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117685. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117686. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117687. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117688. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117689. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117690. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117691. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117692. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117693. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117694. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117695. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117696. 1.20790F, 1.13419F, 1.06499F, 1.F
  117697. };
  117698. void _vp_remove_floor(vorbis_look_psy *p,
  117699. float *mdct,
  117700. int *codedflr,
  117701. float *residue,
  117702. int sliding_lowpass){
  117703. int i,n=p->n;
  117704. if(sliding_lowpass>n)sliding_lowpass=n;
  117705. for(i=0;i<sliding_lowpass;i++){
  117706. residue[i]=
  117707. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117708. }
  117709. for(;i<n;i++)
  117710. residue[i]=0.;
  117711. }
  117712. void _vp_noisemask(vorbis_look_psy *p,
  117713. float *logmdct,
  117714. float *logmask){
  117715. int i,n=p->n;
  117716. float *work=(float*) alloca(n*sizeof(*work));
  117717. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117718. 140.,-1);
  117719. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117720. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117721. p->vi->noisewindowfixed);
  117722. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117723. #if 0
  117724. {
  117725. static int seq=0;
  117726. float work2[n];
  117727. for(i=0;i<n;i++){
  117728. work2[i]=logmask[i]+work[i];
  117729. }
  117730. if(seq&1)
  117731. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117732. else
  117733. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117734. if(seq&1)
  117735. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117736. else
  117737. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117738. seq++;
  117739. }
  117740. #endif
  117741. for(i=0;i<n;i++){
  117742. int dB=logmask[i]+.5;
  117743. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117744. if(dB<0)dB=0;
  117745. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117746. }
  117747. }
  117748. void _vp_tonemask(vorbis_look_psy *p,
  117749. float *logfft,
  117750. float *logmask,
  117751. float global_specmax,
  117752. float local_specmax){
  117753. int i,n=p->n;
  117754. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117755. float att=local_specmax+p->vi->ath_adjatt;
  117756. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117757. /* set the ATH (floating below localmax, not global max by a
  117758. specified att) */
  117759. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117760. for(i=0;i<n;i++)
  117761. logmask[i]=p->ath[i]+att;
  117762. /* tone masking */
  117763. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117764. max_seeds(p,seed,logmask);
  117765. }
  117766. void _vp_offset_and_mix(vorbis_look_psy *p,
  117767. float *noise,
  117768. float *tone,
  117769. int offset_select,
  117770. float *logmask,
  117771. float *mdct,
  117772. float *logmdct){
  117773. int i,n=p->n;
  117774. float de, coeffi, cx;/* AoTuV */
  117775. float toneatt=p->vi->tone_masteratt[offset_select];
  117776. cx = p->m_val;
  117777. for(i=0;i<n;i++){
  117778. float val= noise[i]+p->noiseoffset[offset_select][i];
  117779. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117780. logmask[i]=max(val,tone[i]+toneatt);
  117781. /* AoTuV */
  117782. /** @ M1 **
  117783. The following codes improve a noise problem.
  117784. A fundamental idea uses the value of masking and carries out
  117785. the relative compensation of the MDCT.
  117786. However, this code is not perfect and all noise problems cannot be solved.
  117787. by Aoyumi @ 2004/04/18
  117788. */
  117789. if(offset_select == 1) {
  117790. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117791. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117792. if(val > coeffi){
  117793. /* mdct value is > -17.2 dB below floor */
  117794. de = 1.0-((val-coeffi)*0.005*cx);
  117795. /* pro-rated attenuation:
  117796. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117797. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117798. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117799. etc... */
  117800. if(de < 0) de = 0.0001;
  117801. }else
  117802. /* mdct value is <= -17.2 dB below floor */
  117803. de = 1.0-((val-coeffi)*0.0003*cx);
  117804. /* pro-rated attenuation:
  117805. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117806. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117807. etc... */
  117808. mdct[i] *= de;
  117809. }
  117810. }
  117811. }
  117812. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117813. vorbis_info *vi=vd->vi;
  117814. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117815. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117816. int n=ci->blocksizes[vd->W]/2;
  117817. float secs=(float)n/vi->rate;
  117818. amp+=secs*gi->ampmax_att_per_sec;
  117819. if(amp<-9999)amp=-9999;
  117820. return(amp);
  117821. }
  117822. static void couple_lossless(float A, float B,
  117823. float *qA, float *qB){
  117824. int test1=fabs(*qA)>fabs(*qB);
  117825. test1-= fabs(*qA)<fabs(*qB);
  117826. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117827. if(test1==1){
  117828. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117829. }else{
  117830. float temp=*qB;
  117831. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117832. *qA=temp;
  117833. }
  117834. if(*qB>fabs(*qA)*1.9999f){
  117835. *qB= -fabs(*qA)*2.f;
  117836. *qA= -*qA;
  117837. }
  117838. }
  117839. static float hypot_lookup[32]={
  117840. -0.009935, -0.011245, -0.012726, -0.014397,
  117841. -0.016282, -0.018407, -0.020800, -0.023494,
  117842. -0.026522, -0.029923, -0.033737, -0.038010,
  117843. -0.042787, -0.048121, -0.054064, -0.060671,
  117844. -0.068000, -0.076109, -0.085054, -0.094892,
  117845. -0.105675, -0.117451, -0.130260, -0.144134,
  117846. -0.159093, -0.175146, -0.192286, -0.210490,
  117847. -0.229718, -0.249913, -0.271001, -0.292893};
  117848. static void precomputed_couple_point(float premag,
  117849. int floorA,int floorB,
  117850. float *mag, float *ang){
  117851. int test=(floorA>floorB)-1;
  117852. int offset=31-abs(floorA-floorB);
  117853. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117854. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117855. *mag=premag*floormag;
  117856. *ang=0.f;
  117857. }
  117858. /* just like below, this is currently set up to only do
  117859. single-step-depth coupling. Otherwise, we'd have to do more
  117860. copying (which will be inevitable later) */
  117861. /* doing the real circular magnitude calculation is audibly superior
  117862. to (A+B)/sqrt(2) */
  117863. static float dipole_hypot(float a, float b){
  117864. if(a>0.){
  117865. if(b>0.)return sqrt(a*a+b*b);
  117866. if(a>-b)return sqrt(a*a-b*b);
  117867. return -sqrt(b*b-a*a);
  117868. }
  117869. if(b<0.)return -sqrt(a*a+b*b);
  117870. if(-a>b)return -sqrt(a*a-b*b);
  117871. return sqrt(b*b-a*a);
  117872. }
  117873. static float round_hypot(float a, float b){
  117874. if(a>0.){
  117875. if(b>0.)return sqrt(a*a+b*b);
  117876. if(a>-b)return sqrt(a*a+b*b);
  117877. return -sqrt(b*b+a*a);
  117878. }
  117879. if(b<0.)return -sqrt(a*a+b*b);
  117880. if(-a>b)return -sqrt(a*a+b*b);
  117881. return sqrt(b*b+a*a);
  117882. }
  117883. /* revert to round hypot for now */
  117884. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117885. vorbis_info_psy_global *g,
  117886. vorbis_look_psy *p,
  117887. vorbis_info_mapping0 *vi,
  117888. float **mdct){
  117889. int i,j,n=p->n;
  117890. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117891. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117892. for(i=0;i<vi->coupling_steps;i++){
  117893. float *mdctM=mdct[vi->coupling_mag[i]];
  117894. float *mdctA=mdct[vi->coupling_ang[i]];
  117895. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117896. for(j=0;j<limit;j++)
  117897. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117898. for(;j<n;j++)
  117899. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117900. }
  117901. return(ret);
  117902. }
  117903. /* this is for per-channel noise normalization */
  117904. static int JUCE_CDECL apsort(const void *a, const void *b){
  117905. float f1=fabs(**(float**)a);
  117906. float f2=fabs(**(float**)b);
  117907. return (f1<f2)-(f1>f2);
  117908. }
  117909. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117910. vorbis_look_psy *p,
  117911. vorbis_info_mapping0 *vi,
  117912. float **mags){
  117913. if(p->vi->normal_point_p){
  117914. int i,j,k,n=p->n;
  117915. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117916. int partition=p->vi->normal_partition;
  117917. float **work=(float**) alloca(sizeof(*work)*partition);
  117918. for(i=0;i<vi->coupling_steps;i++){
  117919. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117920. for(j=0;j<n;j+=partition){
  117921. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117922. qsort(work,partition,sizeof(*work),apsort);
  117923. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117924. }
  117925. }
  117926. return(ret);
  117927. }
  117928. return(NULL);
  117929. }
  117930. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117931. float *magnitudes,int *sortedindex){
  117932. int i,j,n=p->n;
  117933. vorbis_info_psy *vi=p->vi;
  117934. int partition=vi->normal_partition;
  117935. float **work=(float**) alloca(sizeof(*work)*partition);
  117936. int start=vi->normal_start;
  117937. for(j=start;j<n;j+=partition){
  117938. if(j+partition>n)partition=n-j;
  117939. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117940. qsort(work,partition,sizeof(*work),apsort);
  117941. for(i=0;i<partition;i++){
  117942. sortedindex[i+j-start]=work[i]-magnitudes;
  117943. }
  117944. }
  117945. }
  117946. void _vp_noise_normalize(vorbis_look_psy *p,
  117947. float *in,float *out,int *sortedindex){
  117948. int flag=0,i,j=0,n=p->n;
  117949. vorbis_info_psy *vi=p->vi;
  117950. int partition=vi->normal_partition;
  117951. int start=vi->normal_start;
  117952. if(start>n)start=n;
  117953. if(vi->normal_channel_p){
  117954. for(;j<start;j++)
  117955. out[j]=rint(in[j]);
  117956. for(;j+partition<=n;j+=partition){
  117957. float acc=0.;
  117958. int k;
  117959. for(i=j;i<j+partition;i++)
  117960. acc+=in[i]*in[i];
  117961. for(i=0;i<partition;i++){
  117962. k=sortedindex[i+j-start];
  117963. if(in[k]*in[k]>=.25f){
  117964. out[k]=rint(in[k]);
  117965. acc-=in[k]*in[k];
  117966. flag=1;
  117967. }else{
  117968. if(acc<vi->normal_thresh)break;
  117969. out[k]=unitnorm(in[k]);
  117970. acc-=1.;
  117971. }
  117972. }
  117973. for(;i<partition;i++){
  117974. k=sortedindex[i+j-start];
  117975. out[k]=0.;
  117976. }
  117977. }
  117978. }
  117979. for(;j<n;j++)
  117980. out[j]=rint(in[j]);
  117981. }
  117982. void _vp_couple(int blobno,
  117983. vorbis_info_psy_global *g,
  117984. vorbis_look_psy *p,
  117985. vorbis_info_mapping0 *vi,
  117986. float **res,
  117987. float **mag_memo,
  117988. int **mag_sort,
  117989. int **ifloor,
  117990. int *nonzero,
  117991. int sliding_lowpass){
  117992. int i,j,k,n=p->n;
  117993. /* perform any requested channel coupling */
  117994. /* point stereo can only be used in a first stage (in this encoder)
  117995. because of the dependency on floor lookups */
  117996. for(i=0;i<vi->coupling_steps;i++){
  117997. /* once we're doing multistage coupling in which a channel goes
  117998. through more than one coupling step, the floor vector
  117999. magnitudes will also have to be recalculated an propogated
  118000. along with PCM. Right now, we're not (that will wait until 5.1
  118001. most likely), so the code isn't here yet. The memory management
  118002. here is all assuming single depth couplings anyway. */
  118003. /* make sure coupling a zero and a nonzero channel results in two
  118004. nonzero channels. */
  118005. if(nonzero[vi->coupling_mag[i]] ||
  118006. nonzero[vi->coupling_ang[i]]){
  118007. float *rM=res[vi->coupling_mag[i]];
  118008. float *rA=res[vi->coupling_ang[i]];
  118009. float *qM=rM+n;
  118010. float *qA=rA+n;
  118011. int *floorM=ifloor[vi->coupling_mag[i]];
  118012. int *floorA=ifloor[vi->coupling_ang[i]];
  118013. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  118014. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  118015. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  118016. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  118017. int pointlimit=limit;
  118018. nonzero[vi->coupling_mag[i]]=1;
  118019. nonzero[vi->coupling_ang[i]]=1;
  118020. /* The threshold of a stereo is changed with the size of n */
  118021. if(n > 1000)
  118022. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  118023. for(j=0;j<p->n;j+=partition){
  118024. float acc=0.f;
  118025. for(k=0;k<partition;k++){
  118026. int l=k+j;
  118027. if(l<sliding_lowpass){
  118028. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118029. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118030. precomputed_couple_point(mag_memo[i][l],
  118031. floorM[l],floorA[l],
  118032. qM+l,qA+l);
  118033. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118034. }else{
  118035. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118036. }
  118037. }else{
  118038. qM[l]=0.;
  118039. qA[l]=0.;
  118040. }
  118041. }
  118042. if(p->vi->normal_point_p){
  118043. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118044. int l=mag_sort[i][j+k];
  118045. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118046. qM[l]=unitnorm(qM[l]);
  118047. acc-=1.f;
  118048. }
  118049. }
  118050. }
  118051. }
  118052. }
  118053. }
  118054. }
  118055. /* AoTuV */
  118056. /** @ M2 **
  118057. The boost problem by the combination of noise normalization and point stereo is eased.
  118058. However, this is a temporary patch.
  118059. by Aoyumi @ 2004/04/18
  118060. */
  118061. void hf_reduction(vorbis_info_psy_global *g,
  118062. vorbis_look_psy *p,
  118063. vorbis_info_mapping0 *vi,
  118064. float **mdct){
  118065. int i,j,n=p->n, de=0.3*p->m_val;
  118066. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118067. for(i=0; i<vi->coupling_steps; i++){
  118068. /* for(j=start; j<limit; j++){} // ???*/
  118069. for(j=limit; j<n; j++)
  118070. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118071. }
  118072. }
  118073. #endif
  118074. /*** End of inlined file: psy.c ***/
  118075. /*** Start of inlined file: registry.c ***/
  118076. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118077. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118078. // tasks..
  118079. #if JUCE_MSVC
  118080. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118081. #endif
  118082. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118083. #if JUCE_USE_OGGVORBIS
  118084. /* seems like major overkill now; the backend numbers will grow into
  118085. the infrastructure soon enough */
  118086. extern vorbis_func_floor floor0_exportbundle;
  118087. extern vorbis_func_floor floor1_exportbundle;
  118088. extern vorbis_func_residue residue0_exportbundle;
  118089. extern vorbis_func_residue residue1_exportbundle;
  118090. extern vorbis_func_residue residue2_exportbundle;
  118091. extern vorbis_func_mapping mapping0_exportbundle;
  118092. vorbis_func_floor *_floor_P[]={
  118093. &floor0_exportbundle,
  118094. &floor1_exportbundle,
  118095. };
  118096. vorbis_func_residue *_residue_P[]={
  118097. &residue0_exportbundle,
  118098. &residue1_exportbundle,
  118099. &residue2_exportbundle,
  118100. };
  118101. vorbis_func_mapping *_mapping_P[]={
  118102. &mapping0_exportbundle,
  118103. };
  118104. #endif
  118105. /*** End of inlined file: registry.c ***/
  118106. /*** Start of inlined file: res0.c ***/
  118107. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118108. encode/decode loops are coded for clarity and performance is not
  118109. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118110. it's slow. */
  118111. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118112. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118113. // tasks..
  118114. #if JUCE_MSVC
  118115. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118116. #endif
  118117. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118118. #if JUCE_USE_OGGVORBIS
  118119. #include <stdlib.h>
  118120. #include <string.h>
  118121. #include <math.h>
  118122. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118123. #include <stdio.h>
  118124. #endif
  118125. typedef struct {
  118126. vorbis_info_residue0 *info;
  118127. int parts;
  118128. int stages;
  118129. codebook *fullbooks;
  118130. codebook *phrasebook;
  118131. codebook ***partbooks;
  118132. int partvals;
  118133. int **decodemap;
  118134. long postbits;
  118135. long phrasebits;
  118136. long frames;
  118137. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118138. int train_seq;
  118139. long *training_data[8][64];
  118140. float training_max[8][64];
  118141. float training_min[8][64];
  118142. float tmin;
  118143. float tmax;
  118144. #endif
  118145. } vorbis_look_residue0;
  118146. void res0_free_info(vorbis_info_residue *i){
  118147. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118148. if(info){
  118149. memset(info,0,sizeof(*info));
  118150. _ogg_free(info);
  118151. }
  118152. }
  118153. void res0_free_look(vorbis_look_residue *i){
  118154. int j;
  118155. if(i){
  118156. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118157. #ifdef TRAIN_RES
  118158. {
  118159. int j,k,l;
  118160. for(j=0;j<look->parts;j++){
  118161. /*fprintf(stderr,"partition %d: ",j);*/
  118162. for(k=0;k<8;k++)
  118163. if(look->training_data[k][j]){
  118164. char buffer[80];
  118165. FILE *of;
  118166. codebook *statebook=look->partbooks[j][k];
  118167. /* long and short into the same bucket by current convention */
  118168. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118169. of=fopen(buffer,"a");
  118170. for(l=0;l<statebook->entries;l++)
  118171. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118172. fclose(of);
  118173. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118174. look->training_min[k][j],look->training_max[k][j]);*/
  118175. _ogg_free(look->training_data[k][j]);
  118176. look->training_data[k][j]=NULL;
  118177. }
  118178. /*fprintf(stderr,"\n");*/
  118179. }
  118180. }
  118181. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118182. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118183. (float)look->phrasebits/look->frames,
  118184. (float)look->postbits/look->frames,
  118185. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118186. #endif
  118187. /*vorbis_info_residue0 *info=look->info;
  118188. fprintf(stderr,
  118189. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118190. "(%g/frame) \n",look->frames,look->phrasebits,
  118191. look->resbitsflat,
  118192. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118193. for(j=0;j<look->parts;j++){
  118194. long acc=0;
  118195. fprintf(stderr,"\t[%d] == ",j);
  118196. for(k=0;k<look->stages;k++)
  118197. if((info->secondstages[j]>>k)&1){
  118198. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118199. acc+=look->resbits[j][k];
  118200. }
  118201. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118202. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118203. }
  118204. fprintf(stderr,"\n");*/
  118205. for(j=0;j<look->parts;j++)
  118206. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118207. _ogg_free(look->partbooks);
  118208. for(j=0;j<look->partvals;j++)
  118209. _ogg_free(look->decodemap[j]);
  118210. _ogg_free(look->decodemap);
  118211. memset(look,0,sizeof(*look));
  118212. _ogg_free(look);
  118213. }
  118214. }
  118215. static int icount(unsigned int v){
  118216. int ret=0;
  118217. while(v){
  118218. ret+=v&1;
  118219. v>>=1;
  118220. }
  118221. return(ret);
  118222. }
  118223. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118224. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118225. int j,acc=0;
  118226. oggpack_write(opb,info->begin,24);
  118227. oggpack_write(opb,info->end,24);
  118228. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118229. code with a partitioned book */
  118230. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118231. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118232. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118233. bitmask of one indicates this partition class has bits to write
  118234. this pass */
  118235. for(j=0;j<info->partitions;j++){
  118236. if(ilog(info->secondstages[j])>3){
  118237. /* yes, this is a minor hack due to not thinking ahead */
  118238. oggpack_write(opb,info->secondstages[j],3);
  118239. oggpack_write(opb,1,1);
  118240. oggpack_write(opb,info->secondstages[j]>>3,5);
  118241. }else
  118242. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118243. acc+=icount(info->secondstages[j]);
  118244. }
  118245. for(j=0;j<acc;j++)
  118246. oggpack_write(opb,info->booklist[j],8);
  118247. }
  118248. /* vorbis_info is for range checking */
  118249. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118250. int j,acc=0;
  118251. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118252. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118253. info->begin=oggpack_read(opb,24);
  118254. info->end=oggpack_read(opb,24);
  118255. info->grouping=oggpack_read(opb,24)+1;
  118256. info->partitions=oggpack_read(opb,6)+1;
  118257. info->groupbook=oggpack_read(opb,8);
  118258. for(j=0;j<info->partitions;j++){
  118259. int cascade=oggpack_read(opb,3);
  118260. if(oggpack_read(opb,1))
  118261. cascade|=(oggpack_read(opb,5)<<3);
  118262. info->secondstages[j]=cascade;
  118263. acc+=icount(cascade);
  118264. }
  118265. for(j=0;j<acc;j++)
  118266. info->booklist[j]=oggpack_read(opb,8);
  118267. if(info->groupbook>=ci->books)goto errout;
  118268. for(j=0;j<acc;j++)
  118269. if(info->booklist[j]>=ci->books)goto errout;
  118270. return(info);
  118271. errout:
  118272. res0_free_info(info);
  118273. return(NULL);
  118274. }
  118275. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118276. vorbis_info_residue *vr){
  118277. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118278. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118279. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118280. int j,k,acc=0;
  118281. int dim;
  118282. int maxstage=0;
  118283. look->info=info;
  118284. look->parts=info->partitions;
  118285. look->fullbooks=ci->fullbooks;
  118286. look->phrasebook=ci->fullbooks+info->groupbook;
  118287. dim=look->phrasebook->dim;
  118288. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118289. for(j=0;j<look->parts;j++){
  118290. int stages=ilog(info->secondstages[j]);
  118291. if(stages){
  118292. if(stages>maxstage)maxstage=stages;
  118293. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118294. for(k=0;k<stages;k++)
  118295. if(info->secondstages[j]&(1<<k)){
  118296. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118297. #ifdef TRAIN_RES
  118298. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118299. sizeof(***look->training_data));
  118300. #endif
  118301. }
  118302. }
  118303. }
  118304. look->partvals=rint(pow((float)look->parts,(float)dim));
  118305. look->stages=maxstage;
  118306. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118307. for(j=0;j<look->partvals;j++){
  118308. long val=j;
  118309. long mult=look->partvals/look->parts;
  118310. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118311. for(k=0;k<dim;k++){
  118312. long deco=val/mult;
  118313. val-=deco*mult;
  118314. mult/=look->parts;
  118315. look->decodemap[j][k]=deco;
  118316. }
  118317. }
  118318. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118319. {
  118320. static int train_seq=0;
  118321. look->train_seq=train_seq++;
  118322. }
  118323. #endif
  118324. return(look);
  118325. }
  118326. /* break an abstraction and copy some code for performance purposes */
  118327. static int local_book_besterror(codebook *book,float *a){
  118328. int dim=book->dim,i,k,o;
  118329. int best=0;
  118330. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118331. /* find the quant val of each scalar */
  118332. for(k=0,o=dim;k<dim;++k){
  118333. float val=a[--o];
  118334. i=tt->threshvals>>1;
  118335. if(val<tt->quantthresh[i]){
  118336. if(val<tt->quantthresh[i-1]){
  118337. for(--i;i>0;--i)
  118338. if(val>=tt->quantthresh[i-1])
  118339. break;
  118340. }
  118341. }else{
  118342. for(++i;i<tt->threshvals-1;++i)
  118343. if(val<tt->quantthresh[i])break;
  118344. }
  118345. best=(best*tt->quantvals)+tt->quantmap[i];
  118346. }
  118347. /* regular lattices are easy :-) */
  118348. if(book->c->lengthlist[best]<=0){
  118349. const static_codebook *c=book->c;
  118350. int i,j;
  118351. float bestf=0.f;
  118352. float *e=book->valuelist;
  118353. best=-1;
  118354. for(i=0;i<book->entries;i++){
  118355. if(c->lengthlist[i]>0){
  118356. float thisx=0.f;
  118357. for(j=0;j<dim;j++){
  118358. float val=(e[j]-a[j]);
  118359. thisx+=val*val;
  118360. }
  118361. if(best==-1 || thisx<bestf){
  118362. bestf=thisx;
  118363. best=i;
  118364. }
  118365. }
  118366. e+=dim;
  118367. }
  118368. }
  118369. {
  118370. float *ptr=book->valuelist+best*dim;
  118371. for(i=0;i<dim;i++)
  118372. *a++ -= *ptr++;
  118373. }
  118374. return(best);
  118375. }
  118376. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118377. codebook *book,long *acc){
  118378. int i,bits=0;
  118379. int dim=book->dim;
  118380. int step=n/dim;
  118381. for(i=0;i<step;i++){
  118382. int entry=local_book_besterror(book,vec+i*dim);
  118383. #ifdef TRAIN_RES
  118384. acc[entry]++;
  118385. #endif
  118386. bits+=vorbis_book_encode(book,entry,opb);
  118387. }
  118388. return(bits);
  118389. }
  118390. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118391. float **in,int ch){
  118392. long i,j,k;
  118393. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118394. vorbis_info_residue0 *info=look->info;
  118395. /* move all this setup out later */
  118396. int samples_per_partition=info->grouping;
  118397. int possible_partitions=info->partitions;
  118398. int n=info->end-info->begin;
  118399. int partvals=n/samples_per_partition;
  118400. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118401. float scale=100./samples_per_partition;
  118402. /* we find the partition type for each partition of each
  118403. channel. We'll go back and do the interleaved encoding in a
  118404. bit. For now, clarity */
  118405. for(i=0;i<ch;i++){
  118406. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118407. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118408. }
  118409. for(i=0;i<partvals;i++){
  118410. int offset=i*samples_per_partition+info->begin;
  118411. for(j=0;j<ch;j++){
  118412. float max=0.;
  118413. float ent=0.;
  118414. for(k=0;k<samples_per_partition;k++){
  118415. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118416. ent+=fabs(rint(in[j][offset+k]));
  118417. }
  118418. ent*=scale;
  118419. for(k=0;k<possible_partitions-1;k++)
  118420. if(max<=info->classmetric1[k] &&
  118421. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118422. break;
  118423. partword[j][i]=k;
  118424. }
  118425. }
  118426. #ifdef TRAIN_RESAUX
  118427. {
  118428. FILE *of;
  118429. char buffer[80];
  118430. for(i=0;i<ch;i++){
  118431. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118432. of=fopen(buffer,"a");
  118433. for(j=0;j<partvals;j++)
  118434. fprintf(of,"%ld, ",partword[i][j]);
  118435. fprintf(of,"\n");
  118436. fclose(of);
  118437. }
  118438. }
  118439. #endif
  118440. look->frames++;
  118441. return(partword);
  118442. }
  118443. /* designed for stereo or other modes where the partition size is an
  118444. integer multiple of the number of channels encoded in the current
  118445. submap */
  118446. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118447. int ch){
  118448. long i,j,k,l;
  118449. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118450. vorbis_info_residue0 *info=look->info;
  118451. /* move all this setup out later */
  118452. int samples_per_partition=info->grouping;
  118453. int possible_partitions=info->partitions;
  118454. int n=info->end-info->begin;
  118455. int partvals=n/samples_per_partition;
  118456. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118457. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118458. FILE *of;
  118459. char buffer[80];
  118460. #endif
  118461. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118462. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118463. for(i=0,l=info->begin/ch;i<partvals;i++){
  118464. float magmax=0.f;
  118465. float angmax=0.f;
  118466. for(j=0;j<samples_per_partition;j+=ch){
  118467. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118468. for(k=1;k<ch;k++)
  118469. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118470. l++;
  118471. }
  118472. for(j=0;j<possible_partitions-1;j++)
  118473. if(magmax<=info->classmetric1[j] &&
  118474. angmax<=info->classmetric2[j])
  118475. break;
  118476. partword[0][i]=j;
  118477. }
  118478. #ifdef TRAIN_RESAUX
  118479. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118480. of=fopen(buffer,"a");
  118481. for(i=0;i<partvals;i++)
  118482. fprintf(of,"%ld, ",partword[0][i]);
  118483. fprintf(of,"\n");
  118484. fclose(of);
  118485. #endif
  118486. look->frames++;
  118487. return(partword);
  118488. }
  118489. static int _01forward(oggpack_buffer *opb,
  118490. vorbis_block *vb,vorbis_look_residue *vl,
  118491. float **in,int ch,
  118492. long **partword,
  118493. int (*encode)(oggpack_buffer *,float *,int,
  118494. codebook *,long *)){
  118495. long i,j,k,s;
  118496. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118497. vorbis_info_residue0 *info=look->info;
  118498. /* move all this setup out later */
  118499. int samples_per_partition=info->grouping;
  118500. int possible_partitions=info->partitions;
  118501. int partitions_per_word=look->phrasebook->dim;
  118502. int n=info->end-info->begin;
  118503. int partvals=n/samples_per_partition;
  118504. long resbits[128];
  118505. long resvals[128];
  118506. #ifdef TRAIN_RES
  118507. for(i=0;i<ch;i++)
  118508. for(j=info->begin;j<info->end;j++){
  118509. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118510. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118511. }
  118512. #endif
  118513. memset(resbits,0,sizeof(resbits));
  118514. memset(resvals,0,sizeof(resvals));
  118515. /* we code the partition words for each channel, then the residual
  118516. words for a partition per channel until we've written all the
  118517. residual words for that partition word. Then write the next
  118518. partition channel words... */
  118519. for(s=0;s<look->stages;s++){
  118520. for(i=0;i<partvals;){
  118521. /* first we encode a partition codeword for each channel */
  118522. if(s==0){
  118523. for(j=0;j<ch;j++){
  118524. long val=partword[j][i];
  118525. for(k=1;k<partitions_per_word;k++){
  118526. val*=possible_partitions;
  118527. if(i+k<partvals)
  118528. val+=partword[j][i+k];
  118529. }
  118530. /* training hack */
  118531. if(val<look->phrasebook->entries)
  118532. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118533. #if 0 /*def TRAIN_RES*/
  118534. else
  118535. fprintf(stderr,"!");
  118536. #endif
  118537. }
  118538. }
  118539. /* now we encode interleaved residual values for the partitions */
  118540. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118541. long offset=i*samples_per_partition+info->begin;
  118542. for(j=0;j<ch;j++){
  118543. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118544. if(info->secondstages[partword[j][i]]&(1<<s)){
  118545. codebook *statebook=look->partbooks[partword[j][i]][s];
  118546. if(statebook){
  118547. int ret;
  118548. long *accumulator=NULL;
  118549. #ifdef TRAIN_RES
  118550. accumulator=look->training_data[s][partword[j][i]];
  118551. {
  118552. int l;
  118553. float *samples=in[j]+offset;
  118554. for(l=0;l<samples_per_partition;l++){
  118555. if(samples[l]<look->training_min[s][partword[j][i]])
  118556. look->training_min[s][partword[j][i]]=samples[l];
  118557. if(samples[l]>look->training_max[s][partword[j][i]])
  118558. look->training_max[s][partword[j][i]]=samples[l];
  118559. }
  118560. }
  118561. #endif
  118562. ret=encode(opb,in[j]+offset,samples_per_partition,
  118563. statebook,accumulator);
  118564. look->postbits+=ret;
  118565. resbits[partword[j][i]]+=ret;
  118566. }
  118567. }
  118568. }
  118569. }
  118570. }
  118571. }
  118572. /*{
  118573. long total=0;
  118574. long totalbits=0;
  118575. fprintf(stderr,"%d :: ",vb->mode);
  118576. for(k=0;k<possible_partitions;k++){
  118577. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118578. total+=resvals[k];
  118579. totalbits+=resbits[k];
  118580. }
  118581. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118582. }*/
  118583. return(0);
  118584. }
  118585. /* a truncated packet here just means 'stop working'; it's not an error */
  118586. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118587. float **in,int ch,
  118588. long (*decodepart)(codebook *, float *,
  118589. oggpack_buffer *,int)){
  118590. long i,j,k,l,s;
  118591. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118592. vorbis_info_residue0 *info=look->info;
  118593. /* move all this setup out later */
  118594. int samples_per_partition=info->grouping;
  118595. int partitions_per_word=look->phrasebook->dim;
  118596. int n=info->end-info->begin;
  118597. int partvals=n/samples_per_partition;
  118598. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118599. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118600. for(j=0;j<ch;j++)
  118601. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118602. for(s=0;s<look->stages;s++){
  118603. /* each loop decodes on partition codeword containing
  118604. partitions_pre_word partitions */
  118605. for(i=0,l=0;i<partvals;l++){
  118606. if(s==0){
  118607. /* fetch the partition word for each channel */
  118608. for(j=0;j<ch;j++){
  118609. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118610. if(temp==-1)goto eopbreak;
  118611. partword[j][l]=look->decodemap[temp];
  118612. if(partword[j][l]==NULL)goto errout;
  118613. }
  118614. }
  118615. /* now we decode residual values for the partitions */
  118616. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118617. for(j=0;j<ch;j++){
  118618. long offset=info->begin+i*samples_per_partition;
  118619. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118620. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118621. if(stagebook){
  118622. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118623. samples_per_partition)==-1)goto eopbreak;
  118624. }
  118625. }
  118626. }
  118627. }
  118628. }
  118629. errout:
  118630. eopbreak:
  118631. return(0);
  118632. }
  118633. #if 0
  118634. /* residue 0 and 1 are just slight variants of one another. 0 is
  118635. interleaved, 1 is not */
  118636. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118637. float **in,int *nonzero,int ch){
  118638. /* we encode only the nonzero parts of a bundle */
  118639. int i,used=0;
  118640. for(i=0;i<ch;i++)
  118641. if(nonzero[i])
  118642. in[used++]=in[i];
  118643. if(used)
  118644. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118645. return(_01class(vb,vl,in,used));
  118646. else
  118647. return(0);
  118648. }
  118649. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118650. float **in,float **out,int *nonzero,int ch,
  118651. long **partword){
  118652. /* we encode only the nonzero parts of a bundle */
  118653. int i,j,used=0,n=vb->pcmend/2;
  118654. for(i=0;i<ch;i++)
  118655. if(nonzero[i]){
  118656. if(out)
  118657. for(j=0;j<n;j++)
  118658. out[i][j]+=in[i][j];
  118659. in[used++]=in[i];
  118660. }
  118661. if(used){
  118662. int ret=_01forward(vb,vl,in,used,partword,
  118663. _interleaved_encodepart);
  118664. if(out){
  118665. used=0;
  118666. for(i=0;i<ch;i++)
  118667. if(nonzero[i]){
  118668. for(j=0;j<n;j++)
  118669. out[i][j]-=in[used][j];
  118670. used++;
  118671. }
  118672. }
  118673. return(ret);
  118674. }else{
  118675. return(0);
  118676. }
  118677. }
  118678. #endif
  118679. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118680. float **in,int *nonzero,int ch){
  118681. int i,used=0;
  118682. for(i=0;i<ch;i++)
  118683. if(nonzero[i])
  118684. in[used++]=in[i];
  118685. if(used)
  118686. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118687. else
  118688. return(0);
  118689. }
  118690. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118691. float **in,float **out,int *nonzero,int ch,
  118692. long **partword){
  118693. int i,j,used=0,n=vb->pcmend/2;
  118694. for(i=0;i<ch;i++)
  118695. if(nonzero[i]){
  118696. if(out)
  118697. for(j=0;j<n;j++)
  118698. out[i][j]+=in[i][j];
  118699. in[used++]=in[i];
  118700. }
  118701. if(used){
  118702. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118703. if(out){
  118704. used=0;
  118705. for(i=0;i<ch;i++)
  118706. if(nonzero[i]){
  118707. for(j=0;j<n;j++)
  118708. out[i][j]-=in[used][j];
  118709. used++;
  118710. }
  118711. }
  118712. return(ret);
  118713. }else{
  118714. return(0);
  118715. }
  118716. }
  118717. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118718. float **in,int *nonzero,int ch){
  118719. int i,used=0;
  118720. for(i=0;i<ch;i++)
  118721. if(nonzero[i])
  118722. in[used++]=in[i];
  118723. if(used)
  118724. return(_01class(vb,vl,in,used));
  118725. else
  118726. return(0);
  118727. }
  118728. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118729. float **in,int *nonzero,int ch){
  118730. int i,used=0;
  118731. for(i=0;i<ch;i++)
  118732. if(nonzero[i])
  118733. in[used++]=in[i];
  118734. if(used)
  118735. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118736. else
  118737. return(0);
  118738. }
  118739. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118740. float **in,int *nonzero,int ch){
  118741. int i,used=0;
  118742. for(i=0;i<ch;i++)
  118743. if(nonzero[i])used++;
  118744. if(used)
  118745. return(_2class(vb,vl,in,ch));
  118746. else
  118747. return(0);
  118748. }
  118749. /* res2 is slightly more different; all the channels are interleaved
  118750. into a single vector and encoded. */
  118751. int res2_forward(oggpack_buffer *opb,
  118752. vorbis_block *vb,vorbis_look_residue *vl,
  118753. float **in,float **out,int *nonzero,int ch,
  118754. long **partword){
  118755. long i,j,k,n=vb->pcmend/2,used=0;
  118756. /* don't duplicate the code; use a working vector hack for now and
  118757. reshape ourselves into a single channel res1 */
  118758. /* ugly; reallocs for each coupling pass :-( */
  118759. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118760. for(i=0;i<ch;i++){
  118761. float *pcm=in[i];
  118762. if(nonzero[i])used++;
  118763. for(j=0,k=i;j<n;j++,k+=ch)
  118764. work[k]=pcm[j];
  118765. }
  118766. if(used){
  118767. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118768. /* update the sofar vector */
  118769. if(out){
  118770. for(i=0;i<ch;i++){
  118771. float *pcm=in[i];
  118772. float *sofar=out[i];
  118773. for(j=0,k=i;j<n;j++,k+=ch)
  118774. sofar[j]+=pcm[j]-work[k];
  118775. }
  118776. }
  118777. return(ret);
  118778. }else{
  118779. return(0);
  118780. }
  118781. }
  118782. /* duplicate code here as speed is somewhat more important */
  118783. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118784. float **in,int *nonzero,int ch){
  118785. long i,k,l,s;
  118786. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118787. vorbis_info_residue0 *info=look->info;
  118788. /* move all this setup out later */
  118789. int samples_per_partition=info->grouping;
  118790. int partitions_per_word=look->phrasebook->dim;
  118791. int n=info->end-info->begin;
  118792. int partvals=n/samples_per_partition;
  118793. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118794. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118795. for(i=0;i<ch;i++)if(nonzero[i])break;
  118796. if(i==ch)return(0); /* no nonzero vectors */
  118797. for(s=0;s<look->stages;s++){
  118798. for(i=0,l=0;i<partvals;l++){
  118799. if(s==0){
  118800. /* fetch the partition word */
  118801. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118802. if(temp==-1)goto eopbreak;
  118803. partword[l]=look->decodemap[temp];
  118804. if(partword[l]==NULL)goto errout;
  118805. }
  118806. /* now we decode residual values for the partitions */
  118807. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118808. if(info->secondstages[partword[l][k]]&(1<<s)){
  118809. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118810. if(stagebook){
  118811. if(vorbis_book_decodevv_add(stagebook,in,
  118812. i*samples_per_partition+info->begin,ch,
  118813. &vb->opb,samples_per_partition)==-1)
  118814. goto eopbreak;
  118815. }
  118816. }
  118817. }
  118818. }
  118819. errout:
  118820. eopbreak:
  118821. return(0);
  118822. }
  118823. vorbis_func_residue residue0_exportbundle={
  118824. NULL,
  118825. &res0_unpack,
  118826. &res0_look,
  118827. &res0_free_info,
  118828. &res0_free_look,
  118829. NULL,
  118830. NULL,
  118831. &res0_inverse
  118832. };
  118833. vorbis_func_residue residue1_exportbundle={
  118834. &res0_pack,
  118835. &res0_unpack,
  118836. &res0_look,
  118837. &res0_free_info,
  118838. &res0_free_look,
  118839. &res1_class,
  118840. &res1_forward,
  118841. &res1_inverse
  118842. };
  118843. vorbis_func_residue residue2_exportbundle={
  118844. &res0_pack,
  118845. &res0_unpack,
  118846. &res0_look,
  118847. &res0_free_info,
  118848. &res0_free_look,
  118849. &res2_class,
  118850. &res2_forward,
  118851. &res2_inverse
  118852. };
  118853. #endif
  118854. /*** End of inlined file: res0.c ***/
  118855. /*** Start of inlined file: sharedbook.c ***/
  118856. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118857. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118858. // tasks..
  118859. #if JUCE_MSVC
  118860. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118861. #endif
  118862. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118863. #if JUCE_USE_OGGVORBIS
  118864. #include <stdlib.h>
  118865. #include <math.h>
  118866. #include <string.h>
  118867. /**** pack/unpack helpers ******************************************/
  118868. int _ilog(unsigned int v){
  118869. int ret=0;
  118870. while(v){
  118871. ret++;
  118872. v>>=1;
  118873. }
  118874. return(ret);
  118875. }
  118876. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118877. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118878. Why not IEEE? It's just not that important here. */
  118879. #define VQ_FEXP 10
  118880. #define VQ_FMAN 21
  118881. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118882. /* doesn't currently guard under/overflow */
  118883. long _float32_pack(float val){
  118884. int sign=0;
  118885. long exp;
  118886. long mant;
  118887. if(val<0){
  118888. sign=0x80000000;
  118889. val= -val;
  118890. }
  118891. exp= floor(log(val)/log(2.f));
  118892. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118893. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118894. return(sign|exp|mant);
  118895. }
  118896. float _float32_unpack(long val){
  118897. double mant=val&0x1fffff;
  118898. int sign=val&0x80000000;
  118899. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118900. if(sign)mant= -mant;
  118901. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118902. }
  118903. /* given a list of word lengths, generate a list of codewords. Works
  118904. for length ordered or unordered, always assigns the lowest valued
  118905. codewords first. Extended to handle unused entries (length 0) */
  118906. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118907. long i,j,count=0;
  118908. ogg_uint32_t marker[33];
  118909. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118910. memset(marker,0,sizeof(marker));
  118911. for(i=0;i<n;i++){
  118912. long length=l[i];
  118913. if(length>0){
  118914. ogg_uint32_t entry=marker[length];
  118915. /* when we claim a node for an entry, we also claim the nodes
  118916. below it (pruning off the imagined tree that may have dangled
  118917. from it) as well as blocking the use of any nodes directly
  118918. above for leaves */
  118919. /* update ourself */
  118920. if(length<32 && (entry>>length)){
  118921. /* error condition; the lengths must specify an overpopulated tree */
  118922. _ogg_free(r);
  118923. return(NULL);
  118924. }
  118925. r[count++]=entry;
  118926. /* Look to see if the next shorter marker points to the node
  118927. above. if so, update it and repeat. */
  118928. {
  118929. for(j=length;j>0;j--){
  118930. if(marker[j]&1){
  118931. /* have to jump branches */
  118932. if(j==1)
  118933. marker[1]++;
  118934. else
  118935. marker[j]=marker[j-1]<<1;
  118936. break; /* invariant says next upper marker would already
  118937. have been moved if it was on the same path */
  118938. }
  118939. marker[j]++;
  118940. }
  118941. }
  118942. /* prune the tree; the implicit invariant says all the longer
  118943. markers were dangling from our just-taken node. Dangle them
  118944. from our *new* node. */
  118945. for(j=length+1;j<33;j++)
  118946. if((marker[j]>>1) == entry){
  118947. entry=marker[j];
  118948. marker[j]=marker[j-1]<<1;
  118949. }else
  118950. break;
  118951. }else
  118952. if(sparsecount==0)count++;
  118953. }
  118954. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118955. endian */
  118956. for(i=0,count=0;i<n;i++){
  118957. ogg_uint32_t temp=0;
  118958. for(j=0;j<l[i];j++){
  118959. temp<<=1;
  118960. temp|=(r[count]>>j)&1;
  118961. }
  118962. if(sparsecount){
  118963. if(l[i])
  118964. r[count++]=temp;
  118965. }else
  118966. r[count++]=temp;
  118967. }
  118968. return(r);
  118969. }
  118970. /* there might be a straightforward one-line way to do the below
  118971. that's portable and totally safe against roundoff, but I haven't
  118972. thought of it. Therefore, we opt on the side of caution */
  118973. long _book_maptype1_quantvals(const static_codebook *b){
  118974. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118975. /* the above *should* be reliable, but we'll not assume that FP is
  118976. ever reliable when bitstream sync is at stake; verify via integer
  118977. means that vals really is the greatest value of dim for which
  118978. vals^b->bim <= b->entries */
  118979. /* treat the above as an initial guess */
  118980. while(1){
  118981. long acc=1;
  118982. long acc1=1;
  118983. int i;
  118984. for(i=0;i<b->dim;i++){
  118985. acc*=vals;
  118986. acc1*=vals+1;
  118987. }
  118988. if(acc<=b->entries && acc1>b->entries){
  118989. return(vals);
  118990. }else{
  118991. if(acc>b->entries){
  118992. vals--;
  118993. }else{
  118994. vals++;
  118995. }
  118996. }
  118997. }
  118998. }
  118999. /* unpack the quantized list of values for encode/decode ***********/
  119000. /* we need to deal with two map types: in map type 1, the values are
  119001. generated algorithmically (each column of the vector counts through
  119002. the values in the quant vector). in map type 2, all the values came
  119003. in in an explicit list. Both value lists must be unpacked */
  119004. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119005. long j,k,count=0;
  119006. if(b->maptype==1 || b->maptype==2){
  119007. int quantvals;
  119008. float mindel=_float32_unpack(b->q_min);
  119009. float delta=_float32_unpack(b->q_delta);
  119010. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119011. /* maptype 1 and 2 both use a quantized value vector, but
  119012. different sizes */
  119013. switch(b->maptype){
  119014. case 1:
  119015. /* most of the time, entries%dimensions == 0, but we need to be
  119016. well defined. We define that the possible vales at each
  119017. scalar is values == entries/dim. If entries%dim != 0, we'll
  119018. have 'too few' values (values*dim<entries), which means that
  119019. we'll have 'left over' entries; left over entries use zeroed
  119020. values (and are wasted). So don't generate codebooks like
  119021. that */
  119022. quantvals=_book_maptype1_quantvals(b);
  119023. for(j=0;j<b->entries;j++){
  119024. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119025. float last=0.f;
  119026. int indexdiv=1;
  119027. for(k=0;k<b->dim;k++){
  119028. int index= (j/indexdiv)%quantvals;
  119029. float val=b->quantlist[index];
  119030. val=fabs(val)*delta+mindel+last;
  119031. if(b->q_sequencep)last=val;
  119032. if(sparsemap)
  119033. r[sparsemap[count]*b->dim+k]=val;
  119034. else
  119035. r[count*b->dim+k]=val;
  119036. indexdiv*=quantvals;
  119037. }
  119038. count++;
  119039. }
  119040. }
  119041. break;
  119042. case 2:
  119043. for(j=0;j<b->entries;j++){
  119044. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119045. float last=0.f;
  119046. for(k=0;k<b->dim;k++){
  119047. float val=b->quantlist[j*b->dim+k];
  119048. val=fabs(val)*delta+mindel+last;
  119049. if(b->q_sequencep)last=val;
  119050. if(sparsemap)
  119051. r[sparsemap[count]*b->dim+k]=val;
  119052. else
  119053. r[count*b->dim+k]=val;
  119054. }
  119055. count++;
  119056. }
  119057. }
  119058. break;
  119059. }
  119060. return(r);
  119061. }
  119062. return(NULL);
  119063. }
  119064. void vorbis_staticbook_clear(static_codebook *b){
  119065. if(b->allocedp){
  119066. if(b->quantlist)_ogg_free(b->quantlist);
  119067. if(b->lengthlist)_ogg_free(b->lengthlist);
  119068. if(b->nearest_tree){
  119069. _ogg_free(b->nearest_tree->ptr0);
  119070. _ogg_free(b->nearest_tree->ptr1);
  119071. _ogg_free(b->nearest_tree->p);
  119072. _ogg_free(b->nearest_tree->q);
  119073. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119074. _ogg_free(b->nearest_tree);
  119075. }
  119076. if(b->thresh_tree){
  119077. _ogg_free(b->thresh_tree->quantthresh);
  119078. _ogg_free(b->thresh_tree->quantmap);
  119079. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119080. _ogg_free(b->thresh_tree);
  119081. }
  119082. memset(b,0,sizeof(*b));
  119083. }
  119084. }
  119085. void vorbis_staticbook_destroy(static_codebook *b){
  119086. if(b->allocedp){
  119087. vorbis_staticbook_clear(b);
  119088. _ogg_free(b);
  119089. }
  119090. }
  119091. void vorbis_book_clear(codebook *b){
  119092. /* static book is not cleared; we're likely called on the lookup and
  119093. the static codebook belongs to the info struct */
  119094. if(b->valuelist)_ogg_free(b->valuelist);
  119095. if(b->codelist)_ogg_free(b->codelist);
  119096. if(b->dec_index)_ogg_free(b->dec_index);
  119097. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119098. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119099. memset(b,0,sizeof(*b));
  119100. }
  119101. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119102. memset(c,0,sizeof(*c));
  119103. c->c=s;
  119104. c->entries=s->entries;
  119105. c->used_entries=s->entries;
  119106. c->dim=s->dim;
  119107. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119108. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119109. return(0);
  119110. }
  119111. static int JUCE_CDECL sort32a(const void *a,const void *b){
  119112. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119113. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119114. }
  119115. /* decode codebook arrangement is more heavily optimized than encode */
  119116. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119117. int i,j,n=0,tabn;
  119118. int *sortindex;
  119119. memset(c,0,sizeof(*c));
  119120. /* count actually used entries */
  119121. for(i=0;i<s->entries;i++)
  119122. if(s->lengthlist[i]>0)
  119123. n++;
  119124. c->entries=s->entries;
  119125. c->used_entries=n;
  119126. c->dim=s->dim;
  119127. /* two different remappings go on here.
  119128. First, we collapse the likely sparse codebook down only to
  119129. actually represented values/words. This collapsing needs to be
  119130. indexed as map-valueless books are used to encode original entry
  119131. positions as integers.
  119132. Second, we reorder all vectors, including the entry index above,
  119133. by sorted bitreversed codeword to allow treeless decode. */
  119134. {
  119135. /* perform sort */
  119136. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119137. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119138. if(codes==NULL)goto err_out;
  119139. for(i=0;i<n;i++){
  119140. codes[i]=ogg_bitreverse(codes[i]);
  119141. codep[i]=codes+i;
  119142. }
  119143. qsort(codep,n,sizeof(*codep),sort32a);
  119144. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119145. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119146. /* the index is a reverse index */
  119147. for(i=0;i<n;i++){
  119148. int position=codep[i]-codes;
  119149. sortindex[position]=i;
  119150. }
  119151. for(i=0;i<n;i++)
  119152. c->codelist[sortindex[i]]=codes[i];
  119153. _ogg_free(codes);
  119154. }
  119155. c->valuelist=_book_unquantize(s,n,sortindex);
  119156. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119157. for(n=0,i=0;i<s->entries;i++)
  119158. if(s->lengthlist[i]>0)
  119159. c->dec_index[sortindex[n++]]=i;
  119160. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119161. for(n=0,i=0;i<s->entries;i++)
  119162. if(s->lengthlist[i]>0)
  119163. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119164. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119165. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119166. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119167. tabn=1<<c->dec_firsttablen;
  119168. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119169. c->dec_maxlength=0;
  119170. for(i=0;i<n;i++){
  119171. if(c->dec_maxlength<c->dec_codelengths[i])
  119172. c->dec_maxlength=c->dec_codelengths[i];
  119173. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119174. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119175. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119176. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119177. }
  119178. }
  119179. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119180. hints for the non-direct-hits */
  119181. {
  119182. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119183. long lo=0,hi=0;
  119184. for(i=0;i<tabn;i++){
  119185. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119186. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119187. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119188. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119189. /* we only actually have 15 bits per hint to play with here.
  119190. In order to overflow gracefully (nothing breaks, efficiency
  119191. just drops), encode as the difference from the extremes. */
  119192. {
  119193. unsigned long loval=lo;
  119194. unsigned long hival=n-hi;
  119195. if(loval>0x7fff)loval=0x7fff;
  119196. if(hival>0x7fff)hival=0x7fff;
  119197. c->dec_firsttable[ogg_bitreverse(word)]=
  119198. 0x80000000UL | (loval<<15) | hival;
  119199. }
  119200. }
  119201. }
  119202. }
  119203. return(0);
  119204. err_out:
  119205. vorbis_book_clear(c);
  119206. return(-1);
  119207. }
  119208. static float _dist(int el,float *ref, float *b,int step){
  119209. int i;
  119210. float acc=0.f;
  119211. for(i=0;i<el;i++){
  119212. float val=(ref[i]-b[i*step]);
  119213. acc+=val*val;
  119214. }
  119215. return(acc);
  119216. }
  119217. int _best(codebook *book, float *a, int step){
  119218. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119219. #if 0
  119220. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119221. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119222. #endif
  119223. int dim=book->dim;
  119224. int k,o;
  119225. /*int savebest=-1;
  119226. float saverr;*/
  119227. /* do we have a threshhold encode hint? */
  119228. if(tt){
  119229. int index=0,i;
  119230. /* find the quant val of each scalar */
  119231. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119232. i=tt->threshvals>>1;
  119233. if(a[o]<tt->quantthresh[i]){
  119234. for(;i>0;i--)
  119235. if(a[o]>=tt->quantthresh[i-1])
  119236. break;
  119237. }else{
  119238. for(i++;i<tt->threshvals-1;i++)
  119239. if(a[o]<tt->quantthresh[i])break;
  119240. }
  119241. index=(index*tt->quantvals)+tt->quantmap[i];
  119242. }
  119243. /* regular lattices are easy :-) */
  119244. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119245. use a decision tree after all
  119246. and fall through*/
  119247. return(index);
  119248. }
  119249. #if 0
  119250. /* do we have a pigeonhole encode hint? */
  119251. if(pt){
  119252. const static_codebook *c=book->c;
  119253. int i,besti=-1;
  119254. float best=0.f;
  119255. int entry=0;
  119256. /* dealing with sequentialness is a pain in the ass */
  119257. if(c->q_sequencep){
  119258. int pv;
  119259. long mul=1;
  119260. float qlast=0;
  119261. for(k=0,o=0;k<dim;k++,o+=step){
  119262. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119263. if(pv<0 || pv>=pt->mapentries)break;
  119264. entry+=pt->pigeonmap[pv]*mul;
  119265. mul*=pt->quantvals;
  119266. qlast+=pv*pt->del+pt->min;
  119267. }
  119268. }else{
  119269. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119270. int pv=(int)((a[o]-pt->min)/pt->del);
  119271. if(pv<0 || pv>=pt->mapentries)break;
  119272. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119273. }
  119274. }
  119275. /* must be within the pigeonholable range; if we quant outside (or
  119276. in an entry that we define no list for), brute force it */
  119277. if(k==dim && pt->fitlength[entry]){
  119278. /* search the abbreviated list */
  119279. long *list=pt->fitlist+pt->fitmap[entry];
  119280. for(i=0;i<pt->fitlength[entry];i++){
  119281. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119282. if(besti==-1 || this<best){
  119283. best=this;
  119284. besti=list[i];
  119285. }
  119286. }
  119287. return(besti);
  119288. }
  119289. }
  119290. if(nt){
  119291. /* optimized using the decision tree */
  119292. while(1){
  119293. float c=0.f;
  119294. float *p=book->valuelist+nt->p[ptr];
  119295. float *q=book->valuelist+nt->q[ptr];
  119296. for(k=0,o=0;k<dim;k++,o+=step)
  119297. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119298. if(c>0.f) /* in A */
  119299. ptr= -nt->ptr0[ptr];
  119300. else /* in B */
  119301. ptr= -nt->ptr1[ptr];
  119302. if(ptr<=0)break;
  119303. }
  119304. return(-ptr);
  119305. }
  119306. #endif
  119307. /* brute force it! */
  119308. {
  119309. const static_codebook *c=book->c;
  119310. int i,besti=-1;
  119311. float best=0.f;
  119312. float *e=book->valuelist;
  119313. for(i=0;i<book->entries;i++){
  119314. if(c->lengthlist[i]>0){
  119315. float thisx=_dist(dim,e,a,step);
  119316. if(besti==-1 || thisx<best){
  119317. best=thisx;
  119318. besti=i;
  119319. }
  119320. }
  119321. e+=dim;
  119322. }
  119323. /*if(savebest!=-1 && savebest!=besti){
  119324. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119325. "original:");
  119326. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119327. fprintf(stderr,"\n"
  119328. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119329. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119330. (book->valuelist+savebest*dim)[i]);
  119331. fprintf(stderr,"\n"
  119332. "bruteforce (entry %d, err %g):",besti,best);
  119333. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119334. (book->valuelist+besti*dim)[i]);
  119335. fprintf(stderr,"\n");
  119336. }*/
  119337. return(besti);
  119338. }
  119339. }
  119340. long vorbis_book_codeword(codebook *book,int entry){
  119341. if(book->c) /* only use with encode; decode optimizations are
  119342. allowed to break this */
  119343. return book->codelist[entry];
  119344. return -1;
  119345. }
  119346. long vorbis_book_codelen(codebook *book,int entry){
  119347. if(book->c) /* only use with encode; decode optimizations are
  119348. allowed to break this */
  119349. return book->c->lengthlist[entry];
  119350. return -1;
  119351. }
  119352. #ifdef _V_SELFTEST
  119353. /* Unit tests of the dequantizer; this stuff will be OK
  119354. cross-platform, I simply want to be sure that special mapping cases
  119355. actually work properly; a bug could go unnoticed for a while */
  119356. #include <stdio.h>
  119357. /* cases:
  119358. no mapping
  119359. full, explicit mapping
  119360. algorithmic mapping
  119361. nonsequential
  119362. sequential
  119363. */
  119364. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119365. static long partial_quantlist1[]={0,7,2};
  119366. /* no mapping */
  119367. static_codebook test1={
  119368. 4,16,
  119369. NULL,
  119370. 0,
  119371. 0,0,0,0,
  119372. NULL,
  119373. NULL,NULL
  119374. };
  119375. static float *test1_result=NULL;
  119376. /* linear, full mapping, nonsequential */
  119377. static_codebook test2={
  119378. 4,3,
  119379. NULL,
  119380. 2,
  119381. -533200896,1611661312,4,0,
  119382. full_quantlist1,
  119383. NULL,NULL
  119384. };
  119385. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119386. /* linear, full mapping, sequential */
  119387. static_codebook test3={
  119388. 4,3,
  119389. NULL,
  119390. 2,
  119391. -533200896,1611661312,4,1,
  119392. full_quantlist1,
  119393. NULL,NULL
  119394. };
  119395. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119396. /* linear, algorithmic mapping, nonsequential */
  119397. static_codebook test4={
  119398. 3,27,
  119399. NULL,
  119400. 1,
  119401. -533200896,1611661312,4,0,
  119402. partial_quantlist1,
  119403. NULL,NULL
  119404. };
  119405. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119406. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119407. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119408. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119409. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119410. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119411. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119412. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119413. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119414. /* linear, algorithmic mapping, sequential */
  119415. static_codebook test5={
  119416. 3,27,
  119417. NULL,
  119418. 1,
  119419. -533200896,1611661312,4,1,
  119420. partial_quantlist1,
  119421. NULL,NULL
  119422. };
  119423. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119424. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119425. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119426. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119427. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119428. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119429. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119430. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119431. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119432. void run_test(static_codebook *b,float *comp){
  119433. float *out=_book_unquantize(b,b->entries,NULL);
  119434. int i;
  119435. if(comp){
  119436. if(!out){
  119437. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119438. exit(1);
  119439. }
  119440. for(i=0;i<b->entries*b->dim;i++)
  119441. if(fabs(out[i]-comp[i])>.0001){
  119442. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119443. "position %d, %g != %g\n",i,out[i],comp[i]);
  119444. exit(1);
  119445. }
  119446. }else{
  119447. if(out){
  119448. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119449. " correct result should have been NULL\n");
  119450. exit(1);
  119451. }
  119452. }
  119453. }
  119454. int main(){
  119455. /* run the nine dequant tests, and compare to the hand-rolled results */
  119456. fprintf(stderr,"Dequant test 1... ");
  119457. run_test(&test1,test1_result);
  119458. fprintf(stderr,"OK\nDequant test 2... ");
  119459. run_test(&test2,test2_result);
  119460. fprintf(stderr,"OK\nDequant test 3... ");
  119461. run_test(&test3,test3_result);
  119462. fprintf(stderr,"OK\nDequant test 4... ");
  119463. run_test(&test4,test4_result);
  119464. fprintf(stderr,"OK\nDequant test 5... ");
  119465. run_test(&test5,test5_result);
  119466. fprintf(stderr,"OK\n\n");
  119467. return(0);
  119468. }
  119469. #endif
  119470. #endif
  119471. /*** End of inlined file: sharedbook.c ***/
  119472. /*** Start of inlined file: smallft.c ***/
  119473. /* FFT implementation from OggSquish, minus cosine transforms,
  119474. * minus all but radix 2/4 case. In Vorbis we only need this
  119475. * cut-down version.
  119476. *
  119477. * To do more than just power-of-two sized vectors, see the full
  119478. * version I wrote for NetLib.
  119479. *
  119480. * Note that the packing is a little strange; rather than the FFT r/i
  119481. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119482. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119483. * FORTRAN version
  119484. */
  119485. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119486. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119487. // tasks..
  119488. #if JUCE_MSVC
  119489. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119490. #endif
  119491. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119492. #if JUCE_USE_OGGVORBIS
  119493. #include <stdlib.h>
  119494. #include <string.h>
  119495. #include <math.h>
  119496. static void drfti1(int n, float *wa, int *ifac){
  119497. static int ntryh[4] = { 4,2,3,5 };
  119498. static float tpi = 6.28318530717958648f;
  119499. float arg,argh,argld,fi;
  119500. int ntry=0,i,j=-1;
  119501. int k1, l1, l2, ib;
  119502. int ld, ii, ip, is, nq, nr;
  119503. int ido, ipm, nfm1;
  119504. int nl=n;
  119505. int nf=0;
  119506. L101:
  119507. j++;
  119508. if (j < 4)
  119509. ntry=ntryh[j];
  119510. else
  119511. ntry+=2;
  119512. L104:
  119513. nq=nl/ntry;
  119514. nr=nl-ntry*nq;
  119515. if (nr!=0) goto L101;
  119516. nf++;
  119517. ifac[nf+1]=ntry;
  119518. nl=nq;
  119519. if(ntry!=2)goto L107;
  119520. if(nf==1)goto L107;
  119521. for (i=1;i<nf;i++){
  119522. ib=nf-i+1;
  119523. ifac[ib+1]=ifac[ib];
  119524. }
  119525. ifac[2] = 2;
  119526. L107:
  119527. if(nl!=1)goto L104;
  119528. ifac[0]=n;
  119529. ifac[1]=nf;
  119530. argh=tpi/n;
  119531. is=0;
  119532. nfm1=nf-1;
  119533. l1=1;
  119534. if(nfm1==0)return;
  119535. for (k1=0;k1<nfm1;k1++){
  119536. ip=ifac[k1+2];
  119537. ld=0;
  119538. l2=l1*ip;
  119539. ido=n/l2;
  119540. ipm=ip-1;
  119541. for (j=0;j<ipm;j++){
  119542. ld+=l1;
  119543. i=is;
  119544. argld=(float)ld*argh;
  119545. fi=0.f;
  119546. for (ii=2;ii<ido;ii+=2){
  119547. fi+=1.f;
  119548. arg=fi*argld;
  119549. wa[i++]=cos(arg);
  119550. wa[i++]=sin(arg);
  119551. }
  119552. is+=ido;
  119553. }
  119554. l1=l2;
  119555. }
  119556. }
  119557. static void fdrffti(int n, float *wsave, int *ifac){
  119558. if (n == 1) return;
  119559. drfti1(n, wsave+n, ifac);
  119560. }
  119561. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119562. int i,k;
  119563. float ti2,tr2;
  119564. int t0,t1,t2,t3,t4,t5,t6;
  119565. t1=0;
  119566. t0=(t2=l1*ido);
  119567. t3=ido<<1;
  119568. for(k=0;k<l1;k++){
  119569. ch[t1<<1]=cc[t1]+cc[t2];
  119570. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119571. t1+=ido;
  119572. t2+=ido;
  119573. }
  119574. if(ido<2)return;
  119575. if(ido==2)goto L105;
  119576. t1=0;
  119577. t2=t0;
  119578. for(k=0;k<l1;k++){
  119579. t3=t2;
  119580. t4=(t1<<1)+(ido<<1);
  119581. t5=t1;
  119582. t6=t1+t1;
  119583. for(i=2;i<ido;i+=2){
  119584. t3+=2;
  119585. t4-=2;
  119586. t5+=2;
  119587. t6+=2;
  119588. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119589. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119590. ch[t6]=cc[t5]+ti2;
  119591. ch[t4]=ti2-cc[t5];
  119592. ch[t6-1]=cc[t5-1]+tr2;
  119593. ch[t4-1]=cc[t5-1]-tr2;
  119594. }
  119595. t1+=ido;
  119596. t2+=ido;
  119597. }
  119598. if(ido%2==1)return;
  119599. L105:
  119600. t3=(t2=(t1=ido)-1);
  119601. t2+=t0;
  119602. for(k=0;k<l1;k++){
  119603. ch[t1]=-cc[t2];
  119604. ch[t1-1]=cc[t3];
  119605. t1+=ido<<1;
  119606. t2+=ido;
  119607. t3+=ido;
  119608. }
  119609. }
  119610. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119611. float *wa2,float *wa3){
  119612. static float hsqt2 = .70710678118654752f;
  119613. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119614. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119615. t0=l1*ido;
  119616. t1=t0;
  119617. t4=t1<<1;
  119618. t2=t1+(t1<<1);
  119619. t3=0;
  119620. for(k=0;k<l1;k++){
  119621. tr1=cc[t1]+cc[t2];
  119622. tr2=cc[t3]+cc[t4];
  119623. ch[t5=t3<<2]=tr1+tr2;
  119624. ch[(ido<<2)+t5-1]=tr2-tr1;
  119625. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119626. ch[t5]=cc[t2]-cc[t1];
  119627. t1+=ido;
  119628. t2+=ido;
  119629. t3+=ido;
  119630. t4+=ido;
  119631. }
  119632. if(ido<2)return;
  119633. if(ido==2)goto L105;
  119634. t1=0;
  119635. for(k=0;k<l1;k++){
  119636. t2=t1;
  119637. t4=t1<<2;
  119638. t5=(t6=ido<<1)+t4;
  119639. for(i=2;i<ido;i+=2){
  119640. t3=(t2+=2);
  119641. t4+=2;
  119642. t5-=2;
  119643. t3+=t0;
  119644. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119645. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119646. t3+=t0;
  119647. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119648. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119649. t3+=t0;
  119650. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119651. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119652. tr1=cr2+cr4;
  119653. tr4=cr4-cr2;
  119654. ti1=ci2+ci4;
  119655. ti4=ci2-ci4;
  119656. ti2=cc[t2]+ci3;
  119657. ti3=cc[t2]-ci3;
  119658. tr2=cc[t2-1]+cr3;
  119659. tr3=cc[t2-1]-cr3;
  119660. ch[t4-1]=tr1+tr2;
  119661. ch[t4]=ti1+ti2;
  119662. ch[t5-1]=tr3-ti4;
  119663. ch[t5]=tr4-ti3;
  119664. ch[t4+t6-1]=ti4+tr3;
  119665. ch[t4+t6]=tr4+ti3;
  119666. ch[t5+t6-1]=tr2-tr1;
  119667. ch[t5+t6]=ti1-ti2;
  119668. }
  119669. t1+=ido;
  119670. }
  119671. if(ido&1)return;
  119672. L105:
  119673. t2=(t1=t0+ido-1)+(t0<<1);
  119674. t3=ido<<2;
  119675. t4=ido;
  119676. t5=ido<<1;
  119677. t6=ido;
  119678. for(k=0;k<l1;k++){
  119679. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119680. tr1=hsqt2*(cc[t1]-cc[t2]);
  119681. ch[t4-1]=tr1+cc[t6-1];
  119682. ch[t4+t5-1]=cc[t6-1]-tr1;
  119683. ch[t4]=ti1-cc[t1+t0];
  119684. ch[t4+t5]=ti1+cc[t1+t0];
  119685. t1+=ido;
  119686. t2+=ido;
  119687. t4+=t3;
  119688. t6+=ido;
  119689. }
  119690. }
  119691. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119692. float *c2,float *ch,float *ch2,float *wa){
  119693. static float tpi=6.283185307179586f;
  119694. int idij,ipph,i,j,k,l,ic,ik,is;
  119695. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119696. float dc2,ai1,ai2,ar1,ar2,ds2;
  119697. int nbd;
  119698. float dcp,arg,dsp,ar1h,ar2h;
  119699. int idp2,ipp2;
  119700. arg=tpi/(float)ip;
  119701. dcp=cos(arg);
  119702. dsp=sin(arg);
  119703. ipph=(ip+1)>>1;
  119704. ipp2=ip;
  119705. idp2=ido;
  119706. nbd=(ido-1)>>1;
  119707. t0=l1*ido;
  119708. t10=ip*ido;
  119709. if(ido==1)goto L119;
  119710. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119711. t1=0;
  119712. for(j=1;j<ip;j++){
  119713. t1+=t0;
  119714. t2=t1;
  119715. for(k=0;k<l1;k++){
  119716. ch[t2]=c1[t2];
  119717. t2+=ido;
  119718. }
  119719. }
  119720. is=-ido;
  119721. t1=0;
  119722. if(nbd>l1){
  119723. for(j=1;j<ip;j++){
  119724. t1+=t0;
  119725. is+=ido;
  119726. t2= -ido+t1;
  119727. for(k=0;k<l1;k++){
  119728. idij=is-1;
  119729. t2+=ido;
  119730. t3=t2;
  119731. for(i=2;i<ido;i+=2){
  119732. idij+=2;
  119733. t3+=2;
  119734. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119735. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119736. }
  119737. }
  119738. }
  119739. }else{
  119740. for(j=1;j<ip;j++){
  119741. is+=ido;
  119742. idij=is-1;
  119743. t1+=t0;
  119744. t2=t1;
  119745. for(i=2;i<ido;i+=2){
  119746. idij+=2;
  119747. t2+=2;
  119748. t3=t2;
  119749. for(k=0;k<l1;k++){
  119750. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119751. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119752. t3+=ido;
  119753. }
  119754. }
  119755. }
  119756. }
  119757. t1=0;
  119758. t2=ipp2*t0;
  119759. if(nbd<l1){
  119760. for(j=1;j<ipph;j++){
  119761. t1+=t0;
  119762. t2-=t0;
  119763. t3=t1;
  119764. t4=t2;
  119765. for(i=2;i<ido;i+=2){
  119766. t3+=2;
  119767. t4+=2;
  119768. t5=t3-ido;
  119769. t6=t4-ido;
  119770. for(k=0;k<l1;k++){
  119771. t5+=ido;
  119772. t6+=ido;
  119773. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119774. c1[t6-1]=ch[t5]-ch[t6];
  119775. c1[t5]=ch[t5]+ch[t6];
  119776. c1[t6]=ch[t6-1]-ch[t5-1];
  119777. }
  119778. }
  119779. }
  119780. }else{
  119781. for(j=1;j<ipph;j++){
  119782. t1+=t0;
  119783. t2-=t0;
  119784. t3=t1;
  119785. t4=t2;
  119786. for(k=0;k<l1;k++){
  119787. t5=t3;
  119788. t6=t4;
  119789. for(i=2;i<ido;i+=2){
  119790. t5+=2;
  119791. t6+=2;
  119792. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119793. c1[t6-1]=ch[t5]-ch[t6];
  119794. c1[t5]=ch[t5]+ch[t6];
  119795. c1[t6]=ch[t6-1]-ch[t5-1];
  119796. }
  119797. t3+=ido;
  119798. t4+=ido;
  119799. }
  119800. }
  119801. }
  119802. L119:
  119803. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119804. t1=0;
  119805. t2=ipp2*idl1;
  119806. for(j=1;j<ipph;j++){
  119807. t1+=t0;
  119808. t2-=t0;
  119809. t3=t1-ido;
  119810. t4=t2-ido;
  119811. for(k=0;k<l1;k++){
  119812. t3+=ido;
  119813. t4+=ido;
  119814. c1[t3]=ch[t3]+ch[t4];
  119815. c1[t4]=ch[t4]-ch[t3];
  119816. }
  119817. }
  119818. ar1=1.f;
  119819. ai1=0.f;
  119820. t1=0;
  119821. t2=ipp2*idl1;
  119822. t3=(ip-1)*idl1;
  119823. for(l=1;l<ipph;l++){
  119824. t1+=idl1;
  119825. t2-=idl1;
  119826. ar1h=dcp*ar1-dsp*ai1;
  119827. ai1=dcp*ai1+dsp*ar1;
  119828. ar1=ar1h;
  119829. t4=t1;
  119830. t5=t2;
  119831. t6=t3;
  119832. t7=idl1;
  119833. for(ik=0;ik<idl1;ik++){
  119834. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119835. ch2[t5++]=ai1*c2[t6++];
  119836. }
  119837. dc2=ar1;
  119838. ds2=ai1;
  119839. ar2=ar1;
  119840. ai2=ai1;
  119841. t4=idl1;
  119842. t5=(ipp2-1)*idl1;
  119843. for(j=2;j<ipph;j++){
  119844. t4+=idl1;
  119845. t5-=idl1;
  119846. ar2h=dc2*ar2-ds2*ai2;
  119847. ai2=dc2*ai2+ds2*ar2;
  119848. ar2=ar2h;
  119849. t6=t1;
  119850. t7=t2;
  119851. t8=t4;
  119852. t9=t5;
  119853. for(ik=0;ik<idl1;ik++){
  119854. ch2[t6++]+=ar2*c2[t8++];
  119855. ch2[t7++]+=ai2*c2[t9++];
  119856. }
  119857. }
  119858. }
  119859. t1=0;
  119860. for(j=1;j<ipph;j++){
  119861. t1+=idl1;
  119862. t2=t1;
  119863. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119864. }
  119865. if(ido<l1)goto L132;
  119866. t1=0;
  119867. t2=0;
  119868. for(k=0;k<l1;k++){
  119869. t3=t1;
  119870. t4=t2;
  119871. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119872. t1+=ido;
  119873. t2+=t10;
  119874. }
  119875. goto L135;
  119876. L132:
  119877. for(i=0;i<ido;i++){
  119878. t1=i;
  119879. t2=i;
  119880. for(k=0;k<l1;k++){
  119881. cc[t2]=ch[t1];
  119882. t1+=ido;
  119883. t2+=t10;
  119884. }
  119885. }
  119886. L135:
  119887. t1=0;
  119888. t2=ido<<1;
  119889. t3=0;
  119890. t4=ipp2*t0;
  119891. for(j=1;j<ipph;j++){
  119892. t1+=t2;
  119893. t3+=t0;
  119894. t4-=t0;
  119895. t5=t1;
  119896. t6=t3;
  119897. t7=t4;
  119898. for(k=0;k<l1;k++){
  119899. cc[t5-1]=ch[t6];
  119900. cc[t5]=ch[t7];
  119901. t5+=t10;
  119902. t6+=ido;
  119903. t7+=ido;
  119904. }
  119905. }
  119906. if(ido==1)return;
  119907. if(nbd<l1)goto L141;
  119908. t1=-ido;
  119909. t3=0;
  119910. t4=0;
  119911. t5=ipp2*t0;
  119912. for(j=1;j<ipph;j++){
  119913. t1+=t2;
  119914. t3+=t2;
  119915. t4+=t0;
  119916. t5-=t0;
  119917. t6=t1;
  119918. t7=t3;
  119919. t8=t4;
  119920. t9=t5;
  119921. for(k=0;k<l1;k++){
  119922. for(i=2;i<ido;i+=2){
  119923. ic=idp2-i;
  119924. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119925. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119926. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119927. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119928. }
  119929. t6+=t10;
  119930. t7+=t10;
  119931. t8+=ido;
  119932. t9+=ido;
  119933. }
  119934. }
  119935. return;
  119936. L141:
  119937. t1=-ido;
  119938. t3=0;
  119939. t4=0;
  119940. t5=ipp2*t0;
  119941. for(j=1;j<ipph;j++){
  119942. t1+=t2;
  119943. t3+=t2;
  119944. t4+=t0;
  119945. t5-=t0;
  119946. for(i=2;i<ido;i+=2){
  119947. t6=idp2+t1-i;
  119948. t7=i+t3;
  119949. t8=i+t4;
  119950. t9=i+t5;
  119951. for(k=0;k<l1;k++){
  119952. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119953. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119954. cc[t7]=ch[t8]+ch[t9];
  119955. cc[t6]=ch[t9]-ch[t8];
  119956. t6+=t10;
  119957. t7+=t10;
  119958. t8+=ido;
  119959. t9+=ido;
  119960. }
  119961. }
  119962. }
  119963. }
  119964. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119965. int i,k1,l1,l2;
  119966. int na,kh,nf;
  119967. int ip,iw,ido,idl1,ix2,ix3;
  119968. nf=ifac[1];
  119969. na=1;
  119970. l2=n;
  119971. iw=n;
  119972. for(k1=0;k1<nf;k1++){
  119973. kh=nf-k1;
  119974. ip=ifac[kh+1];
  119975. l1=l2/ip;
  119976. ido=n/l2;
  119977. idl1=ido*l1;
  119978. iw-=(ip-1)*ido;
  119979. na=1-na;
  119980. if(ip!=4)goto L102;
  119981. ix2=iw+ido;
  119982. ix3=ix2+ido;
  119983. if(na!=0)
  119984. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119985. else
  119986. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119987. goto L110;
  119988. L102:
  119989. if(ip!=2)goto L104;
  119990. if(na!=0)goto L103;
  119991. dradf2(ido,l1,c,ch,wa+iw-1);
  119992. goto L110;
  119993. L103:
  119994. dradf2(ido,l1,ch,c,wa+iw-1);
  119995. goto L110;
  119996. L104:
  119997. if(ido==1)na=1-na;
  119998. if(na!=0)goto L109;
  119999. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120000. na=1;
  120001. goto L110;
  120002. L109:
  120003. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120004. na=0;
  120005. L110:
  120006. l2=l1;
  120007. }
  120008. if(na==1)return;
  120009. for(i=0;i<n;i++)c[i]=ch[i];
  120010. }
  120011. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120012. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120013. float ti2,tr2;
  120014. t0=l1*ido;
  120015. t1=0;
  120016. t2=0;
  120017. t3=(ido<<1)-1;
  120018. for(k=0;k<l1;k++){
  120019. ch[t1]=cc[t2]+cc[t3+t2];
  120020. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120021. t2=(t1+=ido)<<1;
  120022. }
  120023. if(ido<2)return;
  120024. if(ido==2)goto L105;
  120025. t1=0;
  120026. t2=0;
  120027. for(k=0;k<l1;k++){
  120028. t3=t1;
  120029. t5=(t4=t2)+(ido<<1);
  120030. t6=t0+t1;
  120031. for(i=2;i<ido;i+=2){
  120032. t3+=2;
  120033. t4+=2;
  120034. t5-=2;
  120035. t6+=2;
  120036. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120037. tr2=cc[t4-1]-cc[t5-1];
  120038. ch[t3]=cc[t4]-cc[t5];
  120039. ti2=cc[t4]+cc[t5];
  120040. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120041. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120042. }
  120043. t2=(t1+=ido)<<1;
  120044. }
  120045. if(ido%2==1)return;
  120046. L105:
  120047. t1=ido-1;
  120048. t2=ido-1;
  120049. for(k=0;k<l1;k++){
  120050. ch[t1]=cc[t2]+cc[t2];
  120051. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120052. t1+=ido;
  120053. t2+=ido<<1;
  120054. }
  120055. }
  120056. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120057. float *wa2){
  120058. static float taur = -.5f;
  120059. static float taui = .8660254037844386f;
  120060. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120061. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120062. t0=l1*ido;
  120063. t1=0;
  120064. t2=t0<<1;
  120065. t3=ido<<1;
  120066. t4=ido+(ido<<1);
  120067. t5=0;
  120068. for(k=0;k<l1;k++){
  120069. tr2=cc[t3-1]+cc[t3-1];
  120070. cr2=cc[t5]+(taur*tr2);
  120071. ch[t1]=cc[t5]+tr2;
  120072. ci3=taui*(cc[t3]+cc[t3]);
  120073. ch[t1+t0]=cr2-ci3;
  120074. ch[t1+t2]=cr2+ci3;
  120075. t1+=ido;
  120076. t3+=t4;
  120077. t5+=t4;
  120078. }
  120079. if(ido==1)return;
  120080. t1=0;
  120081. t3=ido<<1;
  120082. for(k=0;k<l1;k++){
  120083. t7=t1+(t1<<1);
  120084. t6=(t5=t7+t3);
  120085. t8=t1;
  120086. t10=(t9=t1+t0)+t0;
  120087. for(i=2;i<ido;i+=2){
  120088. t5+=2;
  120089. t6-=2;
  120090. t7+=2;
  120091. t8+=2;
  120092. t9+=2;
  120093. t10+=2;
  120094. tr2=cc[t5-1]+cc[t6-1];
  120095. cr2=cc[t7-1]+(taur*tr2);
  120096. ch[t8-1]=cc[t7-1]+tr2;
  120097. ti2=cc[t5]-cc[t6];
  120098. ci2=cc[t7]+(taur*ti2);
  120099. ch[t8]=cc[t7]+ti2;
  120100. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120101. ci3=taui*(cc[t5]+cc[t6]);
  120102. dr2=cr2-ci3;
  120103. dr3=cr2+ci3;
  120104. di2=ci2+cr3;
  120105. di3=ci2-cr3;
  120106. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120107. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120108. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120109. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120110. }
  120111. t1+=ido;
  120112. }
  120113. }
  120114. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120115. float *wa2,float *wa3){
  120116. static float sqrt2=1.414213562373095f;
  120117. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120118. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120119. t0=l1*ido;
  120120. t1=0;
  120121. t2=ido<<2;
  120122. t3=0;
  120123. t6=ido<<1;
  120124. for(k=0;k<l1;k++){
  120125. t4=t3+t6;
  120126. t5=t1;
  120127. tr3=cc[t4-1]+cc[t4-1];
  120128. tr4=cc[t4]+cc[t4];
  120129. tr1=cc[t3]-cc[(t4+=t6)-1];
  120130. tr2=cc[t3]+cc[t4-1];
  120131. ch[t5]=tr2+tr3;
  120132. ch[t5+=t0]=tr1-tr4;
  120133. ch[t5+=t0]=tr2-tr3;
  120134. ch[t5+=t0]=tr1+tr4;
  120135. t1+=ido;
  120136. t3+=t2;
  120137. }
  120138. if(ido<2)return;
  120139. if(ido==2)goto L105;
  120140. t1=0;
  120141. for(k=0;k<l1;k++){
  120142. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120143. t7=t1;
  120144. for(i=2;i<ido;i+=2){
  120145. t2+=2;
  120146. t3+=2;
  120147. t4-=2;
  120148. t5-=2;
  120149. t7+=2;
  120150. ti1=cc[t2]+cc[t5];
  120151. ti2=cc[t2]-cc[t5];
  120152. ti3=cc[t3]-cc[t4];
  120153. tr4=cc[t3]+cc[t4];
  120154. tr1=cc[t2-1]-cc[t5-1];
  120155. tr2=cc[t2-1]+cc[t5-1];
  120156. ti4=cc[t3-1]-cc[t4-1];
  120157. tr3=cc[t3-1]+cc[t4-1];
  120158. ch[t7-1]=tr2+tr3;
  120159. cr3=tr2-tr3;
  120160. ch[t7]=ti2+ti3;
  120161. ci3=ti2-ti3;
  120162. cr2=tr1-tr4;
  120163. cr4=tr1+tr4;
  120164. ci2=ti1+ti4;
  120165. ci4=ti1-ti4;
  120166. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120167. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120168. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120169. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120170. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120171. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120172. }
  120173. t1+=ido;
  120174. }
  120175. if(ido%2 == 1)return;
  120176. L105:
  120177. t1=ido;
  120178. t2=ido<<2;
  120179. t3=ido-1;
  120180. t4=ido+(ido<<1);
  120181. for(k=0;k<l1;k++){
  120182. t5=t3;
  120183. ti1=cc[t1]+cc[t4];
  120184. ti2=cc[t4]-cc[t1];
  120185. tr1=cc[t1-1]-cc[t4-1];
  120186. tr2=cc[t1-1]+cc[t4-1];
  120187. ch[t5]=tr2+tr2;
  120188. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120189. ch[t5+=t0]=ti2+ti2;
  120190. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120191. t3+=ido;
  120192. t1+=t2;
  120193. t4+=t2;
  120194. }
  120195. }
  120196. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120197. float *c2,float *ch,float *ch2,float *wa){
  120198. static float tpi=6.283185307179586f;
  120199. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120200. t11,t12;
  120201. float dc2,ai1,ai2,ar1,ar2,ds2;
  120202. int nbd;
  120203. float dcp,arg,dsp,ar1h,ar2h;
  120204. int ipp2;
  120205. t10=ip*ido;
  120206. t0=l1*ido;
  120207. arg=tpi/(float)ip;
  120208. dcp=cos(arg);
  120209. dsp=sin(arg);
  120210. nbd=(ido-1)>>1;
  120211. ipp2=ip;
  120212. ipph=(ip+1)>>1;
  120213. if(ido<l1)goto L103;
  120214. t1=0;
  120215. t2=0;
  120216. for(k=0;k<l1;k++){
  120217. t3=t1;
  120218. t4=t2;
  120219. for(i=0;i<ido;i++){
  120220. ch[t3]=cc[t4];
  120221. t3++;
  120222. t4++;
  120223. }
  120224. t1+=ido;
  120225. t2+=t10;
  120226. }
  120227. goto L106;
  120228. L103:
  120229. t1=0;
  120230. for(i=0;i<ido;i++){
  120231. t2=t1;
  120232. t3=t1;
  120233. for(k=0;k<l1;k++){
  120234. ch[t2]=cc[t3];
  120235. t2+=ido;
  120236. t3+=t10;
  120237. }
  120238. t1++;
  120239. }
  120240. L106:
  120241. t1=0;
  120242. t2=ipp2*t0;
  120243. t7=(t5=ido<<1);
  120244. for(j=1;j<ipph;j++){
  120245. t1+=t0;
  120246. t2-=t0;
  120247. t3=t1;
  120248. t4=t2;
  120249. t6=t5;
  120250. for(k=0;k<l1;k++){
  120251. ch[t3]=cc[t6-1]+cc[t6-1];
  120252. ch[t4]=cc[t6]+cc[t6];
  120253. t3+=ido;
  120254. t4+=ido;
  120255. t6+=t10;
  120256. }
  120257. t5+=t7;
  120258. }
  120259. if (ido == 1)goto L116;
  120260. if(nbd<l1)goto L112;
  120261. t1=0;
  120262. t2=ipp2*t0;
  120263. t7=0;
  120264. for(j=1;j<ipph;j++){
  120265. t1+=t0;
  120266. t2-=t0;
  120267. t3=t1;
  120268. t4=t2;
  120269. t7+=(ido<<1);
  120270. t8=t7;
  120271. for(k=0;k<l1;k++){
  120272. t5=t3;
  120273. t6=t4;
  120274. t9=t8;
  120275. t11=t8;
  120276. for(i=2;i<ido;i+=2){
  120277. t5+=2;
  120278. t6+=2;
  120279. t9+=2;
  120280. t11-=2;
  120281. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120282. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120283. ch[t5]=cc[t9]-cc[t11];
  120284. ch[t6]=cc[t9]+cc[t11];
  120285. }
  120286. t3+=ido;
  120287. t4+=ido;
  120288. t8+=t10;
  120289. }
  120290. }
  120291. goto L116;
  120292. L112:
  120293. t1=0;
  120294. t2=ipp2*t0;
  120295. t7=0;
  120296. for(j=1;j<ipph;j++){
  120297. t1+=t0;
  120298. t2-=t0;
  120299. t3=t1;
  120300. t4=t2;
  120301. t7+=(ido<<1);
  120302. t8=t7;
  120303. t9=t7;
  120304. for(i=2;i<ido;i+=2){
  120305. t3+=2;
  120306. t4+=2;
  120307. t8+=2;
  120308. t9-=2;
  120309. t5=t3;
  120310. t6=t4;
  120311. t11=t8;
  120312. t12=t9;
  120313. for(k=0;k<l1;k++){
  120314. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120315. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120316. ch[t5]=cc[t11]-cc[t12];
  120317. ch[t6]=cc[t11]+cc[t12];
  120318. t5+=ido;
  120319. t6+=ido;
  120320. t11+=t10;
  120321. t12+=t10;
  120322. }
  120323. }
  120324. }
  120325. L116:
  120326. ar1=1.f;
  120327. ai1=0.f;
  120328. t1=0;
  120329. t9=(t2=ipp2*idl1);
  120330. t3=(ip-1)*idl1;
  120331. for(l=1;l<ipph;l++){
  120332. t1+=idl1;
  120333. t2-=idl1;
  120334. ar1h=dcp*ar1-dsp*ai1;
  120335. ai1=dcp*ai1+dsp*ar1;
  120336. ar1=ar1h;
  120337. t4=t1;
  120338. t5=t2;
  120339. t6=0;
  120340. t7=idl1;
  120341. t8=t3;
  120342. for(ik=0;ik<idl1;ik++){
  120343. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120344. c2[t5++]=ai1*ch2[t8++];
  120345. }
  120346. dc2=ar1;
  120347. ds2=ai1;
  120348. ar2=ar1;
  120349. ai2=ai1;
  120350. t6=idl1;
  120351. t7=t9-idl1;
  120352. for(j=2;j<ipph;j++){
  120353. t6+=idl1;
  120354. t7-=idl1;
  120355. ar2h=dc2*ar2-ds2*ai2;
  120356. ai2=dc2*ai2+ds2*ar2;
  120357. ar2=ar2h;
  120358. t4=t1;
  120359. t5=t2;
  120360. t11=t6;
  120361. t12=t7;
  120362. for(ik=0;ik<idl1;ik++){
  120363. c2[t4++]+=ar2*ch2[t11++];
  120364. c2[t5++]+=ai2*ch2[t12++];
  120365. }
  120366. }
  120367. }
  120368. t1=0;
  120369. for(j=1;j<ipph;j++){
  120370. t1+=idl1;
  120371. t2=t1;
  120372. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120373. }
  120374. t1=0;
  120375. t2=ipp2*t0;
  120376. for(j=1;j<ipph;j++){
  120377. t1+=t0;
  120378. t2-=t0;
  120379. t3=t1;
  120380. t4=t2;
  120381. for(k=0;k<l1;k++){
  120382. ch[t3]=c1[t3]-c1[t4];
  120383. ch[t4]=c1[t3]+c1[t4];
  120384. t3+=ido;
  120385. t4+=ido;
  120386. }
  120387. }
  120388. if(ido==1)goto L132;
  120389. if(nbd<l1)goto L128;
  120390. t1=0;
  120391. t2=ipp2*t0;
  120392. for(j=1;j<ipph;j++){
  120393. t1+=t0;
  120394. t2-=t0;
  120395. t3=t1;
  120396. t4=t2;
  120397. for(k=0;k<l1;k++){
  120398. t5=t3;
  120399. t6=t4;
  120400. for(i=2;i<ido;i+=2){
  120401. t5+=2;
  120402. t6+=2;
  120403. ch[t5-1]=c1[t5-1]-c1[t6];
  120404. ch[t6-1]=c1[t5-1]+c1[t6];
  120405. ch[t5]=c1[t5]+c1[t6-1];
  120406. ch[t6]=c1[t5]-c1[t6-1];
  120407. }
  120408. t3+=ido;
  120409. t4+=ido;
  120410. }
  120411. }
  120412. goto L132;
  120413. L128:
  120414. t1=0;
  120415. t2=ipp2*t0;
  120416. for(j=1;j<ipph;j++){
  120417. t1+=t0;
  120418. t2-=t0;
  120419. t3=t1;
  120420. t4=t2;
  120421. for(i=2;i<ido;i+=2){
  120422. t3+=2;
  120423. t4+=2;
  120424. t5=t3;
  120425. t6=t4;
  120426. for(k=0;k<l1;k++){
  120427. ch[t5-1]=c1[t5-1]-c1[t6];
  120428. ch[t6-1]=c1[t5-1]+c1[t6];
  120429. ch[t5]=c1[t5]+c1[t6-1];
  120430. ch[t6]=c1[t5]-c1[t6-1];
  120431. t5+=ido;
  120432. t6+=ido;
  120433. }
  120434. }
  120435. }
  120436. L132:
  120437. if(ido==1)return;
  120438. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120439. t1=0;
  120440. for(j=1;j<ip;j++){
  120441. t2=(t1+=t0);
  120442. for(k=0;k<l1;k++){
  120443. c1[t2]=ch[t2];
  120444. t2+=ido;
  120445. }
  120446. }
  120447. if(nbd>l1)goto L139;
  120448. is= -ido-1;
  120449. t1=0;
  120450. for(j=1;j<ip;j++){
  120451. is+=ido;
  120452. t1+=t0;
  120453. idij=is;
  120454. t2=t1;
  120455. for(i=2;i<ido;i+=2){
  120456. t2+=2;
  120457. idij+=2;
  120458. t3=t2;
  120459. for(k=0;k<l1;k++){
  120460. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120461. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120462. t3+=ido;
  120463. }
  120464. }
  120465. }
  120466. return;
  120467. L139:
  120468. is= -ido-1;
  120469. t1=0;
  120470. for(j=1;j<ip;j++){
  120471. is+=ido;
  120472. t1+=t0;
  120473. t2=t1;
  120474. for(k=0;k<l1;k++){
  120475. idij=is;
  120476. t3=t2;
  120477. for(i=2;i<ido;i+=2){
  120478. idij+=2;
  120479. t3+=2;
  120480. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120481. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120482. }
  120483. t2+=ido;
  120484. }
  120485. }
  120486. }
  120487. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120488. int i,k1,l1,l2;
  120489. int na;
  120490. int nf,ip,iw,ix2,ix3,ido,idl1;
  120491. nf=ifac[1];
  120492. na=0;
  120493. l1=1;
  120494. iw=1;
  120495. for(k1=0;k1<nf;k1++){
  120496. ip=ifac[k1 + 2];
  120497. l2=ip*l1;
  120498. ido=n/l2;
  120499. idl1=ido*l1;
  120500. if(ip!=4)goto L103;
  120501. ix2=iw+ido;
  120502. ix3=ix2+ido;
  120503. if(na!=0)
  120504. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120505. else
  120506. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120507. na=1-na;
  120508. goto L115;
  120509. L103:
  120510. if(ip!=2)goto L106;
  120511. if(na!=0)
  120512. dradb2(ido,l1,ch,c,wa+iw-1);
  120513. else
  120514. dradb2(ido,l1,c,ch,wa+iw-1);
  120515. na=1-na;
  120516. goto L115;
  120517. L106:
  120518. if(ip!=3)goto L109;
  120519. ix2=iw+ido;
  120520. if(na!=0)
  120521. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120522. else
  120523. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120524. na=1-na;
  120525. goto L115;
  120526. L109:
  120527. /* The radix five case can be translated later..... */
  120528. /* if(ip!=5)goto L112;
  120529. ix2=iw+ido;
  120530. ix3=ix2+ido;
  120531. ix4=ix3+ido;
  120532. if(na!=0)
  120533. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120534. else
  120535. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120536. na=1-na;
  120537. goto L115;
  120538. L112:*/
  120539. if(na!=0)
  120540. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120541. else
  120542. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120543. if(ido==1)na=1-na;
  120544. L115:
  120545. l1=l2;
  120546. iw+=(ip-1)*ido;
  120547. }
  120548. if(na==0)return;
  120549. for(i=0;i<n;i++)c[i]=ch[i];
  120550. }
  120551. void drft_forward(drft_lookup *l,float *data){
  120552. if(l->n==1)return;
  120553. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120554. }
  120555. void drft_backward(drft_lookup *l,float *data){
  120556. if (l->n==1)return;
  120557. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120558. }
  120559. void drft_init(drft_lookup *l,int n){
  120560. l->n=n;
  120561. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120562. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120563. fdrffti(n, l->trigcache, l->splitcache);
  120564. }
  120565. void drft_clear(drft_lookup *l){
  120566. if(l){
  120567. if(l->trigcache)_ogg_free(l->trigcache);
  120568. if(l->splitcache)_ogg_free(l->splitcache);
  120569. memset(l,0,sizeof(*l));
  120570. }
  120571. }
  120572. #endif
  120573. /*** End of inlined file: smallft.c ***/
  120574. /*** Start of inlined file: synthesis.c ***/
  120575. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120576. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120577. // tasks..
  120578. #if JUCE_MSVC
  120579. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120580. #endif
  120581. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120582. #if JUCE_USE_OGGVORBIS
  120583. #include <stdio.h>
  120584. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120585. vorbis_dsp_state *vd=vb->vd;
  120586. private_state *b=(private_state*)vd->backend_state;
  120587. vorbis_info *vi=vd->vi;
  120588. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120589. oggpack_buffer *opb=&vb->opb;
  120590. int type,mode,i;
  120591. /* first things first. Make sure decode is ready */
  120592. _vorbis_block_ripcord(vb);
  120593. oggpack_readinit(opb,op->packet,op->bytes);
  120594. /* Check the packet type */
  120595. if(oggpack_read(opb,1)!=0){
  120596. /* Oops. This is not an audio data packet */
  120597. return(OV_ENOTAUDIO);
  120598. }
  120599. /* read our mode and pre/post windowsize */
  120600. mode=oggpack_read(opb,b->modebits);
  120601. if(mode==-1)return(OV_EBADPACKET);
  120602. vb->mode=mode;
  120603. vb->W=ci->mode_param[mode]->blockflag;
  120604. if(vb->W){
  120605. /* this doesn;t get mapped through mode selection as it's used
  120606. only for window selection */
  120607. vb->lW=oggpack_read(opb,1);
  120608. vb->nW=oggpack_read(opb,1);
  120609. if(vb->nW==-1) return(OV_EBADPACKET);
  120610. }else{
  120611. vb->lW=0;
  120612. vb->nW=0;
  120613. }
  120614. /* more setup */
  120615. vb->granulepos=op->granulepos;
  120616. vb->sequence=op->packetno;
  120617. vb->eofflag=op->e_o_s;
  120618. /* alloc pcm passback storage */
  120619. vb->pcmend=ci->blocksizes[vb->W];
  120620. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120621. for(i=0;i<vi->channels;i++)
  120622. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120623. /* unpack_header enforces range checking */
  120624. type=ci->map_type[ci->mode_param[mode]->mapping];
  120625. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120626. mapping]));
  120627. }
  120628. /* used to track pcm position without actually performing decode.
  120629. Useful for sequential 'fast forward' */
  120630. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120631. vorbis_dsp_state *vd=vb->vd;
  120632. private_state *b=(private_state*)vd->backend_state;
  120633. vorbis_info *vi=vd->vi;
  120634. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120635. oggpack_buffer *opb=&vb->opb;
  120636. int mode;
  120637. /* first things first. Make sure decode is ready */
  120638. _vorbis_block_ripcord(vb);
  120639. oggpack_readinit(opb,op->packet,op->bytes);
  120640. /* Check the packet type */
  120641. if(oggpack_read(opb,1)!=0){
  120642. /* Oops. This is not an audio data packet */
  120643. return(OV_ENOTAUDIO);
  120644. }
  120645. /* read our mode and pre/post windowsize */
  120646. mode=oggpack_read(opb,b->modebits);
  120647. if(mode==-1)return(OV_EBADPACKET);
  120648. vb->mode=mode;
  120649. vb->W=ci->mode_param[mode]->blockflag;
  120650. if(vb->W){
  120651. vb->lW=oggpack_read(opb,1);
  120652. vb->nW=oggpack_read(opb,1);
  120653. if(vb->nW==-1) return(OV_EBADPACKET);
  120654. }else{
  120655. vb->lW=0;
  120656. vb->nW=0;
  120657. }
  120658. /* more setup */
  120659. vb->granulepos=op->granulepos;
  120660. vb->sequence=op->packetno;
  120661. vb->eofflag=op->e_o_s;
  120662. /* no pcm */
  120663. vb->pcmend=0;
  120664. vb->pcm=NULL;
  120665. return(0);
  120666. }
  120667. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120668. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120669. oggpack_buffer opb;
  120670. int mode;
  120671. oggpack_readinit(&opb,op->packet,op->bytes);
  120672. /* Check the packet type */
  120673. if(oggpack_read(&opb,1)!=0){
  120674. /* Oops. This is not an audio data packet */
  120675. return(OV_ENOTAUDIO);
  120676. }
  120677. {
  120678. int modebits=0;
  120679. int v=ci->modes;
  120680. while(v>1){
  120681. modebits++;
  120682. v>>=1;
  120683. }
  120684. /* read our mode and pre/post windowsize */
  120685. mode=oggpack_read(&opb,modebits);
  120686. }
  120687. if(mode==-1)return(OV_EBADPACKET);
  120688. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120689. }
  120690. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120691. /* set / clear half-sample-rate mode */
  120692. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120693. /* right now, our MDCT can't handle < 64 sample windows. */
  120694. if(ci->blocksizes[0]<=64 && flag)return -1;
  120695. ci->halfrate_flag=(flag?1:0);
  120696. return 0;
  120697. }
  120698. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120699. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120700. return ci->halfrate_flag;
  120701. }
  120702. #endif
  120703. /*** End of inlined file: synthesis.c ***/
  120704. /*** Start of inlined file: vorbisenc.c ***/
  120705. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120706. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120707. // tasks..
  120708. #if JUCE_MSVC
  120709. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120710. #endif
  120711. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120712. #if JUCE_USE_OGGVORBIS
  120713. #include <stdlib.h>
  120714. #include <string.h>
  120715. #include <math.h>
  120716. /* careful with this; it's using static array sizing to make managing
  120717. all the modes a little less annoying. If we use a residue backend
  120718. with > 12 partition types, or a different division of iteration,
  120719. this needs to be updated. */
  120720. typedef struct {
  120721. static_codebook *books[12][3];
  120722. } static_bookblock;
  120723. typedef struct {
  120724. int res_type;
  120725. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120726. vorbis_info_residue0 *res;
  120727. static_codebook *book_aux;
  120728. static_codebook *book_aux_managed;
  120729. static_bookblock *books_base;
  120730. static_bookblock *books_base_managed;
  120731. } vorbis_residue_template;
  120732. typedef struct {
  120733. vorbis_info_mapping0 *map;
  120734. vorbis_residue_template *res;
  120735. } vorbis_mapping_template;
  120736. typedef struct vp_adjblock{
  120737. int block[P_BANDS];
  120738. } vp_adjblock;
  120739. typedef struct {
  120740. int data[NOISE_COMPAND_LEVELS];
  120741. } compandblock;
  120742. /* high level configuration information for setting things up
  120743. step-by-step with the detailed vorbis_encode_ctl interface.
  120744. There's a fair amount of redundancy such that interactive setup
  120745. does not directly deal with any vorbis_info or codec_setup_info
  120746. initialization; it's all stored (until full init) in this highlevel
  120747. setup, then flushed out to the real codec setup structs later. */
  120748. typedef struct {
  120749. int att[P_NOISECURVES];
  120750. float boost;
  120751. float decay;
  120752. } att3;
  120753. typedef struct { int data[P_NOISECURVES]; } adj3;
  120754. typedef struct {
  120755. int pre[PACKETBLOBS];
  120756. int post[PACKETBLOBS];
  120757. float kHz[PACKETBLOBS];
  120758. float lowpasskHz[PACKETBLOBS];
  120759. } adj_stereo;
  120760. typedef struct {
  120761. int lo;
  120762. int hi;
  120763. int fixed;
  120764. } noiseguard;
  120765. typedef struct {
  120766. int data[P_NOISECURVES][17];
  120767. } noise3;
  120768. typedef struct {
  120769. int mappings;
  120770. double *rate_mapping;
  120771. double *quality_mapping;
  120772. int coupling_restriction;
  120773. long samplerate_min_restriction;
  120774. long samplerate_max_restriction;
  120775. int *blocksize_short;
  120776. int *blocksize_long;
  120777. att3 *psy_tone_masteratt;
  120778. int *psy_tone_0dB;
  120779. int *psy_tone_dBsuppress;
  120780. vp_adjblock *psy_tone_adj_impulse;
  120781. vp_adjblock *psy_tone_adj_long;
  120782. vp_adjblock *psy_tone_adj_other;
  120783. noiseguard *psy_noiseguards;
  120784. noise3 *psy_noise_bias_impulse;
  120785. noise3 *psy_noise_bias_padding;
  120786. noise3 *psy_noise_bias_trans;
  120787. noise3 *psy_noise_bias_long;
  120788. int *psy_noise_dBsuppress;
  120789. compandblock *psy_noise_compand;
  120790. double *psy_noise_compand_short_mapping;
  120791. double *psy_noise_compand_long_mapping;
  120792. int *psy_noise_normal_start[2];
  120793. int *psy_noise_normal_partition[2];
  120794. double *psy_noise_normal_thresh;
  120795. int *psy_ath_float;
  120796. int *psy_ath_abs;
  120797. double *psy_lowpass;
  120798. vorbis_info_psy_global *global_params;
  120799. double *global_mapping;
  120800. adj_stereo *stereo_modes;
  120801. static_codebook ***floor_books;
  120802. vorbis_info_floor1 *floor_params;
  120803. int *floor_short_mapping;
  120804. int *floor_long_mapping;
  120805. vorbis_mapping_template *maps;
  120806. } ve_setup_data_template;
  120807. /* a few static coder conventions */
  120808. static vorbis_info_mode _mode_template[2]={
  120809. {0,0,0,0},
  120810. {1,0,0,1}
  120811. };
  120812. static vorbis_info_mapping0 _map_nominal[2]={
  120813. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120814. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120815. };
  120816. /*** Start of inlined file: setup_44.h ***/
  120817. /*** Start of inlined file: floor_all.h ***/
  120818. /*** Start of inlined file: floor_books.h ***/
  120819. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120820. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120821. };
  120822. static static_codebook _huff_book_line_256x7_0sub1 = {
  120823. 1, 9,
  120824. _huff_lengthlist_line_256x7_0sub1,
  120825. 0, 0, 0, 0, 0,
  120826. NULL,
  120827. NULL,
  120828. NULL,
  120829. NULL,
  120830. 0
  120831. };
  120832. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120834. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120835. };
  120836. static static_codebook _huff_book_line_256x7_0sub2 = {
  120837. 1, 25,
  120838. _huff_lengthlist_line_256x7_0sub2,
  120839. 0, 0, 0, 0, 0,
  120840. NULL,
  120841. NULL,
  120842. NULL,
  120843. NULL,
  120844. 0
  120845. };
  120846. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120849. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120850. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120851. };
  120852. static static_codebook _huff_book_line_256x7_0sub3 = {
  120853. 1, 64,
  120854. _huff_lengthlist_line_256x7_0sub3,
  120855. 0, 0, 0, 0, 0,
  120856. NULL,
  120857. NULL,
  120858. NULL,
  120859. NULL,
  120860. 0
  120861. };
  120862. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120863. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120864. };
  120865. static static_codebook _huff_book_line_256x7_1sub1 = {
  120866. 1, 9,
  120867. _huff_lengthlist_line_256x7_1sub1,
  120868. 0, 0, 0, 0, 0,
  120869. NULL,
  120870. NULL,
  120871. NULL,
  120872. NULL,
  120873. 0
  120874. };
  120875. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120877. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120878. };
  120879. static static_codebook _huff_book_line_256x7_1sub2 = {
  120880. 1, 25,
  120881. _huff_lengthlist_line_256x7_1sub2,
  120882. 0, 0, 0, 0, 0,
  120883. NULL,
  120884. NULL,
  120885. NULL,
  120886. NULL,
  120887. 0
  120888. };
  120889. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120892. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120893. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120894. };
  120895. static static_codebook _huff_book_line_256x7_1sub3 = {
  120896. 1, 64,
  120897. _huff_lengthlist_line_256x7_1sub3,
  120898. 0, 0, 0, 0, 0,
  120899. NULL,
  120900. NULL,
  120901. NULL,
  120902. NULL,
  120903. 0
  120904. };
  120905. static long _huff_lengthlist_line_256x7_class0[] = {
  120906. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120907. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120908. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120909. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120910. };
  120911. static static_codebook _huff_book_line_256x7_class0 = {
  120912. 1, 64,
  120913. _huff_lengthlist_line_256x7_class0,
  120914. 0, 0, 0, 0, 0,
  120915. NULL,
  120916. NULL,
  120917. NULL,
  120918. NULL,
  120919. 0
  120920. };
  120921. static long _huff_lengthlist_line_256x7_class1[] = {
  120922. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120923. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120924. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120925. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120926. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120927. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120928. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120929. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120930. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120931. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120932. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120933. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120934. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120935. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120936. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120937. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120938. };
  120939. static static_codebook _huff_book_line_256x7_class1 = {
  120940. 1, 256,
  120941. _huff_lengthlist_line_256x7_class1,
  120942. 0, 0, 0, 0, 0,
  120943. NULL,
  120944. NULL,
  120945. NULL,
  120946. NULL,
  120947. 0
  120948. };
  120949. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120950. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120951. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120952. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120953. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120954. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120955. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120956. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120957. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120958. };
  120959. static static_codebook _huff_book_line_512x17_0sub0 = {
  120960. 1, 128,
  120961. _huff_lengthlist_line_512x17_0sub0,
  120962. 0, 0, 0, 0, 0,
  120963. NULL,
  120964. NULL,
  120965. NULL,
  120966. NULL,
  120967. 0
  120968. };
  120969. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120970. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120971. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120972. };
  120973. static static_codebook _huff_book_line_512x17_1sub0 = {
  120974. 1, 32,
  120975. _huff_lengthlist_line_512x17_1sub0,
  120976. 0, 0, 0, 0, 0,
  120977. NULL,
  120978. NULL,
  120979. NULL,
  120980. NULL,
  120981. 0
  120982. };
  120983. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120986. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120987. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120988. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120989. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120990. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120991. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120992. };
  120993. static static_codebook _huff_book_line_512x17_1sub1 = {
  120994. 1, 128,
  120995. _huff_lengthlist_line_512x17_1sub1,
  120996. 0, 0, 0, 0, 0,
  120997. NULL,
  120998. NULL,
  120999. NULL,
  121000. NULL,
  121001. 0
  121002. };
  121003. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121004. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121005. 5, 3,
  121006. };
  121007. static static_codebook _huff_book_line_512x17_2sub1 = {
  121008. 1, 18,
  121009. _huff_lengthlist_line_512x17_2sub1,
  121010. 0, 0, 0, 0, 0,
  121011. NULL,
  121012. NULL,
  121013. NULL,
  121014. NULL,
  121015. 0
  121016. };
  121017. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121019. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121020. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121021. 9, 8,
  121022. };
  121023. static static_codebook _huff_book_line_512x17_2sub2 = {
  121024. 1, 50,
  121025. _huff_lengthlist_line_512x17_2sub2,
  121026. 0, 0, 0, 0, 0,
  121027. NULL,
  121028. NULL,
  121029. NULL,
  121030. NULL,
  121031. 0
  121032. };
  121033. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121037. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121038. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121039. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121040. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121041. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121042. };
  121043. static static_codebook _huff_book_line_512x17_2sub3 = {
  121044. 1, 128,
  121045. _huff_lengthlist_line_512x17_2sub3,
  121046. 0, 0, 0, 0, 0,
  121047. NULL,
  121048. NULL,
  121049. NULL,
  121050. NULL,
  121051. 0
  121052. };
  121053. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121054. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121055. 5, 5,
  121056. };
  121057. static static_codebook _huff_book_line_512x17_3sub1 = {
  121058. 1, 18,
  121059. _huff_lengthlist_line_512x17_3sub1,
  121060. 0, 0, 0, 0, 0,
  121061. NULL,
  121062. NULL,
  121063. NULL,
  121064. NULL,
  121065. 0
  121066. };
  121067. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121069. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121070. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121071. 11,14,
  121072. };
  121073. static static_codebook _huff_book_line_512x17_3sub2 = {
  121074. 1, 50,
  121075. _huff_lengthlist_line_512x17_3sub2,
  121076. 0, 0, 0, 0, 0,
  121077. NULL,
  121078. NULL,
  121079. NULL,
  121080. NULL,
  121081. 0
  121082. };
  121083. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121087. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121088. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121089. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121090. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121091. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121092. };
  121093. static static_codebook _huff_book_line_512x17_3sub3 = {
  121094. 1, 128,
  121095. _huff_lengthlist_line_512x17_3sub3,
  121096. 0, 0, 0, 0, 0,
  121097. NULL,
  121098. NULL,
  121099. NULL,
  121100. NULL,
  121101. 0
  121102. };
  121103. static long _huff_lengthlist_line_512x17_class1[] = {
  121104. 1, 2, 3, 6, 5, 4, 7, 7,
  121105. };
  121106. static static_codebook _huff_book_line_512x17_class1 = {
  121107. 1, 8,
  121108. _huff_lengthlist_line_512x17_class1,
  121109. 0, 0, 0, 0, 0,
  121110. NULL,
  121111. NULL,
  121112. NULL,
  121113. NULL,
  121114. 0
  121115. };
  121116. static long _huff_lengthlist_line_512x17_class2[] = {
  121117. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121118. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121119. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121120. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121121. };
  121122. static static_codebook _huff_book_line_512x17_class2 = {
  121123. 1, 64,
  121124. _huff_lengthlist_line_512x17_class2,
  121125. 0, 0, 0, 0, 0,
  121126. NULL,
  121127. NULL,
  121128. NULL,
  121129. NULL,
  121130. 0
  121131. };
  121132. static long _huff_lengthlist_line_512x17_class3[] = {
  121133. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121134. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121135. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121136. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121137. };
  121138. static static_codebook _huff_book_line_512x17_class3 = {
  121139. 1, 64,
  121140. _huff_lengthlist_line_512x17_class3,
  121141. 0, 0, 0, 0, 0,
  121142. NULL,
  121143. NULL,
  121144. NULL,
  121145. NULL,
  121146. 0
  121147. };
  121148. static long _huff_lengthlist_line_128x4_class0[] = {
  121149. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121150. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121151. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121152. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121153. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121154. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121155. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121156. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121157. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121158. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121159. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121160. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121161. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121162. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121163. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121164. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121165. };
  121166. static static_codebook _huff_book_line_128x4_class0 = {
  121167. 1, 256,
  121168. _huff_lengthlist_line_128x4_class0,
  121169. 0, 0, 0, 0, 0,
  121170. NULL,
  121171. NULL,
  121172. NULL,
  121173. NULL,
  121174. 0
  121175. };
  121176. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121177. 2, 2, 2, 2,
  121178. };
  121179. static static_codebook _huff_book_line_128x4_0sub0 = {
  121180. 1, 4,
  121181. _huff_lengthlist_line_128x4_0sub0,
  121182. 0, 0, 0, 0, 0,
  121183. NULL,
  121184. NULL,
  121185. NULL,
  121186. NULL,
  121187. 0
  121188. };
  121189. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121190. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121191. };
  121192. static static_codebook _huff_book_line_128x4_0sub1 = {
  121193. 1, 10,
  121194. _huff_lengthlist_line_128x4_0sub1,
  121195. 0, 0, 0, 0, 0,
  121196. NULL,
  121197. NULL,
  121198. NULL,
  121199. NULL,
  121200. 0
  121201. };
  121202. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121204. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121205. };
  121206. static static_codebook _huff_book_line_128x4_0sub2 = {
  121207. 1, 25,
  121208. _huff_lengthlist_line_128x4_0sub2,
  121209. 0, 0, 0, 0, 0,
  121210. NULL,
  121211. NULL,
  121212. NULL,
  121213. NULL,
  121214. 0
  121215. };
  121216. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121219. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121220. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121221. };
  121222. static static_codebook _huff_book_line_128x4_0sub3 = {
  121223. 1, 64,
  121224. _huff_lengthlist_line_128x4_0sub3,
  121225. 0, 0, 0, 0, 0,
  121226. NULL,
  121227. NULL,
  121228. NULL,
  121229. NULL,
  121230. 0
  121231. };
  121232. static long _huff_lengthlist_line_256x4_class0[] = {
  121233. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121234. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121235. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121236. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121237. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121238. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121239. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121240. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121241. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121242. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121243. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121244. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121245. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121246. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121247. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121248. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121249. };
  121250. static static_codebook _huff_book_line_256x4_class0 = {
  121251. 1, 256,
  121252. _huff_lengthlist_line_256x4_class0,
  121253. 0, 0, 0, 0, 0,
  121254. NULL,
  121255. NULL,
  121256. NULL,
  121257. NULL,
  121258. 0
  121259. };
  121260. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121261. 2, 2, 2, 2,
  121262. };
  121263. static static_codebook _huff_book_line_256x4_0sub0 = {
  121264. 1, 4,
  121265. _huff_lengthlist_line_256x4_0sub0,
  121266. 0, 0, 0, 0, 0,
  121267. NULL,
  121268. NULL,
  121269. NULL,
  121270. NULL,
  121271. 0
  121272. };
  121273. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121274. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121275. };
  121276. static static_codebook _huff_book_line_256x4_0sub1 = {
  121277. 1, 10,
  121278. _huff_lengthlist_line_256x4_0sub1,
  121279. 0, 0, 0, 0, 0,
  121280. NULL,
  121281. NULL,
  121282. NULL,
  121283. NULL,
  121284. 0
  121285. };
  121286. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121288. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121289. };
  121290. static static_codebook _huff_book_line_256x4_0sub2 = {
  121291. 1, 25,
  121292. _huff_lengthlist_line_256x4_0sub2,
  121293. 0, 0, 0, 0, 0,
  121294. NULL,
  121295. NULL,
  121296. NULL,
  121297. NULL,
  121298. 0
  121299. };
  121300. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121303. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121304. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121305. };
  121306. static static_codebook _huff_book_line_256x4_0sub3 = {
  121307. 1, 64,
  121308. _huff_lengthlist_line_256x4_0sub3,
  121309. 0, 0, 0, 0, 0,
  121310. NULL,
  121311. NULL,
  121312. NULL,
  121313. NULL,
  121314. 0
  121315. };
  121316. static long _huff_lengthlist_line_128x7_class0[] = {
  121317. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121318. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121319. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121320. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121321. };
  121322. static static_codebook _huff_book_line_128x7_class0 = {
  121323. 1, 64,
  121324. _huff_lengthlist_line_128x7_class0,
  121325. 0, 0, 0, 0, 0,
  121326. NULL,
  121327. NULL,
  121328. NULL,
  121329. NULL,
  121330. 0
  121331. };
  121332. static long _huff_lengthlist_line_128x7_class1[] = {
  121333. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121334. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121335. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121336. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121337. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121338. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121339. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121340. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121341. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121342. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121343. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121344. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121345. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121346. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121347. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121348. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121349. };
  121350. static static_codebook _huff_book_line_128x7_class1 = {
  121351. 1, 256,
  121352. _huff_lengthlist_line_128x7_class1,
  121353. 0, 0, 0, 0, 0,
  121354. NULL,
  121355. NULL,
  121356. NULL,
  121357. NULL,
  121358. 0
  121359. };
  121360. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121361. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121362. };
  121363. static static_codebook _huff_book_line_128x7_0sub1 = {
  121364. 1, 9,
  121365. _huff_lengthlist_line_128x7_0sub1,
  121366. 0, 0, 0, 0, 0,
  121367. NULL,
  121368. NULL,
  121369. NULL,
  121370. NULL,
  121371. 0
  121372. };
  121373. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121375. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121376. };
  121377. static static_codebook _huff_book_line_128x7_0sub2 = {
  121378. 1, 25,
  121379. _huff_lengthlist_line_128x7_0sub2,
  121380. 0, 0, 0, 0, 0,
  121381. NULL,
  121382. NULL,
  121383. NULL,
  121384. NULL,
  121385. 0
  121386. };
  121387. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121390. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121391. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121392. };
  121393. static static_codebook _huff_book_line_128x7_0sub3 = {
  121394. 1, 64,
  121395. _huff_lengthlist_line_128x7_0sub3,
  121396. 0, 0, 0, 0, 0,
  121397. NULL,
  121398. NULL,
  121399. NULL,
  121400. NULL,
  121401. 0
  121402. };
  121403. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121404. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121405. };
  121406. static static_codebook _huff_book_line_128x7_1sub1 = {
  121407. 1, 9,
  121408. _huff_lengthlist_line_128x7_1sub1,
  121409. 0, 0, 0, 0, 0,
  121410. NULL,
  121411. NULL,
  121412. NULL,
  121413. NULL,
  121414. 0
  121415. };
  121416. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121418. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121419. };
  121420. static static_codebook _huff_book_line_128x7_1sub2 = {
  121421. 1, 25,
  121422. _huff_lengthlist_line_128x7_1sub2,
  121423. 0, 0, 0, 0, 0,
  121424. NULL,
  121425. NULL,
  121426. NULL,
  121427. NULL,
  121428. 0
  121429. };
  121430. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121433. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121434. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121435. };
  121436. static static_codebook _huff_book_line_128x7_1sub3 = {
  121437. 1, 64,
  121438. _huff_lengthlist_line_128x7_1sub3,
  121439. 0, 0, 0, 0, 0,
  121440. NULL,
  121441. NULL,
  121442. NULL,
  121443. NULL,
  121444. 0
  121445. };
  121446. static long _huff_lengthlist_line_128x11_class1[] = {
  121447. 1, 6, 3, 7, 2, 4, 5, 7,
  121448. };
  121449. static static_codebook _huff_book_line_128x11_class1 = {
  121450. 1, 8,
  121451. _huff_lengthlist_line_128x11_class1,
  121452. 0, 0, 0, 0, 0,
  121453. NULL,
  121454. NULL,
  121455. NULL,
  121456. NULL,
  121457. 0
  121458. };
  121459. static long _huff_lengthlist_line_128x11_class2[] = {
  121460. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121461. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121462. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121463. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121464. };
  121465. static static_codebook _huff_book_line_128x11_class2 = {
  121466. 1, 64,
  121467. _huff_lengthlist_line_128x11_class2,
  121468. 0, 0, 0, 0, 0,
  121469. NULL,
  121470. NULL,
  121471. NULL,
  121472. NULL,
  121473. 0
  121474. };
  121475. static long _huff_lengthlist_line_128x11_class3[] = {
  121476. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121477. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121478. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121479. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121480. };
  121481. static static_codebook _huff_book_line_128x11_class3 = {
  121482. 1, 64,
  121483. _huff_lengthlist_line_128x11_class3,
  121484. 0, 0, 0, 0, 0,
  121485. NULL,
  121486. NULL,
  121487. NULL,
  121488. NULL,
  121489. 0
  121490. };
  121491. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121492. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121493. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121494. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121495. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121496. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121497. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121498. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121499. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121500. };
  121501. static static_codebook _huff_book_line_128x11_0sub0 = {
  121502. 1, 128,
  121503. _huff_lengthlist_line_128x11_0sub0,
  121504. 0, 0, 0, 0, 0,
  121505. NULL,
  121506. NULL,
  121507. NULL,
  121508. NULL,
  121509. 0
  121510. };
  121511. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121512. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121513. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121514. };
  121515. static static_codebook _huff_book_line_128x11_1sub0 = {
  121516. 1, 32,
  121517. _huff_lengthlist_line_128x11_1sub0,
  121518. 0, 0, 0, 0, 0,
  121519. NULL,
  121520. NULL,
  121521. NULL,
  121522. NULL,
  121523. 0
  121524. };
  121525. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121528. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121529. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121530. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121531. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121532. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121533. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121534. };
  121535. static static_codebook _huff_book_line_128x11_1sub1 = {
  121536. 1, 128,
  121537. _huff_lengthlist_line_128x11_1sub1,
  121538. 0, 0, 0, 0, 0,
  121539. NULL,
  121540. NULL,
  121541. NULL,
  121542. NULL,
  121543. 0
  121544. };
  121545. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121546. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121547. 5, 5,
  121548. };
  121549. static static_codebook _huff_book_line_128x11_2sub1 = {
  121550. 1, 18,
  121551. _huff_lengthlist_line_128x11_2sub1,
  121552. 0, 0, 0, 0, 0,
  121553. NULL,
  121554. NULL,
  121555. NULL,
  121556. NULL,
  121557. 0
  121558. };
  121559. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121561. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121562. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121563. 8,11,
  121564. };
  121565. static static_codebook _huff_book_line_128x11_2sub2 = {
  121566. 1, 50,
  121567. _huff_lengthlist_line_128x11_2sub2,
  121568. 0, 0, 0, 0, 0,
  121569. NULL,
  121570. NULL,
  121571. NULL,
  121572. NULL,
  121573. 0
  121574. };
  121575. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121579. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121580. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121581. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121582. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121583. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121584. };
  121585. static static_codebook _huff_book_line_128x11_2sub3 = {
  121586. 1, 128,
  121587. _huff_lengthlist_line_128x11_2sub3,
  121588. 0, 0, 0, 0, 0,
  121589. NULL,
  121590. NULL,
  121591. NULL,
  121592. NULL,
  121593. 0
  121594. };
  121595. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121596. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121597. 5, 4,
  121598. };
  121599. static static_codebook _huff_book_line_128x11_3sub1 = {
  121600. 1, 18,
  121601. _huff_lengthlist_line_128x11_3sub1,
  121602. 0, 0, 0, 0, 0,
  121603. NULL,
  121604. NULL,
  121605. NULL,
  121606. NULL,
  121607. 0
  121608. };
  121609. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121611. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121612. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121613. 12, 6,
  121614. };
  121615. static static_codebook _huff_book_line_128x11_3sub2 = {
  121616. 1, 50,
  121617. _huff_lengthlist_line_128x11_3sub2,
  121618. 0, 0, 0, 0, 0,
  121619. NULL,
  121620. NULL,
  121621. NULL,
  121622. NULL,
  121623. 0
  121624. };
  121625. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121629. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121630. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121631. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121632. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121633. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121634. };
  121635. static static_codebook _huff_book_line_128x11_3sub3 = {
  121636. 1, 128,
  121637. _huff_lengthlist_line_128x11_3sub3,
  121638. 0, 0, 0, 0, 0,
  121639. NULL,
  121640. NULL,
  121641. NULL,
  121642. NULL,
  121643. 0
  121644. };
  121645. static long _huff_lengthlist_line_128x17_class1[] = {
  121646. 1, 3, 4, 7, 2, 5, 6, 7,
  121647. };
  121648. static static_codebook _huff_book_line_128x17_class1 = {
  121649. 1, 8,
  121650. _huff_lengthlist_line_128x17_class1,
  121651. 0, 0, 0, 0, 0,
  121652. NULL,
  121653. NULL,
  121654. NULL,
  121655. NULL,
  121656. 0
  121657. };
  121658. static long _huff_lengthlist_line_128x17_class2[] = {
  121659. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121660. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121661. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121662. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121663. };
  121664. static static_codebook _huff_book_line_128x17_class2 = {
  121665. 1, 64,
  121666. _huff_lengthlist_line_128x17_class2,
  121667. 0, 0, 0, 0, 0,
  121668. NULL,
  121669. NULL,
  121670. NULL,
  121671. NULL,
  121672. 0
  121673. };
  121674. static long _huff_lengthlist_line_128x17_class3[] = {
  121675. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121676. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121677. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121678. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121679. };
  121680. static static_codebook _huff_book_line_128x17_class3 = {
  121681. 1, 64,
  121682. _huff_lengthlist_line_128x17_class3,
  121683. 0, 0, 0, 0, 0,
  121684. NULL,
  121685. NULL,
  121686. NULL,
  121687. NULL,
  121688. 0
  121689. };
  121690. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121691. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121692. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121693. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121694. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121695. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121696. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121697. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121698. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121699. };
  121700. static static_codebook _huff_book_line_128x17_0sub0 = {
  121701. 1, 128,
  121702. _huff_lengthlist_line_128x17_0sub0,
  121703. 0, 0, 0, 0, 0,
  121704. NULL,
  121705. NULL,
  121706. NULL,
  121707. NULL,
  121708. 0
  121709. };
  121710. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121711. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121712. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121713. };
  121714. static static_codebook _huff_book_line_128x17_1sub0 = {
  121715. 1, 32,
  121716. _huff_lengthlist_line_128x17_1sub0,
  121717. 0, 0, 0, 0, 0,
  121718. NULL,
  121719. NULL,
  121720. NULL,
  121721. NULL,
  121722. 0
  121723. };
  121724. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121727. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121728. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121729. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121730. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121731. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121732. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121733. };
  121734. static static_codebook _huff_book_line_128x17_1sub1 = {
  121735. 1, 128,
  121736. _huff_lengthlist_line_128x17_1sub1,
  121737. 0, 0, 0, 0, 0,
  121738. NULL,
  121739. NULL,
  121740. NULL,
  121741. NULL,
  121742. 0
  121743. };
  121744. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121745. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121746. 9, 4,
  121747. };
  121748. static static_codebook _huff_book_line_128x17_2sub1 = {
  121749. 1, 18,
  121750. _huff_lengthlist_line_128x17_2sub1,
  121751. 0, 0, 0, 0, 0,
  121752. NULL,
  121753. NULL,
  121754. NULL,
  121755. NULL,
  121756. 0
  121757. };
  121758. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121760. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121761. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121762. 13,13,
  121763. };
  121764. static static_codebook _huff_book_line_128x17_2sub2 = {
  121765. 1, 50,
  121766. _huff_lengthlist_line_128x17_2sub2,
  121767. 0, 0, 0, 0, 0,
  121768. NULL,
  121769. NULL,
  121770. NULL,
  121771. NULL,
  121772. 0
  121773. };
  121774. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121779. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121780. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121781. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121782. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121783. };
  121784. static static_codebook _huff_book_line_128x17_2sub3 = {
  121785. 1, 128,
  121786. _huff_lengthlist_line_128x17_2sub3,
  121787. 0, 0, 0, 0, 0,
  121788. NULL,
  121789. NULL,
  121790. NULL,
  121791. NULL,
  121792. 0
  121793. };
  121794. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121795. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121796. 6, 4,
  121797. };
  121798. static static_codebook _huff_book_line_128x17_3sub1 = {
  121799. 1, 18,
  121800. _huff_lengthlist_line_128x17_3sub1,
  121801. 0, 0, 0, 0, 0,
  121802. NULL,
  121803. NULL,
  121804. NULL,
  121805. NULL,
  121806. 0
  121807. };
  121808. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121810. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121811. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121812. 10, 8,
  121813. };
  121814. static static_codebook _huff_book_line_128x17_3sub2 = {
  121815. 1, 50,
  121816. _huff_lengthlist_line_128x17_3sub2,
  121817. 0, 0, 0, 0, 0,
  121818. NULL,
  121819. NULL,
  121820. NULL,
  121821. NULL,
  121822. 0
  121823. };
  121824. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121828. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121829. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121830. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121831. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121832. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121833. };
  121834. static static_codebook _huff_book_line_128x17_3sub3 = {
  121835. 1, 128,
  121836. _huff_lengthlist_line_128x17_3sub3,
  121837. 0, 0, 0, 0, 0,
  121838. NULL,
  121839. NULL,
  121840. NULL,
  121841. NULL,
  121842. 0
  121843. };
  121844. static long _huff_lengthlist_line_1024x27_class1[] = {
  121845. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121846. };
  121847. static static_codebook _huff_book_line_1024x27_class1 = {
  121848. 1, 16,
  121849. _huff_lengthlist_line_1024x27_class1,
  121850. 0, 0, 0, 0, 0,
  121851. NULL,
  121852. NULL,
  121853. NULL,
  121854. NULL,
  121855. 0
  121856. };
  121857. static long _huff_lengthlist_line_1024x27_class2[] = {
  121858. 1, 4, 2, 6, 3, 7, 5, 7,
  121859. };
  121860. static static_codebook _huff_book_line_1024x27_class2 = {
  121861. 1, 8,
  121862. _huff_lengthlist_line_1024x27_class2,
  121863. 0, 0, 0, 0, 0,
  121864. NULL,
  121865. NULL,
  121866. NULL,
  121867. NULL,
  121868. 0
  121869. };
  121870. static long _huff_lengthlist_line_1024x27_class3[] = {
  121871. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121872. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121873. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121874. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121875. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121876. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121877. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121878. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121879. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121880. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121881. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121882. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121883. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121884. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121885. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121886. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121887. };
  121888. static static_codebook _huff_book_line_1024x27_class3 = {
  121889. 1, 256,
  121890. _huff_lengthlist_line_1024x27_class3,
  121891. 0, 0, 0, 0, 0,
  121892. NULL,
  121893. NULL,
  121894. NULL,
  121895. NULL,
  121896. 0
  121897. };
  121898. static long _huff_lengthlist_line_1024x27_class4[] = {
  121899. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121900. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121901. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121902. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121903. };
  121904. static static_codebook _huff_book_line_1024x27_class4 = {
  121905. 1, 64,
  121906. _huff_lengthlist_line_1024x27_class4,
  121907. 0, 0, 0, 0, 0,
  121908. NULL,
  121909. NULL,
  121910. NULL,
  121911. NULL,
  121912. 0
  121913. };
  121914. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121915. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121916. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121917. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121918. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121919. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121920. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121921. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121922. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121923. };
  121924. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121925. 1, 128,
  121926. _huff_lengthlist_line_1024x27_0sub0,
  121927. 0, 0, 0, 0, 0,
  121928. NULL,
  121929. NULL,
  121930. NULL,
  121931. NULL,
  121932. 0
  121933. };
  121934. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121935. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121936. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121937. };
  121938. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121939. 1, 32,
  121940. _huff_lengthlist_line_1024x27_1sub0,
  121941. 0, 0, 0, 0, 0,
  121942. NULL,
  121943. NULL,
  121944. NULL,
  121945. NULL,
  121946. 0
  121947. };
  121948. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121951. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121952. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121953. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121954. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121955. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121956. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121957. };
  121958. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121959. 1, 128,
  121960. _huff_lengthlist_line_1024x27_1sub1,
  121961. 0, 0, 0, 0, 0,
  121962. NULL,
  121963. NULL,
  121964. NULL,
  121965. NULL,
  121966. 0
  121967. };
  121968. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121969. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121970. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121971. };
  121972. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121973. 1, 32,
  121974. _huff_lengthlist_line_1024x27_2sub0,
  121975. 0, 0, 0, 0, 0,
  121976. NULL,
  121977. NULL,
  121978. NULL,
  121979. NULL,
  121980. 0
  121981. };
  121982. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121985. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121986. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121987. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121988. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121989. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121990. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121991. };
  121992. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121993. 1, 128,
  121994. _huff_lengthlist_line_1024x27_2sub1,
  121995. 0, 0, 0, 0, 0,
  121996. NULL,
  121997. NULL,
  121998. NULL,
  121999. NULL,
  122000. 0
  122001. };
  122002. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122003. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122004. 5, 5,
  122005. };
  122006. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122007. 1, 18,
  122008. _huff_lengthlist_line_1024x27_3sub1,
  122009. 0, 0, 0, 0, 0,
  122010. NULL,
  122011. NULL,
  122012. NULL,
  122013. NULL,
  122014. 0
  122015. };
  122016. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122018. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122019. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122020. 9,11,
  122021. };
  122022. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122023. 1, 50,
  122024. _huff_lengthlist_line_1024x27_3sub2,
  122025. 0, 0, 0, 0, 0,
  122026. NULL,
  122027. NULL,
  122028. NULL,
  122029. NULL,
  122030. 0
  122031. };
  122032. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122036. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122037. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122038. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122039. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122040. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122041. };
  122042. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122043. 1, 128,
  122044. _huff_lengthlist_line_1024x27_3sub3,
  122045. 0, 0, 0, 0, 0,
  122046. NULL,
  122047. NULL,
  122048. NULL,
  122049. NULL,
  122050. 0
  122051. };
  122052. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122053. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122054. 5, 4,
  122055. };
  122056. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122057. 1, 18,
  122058. _huff_lengthlist_line_1024x27_4sub1,
  122059. 0, 0, 0, 0, 0,
  122060. NULL,
  122061. NULL,
  122062. NULL,
  122063. NULL,
  122064. 0
  122065. };
  122066. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122068. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122069. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122070. 9,12,
  122071. };
  122072. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122073. 1, 50,
  122074. _huff_lengthlist_line_1024x27_4sub2,
  122075. 0, 0, 0, 0, 0,
  122076. NULL,
  122077. NULL,
  122078. NULL,
  122079. NULL,
  122080. 0
  122081. };
  122082. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122086. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122087. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122088. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122089. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122090. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122091. };
  122092. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122093. 1, 128,
  122094. _huff_lengthlist_line_1024x27_4sub3,
  122095. 0, 0, 0, 0, 0,
  122096. NULL,
  122097. NULL,
  122098. NULL,
  122099. NULL,
  122100. 0
  122101. };
  122102. static long _huff_lengthlist_line_2048x27_class1[] = {
  122103. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122104. };
  122105. static static_codebook _huff_book_line_2048x27_class1 = {
  122106. 1, 16,
  122107. _huff_lengthlist_line_2048x27_class1,
  122108. 0, 0, 0, 0, 0,
  122109. NULL,
  122110. NULL,
  122111. NULL,
  122112. NULL,
  122113. 0
  122114. };
  122115. static long _huff_lengthlist_line_2048x27_class2[] = {
  122116. 1, 2, 3, 6, 4, 7, 5, 7,
  122117. };
  122118. static static_codebook _huff_book_line_2048x27_class2 = {
  122119. 1, 8,
  122120. _huff_lengthlist_line_2048x27_class2,
  122121. 0, 0, 0, 0, 0,
  122122. NULL,
  122123. NULL,
  122124. NULL,
  122125. NULL,
  122126. 0
  122127. };
  122128. static long _huff_lengthlist_line_2048x27_class3[] = {
  122129. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122130. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122131. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122132. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122133. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122134. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122135. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122136. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122137. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122138. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122139. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122140. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122141. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122142. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122143. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122144. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122145. };
  122146. static static_codebook _huff_book_line_2048x27_class3 = {
  122147. 1, 256,
  122148. _huff_lengthlist_line_2048x27_class3,
  122149. 0, 0, 0, 0, 0,
  122150. NULL,
  122151. NULL,
  122152. NULL,
  122153. NULL,
  122154. 0
  122155. };
  122156. static long _huff_lengthlist_line_2048x27_class4[] = {
  122157. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122158. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122159. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122160. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122161. };
  122162. static static_codebook _huff_book_line_2048x27_class4 = {
  122163. 1, 64,
  122164. _huff_lengthlist_line_2048x27_class4,
  122165. 0, 0, 0, 0, 0,
  122166. NULL,
  122167. NULL,
  122168. NULL,
  122169. NULL,
  122170. 0
  122171. };
  122172. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122173. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122174. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122175. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122176. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122177. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122178. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122179. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122180. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122181. };
  122182. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122183. 1, 128,
  122184. _huff_lengthlist_line_2048x27_0sub0,
  122185. 0, 0, 0, 0, 0,
  122186. NULL,
  122187. NULL,
  122188. NULL,
  122189. NULL,
  122190. 0
  122191. };
  122192. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122193. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122194. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122195. };
  122196. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122197. 1, 32,
  122198. _huff_lengthlist_line_2048x27_1sub0,
  122199. 0, 0, 0, 0, 0,
  122200. NULL,
  122201. NULL,
  122202. NULL,
  122203. NULL,
  122204. 0
  122205. };
  122206. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122209. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122210. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122211. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122212. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122213. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122214. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122215. };
  122216. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122217. 1, 128,
  122218. _huff_lengthlist_line_2048x27_1sub1,
  122219. 0, 0, 0, 0, 0,
  122220. NULL,
  122221. NULL,
  122222. NULL,
  122223. NULL,
  122224. 0
  122225. };
  122226. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122227. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122228. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122229. };
  122230. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122231. 1, 32,
  122232. _huff_lengthlist_line_2048x27_2sub0,
  122233. 0, 0, 0, 0, 0,
  122234. NULL,
  122235. NULL,
  122236. NULL,
  122237. NULL,
  122238. 0
  122239. };
  122240. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122243. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122244. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122245. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122246. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122247. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122248. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122249. };
  122250. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122251. 1, 128,
  122252. _huff_lengthlist_line_2048x27_2sub1,
  122253. 0, 0, 0, 0, 0,
  122254. NULL,
  122255. NULL,
  122256. NULL,
  122257. NULL,
  122258. 0
  122259. };
  122260. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122261. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122262. 5, 5,
  122263. };
  122264. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122265. 1, 18,
  122266. _huff_lengthlist_line_2048x27_3sub1,
  122267. 0, 0, 0, 0, 0,
  122268. NULL,
  122269. NULL,
  122270. NULL,
  122271. NULL,
  122272. 0
  122273. };
  122274. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122276. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122277. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122278. 10,12,
  122279. };
  122280. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122281. 1, 50,
  122282. _huff_lengthlist_line_2048x27_3sub2,
  122283. 0, 0, 0, 0, 0,
  122284. NULL,
  122285. NULL,
  122286. NULL,
  122287. NULL,
  122288. 0
  122289. };
  122290. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122294. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122295. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122296. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122297. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122298. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122299. };
  122300. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122301. 1, 128,
  122302. _huff_lengthlist_line_2048x27_3sub3,
  122303. 0, 0, 0, 0, 0,
  122304. NULL,
  122305. NULL,
  122306. NULL,
  122307. NULL,
  122308. 0
  122309. };
  122310. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122311. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122312. 4, 5,
  122313. };
  122314. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122315. 1, 18,
  122316. _huff_lengthlist_line_2048x27_4sub1,
  122317. 0, 0, 0, 0, 0,
  122318. NULL,
  122319. NULL,
  122320. NULL,
  122321. NULL,
  122322. 0
  122323. };
  122324. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122327. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122328. 10,10,
  122329. };
  122330. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122331. 1, 50,
  122332. _huff_lengthlist_line_2048x27_4sub2,
  122333. 0, 0, 0, 0, 0,
  122334. NULL,
  122335. NULL,
  122336. NULL,
  122337. NULL,
  122338. 0
  122339. };
  122340. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122344. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122345. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122346. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122347. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122348. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122349. };
  122350. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122351. 1, 128,
  122352. _huff_lengthlist_line_2048x27_4sub3,
  122353. 0, 0, 0, 0, 0,
  122354. NULL,
  122355. NULL,
  122356. NULL,
  122357. NULL,
  122358. 0
  122359. };
  122360. static long _huff_lengthlist_line_256x4low_class0[] = {
  122361. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122362. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122363. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122364. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122365. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122366. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122367. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122368. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122369. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122370. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122371. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122372. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122373. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122374. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122375. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122376. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122377. };
  122378. static static_codebook _huff_book_line_256x4low_class0 = {
  122379. 1, 256,
  122380. _huff_lengthlist_line_256x4low_class0,
  122381. 0, 0, 0, 0, 0,
  122382. NULL,
  122383. NULL,
  122384. NULL,
  122385. NULL,
  122386. 0
  122387. };
  122388. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122389. 1, 3, 2, 3,
  122390. };
  122391. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122392. 1, 4,
  122393. _huff_lengthlist_line_256x4low_0sub0,
  122394. 0, 0, 0, 0, 0,
  122395. NULL,
  122396. NULL,
  122397. NULL,
  122398. NULL,
  122399. 0
  122400. };
  122401. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122402. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122403. };
  122404. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122405. 1, 10,
  122406. _huff_lengthlist_line_256x4low_0sub1,
  122407. 0, 0, 0, 0, 0,
  122408. NULL,
  122409. NULL,
  122410. NULL,
  122411. NULL,
  122412. 0
  122413. };
  122414. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122416. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122417. };
  122418. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122419. 1, 25,
  122420. _huff_lengthlist_line_256x4low_0sub2,
  122421. 0, 0, 0, 0, 0,
  122422. NULL,
  122423. NULL,
  122424. NULL,
  122425. NULL,
  122426. 0
  122427. };
  122428. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122431. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122432. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122433. };
  122434. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122435. 1, 64,
  122436. _huff_lengthlist_line_256x4low_0sub3,
  122437. 0, 0, 0, 0, 0,
  122438. NULL,
  122439. NULL,
  122440. NULL,
  122441. NULL,
  122442. 0
  122443. };
  122444. /*** End of inlined file: floor_books.h ***/
  122445. static static_codebook *_floor_128x4_books[]={
  122446. &_huff_book_line_128x4_class0,
  122447. &_huff_book_line_128x4_0sub0,
  122448. &_huff_book_line_128x4_0sub1,
  122449. &_huff_book_line_128x4_0sub2,
  122450. &_huff_book_line_128x4_0sub3,
  122451. };
  122452. static static_codebook *_floor_256x4_books[]={
  122453. &_huff_book_line_256x4_class0,
  122454. &_huff_book_line_256x4_0sub0,
  122455. &_huff_book_line_256x4_0sub1,
  122456. &_huff_book_line_256x4_0sub2,
  122457. &_huff_book_line_256x4_0sub3,
  122458. };
  122459. static static_codebook *_floor_128x7_books[]={
  122460. &_huff_book_line_128x7_class0,
  122461. &_huff_book_line_128x7_class1,
  122462. &_huff_book_line_128x7_0sub1,
  122463. &_huff_book_line_128x7_0sub2,
  122464. &_huff_book_line_128x7_0sub3,
  122465. &_huff_book_line_128x7_1sub1,
  122466. &_huff_book_line_128x7_1sub2,
  122467. &_huff_book_line_128x7_1sub3,
  122468. };
  122469. static static_codebook *_floor_256x7_books[]={
  122470. &_huff_book_line_256x7_class0,
  122471. &_huff_book_line_256x7_class1,
  122472. &_huff_book_line_256x7_0sub1,
  122473. &_huff_book_line_256x7_0sub2,
  122474. &_huff_book_line_256x7_0sub3,
  122475. &_huff_book_line_256x7_1sub1,
  122476. &_huff_book_line_256x7_1sub2,
  122477. &_huff_book_line_256x7_1sub3,
  122478. };
  122479. static static_codebook *_floor_128x11_books[]={
  122480. &_huff_book_line_128x11_class1,
  122481. &_huff_book_line_128x11_class2,
  122482. &_huff_book_line_128x11_class3,
  122483. &_huff_book_line_128x11_0sub0,
  122484. &_huff_book_line_128x11_1sub0,
  122485. &_huff_book_line_128x11_1sub1,
  122486. &_huff_book_line_128x11_2sub1,
  122487. &_huff_book_line_128x11_2sub2,
  122488. &_huff_book_line_128x11_2sub3,
  122489. &_huff_book_line_128x11_3sub1,
  122490. &_huff_book_line_128x11_3sub2,
  122491. &_huff_book_line_128x11_3sub3,
  122492. };
  122493. static static_codebook *_floor_128x17_books[]={
  122494. &_huff_book_line_128x17_class1,
  122495. &_huff_book_line_128x17_class2,
  122496. &_huff_book_line_128x17_class3,
  122497. &_huff_book_line_128x17_0sub0,
  122498. &_huff_book_line_128x17_1sub0,
  122499. &_huff_book_line_128x17_1sub1,
  122500. &_huff_book_line_128x17_2sub1,
  122501. &_huff_book_line_128x17_2sub2,
  122502. &_huff_book_line_128x17_2sub3,
  122503. &_huff_book_line_128x17_3sub1,
  122504. &_huff_book_line_128x17_3sub2,
  122505. &_huff_book_line_128x17_3sub3,
  122506. };
  122507. static static_codebook *_floor_256x4low_books[]={
  122508. &_huff_book_line_256x4low_class0,
  122509. &_huff_book_line_256x4low_0sub0,
  122510. &_huff_book_line_256x4low_0sub1,
  122511. &_huff_book_line_256x4low_0sub2,
  122512. &_huff_book_line_256x4low_0sub3,
  122513. };
  122514. static static_codebook *_floor_1024x27_books[]={
  122515. &_huff_book_line_1024x27_class1,
  122516. &_huff_book_line_1024x27_class2,
  122517. &_huff_book_line_1024x27_class3,
  122518. &_huff_book_line_1024x27_class4,
  122519. &_huff_book_line_1024x27_0sub0,
  122520. &_huff_book_line_1024x27_1sub0,
  122521. &_huff_book_line_1024x27_1sub1,
  122522. &_huff_book_line_1024x27_2sub0,
  122523. &_huff_book_line_1024x27_2sub1,
  122524. &_huff_book_line_1024x27_3sub1,
  122525. &_huff_book_line_1024x27_3sub2,
  122526. &_huff_book_line_1024x27_3sub3,
  122527. &_huff_book_line_1024x27_4sub1,
  122528. &_huff_book_line_1024x27_4sub2,
  122529. &_huff_book_line_1024x27_4sub3,
  122530. };
  122531. static static_codebook *_floor_2048x27_books[]={
  122532. &_huff_book_line_2048x27_class1,
  122533. &_huff_book_line_2048x27_class2,
  122534. &_huff_book_line_2048x27_class3,
  122535. &_huff_book_line_2048x27_class4,
  122536. &_huff_book_line_2048x27_0sub0,
  122537. &_huff_book_line_2048x27_1sub0,
  122538. &_huff_book_line_2048x27_1sub1,
  122539. &_huff_book_line_2048x27_2sub0,
  122540. &_huff_book_line_2048x27_2sub1,
  122541. &_huff_book_line_2048x27_3sub1,
  122542. &_huff_book_line_2048x27_3sub2,
  122543. &_huff_book_line_2048x27_3sub3,
  122544. &_huff_book_line_2048x27_4sub1,
  122545. &_huff_book_line_2048x27_4sub2,
  122546. &_huff_book_line_2048x27_4sub3,
  122547. };
  122548. static static_codebook *_floor_512x17_books[]={
  122549. &_huff_book_line_512x17_class1,
  122550. &_huff_book_line_512x17_class2,
  122551. &_huff_book_line_512x17_class3,
  122552. &_huff_book_line_512x17_0sub0,
  122553. &_huff_book_line_512x17_1sub0,
  122554. &_huff_book_line_512x17_1sub1,
  122555. &_huff_book_line_512x17_2sub1,
  122556. &_huff_book_line_512x17_2sub2,
  122557. &_huff_book_line_512x17_2sub3,
  122558. &_huff_book_line_512x17_3sub1,
  122559. &_huff_book_line_512x17_3sub2,
  122560. &_huff_book_line_512x17_3sub3,
  122561. };
  122562. static static_codebook **_floor_books[10]={
  122563. _floor_128x4_books,
  122564. _floor_256x4_books,
  122565. _floor_128x7_books,
  122566. _floor_256x7_books,
  122567. _floor_128x11_books,
  122568. _floor_128x17_books,
  122569. _floor_256x4low_books,
  122570. _floor_1024x27_books,
  122571. _floor_2048x27_books,
  122572. _floor_512x17_books,
  122573. };
  122574. static vorbis_info_floor1 _floor[10]={
  122575. /* 128 x 4 */
  122576. {
  122577. 1,{0},{4},{2},{0},
  122578. {{1,2,3,4}},
  122579. 4,{0,128, 33,8,16,70},
  122580. 60,30,500, 1.,18., -1
  122581. },
  122582. /* 256 x 4 */
  122583. {
  122584. 1,{0},{4},{2},{0},
  122585. {{1,2,3,4}},
  122586. 4,{0,256, 66,16,32,140},
  122587. 60,30,500, 1.,18., -1
  122588. },
  122589. /* 128 x 7 */
  122590. {
  122591. 2,{0,1},{3,4},{2,2},{0,1},
  122592. {{-1,2,3,4},{-1,5,6,7}},
  122593. 4,{0,128, 14,4,58, 2,8,28,90},
  122594. 60,30,500, 1.,18., -1
  122595. },
  122596. /* 256 x 7 */
  122597. {
  122598. 2,{0,1},{3,4},{2,2},{0,1},
  122599. {{-1,2,3,4},{-1,5,6,7}},
  122600. 4,{0,256, 28,8,116, 4,16,56,180},
  122601. 60,30,500, 1.,18., -1
  122602. },
  122603. /* 128 x 11 */
  122604. {
  122605. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122606. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122607. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122608. 60,30,500, 1,18., -1
  122609. },
  122610. /* 128 x 17 */
  122611. {
  122612. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122613. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122614. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122615. 60,30,500, 1,18., -1
  122616. },
  122617. /* 256 x 4 (low bitrate version) */
  122618. {
  122619. 1,{0},{4},{2},{0},
  122620. {{1,2,3,4}},
  122621. 4,{0,256, 66,16,32,140},
  122622. 60,30,500, 1.,18., -1
  122623. },
  122624. /* 1024 x 27 */
  122625. {
  122626. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122627. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122628. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122629. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122630. 60,30,500, 3,18., -1 /* lowpass */
  122631. },
  122632. /* 2048 x 27 */
  122633. {
  122634. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122635. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122636. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122637. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122638. 60,30,500, 3,18., -1 /* lowpass */
  122639. },
  122640. /* 512 x 17 */
  122641. {
  122642. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122643. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122644. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122645. 7,23,39, 55,79,110, 156,232,360},
  122646. 60,30,500, 1,18., -1 /* lowpass! */
  122647. },
  122648. };
  122649. /*** End of inlined file: floor_all.h ***/
  122650. /*** Start of inlined file: residue_44.h ***/
  122651. /*** Start of inlined file: res_books_stereo.h ***/
  122652. static long _vq_quantlist__16c0_s_p1_0[] = {
  122653. 1,
  122654. 0,
  122655. 2,
  122656. };
  122657. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122658. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122659. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122664. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122669. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122704. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122709. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122714. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122750. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122755. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122760. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0,
  123069. };
  123070. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123071. -0.5, 0.5,
  123072. };
  123073. static long _vq_quantmap__16c0_s_p1_0[] = {
  123074. 1, 0, 2,
  123075. };
  123076. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123077. _vq_quantthresh__16c0_s_p1_0,
  123078. _vq_quantmap__16c0_s_p1_0,
  123079. 3,
  123080. 3
  123081. };
  123082. static static_codebook _16c0_s_p1_0 = {
  123083. 8, 6561,
  123084. _vq_lengthlist__16c0_s_p1_0,
  123085. 1, -535822336, 1611661312, 2, 0,
  123086. _vq_quantlist__16c0_s_p1_0,
  123087. NULL,
  123088. &_vq_auxt__16c0_s_p1_0,
  123089. NULL,
  123090. 0
  123091. };
  123092. static long _vq_quantlist__16c0_s_p2_0[] = {
  123093. 2,
  123094. 1,
  123095. 3,
  123096. 0,
  123097. 4,
  123098. };
  123099. static long _vq_lengthlist__16c0_s_p2_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,
  123140. };
  123141. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123142. -1.5, -0.5, 0.5, 1.5,
  123143. };
  123144. static long _vq_quantmap__16c0_s_p2_0[] = {
  123145. 3, 1, 0, 2, 4,
  123146. };
  123147. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123148. _vq_quantthresh__16c0_s_p2_0,
  123149. _vq_quantmap__16c0_s_p2_0,
  123150. 5,
  123151. 5
  123152. };
  123153. static static_codebook _16c0_s_p2_0 = {
  123154. 4, 625,
  123155. _vq_lengthlist__16c0_s_p2_0,
  123156. 1, -533725184, 1611661312, 3, 0,
  123157. _vq_quantlist__16c0_s_p2_0,
  123158. NULL,
  123159. &_vq_auxt__16c0_s_p2_0,
  123160. NULL,
  123161. 0
  123162. };
  123163. static long _vq_quantlist__16c0_s_p3_0[] = {
  123164. 2,
  123165. 1,
  123166. 3,
  123167. 0,
  123168. 4,
  123169. };
  123170. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123171. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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,
  123211. };
  123212. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123213. -1.5, -0.5, 0.5, 1.5,
  123214. };
  123215. static long _vq_quantmap__16c0_s_p3_0[] = {
  123216. 3, 1, 0, 2, 4,
  123217. };
  123218. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123219. _vq_quantthresh__16c0_s_p3_0,
  123220. _vq_quantmap__16c0_s_p3_0,
  123221. 5,
  123222. 5
  123223. };
  123224. static static_codebook _16c0_s_p3_0 = {
  123225. 4, 625,
  123226. _vq_lengthlist__16c0_s_p3_0,
  123227. 1, -533725184, 1611661312, 3, 0,
  123228. _vq_quantlist__16c0_s_p3_0,
  123229. NULL,
  123230. &_vq_auxt__16c0_s_p3_0,
  123231. NULL,
  123232. 0
  123233. };
  123234. static long _vq_quantlist__16c0_s_p4_0[] = {
  123235. 4,
  123236. 3,
  123237. 5,
  123238. 2,
  123239. 6,
  123240. 1,
  123241. 7,
  123242. 0,
  123243. 8,
  123244. };
  123245. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123246. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123247. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123248. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123249. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123250. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0,
  123252. };
  123253. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123254. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123255. };
  123256. static long _vq_quantmap__16c0_s_p4_0[] = {
  123257. 7, 5, 3, 1, 0, 2, 4, 6,
  123258. 8,
  123259. };
  123260. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123261. _vq_quantthresh__16c0_s_p4_0,
  123262. _vq_quantmap__16c0_s_p4_0,
  123263. 9,
  123264. 9
  123265. };
  123266. static static_codebook _16c0_s_p4_0 = {
  123267. 2, 81,
  123268. _vq_lengthlist__16c0_s_p4_0,
  123269. 1, -531628032, 1611661312, 4, 0,
  123270. _vq_quantlist__16c0_s_p4_0,
  123271. NULL,
  123272. &_vq_auxt__16c0_s_p4_0,
  123273. NULL,
  123274. 0
  123275. };
  123276. static long _vq_quantlist__16c0_s_p5_0[] = {
  123277. 4,
  123278. 3,
  123279. 5,
  123280. 2,
  123281. 6,
  123282. 1,
  123283. 7,
  123284. 0,
  123285. 8,
  123286. };
  123287. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123288. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123289. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123290. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123291. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123292. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123293. 10,
  123294. };
  123295. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123296. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123297. };
  123298. static long _vq_quantmap__16c0_s_p5_0[] = {
  123299. 7, 5, 3, 1, 0, 2, 4, 6,
  123300. 8,
  123301. };
  123302. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123303. _vq_quantthresh__16c0_s_p5_0,
  123304. _vq_quantmap__16c0_s_p5_0,
  123305. 9,
  123306. 9
  123307. };
  123308. static static_codebook _16c0_s_p5_0 = {
  123309. 2, 81,
  123310. _vq_lengthlist__16c0_s_p5_0,
  123311. 1, -531628032, 1611661312, 4, 0,
  123312. _vq_quantlist__16c0_s_p5_0,
  123313. NULL,
  123314. &_vq_auxt__16c0_s_p5_0,
  123315. NULL,
  123316. 0
  123317. };
  123318. static long _vq_quantlist__16c0_s_p6_0[] = {
  123319. 8,
  123320. 7,
  123321. 9,
  123322. 6,
  123323. 10,
  123324. 5,
  123325. 11,
  123326. 4,
  123327. 12,
  123328. 3,
  123329. 13,
  123330. 2,
  123331. 14,
  123332. 1,
  123333. 15,
  123334. 0,
  123335. 16,
  123336. };
  123337. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123338. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123339. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123340. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123341. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123342. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123343. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123344. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123345. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123346. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123347. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123348. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123349. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123350. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123351. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123352. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123353. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123354. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123356. 14,
  123357. };
  123358. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123359. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123360. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123361. };
  123362. static long _vq_quantmap__16c0_s_p6_0[] = {
  123363. 15, 13, 11, 9, 7, 5, 3, 1,
  123364. 0, 2, 4, 6, 8, 10, 12, 14,
  123365. 16,
  123366. };
  123367. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123368. _vq_quantthresh__16c0_s_p6_0,
  123369. _vq_quantmap__16c0_s_p6_0,
  123370. 17,
  123371. 17
  123372. };
  123373. static static_codebook _16c0_s_p6_0 = {
  123374. 2, 289,
  123375. _vq_lengthlist__16c0_s_p6_0,
  123376. 1, -529530880, 1611661312, 5, 0,
  123377. _vq_quantlist__16c0_s_p6_0,
  123378. NULL,
  123379. &_vq_auxt__16c0_s_p6_0,
  123380. NULL,
  123381. 0
  123382. };
  123383. static long _vq_quantlist__16c0_s_p7_0[] = {
  123384. 1,
  123385. 0,
  123386. 2,
  123387. };
  123388. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123389. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123390. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123391. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123392. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123393. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123394. 13,
  123395. };
  123396. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123397. -5.5, 5.5,
  123398. };
  123399. static long _vq_quantmap__16c0_s_p7_0[] = {
  123400. 1, 0, 2,
  123401. };
  123402. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123403. _vq_quantthresh__16c0_s_p7_0,
  123404. _vq_quantmap__16c0_s_p7_0,
  123405. 3,
  123406. 3
  123407. };
  123408. static static_codebook _16c0_s_p7_0 = {
  123409. 4, 81,
  123410. _vq_lengthlist__16c0_s_p7_0,
  123411. 1, -529137664, 1618345984, 2, 0,
  123412. _vq_quantlist__16c0_s_p7_0,
  123413. NULL,
  123414. &_vq_auxt__16c0_s_p7_0,
  123415. NULL,
  123416. 0
  123417. };
  123418. static long _vq_quantlist__16c0_s_p7_1[] = {
  123419. 5,
  123420. 4,
  123421. 6,
  123422. 3,
  123423. 7,
  123424. 2,
  123425. 8,
  123426. 1,
  123427. 9,
  123428. 0,
  123429. 10,
  123430. };
  123431. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123432. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123433. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123434. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123435. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123436. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123437. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123438. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123439. 11,11,11, 9, 9, 9, 9,10,10,
  123440. };
  123441. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123442. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123443. 3.5, 4.5,
  123444. };
  123445. static long _vq_quantmap__16c0_s_p7_1[] = {
  123446. 9, 7, 5, 3, 1, 0, 2, 4,
  123447. 6, 8, 10,
  123448. };
  123449. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123450. _vq_quantthresh__16c0_s_p7_1,
  123451. _vq_quantmap__16c0_s_p7_1,
  123452. 11,
  123453. 11
  123454. };
  123455. static static_codebook _16c0_s_p7_1 = {
  123456. 2, 121,
  123457. _vq_lengthlist__16c0_s_p7_1,
  123458. 1, -531365888, 1611661312, 4, 0,
  123459. _vq_quantlist__16c0_s_p7_1,
  123460. NULL,
  123461. &_vq_auxt__16c0_s_p7_1,
  123462. NULL,
  123463. 0
  123464. };
  123465. static long _vq_quantlist__16c0_s_p8_0[] = {
  123466. 6,
  123467. 5,
  123468. 7,
  123469. 4,
  123470. 8,
  123471. 3,
  123472. 9,
  123473. 2,
  123474. 10,
  123475. 1,
  123476. 11,
  123477. 0,
  123478. 12,
  123479. };
  123480. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123481. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123482. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123483. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123484. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123485. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123486. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123487. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123488. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123489. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123490. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123491. 0,12,13,13,12,13,14,14,14,
  123492. };
  123493. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123494. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123495. 12.5, 17.5, 22.5, 27.5,
  123496. };
  123497. static long _vq_quantmap__16c0_s_p8_0[] = {
  123498. 11, 9, 7, 5, 3, 1, 0, 2,
  123499. 4, 6, 8, 10, 12,
  123500. };
  123501. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123502. _vq_quantthresh__16c0_s_p8_0,
  123503. _vq_quantmap__16c0_s_p8_0,
  123504. 13,
  123505. 13
  123506. };
  123507. static static_codebook _16c0_s_p8_0 = {
  123508. 2, 169,
  123509. _vq_lengthlist__16c0_s_p8_0,
  123510. 1, -526516224, 1616117760, 4, 0,
  123511. _vq_quantlist__16c0_s_p8_0,
  123512. NULL,
  123513. &_vq_auxt__16c0_s_p8_0,
  123514. NULL,
  123515. 0
  123516. };
  123517. static long _vq_quantlist__16c0_s_p8_1[] = {
  123518. 2,
  123519. 1,
  123520. 3,
  123521. 0,
  123522. 4,
  123523. };
  123524. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123525. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123526. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123527. };
  123528. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123529. -1.5, -0.5, 0.5, 1.5,
  123530. };
  123531. static long _vq_quantmap__16c0_s_p8_1[] = {
  123532. 3, 1, 0, 2, 4,
  123533. };
  123534. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123535. _vq_quantthresh__16c0_s_p8_1,
  123536. _vq_quantmap__16c0_s_p8_1,
  123537. 5,
  123538. 5
  123539. };
  123540. static static_codebook _16c0_s_p8_1 = {
  123541. 2, 25,
  123542. _vq_lengthlist__16c0_s_p8_1,
  123543. 1, -533725184, 1611661312, 3, 0,
  123544. _vq_quantlist__16c0_s_p8_1,
  123545. NULL,
  123546. &_vq_auxt__16c0_s_p8_1,
  123547. NULL,
  123548. 0
  123549. };
  123550. static long _vq_quantlist__16c0_s_p9_0[] = {
  123551. 1,
  123552. 0,
  123553. 2,
  123554. };
  123555. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123556. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123557. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123558. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123559. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123560. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123561. 7,
  123562. };
  123563. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123564. -157.5, 157.5,
  123565. };
  123566. static long _vq_quantmap__16c0_s_p9_0[] = {
  123567. 1, 0, 2,
  123568. };
  123569. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123570. _vq_quantthresh__16c0_s_p9_0,
  123571. _vq_quantmap__16c0_s_p9_0,
  123572. 3,
  123573. 3
  123574. };
  123575. static static_codebook _16c0_s_p9_0 = {
  123576. 4, 81,
  123577. _vq_lengthlist__16c0_s_p9_0,
  123578. 1, -518803456, 1628680192, 2, 0,
  123579. _vq_quantlist__16c0_s_p9_0,
  123580. NULL,
  123581. &_vq_auxt__16c0_s_p9_0,
  123582. NULL,
  123583. 0
  123584. };
  123585. static long _vq_quantlist__16c0_s_p9_1[] = {
  123586. 7,
  123587. 6,
  123588. 8,
  123589. 5,
  123590. 9,
  123591. 4,
  123592. 10,
  123593. 3,
  123594. 11,
  123595. 2,
  123596. 12,
  123597. 1,
  123598. 13,
  123599. 0,
  123600. 14,
  123601. };
  123602. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123603. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123604. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123605. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123606. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123607. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123608. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123609. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123610. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123611. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123612. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123613. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123614. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123615. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123616. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123617. 10,
  123618. };
  123619. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123620. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123621. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123622. };
  123623. static long _vq_quantmap__16c0_s_p9_1[] = {
  123624. 13, 11, 9, 7, 5, 3, 1, 0,
  123625. 2, 4, 6, 8, 10, 12, 14,
  123626. };
  123627. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123628. _vq_quantthresh__16c0_s_p9_1,
  123629. _vq_quantmap__16c0_s_p9_1,
  123630. 15,
  123631. 15
  123632. };
  123633. static static_codebook _16c0_s_p9_1 = {
  123634. 2, 225,
  123635. _vq_lengthlist__16c0_s_p9_1,
  123636. 1, -520986624, 1620377600, 4, 0,
  123637. _vq_quantlist__16c0_s_p9_1,
  123638. NULL,
  123639. &_vq_auxt__16c0_s_p9_1,
  123640. NULL,
  123641. 0
  123642. };
  123643. static long _vq_quantlist__16c0_s_p9_2[] = {
  123644. 10,
  123645. 9,
  123646. 11,
  123647. 8,
  123648. 12,
  123649. 7,
  123650. 13,
  123651. 6,
  123652. 14,
  123653. 5,
  123654. 15,
  123655. 4,
  123656. 16,
  123657. 3,
  123658. 17,
  123659. 2,
  123660. 18,
  123661. 1,
  123662. 19,
  123663. 0,
  123664. 20,
  123665. };
  123666. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123667. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123668. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123669. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123670. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123671. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123672. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123673. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123674. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123675. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123676. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123677. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123678. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123679. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123680. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123681. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123682. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123683. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123684. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123685. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123686. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123687. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123688. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123689. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123690. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123691. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123692. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123693. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123694. 10,11,10,10,11, 9,10,10,10,
  123695. };
  123696. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123697. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123698. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123699. 6.5, 7.5, 8.5, 9.5,
  123700. };
  123701. static long _vq_quantmap__16c0_s_p9_2[] = {
  123702. 19, 17, 15, 13, 11, 9, 7, 5,
  123703. 3, 1, 0, 2, 4, 6, 8, 10,
  123704. 12, 14, 16, 18, 20,
  123705. };
  123706. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123707. _vq_quantthresh__16c0_s_p9_2,
  123708. _vq_quantmap__16c0_s_p9_2,
  123709. 21,
  123710. 21
  123711. };
  123712. static static_codebook _16c0_s_p9_2 = {
  123713. 2, 441,
  123714. _vq_lengthlist__16c0_s_p9_2,
  123715. 1, -529268736, 1611661312, 5, 0,
  123716. _vq_quantlist__16c0_s_p9_2,
  123717. NULL,
  123718. &_vq_auxt__16c0_s_p9_2,
  123719. NULL,
  123720. 0
  123721. };
  123722. static long _huff_lengthlist__16c0_s_single[] = {
  123723. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123724. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123725. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123726. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123727. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123728. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123729. 16,16,18,18,
  123730. };
  123731. static static_codebook _huff_book__16c0_s_single = {
  123732. 2, 100,
  123733. _huff_lengthlist__16c0_s_single,
  123734. 0, 0, 0, 0, 0,
  123735. NULL,
  123736. NULL,
  123737. NULL,
  123738. NULL,
  123739. 0
  123740. };
  123741. static long _huff_lengthlist__16c1_s_long[] = {
  123742. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123743. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123744. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123745. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123746. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123747. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123748. 12,11,11,13,
  123749. };
  123750. static static_codebook _huff_book__16c1_s_long = {
  123751. 2, 100,
  123752. _huff_lengthlist__16c1_s_long,
  123753. 0, 0, 0, 0, 0,
  123754. NULL,
  123755. NULL,
  123756. NULL,
  123757. NULL,
  123758. 0
  123759. };
  123760. static long _vq_quantlist__16c1_s_p1_0[] = {
  123761. 1,
  123762. 0,
  123763. 2,
  123764. };
  123765. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123766. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123767. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123772. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123777. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123812. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123817. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123822. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123858. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123863. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123868. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0,
  124177. };
  124178. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124179. -0.5, 0.5,
  124180. };
  124181. static long _vq_quantmap__16c1_s_p1_0[] = {
  124182. 1, 0, 2,
  124183. };
  124184. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124185. _vq_quantthresh__16c1_s_p1_0,
  124186. _vq_quantmap__16c1_s_p1_0,
  124187. 3,
  124188. 3
  124189. };
  124190. static static_codebook _16c1_s_p1_0 = {
  124191. 8, 6561,
  124192. _vq_lengthlist__16c1_s_p1_0,
  124193. 1, -535822336, 1611661312, 2, 0,
  124194. _vq_quantlist__16c1_s_p1_0,
  124195. NULL,
  124196. &_vq_auxt__16c1_s_p1_0,
  124197. NULL,
  124198. 0
  124199. };
  124200. static long _vq_quantlist__16c1_s_p2_0[] = {
  124201. 2,
  124202. 1,
  124203. 3,
  124204. 0,
  124205. 4,
  124206. };
  124207. static long _vq_lengthlist__16c1_s_p2_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,
  124248. };
  124249. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124250. -1.5, -0.5, 0.5, 1.5,
  124251. };
  124252. static long _vq_quantmap__16c1_s_p2_0[] = {
  124253. 3, 1, 0, 2, 4,
  124254. };
  124255. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124256. _vq_quantthresh__16c1_s_p2_0,
  124257. _vq_quantmap__16c1_s_p2_0,
  124258. 5,
  124259. 5
  124260. };
  124261. static static_codebook _16c1_s_p2_0 = {
  124262. 4, 625,
  124263. _vq_lengthlist__16c1_s_p2_0,
  124264. 1, -533725184, 1611661312, 3, 0,
  124265. _vq_quantlist__16c1_s_p2_0,
  124266. NULL,
  124267. &_vq_auxt__16c1_s_p2_0,
  124268. NULL,
  124269. 0
  124270. };
  124271. static long _vq_quantlist__16c1_s_p3_0[] = {
  124272. 2,
  124273. 1,
  124274. 3,
  124275. 0,
  124276. 4,
  124277. };
  124278. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124279. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  124319. };
  124320. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124321. -1.5, -0.5, 0.5, 1.5,
  124322. };
  124323. static long _vq_quantmap__16c1_s_p3_0[] = {
  124324. 3, 1, 0, 2, 4,
  124325. };
  124326. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124327. _vq_quantthresh__16c1_s_p3_0,
  124328. _vq_quantmap__16c1_s_p3_0,
  124329. 5,
  124330. 5
  124331. };
  124332. static static_codebook _16c1_s_p3_0 = {
  124333. 4, 625,
  124334. _vq_lengthlist__16c1_s_p3_0,
  124335. 1, -533725184, 1611661312, 3, 0,
  124336. _vq_quantlist__16c1_s_p3_0,
  124337. NULL,
  124338. &_vq_auxt__16c1_s_p3_0,
  124339. NULL,
  124340. 0
  124341. };
  124342. static long _vq_quantlist__16c1_s_p4_0[] = {
  124343. 4,
  124344. 3,
  124345. 5,
  124346. 2,
  124347. 6,
  124348. 1,
  124349. 7,
  124350. 0,
  124351. 8,
  124352. };
  124353. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124354. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124355. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124356. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124357. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124358. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124359. 0,
  124360. };
  124361. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124362. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124363. };
  124364. static long _vq_quantmap__16c1_s_p4_0[] = {
  124365. 7, 5, 3, 1, 0, 2, 4, 6,
  124366. 8,
  124367. };
  124368. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124369. _vq_quantthresh__16c1_s_p4_0,
  124370. _vq_quantmap__16c1_s_p4_0,
  124371. 9,
  124372. 9
  124373. };
  124374. static static_codebook _16c1_s_p4_0 = {
  124375. 2, 81,
  124376. _vq_lengthlist__16c1_s_p4_0,
  124377. 1, -531628032, 1611661312, 4, 0,
  124378. _vq_quantlist__16c1_s_p4_0,
  124379. NULL,
  124380. &_vq_auxt__16c1_s_p4_0,
  124381. NULL,
  124382. 0
  124383. };
  124384. static long _vq_quantlist__16c1_s_p5_0[] = {
  124385. 4,
  124386. 3,
  124387. 5,
  124388. 2,
  124389. 6,
  124390. 1,
  124391. 7,
  124392. 0,
  124393. 8,
  124394. };
  124395. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124396. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124397. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124398. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124399. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124400. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124401. 10,
  124402. };
  124403. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124404. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124405. };
  124406. static long _vq_quantmap__16c1_s_p5_0[] = {
  124407. 7, 5, 3, 1, 0, 2, 4, 6,
  124408. 8,
  124409. };
  124410. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124411. _vq_quantthresh__16c1_s_p5_0,
  124412. _vq_quantmap__16c1_s_p5_0,
  124413. 9,
  124414. 9
  124415. };
  124416. static static_codebook _16c1_s_p5_0 = {
  124417. 2, 81,
  124418. _vq_lengthlist__16c1_s_p5_0,
  124419. 1, -531628032, 1611661312, 4, 0,
  124420. _vq_quantlist__16c1_s_p5_0,
  124421. NULL,
  124422. &_vq_auxt__16c1_s_p5_0,
  124423. NULL,
  124424. 0
  124425. };
  124426. static long _vq_quantlist__16c1_s_p6_0[] = {
  124427. 8,
  124428. 7,
  124429. 9,
  124430. 6,
  124431. 10,
  124432. 5,
  124433. 11,
  124434. 4,
  124435. 12,
  124436. 3,
  124437. 13,
  124438. 2,
  124439. 14,
  124440. 1,
  124441. 15,
  124442. 0,
  124443. 16,
  124444. };
  124445. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124446. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124447. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124448. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124449. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124450. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124451. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124452. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124453. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124454. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124455. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124456. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124457. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124458. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124459. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124460. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124461. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124462. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124463. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124464. 14,
  124465. };
  124466. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124467. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124468. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124469. };
  124470. static long _vq_quantmap__16c1_s_p6_0[] = {
  124471. 15, 13, 11, 9, 7, 5, 3, 1,
  124472. 0, 2, 4, 6, 8, 10, 12, 14,
  124473. 16,
  124474. };
  124475. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124476. _vq_quantthresh__16c1_s_p6_0,
  124477. _vq_quantmap__16c1_s_p6_0,
  124478. 17,
  124479. 17
  124480. };
  124481. static static_codebook _16c1_s_p6_0 = {
  124482. 2, 289,
  124483. _vq_lengthlist__16c1_s_p6_0,
  124484. 1, -529530880, 1611661312, 5, 0,
  124485. _vq_quantlist__16c1_s_p6_0,
  124486. NULL,
  124487. &_vq_auxt__16c1_s_p6_0,
  124488. NULL,
  124489. 0
  124490. };
  124491. static long _vq_quantlist__16c1_s_p7_0[] = {
  124492. 1,
  124493. 0,
  124494. 2,
  124495. };
  124496. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124497. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124498. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124499. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124500. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124501. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124502. 11,
  124503. };
  124504. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124505. -5.5, 5.5,
  124506. };
  124507. static long _vq_quantmap__16c1_s_p7_0[] = {
  124508. 1, 0, 2,
  124509. };
  124510. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124511. _vq_quantthresh__16c1_s_p7_0,
  124512. _vq_quantmap__16c1_s_p7_0,
  124513. 3,
  124514. 3
  124515. };
  124516. static static_codebook _16c1_s_p7_0 = {
  124517. 4, 81,
  124518. _vq_lengthlist__16c1_s_p7_0,
  124519. 1, -529137664, 1618345984, 2, 0,
  124520. _vq_quantlist__16c1_s_p7_0,
  124521. NULL,
  124522. &_vq_auxt__16c1_s_p7_0,
  124523. NULL,
  124524. 0
  124525. };
  124526. static long _vq_quantlist__16c1_s_p7_1[] = {
  124527. 5,
  124528. 4,
  124529. 6,
  124530. 3,
  124531. 7,
  124532. 2,
  124533. 8,
  124534. 1,
  124535. 9,
  124536. 0,
  124537. 10,
  124538. };
  124539. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124540. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124541. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124542. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124543. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124544. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124545. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124546. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124547. 10,10,10, 8, 8, 8, 8, 9, 9,
  124548. };
  124549. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124550. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124551. 3.5, 4.5,
  124552. };
  124553. static long _vq_quantmap__16c1_s_p7_1[] = {
  124554. 9, 7, 5, 3, 1, 0, 2, 4,
  124555. 6, 8, 10,
  124556. };
  124557. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124558. _vq_quantthresh__16c1_s_p7_1,
  124559. _vq_quantmap__16c1_s_p7_1,
  124560. 11,
  124561. 11
  124562. };
  124563. static static_codebook _16c1_s_p7_1 = {
  124564. 2, 121,
  124565. _vq_lengthlist__16c1_s_p7_1,
  124566. 1, -531365888, 1611661312, 4, 0,
  124567. _vq_quantlist__16c1_s_p7_1,
  124568. NULL,
  124569. &_vq_auxt__16c1_s_p7_1,
  124570. NULL,
  124571. 0
  124572. };
  124573. static long _vq_quantlist__16c1_s_p8_0[] = {
  124574. 6,
  124575. 5,
  124576. 7,
  124577. 4,
  124578. 8,
  124579. 3,
  124580. 9,
  124581. 2,
  124582. 10,
  124583. 1,
  124584. 11,
  124585. 0,
  124586. 12,
  124587. };
  124588. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124589. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124590. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124591. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124592. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124593. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124594. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124595. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124596. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124597. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124598. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124599. 0,12,12,12,12,13,13,14,15,
  124600. };
  124601. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124602. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124603. 12.5, 17.5, 22.5, 27.5,
  124604. };
  124605. static long _vq_quantmap__16c1_s_p8_0[] = {
  124606. 11, 9, 7, 5, 3, 1, 0, 2,
  124607. 4, 6, 8, 10, 12,
  124608. };
  124609. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124610. _vq_quantthresh__16c1_s_p8_0,
  124611. _vq_quantmap__16c1_s_p8_0,
  124612. 13,
  124613. 13
  124614. };
  124615. static static_codebook _16c1_s_p8_0 = {
  124616. 2, 169,
  124617. _vq_lengthlist__16c1_s_p8_0,
  124618. 1, -526516224, 1616117760, 4, 0,
  124619. _vq_quantlist__16c1_s_p8_0,
  124620. NULL,
  124621. &_vq_auxt__16c1_s_p8_0,
  124622. NULL,
  124623. 0
  124624. };
  124625. static long _vq_quantlist__16c1_s_p8_1[] = {
  124626. 2,
  124627. 1,
  124628. 3,
  124629. 0,
  124630. 4,
  124631. };
  124632. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124633. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124634. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124635. };
  124636. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124637. -1.5, -0.5, 0.5, 1.5,
  124638. };
  124639. static long _vq_quantmap__16c1_s_p8_1[] = {
  124640. 3, 1, 0, 2, 4,
  124641. };
  124642. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124643. _vq_quantthresh__16c1_s_p8_1,
  124644. _vq_quantmap__16c1_s_p8_1,
  124645. 5,
  124646. 5
  124647. };
  124648. static static_codebook _16c1_s_p8_1 = {
  124649. 2, 25,
  124650. _vq_lengthlist__16c1_s_p8_1,
  124651. 1, -533725184, 1611661312, 3, 0,
  124652. _vq_quantlist__16c1_s_p8_1,
  124653. NULL,
  124654. &_vq_auxt__16c1_s_p8_1,
  124655. NULL,
  124656. 0
  124657. };
  124658. static long _vq_quantlist__16c1_s_p9_0[] = {
  124659. 6,
  124660. 5,
  124661. 7,
  124662. 4,
  124663. 8,
  124664. 3,
  124665. 9,
  124666. 2,
  124667. 10,
  124668. 1,
  124669. 11,
  124670. 0,
  124671. 12,
  124672. };
  124673. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124674. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124675. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124676. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124677. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124678. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124679. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124680. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124681. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124682. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124683. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124684. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124685. };
  124686. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124687. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124688. 787.5, 1102.5, 1417.5, 1732.5,
  124689. };
  124690. static long _vq_quantmap__16c1_s_p9_0[] = {
  124691. 11, 9, 7, 5, 3, 1, 0, 2,
  124692. 4, 6, 8, 10, 12,
  124693. };
  124694. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124695. _vq_quantthresh__16c1_s_p9_0,
  124696. _vq_quantmap__16c1_s_p9_0,
  124697. 13,
  124698. 13
  124699. };
  124700. static static_codebook _16c1_s_p9_0 = {
  124701. 2, 169,
  124702. _vq_lengthlist__16c1_s_p9_0,
  124703. 1, -513964032, 1628680192, 4, 0,
  124704. _vq_quantlist__16c1_s_p9_0,
  124705. NULL,
  124706. &_vq_auxt__16c1_s_p9_0,
  124707. NULL,
  124708. 0
  124709. };
  124710. static long _vq_quantlist__16c1_s_p9_1[] = {
  124711. 7,
  124712. 6,
  124713. 8,
  124714. 5,
  124715. 9,
  124716. 4,
  124717. 10,
  124718. 3,
  124719. 11,
  124720. 2,
  124721. 12,
  124722. 1,
  124723. 13,
  124724. 0,
  124725. 14,
  124726. };
  124727. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124728. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124729. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124730. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124731. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124732. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124733. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124734. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124735. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124736. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124737. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124738. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124739. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124740. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124741. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124742. 13,
  124743. };
  124744. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124745. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124746. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124747. };
  124748. static long _vq_quantmap__16c1_s_p9_1[] = {
  124749. 13, 11, 9, 7, 5, 3, 1, 0,
  124750. 2, 4, 6, 8, 10, 12, 14,
  124751. };
  124752. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124753. _vq_quantthresh__16c1_s_p9_1,
  124754. _vq_quantmap__16c1_s_p9_1,
  124755. 15,
  124756. 15
  124757. };
  124758. static static_codebook _16c1_s_p9_1 = {
  124759. 2, 225,
  124760. _vq_lengthlist__16c1_s_p9_1,
  124761. 1, -520986624, 1620377600, 4, 0,
  124762. _vq_quantlist__16c1_s_p9_1,
  124763. NULL,
  124764. &_vq_auxt__16c1_s_p9_1,
  124765. NULL,
  124766. 0
  124767. };
  124768. static long _vq_quantlist__16c1_s_p9_2[] = {
  124769. 10,
  124770. 9,
  124771. 11,
  124772. 8,
  124773. 12,
  124774. 7,
  124775. 13,
  124776. 6,
  124777. 14,
  124778. 5,
  124779. 15,
  124780. 4,
  124781. 16,
  124782. 3,
  124783. 17,
  124784. 2,
  124785. 18,
  124786. 1,
  124787. 19,
  124788. 0,
  124789. 20,
  124790. };
  124791. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124792. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124793. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124794. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124795. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124796. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124797. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124798. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124799. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124800. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124801. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124802. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124803. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124804. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124805. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124806. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124807. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124808. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124809. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124810. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124811. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124812. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124813. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124814. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124815. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124816. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124817. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124818. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124819. 11,11,11,11,12,11,11,12,11,
  124820. };
  124821. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124822. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124823. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124824. 6.5, 7.5, 8.5, 9.5,
  124825. };
  124826. static long _vq_quantmap__16c1_s_p9_2[] = {
  124827. 19, 17, 15, 13, 11, 9, 7, 5,
  124828. 3, 1, 0, 2, 4, 6, 8, 10,
  124829. 12, 14, 16, 18, 20,
  124830. };
  124831. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124832. _vq_quantthresh__16c1_s_p9_2,
  124833. _vq_quantmap__16c1_s_p9_2,
  124834. 21,
  124835. 21
  124836. };
  124837. static static_codebook _16c1_s_p9_2 = {
  124838. 2, 441,
  124839. _vq_lengthlist__16c1_s_p9_2,
  124840. 1, -529268736, 1611661312, 5, 0,
  124841. _vq_quantlist__16c1_s_p9_2,
  124842. NULL,
  124843. &_vq_auxt__16c1_s_p9_2,
  124844. NULL,
  124845. 0
  124846. };
  124847. static long _huff_lengthlist__16c1_s_short[] = {
  124848. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124849. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124850. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124851. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124852. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124853. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124854. 9, 9,10,13,
  124855. };
  124856. static static_codebook _huff_book__16c1_s_short = {
  124857. 2, 100,
  124858. _huff_lengthlist__16c1_s_short,
  124859. 0, 0, 0, 0, 0,
  124860. NULL,
  124861. NULL,
  124862. NULL,
  124863. NULL,
  124864. 0
  124865. };
  124866. static long _huff_lengthlist__16c2_s_long[] = {
  124867. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124868. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124869. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124870. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124871. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124872. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124873. 14,14,16,18,
  124874. };
  124875. static static_codebook _huff_book__16c2_s_long = {
  124876. 2, 100,
  124877. _huff_lengthlist__16c2_s_long,
  124878. 0, 0, 0, 0, 0,
  124879. NULL,
  124880. NULL,
  124881. NULL,
  124882. NULL,
  124883. 0
  124884. };
  124885. static long _vq_quantlist__16c2_s_p1_0[] = {
  124886. 1,
  124887. 0,
  124888. 2,
  124889. };
  124890. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124891. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124892. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124896. 0,
  124897. };
  124898. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124899. -0.5, 0.5,
  124900. };
  124901. static long _vq_quantmap__16c2_s_p1_0[] = {
  124902. 1, 0, 2,
  124903. };
  124904. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124905. _vq_quantthresh__16c2_s_p1_0,
  124906. _vq_quantmap__16c2_s_p1_0,
  124907. 3,
  124908. 3
  124909. };
  124910. static static_codebook _16c2_s_p1_0 = {
  124911. 4, 81,
  124912. _vq_lengthlist__16c2_s_p1_0,
  124913. 1, -535822336, 1611661312, 2, 0,
  124914. _vq_quantlist__16c2_s_p1_0,
  124915. NULL,
  124916. &_vq_auxt__16c2_s_p1_0,
  124917. NULL,
  124918. 0
  124919. };
  124920. static long _vq_quantlist__16c2_s_p2_0[] = {
  124921. 2,
  124922. 1,
  124923. 3,
  124924. 0,
  124925. 4,
  124926. };
  124927. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124928. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124929. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124930. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124931. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124932. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124933. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124934. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124935. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124940. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124941. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124942. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124943. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124948. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124949. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124950. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124951. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124956. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124957. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124958. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124959. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124964. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124965. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124966. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124967. 13,
  124968. };
  124969. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124970. -1.5, -0.5, 0.5, 1.5,
  124971. };
  124972. static long _vq_quantmap__16c2_s_p2_0[] = {
  124973. 3, 1, 0, 2, 4,
  124974. };
  124975. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124976. _vq_quantthresh__16c2_s_p2_0,
  124977. _vq_quantmap__16c2_s_p2_0,
  124978. 5,
  124979. 5
  124980. };
  124981. static static_codebook _16c2_s_p2_0 = {
  124982. 4, 625,
  124983. _vq_lengthlist__16c2_s_p2_0,
  124984. 1, -533725184, 1611661312, 3, 0,
  124985. _vq_quantlist__16c2_s_p2_0,
  124986. NULL,
  124987. &_vq_auxt__16c2_s_p2_0,
  124988. NULL,
  124989. 0
  124990. };
  124991. static long _vq_quantlist__16c2_s_p3_0[] = {
  124992. 4,
  124993. 3,
  124994. 5,
  124995. 2,
  124996. 6,
  124997. 1,
  124998. 7,
  124999. 0,
  125000. 8,
  125001. };
  125002. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125003. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125004. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125005. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125006. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125008. 0,
  125009. };
  125010. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125011. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125012. };
  125013. static long _vq_quantmap__16c2_s_p3_0[] = {
  125014. 7, 5, 3, 1, 0, 2, 4, 6,
  125015. 8,
  125016. };
  125017. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125018. _vq_quantthresh__16c2_s_p3_0,
  125019. _vq_quantmap__16c2_s_p3_0,
  125020. 9,
  125021. 9
  125022. };
  125023. static static_codebook _16c2_s_p3_0 = {
  125024. 2, 81,
  125025. _vq_lengthlist__16c2_s_p3_0,
  125026. 1, -531628032, 1611661312, 4, 0,
  125027. _vq_quantlist__16c2_s_p3_0,
  125028. NULL,
  125029. &_vq_auxt__16c2_s_p3_0,
  125030. NULL,
  125031. 0
  125032. };
  125033. static long _vq_quantlist__16c2_s_p4_0[] = {
  125034. 8,
  125035. 7,
  125036. 9,
  125037. 6,
  125038. 10,
  125039. 5,
  125040. 11,
  125041. 4,
  125042. 12,
  125043. 3,
  125044. 13,
  125045. 2,
  125046. 14,
  125047. 1,
  125048. 15,
  125049. 0,
  125050. 16,
  125051. };
  125052. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125053. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125054. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125055. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125056. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125057. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125058. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125059. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125060. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125061. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125062. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125071. 0,
  125072. };
  125073. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125074. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125075. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125076. };
  125077. static long _vq_quantmap__16c2_s_p4_0[] = {
  125078. 15, 13, 11, 9, 7, 5, 3, 1,
  125079. 0, 2, 4, 6, 8, 10, 12, 14,
  125080. 16,
  125081. };
  125082. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125083. _vq_quantthresh__16c2_s_p4_0,
  125084. _vq_quantmap__16c2_s_p4_0,
  125085. 17,
  125086. 17
  125087. };
  125088. static static_codebook _16c2_s_p4_0 = {
  125089. 2, 289,
  125090. _vq_lengthlist__16c2_s_p4_0,
  125091. 1, -529530880, 1611661312, 5, 0,
  125092. _vq_quantlist__16c2_s_p4_0,
  125093. NULL,
  125094. &_vq_auxt__16c2_s_p4_0,
  125095. NULL,
  125096. 0
  125097. };
  125098. static long _vq_quantlist__16c2_s_p5_0[] = {
  125099. 1,
  125100. 0,
  125101. 2,
  125102. };
  125103. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125104. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125105. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125106. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125107. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125108. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125109. 12,
  125110. };
  125111. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125112. -5.5, 5.5,
  125113. };
  125114. static long _vq_quantmap__16c2_s_p5_0[] = {
  125115. 1, 0, 2,
  125116. };
  125117. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125118. _vq_quantthresh__16c2_s_p5_0,
  125119. _vq_quantmap__16c2_s_p5_0,
  125120. 3,
  125121. 3
  125122. };
  125123. static static_codebook _16c2_s_p5_0 = {
  125124. 4, 81,
  125125. _vq_lengthlist__16c2_s_p5_0,
  125126. 1, -529137664, 1618345984, 2, 0,
  125127. _vq_quantlist__16c2_s_p5_0,
  125128. NULL,
  125129. &_vq_auxt__16c2_s_p5_0,
  125130. NULL,
  125131. 0
  125132. };
  125133. static long _vq_quantlist__16c2_s_p5_1[] = {
  125134. 5,
  125135. 4,
  125136. 6,
  125137. 3,
  125138. 7,
  125139. 2,
  125140. 8,
  125141. 1,
  125142. 9,
  125143. 0,
  125144. 10,
  125145. };
  125146. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125147. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125148. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125149. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125150. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125151. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125152. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125153. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125154. 11,11,11, 7, 7, 8, 8, 8, 8,
  125155. };
  125156. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125157. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125158. 3.5, 4.5,
  125159. };
  125160. static long _vq_quantmap__16c2_s_p5_1[] = {
  125161. 9, 7, 5, 3, 1, 0, 2, 4,
  125162. 6, 8, 10,
  125163. };
  125164. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125165. _vq_quantthresh__16c2_s_p5_1,
  125166. _vq_quantmap__16c2_s_p5_1,
  125167. 11,
  125168. 11
  125169. };
  125170. static static_codebook _16c2_s_p5_1 = {
  125171. 2, 121,
  125172. _vq_lengthlist__16c2_s_p5_1,
  125173. 1, -531365888, 1611661312, 4, 0,
  125174. _vq_quantlist__16c2_s_p5_1,
  125175. NULL,
  125176. &_vq_auxt__16c2_s_p5_1,
  125177. NULL,
  125178. 0
  125179. };
  125180. static long _vq_quantlist__16c2_s_p6_0[] = {
  125181. 6,
  125182. 5,
  125183. 7,
  125184. 4,
  125185. 8,
  125186. 3,
  125187. 9,
  125188. 2,
  125189. 10,
  125190. 1,
  125191. 11,
  125192. 0,
  125193. 12,
  125194. };
  125195. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125196. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125197. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125198. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125199. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125200. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125201. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125206. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125207. };
  125208. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125209. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125210. 12.5, 17.5, 22.5, 27.5,
  125211. };
  125212. static long _vq_quantmap__16c2_s_p6_0[] = {
  125213. 11, 9, 7, 5, 3, 1, 0, 2,
  125214. 4, 6, 8, 10, 12,
  125215. };
  125216. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125217. _vq_quantthresh__16c2_s_p6_0,
  125218. _vq_quantmap__16c2_s_p6_0,
  125219. 13,
  125220. 13
  125221. };
  125222. static static_codebook _16c2_s_p6_0 = {
  125223. 2, 169,
  125224. _vq_lengthlist__16c2_s_p6_0,
  125225. 1, -526516224, 1616117760, 4, 0,
  125226. _vq_quantlist__16c2_s_p6_0,
  125227. NULL,
  125228. &_vq_auxt__16c2_s_p6_0,
  125229. NULL,
  125230. 0
  125231. };
  125232. static long _vq_quantlist__16c2_s_p6_1[] = {
  125233. 2,
  125234. 1,
  125235. 3,
  125236. 0,
  125237. 4,
  125238. };
  125239. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125240. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125241. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125242. };
  125243. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125244. -1.5, -0.5, 0.5, 1.5,
  125245. };
  125246. static long _vq_quantmap__16c2_s_p6_1[] = {
  125247. 3, 1, 0, 2, 4,
  125248. };
  125249. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125250. _vq_quantthresh__16c2_s_p6_1,
  125251. _vq_quantmap__16c2_s_p6_1,
  125252. 5,
  125253. 5
  125254. };
  125255. static static_codebook _16c2_s_p6_1 = {
  125256. 2, 25,
  125257. _vq_lengthlist__16c2_s_p6_1,
  125258. 1, -533725184, 1611661312, 3, 0,
  125259. _vq_quantlist__16c2_s_p6_1,
  125260. NULL,
  125261. &_vq_auxt__16c2_s_p6_1,
  125262. NULL,
  125263. 0
  125264. };
  125265. static long _vq_quantlist__16c2_s_p7_0[] = {
  125266. 6,
  125267. 5,
  125268. 7,
  125269. 4,
  125270. 8,
  125271. 3,
  125272. 9,
  125273. 2,
  125274. 10,
  125275. 1,
  125276. 11,
  125277. 0,
  125278. 12,
  125279. };
  125280. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125281. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125282. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125283. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125284. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125285. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125286. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125287. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125288. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125289. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125290. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125291. 18,13,14,13,13,14,13,15,14,
  125292. };
  125293. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125294. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125295. 27.5, 38.5, 49.5, 60.5,
  125296. };
  125297. static long _vq_quantmap__16c2_s_p7_0[] = {
  125298. 11, 9, 7, 5, 3, 1, 0, 2,
  125299. 4, 6, 8, 10, 12,
  125300. };
  125301. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125302. _vq_quantthresh__16c2_s_p7_0,
  125303. _vq_quantmap__16c2_s_p7_0,
  125304. 13,
  125305. 13
  125306. };
  125307. static static_codebook _16c2_s_p7_0 = {
  125308. 2, 169,
  125309. _vq_lengthlist__16c2_s_p7_0,
  125310. 1, -523206656, 1618345984, 4, 0,
  125311. _vq_quantlist__16c2_s_p7_0,
  125312. NULL,
  125313. &_vq_auxt__16c2_s_p7_0,
  125314. NULL,
  125315. 0
  125316. };
  125317. static long _vq_quantlist__16c2_s_p7_1[] = {
  125318. 5,
  125319. 4,
  125320. 6,
  125321. 3,
  125322. 7,
  125323. 2,
  125324. 8,
  125325. 1,
  125326. 9,
  125327. 0,
  125328. 10,
  125329. };
  125330. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125331. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125332. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125333. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125334. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125335. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125336. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125337. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125338. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125339. };
  125340. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125341. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125342. 3.5, 4.5,
  125343. };
  125344. static long _vq_quantmap__16c2_s_p7_1[] = {
  125345. 9, 7, 5, 3, 1, 0, 2, 4,
  125346. 6, 8, 10,
  125347. };
  125348. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125349. _vq_quantthresh__16c2_s_p7_1,
  125350. _vq_quantmap__16c2_s_p7_1,
  125351. 11,
  125352. 11
  125353. };
  125354. static static_codebook _16c2_s_p7_1 = {
  125355. 2, 121,
  125356. _vq_lengthlist__16c2_s_p7_1,
  125357. 1, -531365888, 1611661312, 4, 0,
  125358. _vq_quantlist__16c2_s_p7_1,
  125359. NULL,
  125360. &_vq_auxt__16c2_s_p7_1,
  125361. NULL,
  125362. 0
  125363. };
  125364. static long _vq_quantlist__16c2_s_p8_0[] = {
  125365. 7,
  125366. 6,
  125367. 8,
  125368. 5,
  125369. 9,
  125370. 4,
  125371. 10,
  125372. 3,
  125373. 11,
  125374. 2,
  125375. 12,
  125376. 1,
  125377. 13,
  125378. 0,
  125379. 14,
  125380. };
  125381. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125382. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125383. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125384. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125385. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125386. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125387. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125388. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125389. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125390. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125391. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125392. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125393. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125394. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125395. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125396. 13,
  125397. };
  125398. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125399. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125400. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125401. };
  125402. static long _vq_quantmap__16c2_s_p8_0[] = {
  125403. 13, 11, 9, 7, 5, 3, 1, 0,
  125404. 2, 4, 6, 8, 10, 12, 14,
  125405. };
  125406. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125407. _vq_quantthresh__16c2_s_p8_0,
  125408. _vq_quantmap__16c2_s_p8_0,
  125409. 15,
  125410. 15
  125411. };
  125412. static static_codebook _16c2_s_p8_0 = {
  125413. 2, 225,
  125414. _vq_lengthlist__16c2_s_p8_0,
  125415. 1, -520986624, 1620377600, 4, 0,
  125416. _vq_quantlist__16c2_s_p8_0,
  125417. NULL,
  125418. &_vq_auxt__16c2_s_p8_0,
  125419. NULL,
  125420. 0
  125421. };
  125422. static long _vq_quantlist__16c2_s_p8_1[] = {
  125423. 10,
  125424. 9,
  125425. 11,
  125426. 8,
  125427. 12,
  125428. 7,
  125429. 13,
  125430. 6,
  125431. 14,
  125432. 5,
  125433. 15,
  125434. 4,
  125435. 16,
  125436. 3,
  125437. 17,
  125438. 2,
  125439. 18,
  125440. 1,
  125441. 19,
  125442. 0,
  125443. 20,
  125444. };
  125445. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125446. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125447. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125448. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125449. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125450. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125451. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125452. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125453. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125454. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125455. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125456. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125457. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125458. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125459. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125460. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125461. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125462. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125463. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125464. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125465. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125466. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125467. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125468. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125469. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125470. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125471. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125472. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125473. 10,11,10,10,10,10,10,10,10,
  125474. };
  125475. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125476. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125477. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125478. 6.5, 7.5, 8.5, 9.5,
  125479. };
  125480. static long _vq_quantmap__16c2_s_p8_1[] = {
  125481. 19, 17, 15, 13, 11, 9, 7, 5,
  125482. 3, 1, 0, 2, 4, 6, 8, 10,
  125483. 12, 14, 16, 18, 20,
  125484. };
  125485. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125486. _vq_quantthresh__16c2_s_p8_1,
  125487. _vq_quantmap__16c2_s_p8_1,
  125488. 21,
  125489. 21
  125490. };
  125491. static static_codebook _16c2_s_p8_1 = {
  125492. 2, 441,
  125493. _vq_lengthlist__16c2_s_p8_1,
  125494. 1, -529268736, 1611661312, 5, 0,
  125495. _vq_quantlist__16c2_s_p8_1,
  125496. NULL,
  125497. &_vq_auxt__16c2_s_p8_1,
  125498. NULL,
  125499. 0
  125500. };
  125501. static long _vq_quantlist__16c2_s_p9_0[] = {
  125502. 6,
  125503. 5,
  125504. 7,
  125505. 4,
  125506. 8,
  125507. 3,
  125508. 9,
  125509. 2,
  125510. 10,
  125511. 1,
  125512. 11,
  125513. 0,
  125514. 12,
  125515. };
  125516. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125517. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125518. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125519. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125520. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125521. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125522. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125523. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125524. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125525. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125526. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125527. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125528. };
  125529. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125530. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125531. 2327.5, 3258.5, 4189.5, 5120.5,
  125532. };
  125533. static long _vq_quantmap__16c2_s_p9_0[] = {
  125534. 11, 9, 7, 5, 3, 1, 0, 2,
  125535. 4, 6, 8, 10, 12,
  125536. };
  125537. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125538. _vq_quantthresh__16c2_s_p9_0,
  125539. _vq_quantmap__16c2_s_p9_0,
  125540. 13,
  125541. 13
  125542. };
  125543. static static_codebook _16c2_s_p9_0 = {
  125544. 2, 169,
  125545. _vq_lengthlist__16c2_s_p9_0,
  125546. 1, -510275072, 1631393792, 4, 0,
  125547. _vq_quantlist__16c2_s_p9_0,
  125548. NULL,
  125549. &_vq_auxt__16c2_s_p9_0,
  125550. NULL,
  125551. 0
  125552. };
  125553. static long _vq_quantlist__16c2_s_p9_1[] = {
  125554. 8,
  125555. 7,
  125556. 9,
  125557. 6,
  125558. 10,
  125559. 5,
  125560. 11,
  125561. 4,
  125562. 12,
  125563. 3,
  125564. 13,
  125565. 2,
  125566. 14,
  125567. 1,
  125568. 15,
  125569. 0,
  125570. 16,
  125571. };
  125572. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125573. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125574. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125575. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125576. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125577. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125578. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125579. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125580. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125581. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125582. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125583. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125584. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125585. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125586. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125587. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125588. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125589. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125590. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125591. 10,
  125592. };
  125593. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125594. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125595. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125596. };
  125597. static long _vq_quantmap__16c2_s_p9_1[] = {
  125598. 15, 13, 11, 9, 7, 5, 3, 1,
  125599. 0, 2, 4, 6, 8, 10, 12, 14,
  125600. 16,
  125601. };
  125602. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125603. _vq_quantthresh__16c2_s_p9_1,
  125604. _vq_quantmap__16c2_s_p9_1,
  125605. 17,
  125606. 17
  125607. };
  125608. static static_codebook _16c2_s_p9_1 = {
  125609. 2, 289,
  125610. _vq_lengthlist__16c2_s_p9_1,
  125611. 1, -518488064, 1622704128, 5, 0,
  125612. _vq_quantlist__16c2_s_p9_1,
  125613. NULL,
  125614. &_vq_auxt__16c2_s_p9_1,
  125615. NULL,
  125616. 0
  125617. };
  125618. static long _vq_quantlist__16c2_s_p9_2[] = {
  125619. 13,
  125620. 12,
  125621. 14,
  125622. 11,
  125623. 15,
  125624. 10,
  125625. 16,
  125626. 9,
  125627. 17,
  125628. 8,
  125629. 18,
  125630. 7,
  125631. 19,
  125632. 6,
  125633. 20,
  125634. 5,
  125635. 21,
  125636. 4,
  125637. 22,
  125638. 3,
  125639. 23,
  125640. 2,
  125641. 24,
  125642. 1,
  125643. 25,
  125644. 0,
  125645. 26,
  125646. };
  125647. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125648. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125649. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125650. };
  125651. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125652. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125653. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125654. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125655. 11.5, 12.5,
  125656. };
  125657. static long _vq_quantmap__16c2_s_p9_2[] = {
  125658. 25, 23, 21, 19, 17, 15, 13, 11,
  125659. 9, 7, 5, 3, 1, 0, 2, 4,
  125660. 6, 8, 10, 12, 14, 16, 18, 20,
  125661. 22, 24, 26,
  125662. };
  125663. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125664. _vq_quantthresh__16c2_s_p9_2,
  125665. _vq_quantmap__16c2_s_p9_2,
  125666. 27,
  125667. 27
  125668. };
  125669. static static_codebook _16c2_s_p9_2 = {
  125670. 1, 27,
  125671. _vq_lengthlist__16c2_s_p9_2,
  125672. 1, -528875520, 1611661312, 5, 0,
  125673. _vq_quantlist__16c2_s_p9_2,
  125674. NULL,
  125675. &_vq_auxt__16c2_s_p9_2,
  125676. NULL,
  125677. 0
  125678. };
  125679. static long _huff_lengthlist__16c2_s_short[] = {
  125680. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125681. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125682. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125683. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125684. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125685. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125686. 15,12,14,14,
  125687. };
  125688. static static_codebook _huff_book__16c2_s_short = {
  125689. 2, 100,
  125690. _huff_lengthlist__16c2_s_short,
  125691. 0, 0, 0, 0, 0,
  125692. NULL,
  125693. NULL,
  125694. NULL,
  125695. NULL,
  125696. 0
  125697. };
  125698. static long _vq_quantlist__8c0_s_p1_0[] = {
  125699. 1,
  125700. 0,
  125701. 2,
  125702. };
  125703. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125704. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125705. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125710. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125715. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125750. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125755. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125760. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125796. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125801. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125806. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0,
  126115. };
  126116. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126117. -0.5, 0.5,
  126118. };
  126119. static long _vq_quantmap__8c0_s_p1_0[] = {
  126120. 1, 0, 2,
  126121. };
  126122. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126123. _vq_quantthresh__8c0_s_p1_0,
  126124. _vq_quantmap__8c0_s_p1_0,
  126125. 3,
  126126. 3
  126127. };
  126128. static static_codebook _8c0_s_p1_0 = {
  126129. 8, 6561,
  126130. _vq_lengthlist__8c0_s_p1_0,
  126131. 1, -535822336, 1611661312, 2, 0,
  126132. _vq_quantlist__8c0_s_p1_0,
  126133. NULL,
  126134. &_vq_auxt__8c0_s_p1_0,
  126135. NULL,
  126136. 0
  126137. };
  126138. static long _vq_quantlist__8c0_s_p2_0[] = {
  126139. 2,
  126140. 1,
  126141. 3,
  126142. 0,
  126143. 4,
  126144. };
  126145. static long _vq_lengthlist__8c0_s_p2_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,
  126186. };
  126187. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126188. -1.5, -0.5, 0.5, 1.5,
  126189. };
  126190. static long _vq_quantmap__8c0_s_p2_0[] = {
  126191. 3, 1, 0, 2, 4,
  126192. };
  126193. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126194. _vq_quantthresh__8c0_s_p2_0,
  126195. _vq_quantmap__8c0_s_p2_0,
  126196. 5,
  126197. 5
  126198. };
  126199. static static_codebook _8c0_s_p2_0 = {
  126200. 4, 625,
  126201. _vq_lengthlist__8c0_s_p2_0,
  126202. 1, -533725184, 1611661312, 3, 0,
  126203. _vq_quantlist__8c0_s_p2_0,
  126204. NULL,
  126205. &_vq_auxt__8c0_s_p2_0,
  126206. NULL,
  126207. 0
  126208. };
  126209. static long _vq_quantlist__8c0_s_p3_0[] = {
  126210. 2,
  126211. 1,
  126212. 3,
  126213. 0,
  126214. 4,
  126215. };
  126216. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126217. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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,
  126257. };
  126258. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126259. -1.5, -0.5, 0.5, 1.5,
  126260. };
  126261. static long _vq_quantmap__8c0_s_p3_0[] = {
  126262. 3, 1, 0, 2, 4,
  126263. };
  126264. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126265. _vq_quantthresh__8c0_s_p3_0,
  126266. _vq_quantmap__8c0_s_p3_0,
  126267. 5,
  126268. 5
  126269. };
  126270. static static_codebook _8c0_s_p3_0 = {
  126271. 4, 625,
  126272. _vq_lengthlist__8c0_s_p3_0,
  126273. 1, -533725184, 1611661312, 3, 0,
  126274. _vq_quantlist__8c0_s_p3_0,
  126275. NULL,
  126276. &_vq_auxt__8c0_s_p3_0,
  126277. NULL,
  126278. 0
  126279. };
  126280. static long _vq_quantlist__8c0_s_p4_0[] = {
  126281. 4,
  126282. 3,
  126283. 5,
  126284. 2,
  126285. 6,
  126286. 1,
  126287. 7,
  126288. 0,
  126289. 8,
  126290. };
  126291. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126292. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126293. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126294. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126295. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126296. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126297. 0,
  126298. };
  126299. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126300. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126301. };
  126302. static long _vq_quantmap__8c0_s_p4_0[] = {
  126303. 7, 5, 3, 1, 0, 2, 4, 6,
  126304. 8,
  126305. };
  126306. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126307. _vq_quantthresh__8c0_s_p4_0,
  126308. _vq_quantmap__8c0_s_p4_0,
  126309. 9,
  126310. 9
  126311. };
  126312. static static_codebook _8c0_s_p4_0 = {
  126313. 2, 81,
  126314. _vq_lengthlist__8c0_s_p4_0,
  126315. 1, -531628032, 1611661312, 4, 0,
  126316. _vq_quantlist__8c0_s_p4_0,
  126317. NULL,
  126318. &_vq_auxt__8c0_s_p4_0,
  126319. NULL,
  126320. 0
  126321. };
  126322. static long _vq_quantlist__8c0_s_p5_0[] = {
  126323. 4,
  126324. 3,
  126325. 5,
  126326. 2,
  126327. 6,
  126328. 1,
  126329. 7,
  126330. 0,
  126331. 8,
  126332. };
  126333. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126334. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126335. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126336. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126337. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126338. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126339. 10,
  126340. };
  126341. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126342. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126343. };
  126344. static long _vq_quantmap__8c0_s_p5_0[] = {
  126345. 7, 5, 3, 1, 0, 2, 4, 6,
  126346. 8,
  126347. };
  126348. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126349. _vq_quantthresh__8c0_s_p5_0,
  126350. _vq_quantmap__8c0_s_p5_0,
  126351. 9,
  126352. 9
  126353. };
  126354. static static_codebook _8c0_s_p5_0 = {
  126355. 2, 81,
  126356. _vq_lengthlist__8c0_s_p5_0,
  126357. 1, -531628032, 1611661312, 4, 0,
  126358. _vq_quantlist__8c0_s_p5_0,
  126359. NULL,
  126360. &_vq_auxt__8c0_s_p5_0,
  126361. NULL,
  126362. 0
  126363. };
  126364. static long _vq_quantlist__8c0_s_p6_0[] = {
  126365. 8,
  126366. 7,
  126367. 9,
  126368. 6,
  126369. 10,
  126370. 5,
  126371. 11,
  126372. 4,
  126373. 12,
  126374. 3,
  126375. 13,
  126376. 2,
  126377. 14,
  126378. 1,
  126379. 15,
  126380. 0,
  126381. 16,
  126382. };
  126383. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126384. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126385. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126386. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126387. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126388. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126389. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126390. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126391. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126392. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126393. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126394. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126395. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126396. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126397. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126398. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126399. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126400. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126402. 14,
  126403. };
  126404. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126405. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126406. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126407. };
  126408. static long _vq_quantmap__8c0_s_p6_0[] = {
  126409. 15, 13, 11, 9, 7, 5, 3, 1,
  126410. 0, 2, 4, 6, 8, 10, 12, 14,
  126411. 16,
  126412. };
  126413. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126414. _vq_quantthresh__8c0_s_p6_0,
  126415. _vq_quantmap__8c0_s_p6_0,
  126416. 17,
  126417. 17
  126418. };
  126419. static static_codebook _8c0_s_p6_0 = {
  126420. 2, 289,
  126421. _vq_lengthlist__8c0_s_p6_0,
  126422. 1, -529530880, 1611661312, 5, 0,
  126423. _vq_quantlist__8c0_s_p6_0,
  126424. NULL,
  126425. &_vq_auxt__8c0_s_p6_0,
  126426. NULL,
  126427. 0
  126428. };
  126429. static long _vq_quantlist__8c0_s_p7_0[] = {
  126430. 1,
  126431. 0,
  126432. 2,
  126433. };
  126434. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126435. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126436. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126437. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126438. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126439. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126440. 10,
  126441. };
  126442. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126443. -5.5, 5.5,
  126444. };
  126445. static long _vq_quantmap__8c0_s_p7_0[] = {
  126446. 1, 0, 2,
  126447. };
  126448. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126449. _vq_quantthresh__8c0_s_p7_0,
  126450. _vq_quantmap__8c0_s_p7_0,
  126451. 3,
  126452. 3
  126453. };
  126454. static static_codebook _8c0_s_p7_0 = {
  126455. 4, 81,
  126456. _vq_lengthlist__8c0_s_p7_0,
  126457. 1, -529137664, 1618345984, 2, 0,
  126458. _vq_quantlist__8c0_s_p7_0,
  126459. NULL,
  126460. &_vq_auxt__8c0_s_p7_0,
  126461. NULL,
  126462. 0
  126463. };
  126464. static long _vq_quantlist__8c0_s_p7_1[] = {
  126465. 5,
  126466. 4,
  126467. 6,
  126468. 3,
  126469. 7,
  126470. 2,
  126471. 8,
  126472. 1,
  126473. 9,
  126474. 0,
  126475. 10,
  126476. };
  126477. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126478. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126479. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126480. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126481. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126482. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126483. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126484. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126485. 10,10,10, 9, 9, 9,10,10,10,
  126486. };
  126487. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126488. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126489. 3.5, 4.5,
  126490. };
  126491. static long _vq_quantmap__8c0_s_p7_1[] = {
  126492. 9, 7, 5, 3, 1, 0, 2, 4,
  126493. 6, 8, 10,
  126494. };
  126495. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126496. _vq_quantthresh__8c0_s_p7_1,
  126497. _vq_quantmap__8c0_s_p7_1,
  126498. 11,
  126499. 11
  126500. };
  126501. static static_codebook _8c0_s_p7_1 = {
  126502. 2, 121,
  126503. _vq_lengthlist__8c0_s_p7_1,
  126504. 1, -531365888, 1611661312, 4, 0,
  126505. _vq_quantlist__8c0_s_p7_1,
  126506. NULL,
  126507. &_vq_auxt__8c0_s_p7_1,
  126508. NULL,
  126509. 0
  126510. };
  126511. static long _vq_quantlist__8c0_s_p8_0[] = {
  126512. 6,
  126513. 5,
  126514. 7,
  126515. 4,
  126516. 8,
  126517. 3,
  126518. 9,
  126519. 2,
  126520. 10,
  126521. 1,
  126522. 11,
  126523. 0,
  126524. 12,
  126525. };
  126526. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126527. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126528. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126529. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126530. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126531. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126532. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126533. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126534. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126535. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126536. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126537. 0, 0,13,13,11,13,13,11,12,
  126538. };
  126539. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126540. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126541. 12.5, 17.5, 22.5, 27.5,
  126542. };
  126543. static long _vq_quantmap__8c0_s_p8_0[] = {
  126544. 11, 9, 7, 5, 3, 1, 0, 2,
  126545. 4, 6, 8, 10, 12,
  126546. };
  126547. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126548. _vq_quantthresh__8c0_s_p8_0,
  126549. _vq_quantmap__8c0_s_p8_0,
  126550. 13,
  126551. 13
  126552. };
  126553. static static_codebook _8c0_s_p8_0 = {
  126554. 2, 169,
  126555. _vq_lengthlist__8c0_s_p8_0,
  126556. 1, -526516224, 1616117760, 4, 0,
  126557. _vq_quantlist__8c0_s_p8_0,
  126558. NULL,
  126559. &_vq_auxt__8c0_s_p8_0,
  126560. NULL,
  126561. 0
  126562. };
  126563. static long _vq_quantlist__8c0_s_p8_1[] = {
  126564. 2,
  126565. 1,
  126566. 3,
  126567. 0,
  126568. 4,
  126569. };
  126570. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126571. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126572. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126573. };
  126574. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126575. -1.5, -0.5, 0.5, 1.5,
  126576. };
  126577. static long _vq_quantmap__8c0_s_p8_1[] = {
  126578. 3, 1, 0, 2, 4,
  126579. };
  126580. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126581. _vq_quantthresh__8c0_s_p8_1,
  126582. _vq_quantmap__8c0_s_p8_1,
  126583. 5,
  126584. 5
  126585. };
  126586. static static_codebook _8c0_s_p8_1 = {
  126587. 2, 25,
  126588. _vq_lengthlist__8c0_s_p8_1,
  126589. 1, -533725184, 1611661312, 3, 0,
  126590. _vq_quantlist__8c0_s_p8_1,
  126591. NULL,
  126592. &_vq_auxt__8c0_s_p8_1,
  126593. NULL,
  126594. 0
  126595. };
  126596. static long _vq_quantlist__8c0_s_p9_0[] = {
  126597. 1,
  126598. 0,
  126599. 2,
  126600. };
  126601. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126602. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126603. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126604. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126605. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126606. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126607. 7,
  126608. };
  126609. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126610. -157.5, 157.5,
  126611. };
  126612. static long _vq_quantmap__8c0_s_p9_0[] = {
  126613. 1, 0, 2,
  126614. };
  126615. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126616. _vq_quantthresh__8c0_s_p9_0,
  126617. _vq_quantmap__8c0_s_p9_0,
  126618. 3,
  126619. 3
  126620. };
  126621. static static_codebook _8c0_s_p9_0 = {
  126622. 4, 81,
  126623. _vq_lengthlist__8c0_s_p9_0,
  126624. 1, -518803456, 1628680192, 2, 0,
  126625. _vq_quantlist__8c0_s_p9_0,
  126626. NULL,
  126627. &_vq_auxt__8c0_s_p9_0,
  126628. NULL,
  126629. 0
  126630. };
  126631. static long _vq_quantlist__8c0_s_p9_1[] = {
  126632. 7,
  126633. 6,
  126634. 8,
  126635. 5,
  126636. 9,
  126637. 4,
  126638. 10,
  126639. 3,
  126640. 11,
  126641. 2,
  126642. 12,
  126643. 1,
  126644. 13,
  126645. 0,
  126646. 14,
  126647. };
  126648. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126649. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126650. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126651. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126652. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126653. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126654. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126655. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126656. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126657. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126658. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126659. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126660. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126661. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126662. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126663. 11,
  126664. };
  126665. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126666. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126667. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126668. };
  126669. static long _vq_quantmap__8c0_s_p9_1[] = {
  126670. 13, 11, 9, 7, 5, 3, 1, 0,
  126671. 2, 4, 6, 8, 10, 12, 14,
  126672. };
  126673. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126674. _vq_quantthresh__8c0_s_p9_1,
  126675. _vq_quantmap__8c0_s_p9_1,
  126676. 15,
  126677. 15
  126678. };
  126679. static static_codebook _8c0_s_p9_1 = {
  126680. 2, 225,
  126681. _vq_lengthlist__8c0_s_p9_1,
  126682. 1, -520986624, 1620377600, 4, 0,
  126683. _vq_quantlist__8c0_s_p9_1,
  126684. NULL,
  126685. &_vq_auxt__8c0_s_p9_1,
  126686. NULL,
  126687. 0
  126688. };
  126689. static long _vq_quantlist__8c0_s_p9_2[] = {
  126690. 10,
  126691. 9,
  126692. 11,
  126693. 8,
  126694. 12,
  126695. 7,
  126696. 13,
  126697. 6,
  126698. 14,
  126699. 5,
  126700. 15,
  126701. 4,
  126702. 16,
  126703. 3,
  126704. 17,
  126705. 2,
  126706. 18,
  126707. 1,
  126708. 19,
  126709. 0,
  126710. 20,
  126711. };
  126712. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126713. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126714. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126715. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126716. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126717. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126718. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126719. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126720. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126721. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126722. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126723. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126724. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126725. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126726. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126727. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126728. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126729. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126730. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126731. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126732. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126733. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126734. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126735. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126736. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126737. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126738. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126739. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126740. 10,11, 9,11,10, 9,10, 9,10,
  126741. };
  126742. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126743. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126744. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126745. 6.5, 7.5, 8.5, 9.5,
  126746. };
  126747. static long _vq_quantmap__8c0_s_p9_2[] = {
  126748. 19, 17, 15, 13, 11, 9, 7, 5,
  126749. 3, 1, 0, 2, 4, 6, 8, 10,
  126750. 12, 14, 16, 18, 20,
  126751. };
  126752. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126753. _vq_quantthresh__8c0_s_p9_2,
  126754. _vq_quantmap__8c0_s_p9_2,
  126755. 21,
  126756. 21
  126757. };
  126758. static static_codebook _8c0_s_p9_2 = {
  126759. 2, 441,
  126760. _vq_lengthlist__8c0_s_p9_2,
  126761. 1, -529268736, 1611661312, 5, 0,
  126762. _vq_quantlist__8c0_s_p9_2,
  126763. NULL,
  126764. &_vq_auxt__8c0_s_p9_2,
  126765. NULL,
  126766. 0
  126767. };
  126768. static long _huff_lengthlist__8c0_s_single[] = {
  126769. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126770. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126771. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126772. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126773. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126774. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126775. 17,16,17,17,
  126776. };
  126777. static static_codebook _huff_book__8c0_s_single = {
  126778. 2, 100,
  126779. _huff_lengthlist__8c0_s_single,
  126780. 0, 0, 0, 0, 0,
  126781. NULL,
  126782. NULL,
  126783. NULL,
  126784. NULL,
  126785. 0
  126786. };
  126787. static long _vq_quantlist__8c1_s_p1_0[] = {
  126788. 1,
  126789. 0,
  126790. 2,
  126791. };
  126792. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126793. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126794. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126799. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126804. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126839. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126844. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126849. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126885. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126890. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126895. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0,
  127204. };
  127205. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127206. -0.5, 0.5,
  127207. };
  127208. static long _vq_quantmap__8c1_s_p1_0[] = {
  127209. 1, 0, 2,
  127210. };
  127211. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127212. _vq_quantthresh__8c1_s_p1_0,
  127213. _vq_quantmap__8c1_s_p1_0,
  127214. 3,
  127215. 3
  127216. };
  127217. static static_codebook _8c1_s_p1_0 = {
  127218. 8, 6561,
  127219. _vq_lengthlist__8c1_s_p1_0,
  127220. 1, -535822336, 1611661312, 2, 0,
  127221. _vq_quantlist__8c1_s_p1_0,
  127222. NULL,
  127223. &_vq_auxt__8c1_s_p1_0,
  127224. NULL,
  127225. 0
  127226. };
  127227. static long _vq_quantlist__8c1_s_p2_0[] = {
  127228. 2,
  127229. 1,
  127230. 3,
  127231. 0,
  127232. 4,
  127233. };
  127234. static long _vq_lengthlist__8c1_s_p2_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,
  127275. };
  127276. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127277. -1.5, -0.5, 0.5, 1.5,
  127278. };
  127279. static long _vq_quantmap__8c1_s_p2_0[] = {
  127280. 3, 1, 0, 2, 4,
  127281. };
  127282. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127283. _vq_quantthresh__8c1_s_p2_0,
  127284. _vq_quantmap__8c1_s_p2_0,
  127285. 5,
  127286. 5
  127287. };
  127288. static static_codebook _8c1_s_p2_0 = {
  127289. 4, 625,
  127290. _vq_lengthlist__8c1_s_p2_0,
  127291. 1, -533725184, 1611661312, 3, 0,
  127292. _vq_quantlist__8c1_s_p2_0,
  127293. NULL,
  127294. &_vq_auxt__8c1_s_p2_0,
  127295. NULL,
  127296. 0
  127297. };
  127298. static long _vq_quantlist__8c1_s_p3_0[] = {
  127299. 2,
  127300. 1,
  127301. 3,
  127302. 0,
  127303. 4,
  127304. };
  127305. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127306. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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,
  127346. };
  127347. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127348. -1.5, -0.5, 0.5, 1.5,
  127349. };
  127350. static long _vq_quantmap__8c1_s_p3_0[] = {
  127351. 3, 1, 0, 2, 4,
  127352. };
  127353. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127354. _vq_quantthresh__8c1_s_p3_0,
  127355. _vq_quantmap__8c1_s_p3_0,
  127356. 5,
  127357. 5
  127358. };
  127359. static static_codebook _8c1_s_p3_0 = {
  127360. 4, 625,
  127361. _vq_lengthlist__8c1_s_p3_0,
  127362. 1, -533725184, 1611661312, 3, 0,
  127363. _vq_quantlist__8c1_s_p3_0,
  127364. NULL,
  127365. &_vq_auxt__8c1_s_p3_0,
  127366. NULL,
  127367. 0
  127368. };
  127369. static long _vq_quantlist__8c1_s_p4_0[] = {
  127370. 4,
  127371. 3,
  127372. 5,
  127373. 2,
  127374. 6,
  127375. 1,
  127376. 7,
  127377. 0,
  127378. 8,
  127379. };
  127380. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127381. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127382. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127383. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127384. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127385. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127386. 0,
  127387. };
  127388. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127389. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127390. };
  127391. static long _vq_quantmap__8c1_s_p4_0[] = {
  127392. 7, 5, 3, 1, 0, 2, 4, 6,
  127393. 8,
  127394. };
  127395. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127396. _vq_quantthresh__8c1_s_p4_0,
  127397. _vq_quantmap__8c1_s_p4_0,
  127398. 9,
  127399. 9
  127400. };
  127401. static static_codebook _8c1_s_p4_0 = {
  127402. 2, 81,
  127403. _vq_lengthlist__8c1_s_p4_0,
  127404. 1, -531628032, 1611661312, 4, 0,
  127405. _vq_quantlist__8c1_s_p4_0,
  127406. NULL,
  127407. &_vq_auxt__8c1_s_p4_0,
  127408. NULL,
  127409. 0
  127410. };
  127411. static long _vq_quantlist__8c1_s_p5_0[] = {
  127412. 4,
  127413. 3,
  127414. 5,
  127415. 2,
  127416. 6,
  127417. 1,
  127418. 7,
  127419. 0,
  127420. 8,
  127421. };
  127422. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127423. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127424. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127425. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127426. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127427. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127428. 10,
  127429. };
  127430. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127431. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127432. };
  127433. static long _vq_quantmap__8c1_s_p5_0[] = {
  127434. 7, 5, 3, 1, 0, 2, 4, 6,
  127435. 8,
  127436. };
  127437. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127438. _vq_quantthresh__8c1_s_p5_0,
  127439. _vq_quantmap__8c1_s_p5_0,
  127440. 9,
  127441. 9
  127442. };
  127443. static static_codebook _8c1_s_p5_0 = {
  127444. 2, 81,
  127445. _vq_lengthlist__8c1_s_p5_0,
  127446. 1, -531628032, 1611661312, 4, 0,
  127447. _vq_quantlist__8c1_s_p5_0,
  127448. NULL,
  127449. &_vq_auxt__8c1_s_p5_0,
  127450. NULL,
  127451. 0
  127452. };
  127453. static long _vq_quantlist__8c1_s_p6_0[] = {
  127454. 8,
  127455. 7,
  127456. 9,
  127457. 6,
  127458. 10,
  127459. 5,
  127460. 11,
  127461. 4,
  127462. 12,
  127463. 3,
  127464. 13,
  127465. 2,
  127466. 14,
  127467. 1,
  127468. 15,
  127469. 0,
  127470. 16,
  127471. };
  127472. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127473. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127474. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127475. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127476. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127477. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127478. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127479. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127480. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127481. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127482. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127483. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127484. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127485. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127486. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127487. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127488. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127489. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127491. 14,
  127492. };
  127493. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127494. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127495. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127496. };
  127497. static long _vq_quantmap__8c1_s_p6_0[] = {
  127498. 15, 13, 11, 9, 7, 5, 3, 1,
  127499. 0, 2, 4, 6, 8, 10, 12, 14,
  127500. 16,
  127501. };
  127502. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127503. _vq_quantthresh__8c1_s_p6_0,
  127504. _vq_quantmap__8c1_s_p6_0,
  127505. 17,
  127506. 17
  127507. };
  127508. static static_codebook _8c1_s_p6_0 = {
  127509. 2, 289,
  127510. _vq_lengthlist__8c1_s_p6_0,
  127511. 1, -529530880, 1611661312, 5, 0,
  127512. _vq_quantlist__8c1_s_p6_0,
  127513. NULL,
  127514. &_vq_auxt__8c1_s_p6_0,
  127515. NULL,
  127516. 0
  127517. };
  127518. static long _vq_quantlist__8c1_s_p7_0[] = {
  127519. 1,
  127520. 0,
  127521. 2,
  127522. };
  127523. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127524. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127525. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127526. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127527. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127528. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127529. 9,
  127530. };
  127531. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127532. -5.5, 5.5,
  127533. };
  127534. static long _vq_quantmap__8c1_s_p7_0[] = {
  127535. 1, 0, 2,
  127536. };
  127537. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127538. _vq_quantthresh__8c1_s_p7_0,
  127539. _vq_quantmap__8c1_s_p7_0,
  127540. 3,
  127541. 3
  127542. };
  127543. static static_codebook _8c1_s_p7_0 = {
  127544. 4, 81,
  127545. _vq_lengthlist__8c1_s_p7_0,
  127546. 1, -529137664, 1618345984, 2, 0,
  127547. _vq_quantlist__8c1_s_p7_0,
  127548. NULL,
  127549. &_vq_auxt__8c1_s_p7_0,
  127550. NULL,
  127551. 0
  127552. };
  127553. static long _vq_quantlist__8c1_s_p7_1[] = {
  127554. 5,
  127555. 4,
  127556. 6,
  127557. 3,
  127558. 7,
  127559. 2,
  127560. 8,
  127561. 1,
  127562. 9,
  127563. 0,
  127564. 10,
  127565. };
  127566. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127567. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127568. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127569. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127570. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127571. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127572. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127573. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127574. 10,10,10, 8, 8, 8, 8, 8, 8,
  127575. };
  127576. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127577. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127578. 3.5, 4.5,
  127579. };
  127580. static long _vq_quantmap__8c1_s_p7_1[] = {
  127581. 9, 7, 5, 3, 1, 0, 2, 4,
  127582. 6, 8, 10,
  127583. };
  127584. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127585. _vq_quantthresh__8c1_s_p7_1,
  127586. _vq_quantmap__8c1_s_p7_1,
  127587. 11,
  127588. 11
  127589. };
  127590. static static_codebook _8c1_s_p7_1 = {
  127591. 2, 121,
  127592. _vq_lengthlist__8c1_s_p7_1,
  127593. 1, -531365888, 1611661312, 4, 0,
  127594. _vq_quantlist__8c1_s_p7_1,
  127595. NULL,
  127596. &_vq_auxt__8c1_s_p7_1,
  127597. NULL,
  127598. 0
  127599. };
  127600. static long _vq_quantlist__8c1_s_p8_0[] = {
  127601. 6,
  127602. 5,
  127603. 7,
  127604. 4,
  127605. 8,
  127606. 3,
  127607. 9,
  127608. 2,
  127609. 10,
  127610. 1,
  127611. 11,
  127612. 0,
  127613. 12,
  127614. };
  127615. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127616. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127617. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127618. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127619. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127620. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127621. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127622. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127623. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127624. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127625. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127626. 0,12,12,11,10,12,11,13,12,
  127627. };
  127628. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127629. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127630. 12.5, 17.5, 22.5, 27.5,
  127631. };
  127632. static long _vq_quantmap__8c1_s_p8_0[] = {
  127633. 11, 9, 7, 5, 3, 1, 0, 2,
  127634. 4, 6, 8, 10, 12,
  127635. };
  127636. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127637. _vq_quantthresh__8c1_s_p8_0,
  127638. _vq_quantmap__8c1_s_p8_0,
  127639. 13,
  127640. 13
  127641. };
  127642. static static_codebook _8c1_s_p8_0 = {
  127643. 2, 169,
  127644. _vq_lengthlist__8c1_s_p8_0,
  127645. 1, -526516224, 1616117760, 4, 0,
  127646. _vq_quantlist__8c1_s_p8_0,
  127647. NULL,
  127648. &_vq_auxt__8c1_s_p8_0,
  127649. NULL,
  127650. 0
  127651. };
  127652. static long _vq_quantlist__8c1_s_p8_1[] = {
  127653. 2,
  127654. 1,
  127655. 3,
  127656. 0,
  127657. 4,
  127658. };
  127659. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127660. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127661. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127662. };
  127663. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127664. -1.5, -0.5, 0.5, 1.5,
  127665. };
  127666. static long _vq_quantmap__8c1_s_p8_1[] = {
  127667. 3, 1, 0, 2, 4,
  127668. };
  127669. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127670. _vq_quantthresh__8c1_s_p8_1,
  127671. _vq_quantmap__8c1_s_p8_1,
  127672. 5,
  127673. 5
  127674. };
  127675. static static_codebook _8c1_s_p8_1 = {
  127676. 2, 25,
  127677. _vq_lengthlist__8c1_s_p8_1,
  127678. 1, -533725184, 1611661312, 3, 0,
  127679. _vq_quantlist__8c1_s_p8_1,
  127680. NULL,
  127681. &_vq_auxt__8c1_s_p8_1,
  127682. NULL,
  127683. 0
  127684. };
  127685. static long _vq_quantlist__8c1_s_p9_0[] = {
  127686. 6,
  127687. 5,
  127688. 7,
  127689. 4,
  127690. 8,
  127691. 3,
  127692. 9,
  127693. 2,
  127694. 10,
  127695. 1,
  127696. 11,
  127697. 0,
  127698. 12,
  127699. };
  127700. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127701. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127702. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127703. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127704. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127705. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127706. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127707. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127708. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127709. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127710. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127711. 10,10,10,10,10, 9, 9, 9, 9,
  127712. };
  127713. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127714. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127715. 787.5, 1102.5, 1417.5, 1732.5,
  127716. };
  127717. static long _vq_quantmap__8c1_s_p9_0[] = {
  127718. 11, 9, 7, 5, 3, 1, 0, 2,
  127719. 4, 6, 8, 10, 12,
  127720. };
  127721. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127722. _vq_quantthresh__8c1_s_p9_0,
  127723. _vq_quantmap__8c1_s_p9_0,
  127724. 13,
  127725. 13
  127726. };
  127727. static static_codebook _8c1_s_p9_0 = {
  127728. 2, 169,
  127729. _vq_lengthlist__8c1_s_p9_0,
  127730. 1, -513964032, 1628680192, 4, 0,
  127731. _vq_quantlist__8c1_s_p9_0,
  127732. NULL,
  127733. &_vq_auxt__8c1_s_p9_0,
  127734. NULL,
  127735. 0
  127736. };
  127737. static long _vq_quantlist__8c1_s_p9_1[] = {
  127738. 7,
  127739. 6,
  127740. 8,
  127741. 5,
  127742. 9,
  127743. 4,
  127744. 10,
  127745. 3,
  127746. 11,
  127747. 2,
  127748. 12,
  127749. 1,
  127750. 13,
  127751. 0,
  127752. 14,
  127753. };
  127754. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127755. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127756. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127757. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127758. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127759. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127760. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127761. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127762. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127763. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127764. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127765. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127766. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127767. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127768. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127769. 15,
  127770. };
  127771. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127772. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127773. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127774. };
  127775. static long _vq_quantmap__8c1_s_p9_1[] = {
  127776. 13, 11, 9, 7, 5, 3, 1, 0,
  127777. 2, 4, 6, 8, 10, 12, 14,
  127778. };
  127779. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127780. _vq_quantthresh__8c1_s_p9_1,
  127781. _vq_quantmap__8c1_s_p9_1,
  127782. 15,
  127783. 15
  127784. };
  127785. static static_codebook _8c1_s_p9_1 = {
  127786. 2, 225,
  127787. _vq_lengthlist__8c1_s_p9_1,
  127788. 1, -520986624, 1620377600, 4, 0,
  127789. _vq_quantlist__8c1_s_p9_1,
  127790. NULL,
  127791. &_vq_auxt__8c1_s_p9_1,
  127792. NULL,
  127793. 0
  127794. };
  127795. static long _vq_quantlist__8c1_s_p9_2[] = {
  127796. 10,
  127797. 9,
  127798. 11,
  127799. 8,
  127800. 12,
  127801. 7,
  127802. 13,
  127803. 6,
  127804. 14,
  127805. 5,
  127806. 15,
  127807. 4,
  127808. 16,
  127809. 3,
  127810. 17,
  127811. 2,
  127812. 18,
  127813. 1,
  127814. 19,
  127815. 0,
  127816. 20,
  127817. };
  127818. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127819. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127820. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127821. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127822. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127823. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127824. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127825. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127826. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127827. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127828. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127829. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127830. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127831. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127832. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127833. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127834. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127835. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127836. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127837. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127838. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127839. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127840. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127841. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127842. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127843. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127844. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127845. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127846. 10,10,10,10,10,10,10,10,10,
  127847. };
  127848. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127849. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127850. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127851. 6.5, 7.5, 8.5, 9.5,
  127852. };
  127853. static long _vq_quantmap__8c1_s_p9_2[] = {
  127854. 19, 17, 15, 13, 11, 9, 7, 5,
  127855. 3, 1, 0, 2, 4, 6, 8, 10,
  127856. 12, 14, 16, 18, 20,
  127857. };
  127858. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127859. _vq_quantthresh__8c1_s_p9_2,
  127860. _vq_quantmap__8c1_s_p9_2,
  127861. 21,
  127862. 21
  127863. };
  127864. static static_codebook _8c1_s_p9_2 = {
  127865. 2, 441,
  127866. _vq_lengthlist__8c1_s_p9_2,
  127867. 1, -529268736, 1611661312, 5, 0,
  127868. _vq_quantlist__8c1_s_p9_2,
  127869. NULL,
  127870. &_vq_auxt__8c1_s_p9_2,
  127871. NULL,
  127872. 0
  127873. };
  127874. static long _huff_lengthlist__8c1_s_single[] = {
  127875. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127876. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127877. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127878. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127879. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127880. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127881. 9, 7, 7, 8,
  127882. };
  127883. static static_codebook _huff_book__8c1_s_single = {
  127884. 2, 100,
  127885. _huff_lengthlist__8c1_s_single,
  127886. 0, 0, 0, 0, 0,
  127887. NULL,
  127888. NULL,
  127889. NULL,
  127890. NULL,
  127891. 0
  127892. };
  127893. static long _huff_lengthlist__44c2_s_long[] = {
  127894. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127895. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127896. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127897. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127898. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127899. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127900. 10, 8, 8, 9,
  127901. };
  127902. static static_codebook _huff_book__44c2_s_long = {
  127903. 2, 100,
  127904. _huff_lengthlist__44c2_s_long,
  127905. 0, 0, 0, 0, 0,
  127906. NULL,
  127907. NULL,
  127908. NULL,
  127909. NULL,
  127910. 0
  127911. };
  127912. static long _vq_quantlist__44c2_s_p1_0[] = {
  127913. 1,
  127914. 0,
  127915. 2,
  127916. };
  127917. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127918. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127919. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127923. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127924. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127929. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127964. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127969. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127974. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128010. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128015. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128020. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0,
  128329. };
  128330. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128331. -0.5, 0.5,
  128332. };
  128333. static long _vq_quantmap__44c2_s_p1_0[] = {
  128334. 1, 0, 2,
  128335. };
  128336. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128337. _vq_quantthresh__44c2_s_p1_0,
  128338. _vq_quantmap__44c2_s_p1_0,
  128339. 3,
  128340. 3
  128341. };
  128342. static static_codebook _44c2_s_p1_0 = {
  128343. 8, 6561,
  128344. _vq_lengthlist__44c2_s_p1_0,
  128345. 1, -535822336, 1611661312, 2, 0,
  128346. _vq_quantlist__44c2_s_p1_0,
  128347. NULL,
  128348. &_vq_auxt__44c2_s_p1_0,
  128349. NULL,
  128350. 0
  128351. };
  128352. static long _vq_quantlist__44c2_s_p2_0[] = {
  128353. 2,
  128354. 1,
  128355. 3,
  128356. 0,
  128357. 4,
  128358. };
  128359. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128360. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128361. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128362. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128363. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128364. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128370. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128371. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128372. 12, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128378. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128379. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128386. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128387. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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,
  128400. };
  128401. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128402. -1.5, -0.5, 0.5, 1.5,
  128403. };
  128404. static long _vq_quantmap__44c2_s_p2_0[] = {
  128405. 3, 1, 0, 2, 4,
  128406. };
  128407. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128408. _vq_quantthresh__44c2_s_p2_0,
  128409. _vq_quantmap__44c2_s_p2_0,
  128410. 5,
  128411. 5
  128412. };
  128413. static static_codebook _44c2_s_p2_0 = {
  128414. 4, 625,
  128415. _vq_lengthlist__44c2_s_p2_0,
  128416. 1, -533725184, 1611661312, 3, 0,
  128417. _vq_quantlist__44c2_s_p2_0,
  128418. NULL,
  128419. &_vq_auxt__44c2_s_p2_0,
  128420. NULL,
  128421. 0
  128422. };
  128423. static long _vq_quantlist__44c2_s_p3_0[] = {
  128424. 2,
  128425. 1,
  128426. 3,
  128427. 0,
  128428. 4,
  128429. };
  128430. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128431. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  128471. };
  128472. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128473. -1.5, -0.5, 0.5, 1.5,
  128474. };
  128475. static long _vq_quantmap__44c2_s_p3_0[] = {
  128476. 3, 1, 0, 2, 4,
  128477. };
  128478. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128479. _vq_quantthresh__44c2_s_p3_0,
  128480. _vq_quantmap__44c2_s_p3_0,
  128481. 5,
  128482. 5
  128483. };
  128484. static static_codebook _44c2_s_p3_0 = {
  128485. 4, 625,
  128486. _vq_lengthlist__44c2_s_p3_0,
  128487. 1, -533725184, 1611661312, 3, 0,
  128488. _vq_quantlist__44c2_s_p3_0,
  128489. NULL,
  128490. &_vq_auxt__44c2_s_p3_0,
  128491. NULL,
  128492. 0
  128493. };
  128494. static long _vq_quantlist__44c2_s_p4_0[] = {
  128495. 4,
  128496. 3,
  128497. 5,
  128498. 2,
  128499. 6,
  128500. 1,
  128501. 7,
  128502. 0,
  128503. 8,
  128504. };
  128505. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128506. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128507. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128508. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128509. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128510. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128511. 0,
  128512. };
  128513. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128514. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128515. };
  128516. static long _vq_quantmap__44c2_s_p4_0[] = {
  128517. 7, 5, 3, 1, 0, 2, 4, 6,
  128518. 8,
  128519. };
  128520. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128521. _vq_quantthresh__44c2_s_p4_0,
  128522. _vq_quantmap__44c2_s_p4_0,
  128523. 9,
  128524. 9
  128525. };
  128526. static static_codebook _44c2_s_p4_0 = {
  128527. 2, 81,
  128528. _vq_lengthlist__44c2_s_p4_0,
  128529. 1, -531628032, 1611661312, 4, 0,
  128530. _vq_quantlist__44c2_s_p4_0,
  128531. NULL,
  128532. &_vq_auxt__44c2_s_p4_0,
  128533. NULL,
  128534. 0
  128535. };
  128536. static long _vq_quantlist__44c2_s_p5_0[] = {
  128537. 4,
  128538. 3,
  128539. 5,
  128540. 2,
  128541. 6,
  128542. 1,
  128543. 7,
  128544. 0,
  128545. 8,
  128546. };
  128547. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128548. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128549. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128550. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128551. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128552. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128553. 11,
  128554. };
  128555. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128556. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128557. };
  128558. static long _vq_quantmap__44c2_s_p5_0[] = {
  128559. 7, 5, 3, 1, 0, 2, 4, 6,
  128560. 8,
  128561. };
  128562. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128563. _vq_quantthresh__44c2_s_p5_0,
  128564. _vq_quantmap__44c2_s_p5_0,
  128565. 9,
  128566. 9
  128567. };
  128568. static static_codebook _44c2_s_p5_0 = {
  128569. 2, 81,
  128570. _vq_lengthlist__44c2_s_p5_0,
  128571. 1, -531628032, 1611661312, 4, 0,
  128572. _vq_quantlist__44c2_s_p5_0,
  128573. NULL,
  128574. &_vq_auxt__44c2_s_p5_0,
  128575. NULL,
  128576. 0
  128577. };
  128578. static long _vq_quantlist__44c2_s_p6_0[] = {
  128579. 8,
  128580. 7,
  128581. 9,
  128582. 6,
  128583. 10,
  128584. 5,
  128585. 11,
  128586. 4,
  128587. 12,
  128588. 3,
  128589. 13,
  128590. 2,
  128591. 14,
  128592. 1,
  128593. 15,
  128594. 0,
  128595. 16,
  128596. };
  128597. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128598. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128599. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128600. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128601. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128602. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128603. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128604. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128605. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128606. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128607. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128608. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128609. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128610. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128611. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128612. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128613. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128614. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128616. 14,
  128617. };
  128618. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128619. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128620. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128621. };
  128622. static long _vq_quantmap__44c2_s_p6_0[] = {
  128623. 15, 13, 11, 9, 7, 5, 3, 1,
  128624. 0, 2, 4, 6, 8, 10, 12, 14,
  128625. 16,
  128626. };
  128627. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128628. _vq_quantthresh__44c2_s_p6_0,
  128629. _vq_quantmap__44c2_s_p6_0,
  128630. 17,
  128631. 17
  128632. };
  128633. static static_codebook _44c2_s_p6_0 = {
  128634. 2, 289,
  128635. _vq_lengthlist__44c2_s_p6_0,
  128636. 1, -529530880, 1611661312, 5, 0,
  128637. _vq_quantlist__44c2_s_p6_0,
  128638. NULL,
  128639. &_vq_auxt__44c2_s_p6_0,
  128640. NULL,
  128641. 0
  128642. };
  128643. static long _vq_quantlist__44c2_s_p7_0[] = {
  128644. 1,
  128645. 0,
  128646. 2,
  128647. };
  128648. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128649. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128650. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128651. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128652. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128653. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128654. 11,
  128655. };
  128656. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128657. -5.5, 5.5,
  128658. };
  128659. static long _vq_quantmap__44c2_s_p7_0[] = {
  128660. 1, 0, 2,
  128661. };
  128662. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128663. _vq_quantthresh__44c2_s_p7_0,
  128664. _vq_quantmap__44c2_s_p7_0,
  128665. 3,
  128666. 3
  128667. };
  128668. static static_codebook _44c2_s_p7_0 = {
  128669. 4, 81,
  128670. _vq_lengthlist__44c2_s_p7_0,
  128671. 1, -529137664, 1618345984, 2, 0,
  128672. _vq_quantlist__44c2_s_p7_0,
  128673. NULL,
  128674. &_vq_auxt__44c2_s_p7_0,
  128675. NULL,
  128676. 0
  128677. };
  128678. static long _vq_quantlist__44c2_s_p7_1[] = {
  128679. 5,
  128680. 4,
  128681. 6,
  128682. 3,
  128683. 7,
  128684. 2,
  128685. 8,
  128686. 1,
  128687. 9,
  128688. 0,
  128689. 10,
  128690. };
  128691. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128692. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128693. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128694. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128695. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128696. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128697. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128698. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128699. 10,10,10, 8, 8, 8, 8, 8, 8,
  128700. };
  128701. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128702. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128703. 3.5, 4.5,
  128704. };
  128705. static long _vq_quantmap__44c2_s_p7_1[] = {
  128706. 9, 7, 5, 3, 1, 0, 2, 4,
  128707. 6, 8, 10,
  128708. };
  128709. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128710. _vq_quantthresh__44c2_s_p7_1,
  128711. _vq_quantmap__44c2_s_p7_1,
  128712. 11,
  128713. 11
  128714. };
  128715. static static_codebook _44c2_s_p7_1 = {
  128716. 2, 121,
  128717. _vq_lengthlist__44c2_s_p7_1,
  128718. 1, -531365888, 1611661312, 4, 0,
  128719. _vq_quantlist__44c2_s_p7_1,
  128720. NULL,
  128721. &_vq_auxt__44c2_s_p7_1,
  128722. NULL,
  128723. 0
  128724. };
  128725. static long _vq_quantlist__44c2_s_p8_0[] = {
  128726. 6,
  128727. 5,
  128728. 7,
  128729. 4,
  128730. 8,
  128731. 3,
  128732. 9,
  128733. 2,
  128734. 10,
  128735. 1,
  128736. 11,
  128737. 0,
  128738. 12,
  128739. };
  128740. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128741. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128742. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128743. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128744. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128745. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128746. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128747. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128748. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128749. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128750. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128751. 0,12,12,12,12,13,12,14,14,
  128752. };
  128753. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128754. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128755. 12.5, 17.5, 22.5, 27.5,
  128756. };
  128757. static long _vq_quantmap__44c2_s_p8_0[] = {
  128758. 11, 9, 7, 5, 3, 1, 0, 2,
  128759. 4, 6, 8, 10, 12,
  128760. };
  128761. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128762. _vq_quantthresh__44c2_s_p8_0,
  128763. _vq_quantmap__44c2_s_p8_0,
  128764. 13,
  128765. 13
  128766. };
  128767. static static_codebook _44c2_s_p8_0 = {
  128768. 2, 169,
  128769. _vq_lengthlist__44c2_s_p8_0,
  128770. 1, -526516224, 1616117760, 4, 0,
  128771. _vq_quantlist__44c2_s_p8_0,
  128772. NULL,
  128773. &_vq_auxt__44c2_s_p8_0,
  128774. NULL,
  128775. 0
  128776. };
  128777. static long _vq_quantlist__44c2_s_p8_1[] = {
  128778. 2,
  128779. 1,
  128780. 3,
  128781. 0,
  128782. 4,
  128783. };
  128784. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128785. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128786. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128787. };
  128788. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128789. -1.5, -0.5, 0.5, 1.5,
  128790. };
  128791. static long _vq_quantmap__44c2_s_p8_1[] = {
  128792. 3, 1, 0, 2, 4,
  128793. };
  128794. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128795. _vq_quantthresh__44c2_s_p8_1,
  128796. _vq_quantmap__44c2_s_p8_1,
  128797. 5,
  128798. 5
  128799. };
  128800. static static_codebook _44c2_s_p8_1 = {
  128801. 2, 25,
  128802. _vq_lengthlist__44c2_s_p8_1,
  128803. 1, -533725184, 1611661312, 3, 0,
  128804. _vq_quantlist__44c2_s_p8_1,
  128805. NULL,
  128806. &_vq_auxt__44c2_s_p8_1,
  128807. NULL,
  128808. 0
  128809. };
  128810. static long _vq_quantlist__44c2_s_p9_0[] = {
  128811. 6,
  128812. 5,
  128813. 7,
  128814. 4,
  128815. 8,
  128816. 3,
  128817. 9,
  128818. 2,
  128819. 10,
  128820. 1,
  128821. 11,
  128822. 0,
  128823. 12,
  128824. };
  128825. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128826. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128827. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128828. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128829. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128830. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128831. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128832. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128833. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128834. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128835. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128836. 11,11,11,11,11,11,11,11,11,
  128837. };
  128838. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128839. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128840. 552.5, 773.5, 994.5, 1215.5,
  128841. };
  128842. static long _vq_quantmap__44c2_s_p9_0[] = {
  128843. 11, 9, 7, 5, 3, 1, 0, 2,
  128844. 4, 6, 8, 10, 12,
  128845. };
  128846. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128847. _vq_quantthresh__44c2_s_p9_0,
  128848. _vq_quantmap__44c2_s_p9_0,
  128849. 13,
  128850. 13
  128851. };
  128852. static static_codebook _44c2_s_p9_0 = {
  128853. 2, 169,
  128854. _vq_lengthlist__44c2_s_p9_0,
  128855. 1, -514541568, 1627103232, 4, 0,
  128856. _vq_quantlist__44c2_s_p9_0,
  128857. NULL,
  128858. &_vq_auxt__44c2_s_p9_0,
  128859. NULL,
  128860. 0
  128861. };
  128862. static long _vq_quantlist__44c2_s_p9_1[] = {
  128863. 6,
  128864. 5,
  128865. 7,
  128866. 4,
  128867. 8,
  128868. 3,
  128869. 9,
  128870. 2,
  128871. 10,
  128872. 1,
  128873. 11,
  128874. 0,
  128875. 12,
  128876. };
  128877. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128878. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128879. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128880. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128881. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128882. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128883. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128884. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128885. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128886. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128887. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128888. 17,13,12,12,10,13,11,14,14,
  128889. };
  128890. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128891. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128892. 42.5, 59.5, 76.5, 93.5,
  128893. };
  128894. static long _vq_quantmap__44c2_s_p9_1[] = {
  128895. 11, 9, 7, 5, 3, 1, 0, 2,
  128896. 4, 6, 8, 10, 12,
  128897. };
  128898. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128899. _vq_quantthresh__44c2_s_p9_1,
  128900. _vq_quantmap__44c2_s_p9_1,
  128901. 13,
  128902. 13
  128903. };
  128904. static static_codebook _44c2_s_p9_1 = {
  128905. 2, 169,
  128906. _vq_lengthlist__44c2_s_p9_1,
  128907. 1, -522616832, 1620115456, 4, 0,
  128908. _vq_quantlist__44c2_s_p9_1,
  128909. NULL,
  128910. &_vq_auxt__44c2_s_p9_1,
  128911. NULL,
  128912. 0
  128913. };
  128914. static long _vq_quantlist__44c2_s_p9_2[] = {
  128915. 8,
  128916. 7,
  128917. 9,
  128918. 6,
  128919. 10,
  128920. 5,
  128921. 11,
  128922. 4,
  128923. 12,
  128924. 3,
  128925. 13,
  128926. 2,
  128927. 14,
  128928. 1,
  128929. 15,
  128930. 0,
  128931. 16,
  128932. };
  128933. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128934. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128935. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128936. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128937. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128938. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128939. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128940. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128941. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128942. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128943. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128944. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128945. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128946. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128947. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128948. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128949. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128950. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128951. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128952. 10,
  128953. };
  128954. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128955. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128956. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128957. };
  128958. static long _vq_quantmap__44c2_s_p9_2[] = {
  128959. 15, 13, 11, 9, 7, 5, 3, 1,
  128960. 0, 2, 4, 6, 8, 10, 12, 14,
  128961. 16,
  128962. };
  128963. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128964. _vq_quantthresh__44c2_s_p9_2,
  128965. _vq_quantmap__44c2_s_p9_2,
  128966. 17,
  128967. 17
  128968. };
  128969. static static_codebook _44c2_s_p9_2 = {
  128970. 2, 289,
  128971. _vq_lengthlist__44c2_s_p9_2,
  128972. 1, -529530880, 1611661312, 5, 0,
  128973. _vq_quantlist__44c2_s_p9_2,
  128974. NULL,
  128975. &_vq_auxt__44c2_s_p9_2,
  128976. NULL,
  128977. 0
  128978. };
  128979. static long _huff_lengthlist__44c2_s_short[] = {
  128980. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128981. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128982. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128983. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128984. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128985. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128986. 6, 8, 9,12,
  128987. };
  128988. static static_codebook _huff_book__44c2_s_short = {
  128989. 2, 100,
  128990. _huff_lengthlist__44c2_s_short,
  128991. 0, 0, 0, 0, 0,
  128992. NULL,
  128993. NULL,
  128994. NULL,
  128995. NULL,
  128996. 0
  128997. };
  128998. static long _huff_lengthlist__44c3_s_long[] = {
  128999. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129000. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129001. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129002. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129003. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129004. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129005. 9, 8, 8, 8,
  129006. };
  129007. static static_codebook _huff_book__44c3_s_long = {
  129008. 2, 100,
  129009. _huff_lengthlist__44c3_s_long,
  129010. 0, 0, 0, 0, 0,
  129011. NULL,
  129012. NULL,
  129013. NULL,
  129014. NULL,
  129015. 0
  129016. };
  129017. static long _vq_quantlist__44c3_s_p1_0[] = {
  129018. 1,
  129019. 0,
  129020. 2,
  129021. };
  129022. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129023. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129024. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129028. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129029. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129033. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129034. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129069. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129074. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129079. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129115. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129120. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129125. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0,
  129434. };
  129435. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129436. -0.5, 0.5,
  129437. };
  129438. static long _vq_quantmap__44c3_s_p1_0[] = {
  129439. 1, 0, 2,
  129440. };
  129441. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129442. _vq_quantthresh__44c3_s_p1_0,
  129443. _vq_quantmap__44c3_s_p1_0,
  129444. 3,
  129445. 3
  129446. };
  129447. static static_codebook _44c3_s_p1_0 = {
  129448. 8, 6561,
  129449. _vq_lengthlist__44c3_s_p1_0,
  129450. 1, -535822336, 1611661312, 2, 0,
  129451. _vq_quantlist__44c3_s_p1_0,
  129452. NULL,
  129453. &_vq_auxt__44c3_s_p1_0,
  129454. NULL,
  129455. 0
  129456. };
  129457. static long _vq_quantlist__44c3_s_p2_0[] = {
  129458. 2,
  129459. 1,
  129460. 3,
  129461. 0,
  129462. 4,
  129463. };
  129464. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129465. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129466. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129467. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129468. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129469. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129475. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129476. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129477. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129483. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129484. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129491. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129492. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  129505. };
  129506. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129507. -1.5, -0.5, 0.5, 1.5,
  129508. };
  129509. static long _vq_quantmap__44c3_s_p2_0[] = {
  129510. 3, 1, 0, 2, 4,
  129511. };
  129512. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129513. _vq_quantthresh__44c3_s_p2_0,
  129514. _vq_quantmap__44c3_s_p2_0,
  129515. 5,
  129516. 5
  129517. };
  129518. static static_codebook _44c3_s_p2_0 = {
  129519. 4, 625,
  129520. _vq_lengthlist__44c3_s_p2_0,
  129521. 1, -533725184, 1611661312, 3, 0,
  129522. _vq_quantlist__44c3_s_p2_0,
  129523. NULL,
  129524. &_vq_auxt__44c3_s_p2_0,
  129525. NULL,
  129526. 0
  129527. };
  129528. static long _vq_quantlist__44c3_s_p3_0[] = {
  129529. 2,
  129530. 1,
  129531. 3,
  129532. 0,
  129533. 4,
  129534. };
  129535. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129536. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  129576. };
  129577. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129578. -1.5, -0.5, 0.5, 1.5,
  129579. };
  129580. static long _vq_quantmap__44c3_s_p3_0[] = {
  129581. 3, 1, 0, 2, 4,
  129582. };
  129583. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129584. _vq_quantthresh__44c3_s_p3_0,
  129585. _vq_quantmap__44c3_s_p3_0,
  129586. 5,
  129587. 5
  129588. };
  129589. static static_codebook _44c3_s_p3_0 = {
  129590. 4, 625,
  129591. _vq_lengthlist__44c3_s_p3_0,
  129592. 1, -533725184, 1611661312, 3, 0,
  129593. _vq_quantlist__44c3_s_p3_0,
  129594. NULL,
  129595. &_vq_auxt__44c3_s_p3_0,
  129596. NULL,
  129597. 0
  129598. };
  129599. static long _vq_quantlist__44c3_s_p4_0[] = {
  129600. 4,
  129601. 3,
  129602. 5,
  129603. 2,
  129604. 6,
  129605. 1,
  129606. 7,
  129607. 0,
  129608. 8,
  129609. };
  129610. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129611. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129612. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129613. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129614. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129615. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129616. 0,
  129617. };
  129618. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129619. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129620. };
  129621. static long _vq_quantmap__44c3_s_p4_0[] = {
  129622. 7, 5, 3, 1, 0, 2, 4, 6,
  129623. 8,
  129624. };
  129625. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129626. _vq_quantthresh__44c3_s_p4_0,
  129627. _vq_quantmap__44c3_s_p4_0,
  129628. 9,
  129629. 9
  129630. };
  129631. static static_codebook _44c3_s_p4_0 = {
  129632. 2, 81,
  129633. _vq_lengthlist__44c3_s_p4_0,
  129634. 1, -531628032, 1611661312, 4, 0,
  129635. _vq_quantlist__44c3_s_p4_0,
  129636. NULL,
  129637. &_vq_auxt__44c3_s_p4_0,
  129638. NULL,
  129639. 0
  129640. };
  129641. static long _vq_quantlist__44c3_s_p5_0[] = {
  129642. 4,
  129643. 3,
  129644. 5,
  129645. 2,
  129646. 6,
  129647. 1,
  129648. 7,
  129649. 0,
  129650. 8,
  129651. };
  129652. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129653. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129654. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129655. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129656. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129657. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129658. 11,
  129659. };
  129660. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129661. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129662. };
  129663. static long _vq_quantmap__44c3_s_p5_0[] = {
  129664. 7, 5, 3, 1, 0, 2, 4, 6,
  129665. 8,
  129666. };
  129667. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129668. _vq_quantthresh__44c3_s_p5_0,
  129669. _vq_quantmap__44c3_s_p5_0,
  129670. 9,
  129671. 9
  129672. };
  129673. static static_codebook _44c3_s_p5_0 = {
  129674. 2, 81,
  129675. _vq_lengthlist__44c3_s_p5_0,
  129676. 1, -531628032, 1611661312, 4, 0,
  129677. _vq_quantlist__44c3_s_p5_0,
  129678. NULL,
  129679. &_vq_auxt__44c3_s_p5_0,
  129680. NULL,
  129681. 0
  129682. };
  129683. static long _vq_quantlist__44c3_s_p6_0[] = {
  129684. 8,
  129685. 7,
  129686. 9,
  129687. 6,
  129688. 10,
  129689. 5,
  129690. 11,
  129691. 4,
  129692. 12,
  129693. 3,
  129694. 13,
  129695. 2,
  129696. 14,
  129697. 1,
  129698. 15,
  129699. 0,
  129700. 16,
  129701. };
  129702. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129703. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129704. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129705. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129706. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129707. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129708. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129709. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129710. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129711. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129712. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129713. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129714. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129715. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129716. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129717. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129718. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129719. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129720. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129721. 13,
  129722. };
  129723. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129724. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129725. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129726. };
  129727. static long _vq_quantmap__44c3_s_p6_0[] = {
  129728. 15, 13, 11, 9, 7, 5, 3, 1,
  129729. 0, 2, 4, 6, 8, 10, 12, 14,
  129730. 16,
  129731. };
  129732. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129733. _vq_quantthresh__44c3_s_p6_0,
  129734. _vq_quantmap__44c3_s_p6_0,
  129735. 17,
  129736. 17
  129737. };
  129738. static static_codebook _44c3_s_p6_0 = {
  129739. 2, 289,
  129740. _vq_lengthlist__44c3_s_p6_0,
  129741. 1, -529530880, 1611661312, 5, 0,
  129742. _vq_quantlist__44c3_s_p6_0,
  129743. NULL,
  129744. &_vq_auxt__44c3_s_p6_0,
  129745. NULL,
  129746. 0
  129747. };
  129748. static long _vq_quantlist__44c3_s_p7_0[] = {
  129749. 1,
  129750. 0,
  129751. 2,
  129752. };
  129753. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129754. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129755. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129756. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129757. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129758. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129759. 10,
  129760. };
  129761. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129762. -5.5, 5.5,
  129763. };
  129764. static long _vq_quantmap__44c3_s_p7_0[] = {
  129765. 1, 0, 2,
  129766. };
  129767. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129768. _vq_quantthresh__44c3_s_p7_0,
  129769. _vq_quantmap__44c3_s_p7_0,
  129770. 3,
  129771. 3
  129772. };
  129773. static static_codebook _44c3_s_p7_0 = {
  129774. 4, 81,
  129775. _vq_lengthlist__44c3_s_p7_0,
  129776. 1, -529137664, 1618345984, 2, 0,
  129777. _vq_quantlist__44c3_s_p7_0,
  129778. NULL,
  129779. &_vq_auxt__44c3_s_p7_0,
  129780. NULL,
  129781. 0
  129782. };
  129783. static long _vq_quantlist__44c3_s_p7_1[] = {
  129784. 5,
  129785. 4,
  129786. 6,
  129787. 3,
  129788. 7,
  129789. 2,
  129790. 8,
  129791. 1,
  129792. 9,
  129793. 0,
  129794. 10,
  129795. };
  129796. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129797. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129798. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129799. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129800. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129801. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129802. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129803. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129804. 10,10,10, 8, 8, 8, 8, 8, 8,
  129805. };
  129806. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129807. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129808. 3.5, 4.5,
  129809. };
  129810. static long _vq_quantmap__44c3_s_p7_1[] = {
  129811. 9, 7, 5, 3, 1, 0, 2, 4,
  129812. 6, 8, 10,
  129813. };
  129814. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129815. _vq_quantthresh__44c3_s_p7_1,
  129816. _vq_quantmap__44c3_s_p7_1,
  129817. 11,
  129818. 11
  129819. };
  129820. static static_codebook _44c3_s_p7_1 = {
  129821. 2, 121,
  129822. _vq_lengthlist__44c3_s_p7_1,
  129823. 1, -531365888, 1611661312, 4, 0,
  129824. _vq_quantlist__44c3_s_p7_1,
  129825. NULL,
  129826. &_vq_auxt__44c3_s_p7_1,
  129827. NULL,
  129828. 0
  129829. };
  129830. static long _vq_quantlist__44c3_s_p8_0[] = {
  129831. 6,
  129832. 5,
  129833. 7,
  129834. 4,
  129835. 8,
  129836. 3,
  129837. 9,
  129838. 2,
  129839. 10,
  129840. 1,
  129841. 11,
  129842. 0,
  129843. 12,
  129844. };
  129845. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129846. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129847. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129848. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129849. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129850. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129851. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129852. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129853. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129854. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129855. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129856. 0,13,13,12,12,13,12,14,13,
  129857. };
  129858. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129859. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129860. 12.5, 17.5, 22.5, 27.5,
  129861. };
  129862. static long _vq_quantmap__44c3_s_p8_0[] = {
  129863. 11, 9, 7, 5, 3, 1, 0, 2,
  129864. 4, 6, 8, 10, 12,
  129865. };
  129866. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129867. _vq_quantthresh__44c3_s_p8_0,
  129868. _vq_quantmap__44c3_s_p8_0,
  129869. 13,
  129870. 13
  129871. };
  129872. static static_codebook _44c3_s_p8_0 = {
  129873. 2, 169,
  129874. _vq_lengthlist__44c3_s_p8_0,
  129875. 1, -526516224, 1616117760, 4, 0,
  129876. _vq_quantlist__44c3_s_p8_0,
  129877. NULL,
  129878. &_vq_auxt__44c3_s_p8_0,
  129879. NULL,
  129880. 0
  129881. };
  129882. static long _vq_quantlist__44c3_s_p8_1[] = {
  129883. 2,
  129884. 1,
  129885. 3,
  129886. 0,
  129887. 4,
  129888. };
  129889. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129890. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129891. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129892. };
  129893. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129894. -1.5, -0.5, 0.5, 1.5,
  129895. };
  129896. static long _vq_quantmap__44c3_s_p8_1[] = {
  129897. 3, 1, 0, 2, 4,
  129898. };
  129899. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129900. _vq_quantthresh__44c3_s_p8_1,
  129901. _vq_quantmap__44c3_s_p8_1,
  129902. 5,
  129903. 5
  129904. };
  129905. static static_codebook _44c3_s_p8_1 = {
  129906. 2, 25,
  129907. _vq_lengthlist__44c3_s_p8_1,
  129908. 1, -533725184, 1611661312, 3, 0,
  129909. _vq_quantlist__44c3_s_p8_1,
  129910. NULL,
  129911. &_vq_auxt__44c3_s_p8_1,
  129912. NULL,
  129913. 0
  129914. };
  129915. static long _vq_quantlist__44c3_s_p9_0[] = {
  129916. 6,
  129917. 5,
  129918. 7,
  129919. 4,
  129920. 8,
  129921. 3,
  129922. 9,
  129923. 2,
  129924. 10,
  129925. 1,
  129926. 11,
  129927. 0,
  129928. 12,
  129929. };
  129930. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129931. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129932. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129933. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129934. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129935. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129936. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129937. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129938. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129939. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129941. 11,11,11,11,11,11,11,11,11,
  129942. };
  129943. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129944. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129945. 637.5, 892.5, 1147.5, 1402.5,
  129946. };
  129947. static long _vq_quantmap__44c3_s_p9_0[] = {
  129948. 11, 9, 7, 5, 3, 1, 0, 2,
  129949. 4, 6, 8, 10, 12,
  129950. };
  129951. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129952. _vq_quantthresh__44c3_s_p9_0,
  129953. _vq_quantmap__44c3_s_p9_0,
  129954. 13,
  129955. 13
  129956. };
  129957. static static_codebook _44c3_s_p9_0 = {
  129958. 2, 169,
  129959. _vq_lengthlist__44c3_s_p9_0,
  129960. 1, -514332672, 1627381760, 4, 0,
  129961. _vq_quantlist__44c3_s_p9_0,
  129962. NULL,
  129963. &_vq_auxt__44c3_s_p9_0,
  129964. NULL,
  129965. 0
  129966. };
  129967. static long _vq_quantlist__44c3_s_p9_1[] = {
  129968. 7,
  129969. 6,
  129970. 8,
  129971. 5,
  129972. 9,
  129973. 4,
  129974. 10,
  129975. 3,
  129976. 11,
  129977. 2,
  129978. 12,
  129979. 1,
  129980. 13,
  129981. 0,
  129982. 14,
  129983. };
  129984. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129985. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129986. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129987. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129988. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129989. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129990. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129991. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129992. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129993. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129994. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129995. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129996. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129997. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129998. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129999. 15,
  130000. };
  130001. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130002. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130003. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130004. };
  130005. static long _vq_quantmap__44c3_s_p9_1[] = {
  130006. 13, 11, 9, 7, 5, 3, 1, 0,
  130007. 2, 4, 6, 8, 10, 12, 14,
  130008. };
  130009. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130010. _vq_quantthresh__44c3_s_p9_1,
  130011. _vq_quantmap__44c3_s_p9_1,
  130012. 15,
  130013. 15
  130014. };
  130015. static static_codebook _44c3_s_p9_1 = {
  130016. 2, 225,
  130017. _vq_lengthlist__44c3_s_p9_1,
  130018. 1, -522338304, 1620115456, 4, 0,
  130019. _vq_quantlist__44c3_s_p9_1,
  130020. NULL,
  130021. &_vq_auxt__44c3_s_p9_1,
  130022. NULL,
  130023. 0
  130024. };
  130025. static long _vq_quantlist__44c3_s_p9_2[] = {
  130026. 8,
  130027. 7,
  130028. 9,
  130029. 6,
  130030. 10,
  130031. 5,
  130032. 11,
  130033. 4,
  130034. 12,
  130035. 3,
  130036. 13,
  130037. 2,
  130038. 14,
  130039. 1,
  130040. 15,
  130041. 0,
  130042. 16,
  130043. };
  130044. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130045. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130046. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130047. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130048. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130049. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130050. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130051. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130052. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130053. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130054. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130055. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130056. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130057. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130058. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130059. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130060. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130061. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130062. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130063. 10,
  130064. };
  130065. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130066. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130067. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130068. };
  130069. static long _vq_quantmap__44c3_s_p9_2[] = {
  130070. 15, 13, 11, 9, 7, 5, 3, 1,
  130071. 0, 2, 4, 6, 8, 10, 12, 14,
  130072. 16,
  130073. };
  130074. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130075. _vq_quantthresh__44c3_s_p9_2,
  130076. _vq_quantmap__44c3_s_p9_2,
  130077. 17,
  130078. 17
  130079. };
  130080. static static_codebook _44c3_s_p9_2 = {
  130081. 2, 289,
  130082. _vq_lengthlist__44c3_s_p9_2,
  130083. 1, -529530880, 1611661312, 5, 0,
  130084. _vq_quantlist__44c3_s_p9_2,
  130085. NULL,
  130086. &_vq_auxt__44c3_s_p9_2,
  130087. NULL,
  130088. 0
  130089. };
  130090. static long _huff_lengthlist__44c3_s_short[] = {
  130091. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130092. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130093. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130094. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130095. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130096. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130097. 6, 8, 9,11,
  130098. };
  130099. static static_codebook _huff_book__44c3_s_short = {
  130100. 2, 100,
  130101. _huff_lengthlist__44c3_s_short,
  130102. 0, 0, 0, 0, 0,
  130103. NULL,
  130104. NULL,
  130105. NULL,
  130106. NULL,
  130107. 0
  130108. };
  130109. static long _huff_lengthlist__44c4_s_long[] = {
  130110. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130111. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130112. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130113. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130114. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130115. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130116. 9, 8, 7, 7,
  130117. };
  130118. static static_codebook _huff_book__44c4_s_long = {
  130119. 2, 100,
  130120. _huff_lengthlist__44c4_s_long,
  130121. 0, 0, 0, 0, 0,
  130122. NULL,
  130123. NULL,
  130124. NULL,
  130125. NULL,
  130126. 0
  130127. };
  130128. static long _vq_quantlist__44c4_s_p1_0[] = {
  130129. 1,
  130130. 0,
  130131. 2,
  130132. };
  130133. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130134. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130135. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130140. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130145. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130180. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130185. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  130190. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130226. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130231. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130236. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0,
  130545. };
  130546. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130547. -0.5, 0.5,
  130548. };
  130549. static long _vq_quantmap__44c4_s_p1_0[] = {
  130550. 1, 0, 2,
  130551. };
  130552. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130553. _vq_quantthresh__44c4_s_p1_0,
  130554. _vq_quantmap__44c4_s_p1_0,
  130555. 3,
  130556. 3
  130557. };
  130558. static static_codebook _44c4_s_p1_0 = {
  130559. 8, 6561,
  130560. _vq_lengthlist__44c4_s_p1_0,
  130561. 1, -535822336, 1611661312, 2, 0,
  130562. _vq_quantlist__44c4_s_p1_0,
  130563. NULL,
  130564. &_vq_auxt__44c4_s_p1_0,
  130565. NULL,
  130566. 0
  130567. };
  130568. static long _vq_quantlist__44c4_s_p2_0[] = {
  130569. 2,
  130570. 1,
  130571. 3,
  130572. 0,
  130573. 4,
  130574. };
  130575. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130576. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130577. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130578. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130579. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130580. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130586. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130587. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130588. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130594. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130595. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130602. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130603. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  130616. };
  130617. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130618. -1.5, -0.5, 0.5, 1.5,
  130619. };
  130620. static long _vq_quantmap__44c4_s_p2_0[] = {
  130621. 3, 1, 0, 2, 4,
  130622. };
  130623. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130624. _vq_quantthresh__44c4_s_p2_0,
  130625. _vq_quantmap__44c4_s_p2_0,
  130626. 5,
  130627. 5
  130628. };
  130629. static static_codebook _44c4_s_p2_0 = {
  130630. 4, 625,
  130631. _vq_lengthlist__44c4_s_p2_0,
  130632. 1, -533725184, 1611661312, 3, 0,
  130633. _vq_quantlist__44c4_s_p2_0,
  130634. NULL,
  130635. &_vq_auxt__44c4_s_p2_0,
  130636. NULL,
  130637. 0
  130638. };
  130639. static long _vq_quantlist__44c4_s_p3_0[] = {
  130640. 2,
  130641. 1,
  130642. 3,
  130643. 0,
  130644. 4,
  130645. };
  130646. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130647. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  130687. };
  130688. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130689. -1.5, -0.5, 0.5, 1.5,
  130690. };
  130691. static long _vq_quantmap__44c4_s_p3_0[] = {
  130692. 3, 1, 0, 2, 4,
  130693. };
  130694. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130695. _vq_quantthresh__44c4_s_p3_0,
  130696. _vq_quantmap__44c4_s_p3_0,
  130697. 5,
  130698. 5
  130699. };
  130700. static static_codebook _44c4_s_p3_0 = {
  130701. 4, 625,
  130702. _vq_lengthlist__44c4_s_p3_0,
  130703. 1, -533725184, 1611661312, 3, 0,
  130704. _vq_quantlist__44c4_s_p3_0,
  130705. NULL,
  130706. &_vq_auxt__44c4_s_p3_0,
  130707. NULL,
  130708. 0
  130709. };
  130710. static long _vq_quantlist__44c4_s_p4_0[] = {
  130711. 4,
  130712. 3,
  130713. 5,
  130714. 2,
  130715. 6,
  130716. 1,
  130717. 7,
  130718. 0,
  130719. 8,
  130720. };
  130721. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130722. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130723. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130724. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130725. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130726. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130727. 0,
  130728. };
  130729. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130730. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130731. };
  130732. static long _vq_quantmap__44c4_s_p4_0[] = {
  130733. 7, 5, 3, 1, 0, 2, 4, 6,
  130734. 8,
  130735. };
  130736. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130737. _vq_quantthresh__44c4_s_p4_0,
  130738. _vq_quantmap__44c4_s_p4_0,
  130739. 9,
  130740. 9
  130741. };
  130742. static static_codebook _44c4_s_p4_0 = {
  130743. 2, 81,
  130744. _vq_lengthlist__44c4_s_p4_0,
  130745. 1, -531628032, 1611661312, 4, 0,
  130746. _vq_quantlist__44c4_s_p4_0,
  130747. NULL,
  130748. &_vq_auxt__44c4_s_p4_0,
  130749. NULL,
  130750. 0
  130751. };
  130752. static long _vq_quantlist__44c4_s_p5_0[] = {
  130753. 4,
  130754. 3,
  130755. 5,
  130756. 2,
  130757. 6,
  130758. 1,
  130759. 7,
  130760. 0,
  130761. 8,
  130762. };
  130763. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130764. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130765. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130766. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130767. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130768. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130769. 10,
  130770. };
  130771. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130772. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130773. };
  130774. static long _vq_quantmap__44c4_s_p5_0[] = {
  130775. 7, 5, 3, 1, 0, 2, 4, 6,
  130776. 8,
  130777. };
  130778. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130779. _vq_quantthresh__44c4_s_p5_0,
  130780. _vq_quantmap__44c4_s_p5_0,
  130781. 9,
  130782. 9
  130783. };
  130784. static static_codebook _44c4_s_p5_0 = {
  130785. 2, 81,
  130786. _vq_lengthlist__44c4_s_p5_0,
  130787. 1, -531628032, 1611661312, 4, 0,
  130788. _vq_quantlist__44c4_s_p5_0,
  130789. NULL,
  130790. &_vq_auxt__44c4_s_p5_0,
  130791. NULL,
  130792. 0
  130793. };
  130794. static long _vq_quantlist__44c4_s_p6_0[] = {
  130795. 8,
  130796. 7,
  130797. 9,
  130798. 6,
  130799. 10,
  130800. 5,
  130801. 11,
  130802. 4,
  130803. 12,
  130804. 3,
  130805. 13,
  130806. 2,
  130807. 14,
  130808. 1,
  130809. 15,
  130810. 0,
  130811. 16,
  130812. };
  130813. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130814. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130815. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130816. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130817. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130818. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130819. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130820. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130821. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130822. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130823. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130824. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130825. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130826. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130827. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130828. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130829. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130830. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130832. 13,
  130833. };
  130834. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130835. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130836. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130837. };
  130838. static long _vq_quantmap__44c4_s_p6_0[] = {
  130839. 15, 13, 11, 9, 7, 5, 3, 1,
  130840. 0, 2, 4, 6, 8, 10, 12, 14,
  130841. 16,
  130842. };
  130843. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130844. _vq_quantthresh__44c4_s_p6_0,
  130845. _vq_quantmap__44c4_s_p6_0,
  130846. 17,
  130847. 17
  130848. };
  130849. static static_codebook _44c4_s_p6_0 = {
  130850. 2, 289,
  130851. _vq_lengthlist__44c4_s_p6_0,
  130852. 1, -529530880, 1611661312, 5, 0,
  130853. _vq_quantlist__44c4_s_p6_0,
  130854. NULL,
  130855. &_vq_auxt__44c4_s_p6_0,
  130856. NULL,
  130857. 0
  130858. };
  130859. static long _vq_quantlist__44c4_s_p7_0[] = {
  130860. 1,
  130861. 0,
  130862. 2,
  130863. };
  130864. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130865. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130866. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130867. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130868. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130869. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130870. 10,
  130871. };
  130872. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130873. -5.5, 5.5,
  130874. };
  130875. static long _vq_quantmap__44c4_s_p7_0[] = {
  130876. 1, 0, 2,
  130877. };
  130878. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130879. _vq_quantthresh__44c4_s_p7_0,
  130880. _vq_quantmap__44c4_s_p7_0,
  130881. 3,
  130882. 3
  130883. };
  130884. static static_codebook _44c4_s_p7_0 = {
  130885. 4, 81,
  130886. _vq_lengthlist__44c4_s_p7_0,
  130887. 1, -529137664, 1618345984, 2, 0,
  130888. _vq_quantlist__44c4_s_p7_0,
  130889. NULL,
  130890. &_vq_auxt__44c4_s_p7_0,
  130891. NULL,
  130892. 0
  130893. };
  130894. static long _vq_quantlist__44c4_s_p7_1[] = {
  130895. 5,
  130896. 4,
  130897. 6,
  130898. 3,
  130899. 7,
  130900. 2,
  130901. 8,
  130902. 1,
  130903. 9,
  130904. 0,
  130905. 10,
  130906. };
  130907. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130908. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130909. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130910. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130911. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130912. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130913. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130914. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130915. 10,10,10, 8, 8, 8, 8, 9, 9,
  130916. };
  130917. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130918. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130919. 3.5, 4.5,
  130920. };
  130921. static long _vq_quantmap__44c4_s_p7_1[] = {
  130922. 9, 7, 5, 3, 1, 0, 2, 4,
  130923. 6, 8, 10,
  130924. };
  130925. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130926. _vq_quantthresh__44c4_s_p7_1,
  130927. _vq_quantmap__44c4_s_p7_1,
  130928. 11,
  130929. 11
  130930. };
  130931. static static_codebook _44c4_s_p7_1 = {
  130932. 2, 121,
  130933. _vq_lengthlist__44c4_s_p7_1,
  130934. 1, -531365888, 1611661312, 4, 0,
  130935. _vq_quantlist__44c4_s_p7_1,
  130936. NULL,
  130937. &_vq_auxt__44c4_s_p7_1,
  130938. NULL,
  130939. 0
  130940. };
  130941. static long _vq_quantlist__44c4_s_p8_0[] = {
  130942. 6,
  130943. 5,
  130944. 7,
  130945. 4,
  130946. 8,
  130947. 3,
  130948. 9,
  130949. 2,
  130950. 10,
  130951. 1,
  130952. 11,
  130953. 0,
  130954. 12,
  130955. };
  130956. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130957. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130958. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130959. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130960. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130961. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130962. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130963. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130964. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130965. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130966. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130967. 0,13,12,12,12,12,12,13,13,
  130968. };
  130969. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130970. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130971. 12.5, 17.5, 22.5, 27.5,
  130972. };
  130973. static long _vq_quantmap__44c4_s_p8_0[] = {
  130974. 11, 9, 7, 5, 3, 1, 0, 2,
  130975. 4, 6, 8, 10, 12,
  130976. };
  130977. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130978. _vq_quantthresh__44c4_s_p8_0,
  130979. _vq_quantmap__44c4_s_p8_0,
  130980. 13,
  130981. 13
  130982. };
  130983. static static_codebook _44c4_s_p8_0 = {
  130984. 2, 169,
  130985. _vq_lengthlist__44c4_s_p8_0,
  130986. 1, -526516224, 1616117760, 4, 0,
  130987. _vq_quantlist__44c4_s_p8_0,
  130988. NULL,
  130989. &_vq_auxt__44c4_s_p8_0,
  130990. NULL,
  130991. 0
  130992. };
  130993. static long _vq_quantlist__44c4_s_p8_1[] = {
  130994. 2,
  130995. 1,
  130996. 3,
  130997. 0,
  130998. 4,
  130999. };
  131000. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131001. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131002. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131003. };
  131004. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131005. -1.5, -0.5, 0.5, 1.5,
  131006. };
  131007. static long _vq_quantmap__44c4_s_p8_1[] = {
  131008. 3, 1, 0, 2, 4,
  131009. };
  131010. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131011. _vq_quantthresh__44c4_s_p8_1,
  131012. _vq_quantmap__44c4_s_p8_1,
  131013. 5,
  131014. 5
  131015. };
  131016. static static_codebook _44c4_s_p8_1 = {
  131017. 2, 25,
  131018. _vq_lengthlist__44c4_s_p8_1,
  131019. 1, -533725184, 1611661312, 3, 0,
  131020. _vq_quantlist__44c4_s_p8_1,
  131021. NULL,
  131022. &_vq_auxt__44c4_s_p8_1,
  131023. NULL,
  131024. 0
  131025. };
  131026. static long _vq_quantlist__44c4_s_p9_0[] = {
  131027. 6,
  131028. 5,
  131029. 7,
  131030. 4,
  131031. 8,
  131032. 3,
  131033. 9,
  131034. 2,
  131035. 10,
  131036. 1,
  131037. 11,
  131038. 0,
  131039. 12,
  131040. };
  131041. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131042. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131043. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131044. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131045. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131046. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131047. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131048. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131049. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131050. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131051. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131052. 12,12,12,12,12,12,12,12,12,
  131053. };
  131054. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131055. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131056. 787.5, 1102.5, 1417.5, 1732.5,
  131057. };
  131058. static long _vq_quantmap__44c4_s_p9_0[] = {
  131059. 11, 9, 7, 5, 3, 1, 0, 2,
  131060. 4, 6, 8, 10, 12,
  131061. };
  131062. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131063. _vq_quantthresh__44c4_s_p9_0,
  131064. _vq_quantmap__44c4_s_p9_0,
  131065. 13,
  131066. 13
  131067. };
  131068. static static_codebook _44c4_s_p9_0 = {
  131069. 2, 169,
  131070. _vq_lengthlist__44c4_s_p9_0,
  131071. 1, -513964032, 1628680192, 4, 0,
  131072. _vq_quantlist__44c4_s_p9_0,
  131073. NULL,
  131074. &_vq_auxt__44c4_s_p9_0,
  131075. NULL,
  131076. 0
  131077. };
  131078. static long _vq_quantlist__44c4_s_p9_1[] = {
  131079. 7,
  131080. 6,
  131081. 8,
  131082. 5,
  131083. 9,
  131084. 4,
  131085. 10,
  131086. 3,
  131087. 11,
  131088. 2,
  131089. 12,
  131090. 1,
  131091. 13,
  131092. 0,
  131093. 14,
  131094. };
  131095. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131096. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131097. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131098. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131099. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131100. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131101. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131102. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131103. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131104. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131105. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131106. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131107. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131108. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131109. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131110. 15,
  131111. };
  131112. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131113. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131114. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131115. };
  131116. static long _vq_quantmap__44c4_s_p9_1[] = {
  131117. 13, 11, 9, 7, 5, 3, 1, 0,
  131118. 2, 4, 6, 8, 10, 12, 14,
  131119. };
  131120. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131121. _vq_quantthresh__44c4_s_p9_1,
  131122. _vq_quantmap__44c4_s_p9_1,
  131123. 15,
  131124. 15
  131125. };
  131126. static static_codebook _44c4_s_p9_1 = {
  131127. 2, 225,
  131128. _vq_lengthlist__44c4_s_p9_1,
  131129. 1, -520986624, 1620377600, 4, 0,
  131130. _vq_quantlist__44c4_s_p9_1,
  131131. NULL,
  131132. &_vq_auxt__44c4_s_p9_1,
  131133. NULL,
  131134. 0
  131135. };
  131136. static long _vq_quantlist__44c4_s_p9_2[] = {
  131137. 10,
  131138. 9,
  131139. 11,
  131140. 8,
  131141. 12,
  131142. 7,
  131143. 13,
  131144. 6,
  131145. 14,
  131146. 5,
  131147. 15,
  131148. 4,
  131149. 16,
  131150. 3,
  131151. 17,
  131152. 2,
  131153. 18,
  131154. 1,
  131155. 19,
  131156. 0,
  131157. 20,
  131158. };
  131159. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131160. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131161. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131162. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131163. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131164. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131165. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131166. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131167. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131168. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131169. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131170. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131171. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131172. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131173. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131174. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131175. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131176. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131177. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131178. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131179. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131180. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131181. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131182. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131183. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131184. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131185. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131186. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131187. 10,10,10,10,10,10,10,10,10,
  131188. };
  131189. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131190. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131191. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131192. 6.5, 7.5, 8.5, 9.5,
  131193. };
  131194. static long _vq_quantmap__44c4_s_p9_2[] = {
  131195. 19, 17, 15, 13, 11, 9, 7, 5,
  131196. 3, 1, 0, 2, 4, 6, 8, 10,
  131197. 12, 14, 16, 18, 20,
  131198. };
  131199. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131200. _vq_quantthresh__44c4_s_p9_2,
  131201. _vq_quantmap__44c4_s_p9_2,
  131202. 21,
  131203. 21
  131204. };
  131205. static static_codebook _44c4_s_p9_2 = {
  131206. 2, 441,
  131207. _vq_lengthlist__44c4_s_p9_2,
  131208. 1, -529268736, 1611661312, 5, 0,
  131209. _vq_quantlist__44c4_s_p9_2,
  131210. NULL,
  131211. &_vq_auxt__44c4_s_p9_2,
  131212. NULL,
  131213. 0
  131214. };
  131215. static long _huff_lengthlist__44c4_s_short[] = {
  131216. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131217. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131218. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131219. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131220. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131221. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131222. 7, 9,12,17,
  131223. };
  131224. static static_codebook _huff_book__44c4_s_short = {
  131225. 2, 100,
  131226. _huff_lengthlist__44c4_s_short,
  131227. 0, 0, 0, 0, 0,
  131228. NULL,
  131229. NULL,
  131230. NULL,
  131231. NULL,
  131232. 0
  131233. };
  131234. static long _huff_lengthlist__44c5_s_long[] = {
  131235. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131236. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131237. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131238. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131239. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131240. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131241. 9, 8, 7, 7,
  131242. };
  131243. static static_codebook _huff_book__44c5_s_long = {
  131244. 2, 100,
  131245. _huff_lengthlist__44c5_s_long,
  131246. 0, 0, 0, 0, 0,
  131247. NULL,
  131248. NULL,
  131249. NULL,
  131250. NULL,
  131251. 0
  131252. };
  131253. static long _vq_quantlist__44c5_s_p1_0[] = {
  131254. 1,
  131255. 0,
  131256. 2,
  131257. };
  131258. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131259. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131260. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131265. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131270. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131305. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131310. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131315. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131351. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131356. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131361. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0,
  131670. };
  131671. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131672. -0.5, 0.5,
  131673. };
  131674. static long _vq_quantmap__44c5_s_p1_0[] = {
  131675. 1, 0, 2,
  131676. };
  131677. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131678. _vq_quantthresh__44c5_s_p1_0,
  131679. _vq_quantmap__44c5_s_p1_0,
  131680. 3,
  131681. 3
  131682. };
  131683. static static_codebook _44c5_s_p1_0 = {
  131684. 8, 6561,
  131685. _vq_lengthlist__44c5_s_p1_0,
  131686. 1, -535822336, 1611661312, 2, 0,
  131687. _vq_quantlist__44c5_s_p1_0,
  131688. NULL,
  131689. &_vq_auxt__44c5_s_p1_0,
  131690. NULL,
  131691. 0
  131692. };
  131693. static long _vq_quantlist__44c5_s_p2_0[] = {
  131694. 2,
  131695. 1,
  131696. 3,
  131697. 0,
  131698. 4,
  131699. };
  131700. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131701. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131702. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131703. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131704. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131705. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131711. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131712. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131713. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131719. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131720. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131727. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131728. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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,
  131741. };
  131742. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131743. -1.5, -0.5, 0.5, 1.5,
  131744. };
  131745. static long _vq_quantmap__44c5_s_p2_0[] = {
  131746. 3, 1, 0, 2, 4,
  131747. };
  131748. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131749. _vq_quantthresh__44c5_s_p2_0,
  131750. _vq_quantmap__44c5_s_p2_0,
  131751. 5,
  131752. 5
  131753. };
  131754. static static_codebook _44c5_s_p2_0 = {
  131755. 4, 625,
  131756. _vq_lengthlist__44c5_s_p2_0,
  131757. 1, -533725184, 1611661312, 3, 0,
  131758. _vq_quantlist__44c5_s_p2_0,
  131759. NULL,
  131760. &_vq_auxt__44c5_s_p2_0,
  131761. NULL,
  131762. 0
  131763. };
  131764. static long _vq_quantlist__44c5_s_p3_0[] = {
  131765. 2,
  131766. 1,
  131767. 3,
  131768. 0,
  131769. 4,
  131770. };
  131771. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131772. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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,
  131812. };
  131813. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131814. -1.5, -0.5, 0.5, 1.5,
  131815. };
  131816. static long _vq_quantmap__44c5_s_p3_0[] = {
  131817. 3, 1, 0, 2, 4,
  131818. };
  131819. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131820. _vq_quantthresh__44c5_s_p3_0,
  131821. _vq_quantmap__44c5_s_p3_0,
  131822. 5,
  131823. 5
  131824. };
  131825. static static_codebook _44c5_s_p3_0 = {
  131826. 4, 625,
  131827. _vq_lengthlist__44c5_s_p3_0,
  131828. 1, -533725184, 1611661312, 3, 0,
  131829. _vq_quantlist__44c5_s_p3_0,
  131830. NULL,
  131831. &_vq_auxt__44c5_s_p3_0,
  131832. NULL,
  131833. 0
  131834. };
  131835. static long _vq_quantlist__44c5_s_p4_0[] = {
  131836. 4,
  131837. 3,
  131838. 5,
  131839. 2,
  131840. 6,
  131841. 1,
  131842. 7,
  131843. 0,
  131844. 8,
  131845. };
  131846. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131847. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131848. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131849. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131850. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131851. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131852. 0,
  131853. };
  131854. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131855. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131856. };
  131857. static long _vq_quantmap__44c5_s_p4_0[] = {
  131858. 7, 5, 3, 1, 0, 2, 4, 6,
  131859. 8,
  131860. };
  131861. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131862. _vq_quantthresh__44c5_s_p4_0,
  131863. _vq_quantmap__44c5_s_p4_0,
  131864. 9,
  131865. 9
  131866. };
  131867. static static_codebook _44c5_s_p4_0 = {
  131868. 2, 81,
  131869. _vq_lengthlist__44c5_s_p4_0,
  131870. 1, -531628032, 1611661312, 4, 0,
  131871. _vq_quantlist__44c5_s_p4_0,
  131872. NULL,
  131873. &_vq_auxt__44c5_s_p4_0,
  131874. NULL,
  131875. 0
  131876. };
  131877. static long _vq_quantlist__44c5_s_p5_0[] = {
  131878. 4,
  131879. 3,
  131880. 5,
  131881. 2,
  131882. 6,
  131883. 1,
  131884. 7,
  131885. 0,
  131886. 8,
  131887. };
  131888. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131889. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131890. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131891. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131892. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131893. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131894. 10,
  131895. };
  131896. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131897. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131898. };
  131899. static long _vq_quantmap__44c5_s_p5_0[] = {
  131900. 7, 5, 3, 1, 0, 2, 4, 6,
  131901. 8,
  131902. };
  131903. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131904. _vq_quantthresh__44c5_s_p5_0,
  131905. _vq_quantmap__44c5_s_p5_0,
  131906. 9,
  131907. 9
  131908. };
  131909. static static_codebook _44c5_s_p5_0 = {
  131910. 2, 81,
  131911. _vq_lengthlist__44c5_s_p5_0,
  131912. 1, -531628032, 1611661312, 4, 0,
  131913. _vq_quantlist__44c5_s_p5_0,
  131914. NULL,
  131915. &_vq_auxt__44c5_s_p5_0,
  131916. NULL,
  131917. 0
  131918. };
  131919. static long _vq_quantlist__44c5_s_p6_0[] = {
  131920. 8,
  131921. 7,
  131922. 9,
  131923. 6,
  131924. 10,
  131925. 5,
  131926. 11,
  131927. 4,
  131928. 12,
  131929. 3,
  131930. 13,
  131931. 2,
  131932. 14,
  131933. 1,
  131934. 15,
  131935. 0,
  131936. 16,
  131937. };
  131938. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131939. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131940. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131941. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131942. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131943. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131944. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131945. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131946. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131947. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131948. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131949. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131950. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131951. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131952. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131953. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131954. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131955. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131957. 13,
  131958. };
  131959. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131960. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131961. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131962. };
  131963. static long _vq_quantmap__44c5_s_p6_0[] = {
  131964. 15, 13, 11, 9, 7, 5, 3, 1,
  131965. 0, 2, 4, 6, 8, 10, 12, 14,
  131966. 16,
  131967. };
  131968. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131969. _vq_quantthresh__44c5_s_p6_0,
  131970. _vq_quantmap__44c5_s_p6_0,
  131971. 17,
  131972. 17
  131973. };
  131974. static static_codebook _44c5_s_p6_0 = {
  131975. 2, 289,
  131976. _vq_lengthlist__44c5_s_p6_0,
  131977. 1, -529530880, 1611661312, 5, 0,
  131978. _vq_quantlist__44c5_s_p6_0,
  131979. NULL,
  131980. &_vq_auxt__44c5_s_p6_0,
  131981. NULL,
  131982. 0
  131983. };
  131984. static long _vq_quantlist__44c5_s_p7_0[] = {
  131985. 1,
  131986. 0,
  131987. 2,
  131988. };
  131989. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131990. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131991. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131992. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131993. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131994. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131995. 10,
  131996. };
  131997. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131998. -5.5, 5.5,
  131999. };
  132000. static long _vq_quantmap__44c5_s_p7_0[] = {
  132001. 1, 0, 2,
  132002. };
  132003. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132004. _vq_quantthresh__44c5_s_p7_0,
  132005. _vq_quantmap__44c5_s_p7_0,
  132006. 3,
  132007. 3
  132008. };
  132009. static static_codebook _44c5_s_p7_0 = {
  132010. 4, 81,
  132011. _vq_lengthlist__44c5_s_p7_0,
  132012. 1, -529137664, 1618345984, 2, 0,
  132013. _vq_quantlist__44c5_s_p7_0,
  132014. NULL,
  132015. &_vq_auxt__44c5_s_p7_0,
  132016. NULL,
  132017. 0
  132018. };
  132019. static long _vq_quantlist__44c5_s_p7_1[] = {
  132020. 5,
  132021. 4,
  132022. 6,
  132023. 3,
  132024. 7,
  132025. 2,
  132026. 8,
  132027. 1,
  132028. 9,
  132029. 0,
  132030. 10,
  132031. };
  132032. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132033. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132034. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132035. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132036. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132037. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132038. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132039. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132040. 10,10,10, 8, 8, 8, 8, 8, 8,
  132041. };
  132042. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132043. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132044. 3.5, 4.5,
  132045. };
  132046. static long _vq_quantmap__44c5_s_p7_1[] = {
  132047. 9, 7, 5, 3, 1, 0, 2, 4,
  132048. 6, 8, 10,
  132049. };
  132050. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132051. _vq_quantthresh__44c5_s_p7_1,
  132052. _vq_quantmap__44c5_s_p7_1,
  132053. 11,
  132054. 11
  132055. };
  132056. static static_codebook _44c5_s_p7_1 = {
  132057. 2, 121,
  132058. _vq_lengthlist__44c5_s_p7_1,
  132059. 1, -531365888, 1611661312, 4, 0,
  132060. _vq_quantlist__44c5_s_p7_1,
  132061. NULL,
  132062. &_vq_auxt__44c5_s_p7_1,
  132063. NULL,
  132064. 0
  132065. };
  132066. static long _vq_quantlist__44c5_s_p8_0[] = {
  132067. 6,
  132068. 5,
  132069. 7,
  132070. 4,
  132071. 8,
  132072. 3,
  132073. 9,
  132074. 2,
  132075. 10,
  132076. 1,
  132077. 11,
  132078. 0,
  132079. 12,
  132080. };
  132081. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132082. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132083. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132084. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132085. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132086. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132087. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132088. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132089. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132090. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132091. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132092. 0,12,12,12,12,12,12,13,13,
  132093. };
  132094. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132095. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132096. 12.5, 17.5, 22.5, 27.5,
  132097. };
  132098. static long _vq_quantmap__44c5_s_p8_0[] = {
  132099. 11, 9, 7, 5, 3, 1, 0, 2,
  132100. 4, 6, 8, 10, 12,
  132101. };
  132102. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132103. _vq_quantthresh__44c5_s_p8_0,
  132104. _vq_quantmap__44c5_s_p8_0,
  132105. 13,
  132106. 13
  132107. };
  132108. static static_codebook _44c5_s_p8_0 = {
  132109. 2, 169,
  132110. _vq_lengthlist__44c5_s_p8_0,
  132111. 1, -526516224, 1616117760, 4, 0,
  132112. _vq_quantlist__44c5_s_p8_0,
  132113. NULL,
  132114. &_vq_auxt__44c5_s_p8_0,
  132115. NULL,
  132116. 0
  132117. };
  132118. static long _vq_quantlist__44c5_s_p8_1[] = {
  132119. 2,
  132120. 1,
  132121. 3,
  132122. 0,
  132123. 4,
  132124. };
  132125. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132126. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132127. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132128. };
  132129. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132130. -1.5, -0.5, 0.5, 1.5,
  132131. };
  132132. static long _vq_quantmap__44c5_s_p8_1[] = {
  132133. 3, 1, 0, 2, 4,
  132134. };
  132135. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132136. _vq_quantthresh__44c5_s_p8_1,
  132137. _vq_quantmap__44c5_s_p8_1,
  132138. 5,
  132139. 5
  132140. };
  132141. static static_codebook _44c5_s_p8_1 = {
  132142. 2, 25,
  132143. _vq_lengthlist__44c5_s_p8_1,
  132144. 1, -533725184, 1611661312, 3, 0,
  132145. _vq_quantlist__44c5_s_p8_1,
  132146. NULL,
  132147. &_vq_auxt__44c5_s_p8_1,
  132148. NULL,
  132149. 0
  132150. };
  132151. static long _vq_quantlist__44c5_s_p9_0[] = {
  132152. 7,
  132153. 6,
  132154. 8,
  132155. 5,
  132156. 9,
  132157. 4,
  132158. 10,
  132159. 3,
  132160. 11,
  132161. 2,
  132162. 12,
  132163. 1,
  132164. 13,
  132165. 0,
  132166. 14,
  132167. };
  132168. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132169. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132170. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132171. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132172. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132173. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132174. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132175. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132176. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132177. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132178. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132179. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132180. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132181. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132182. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132183. 12,
  132184. };
  132185. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132186. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132187. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132188. };
  132189. static long _vq_quantmap__44c5_s_p9_0[] = {
  132190. 13, 11, 9, 7, 5, 3, 1, 0,
  132191. 2, 4, 6, 8, 10, 12, 14,
  132192. };
  132193. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132194. _vq_quantthresh__44c5_s_p9_0,
  132195. _vq_quantmap__44c5_s_p9_0,
  132196. 15,
  132197. 15
  132198. };
  132199. static static_codebook _44c5_s_p9_0 = {
  132200. 2, 225,
  132201. _vq_lengthlist__44c5_s_p9_0,
  132202. 1, -512522752, 1628852224, 4, 0,
  132203. _vq_quantlist__44c5_s_p9_0,
  132204. NULL,
  132205. &_vq_auxt__44c5_s_p9_0,
  132206. NULL,
  132207. 0
  132208. };
  132209. static long _vq_quantlist__44c5_s_p9_1[] = {
  132210. 8,
  132211. 7,
  132212. 9,
  132213. 6,
  132214. 10,
  132215. 5,
  132216. 11,
  132217. 4,
  132218. 12,
  132219. 3,
  132220. 13,
  132221. 2,
  132222. 14,
  132223. 1,
  132224. 15,
  132225. 0,
  132226. 16,
  132227. };
  132228. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132229. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132230. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132231. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132232. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132233. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132234. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132235. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132236. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132237. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132238. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132239. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132240. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132241. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132242. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132243. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132244. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132245. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132246. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132247. 15,
  132248. };
  132249. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132250. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132251. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132252. };
  132253. static long _vq_quantmap__44c5_s_p9_1[] = {
  132254. 15, 13, 11, 9, 7, 5, 3, 1,
  132255. 0, 2, 4, 6, 8, 10, 12, 14,
  132256. 16,
  132257. };
  132258. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132259. _vq_quantthresh__44c5_s_p9_1,
  132260. _vq_quantmap__44c5_s_p9_1,
  132261. 17,
  132262. 17
  132263. };
  132264. static static_codebook _44c5_s_p9_1 = {
  132265. 2, 289,
  132266. _vq_lengthlist__44c5_s_p9_1,
  132267. 1, -520814592, 1620377600, 5, 0,
  132268. _vq_quantlist__44c5_s_p9_1,
  132269. NULL,
  132270. &_vq_auxt__44c5_s_p9_1,
  132271. NULL,
  132272. 0
  132273. };
  132274. static long _vq_quantlist__44c5_s_p9_2[] = {
  132275. 10,
  132276. 9,
  132277. 11,
  132278. 8,
  132279. 12,
  132280. 7,
  132281. 13,
  132282. 6,
  132283. 14,
  132284. 5,
  132285. 15,
  132286. 4,
  132287. 16,
  132288. 3,
  132289. 17,
  132290. 2,
  132291. 18,
  132292. 1,
  132293. 19,
  132294. 0,
  132295. 20,
  132296. };
  132297. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132298. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132299. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132300. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132301. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132302. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132303. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132304. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132305. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132306. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132307. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132308. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132309. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132310. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132311. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132312. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132313. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132314. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132315. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132316. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132317. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132318. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132319. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132320. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132321. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132322. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132323. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132324. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132325. 10,10,10,10,10,10,10,10,10,
  132326. };
  132327. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132328. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132329. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132330. 6.5, 7.5, 8.5, 9.5,
  132331. };
  132332. static long _vq_quantmap__44c5_s_p9_2[] = {
  132333. 19, 17, 15, 13, 11, 9, 7, 5,
  132334. 3, 1, 0, 2, 4, 6, 8, 10,
  132335. 12, 14, 16, 18, 20,
  132336. };
  132337. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132338. _vq_quantthresh__44c5_s_p9_2,
  132339. _vq_quantmap__44c5_s_p9_2,
  132340. 21,
  132341. 21
  132342. };
  132343. static static_codebook _44c5_s_p9_2 = {
  132344. 2, 441,
  132345. _vq_lengthlist__44c5_s_p9_2,
  132346. 1, -529268736, 1611661312, 5, 0,
  132347. _vq_quantlist__44c5_s_p9_2,
  132348. NULL,
  132349. &_vq_auxt__44c5_s_p9_2,
  132350. NULL,
  132351. 0
  132352. };
  132353. static long _huff_lengthlist__44c5_s_short[] = {
  132354. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132355. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132356. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132357. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132358. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132359. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132360. 6, 8,11,16,
  132361. };
  132362. static static_codebook _huff_book__44c5_s_short = {
  132363. 2, 100,
  132364. _huff_lengthlist__44c5_s_short,
  132365. 0, 0, 0, 0, 0,
  132366. NULL,
  132367. NULL,
  132368. NULL,
  132369. NULL,
  132370. 0
  132371. };
  132372. static long _huff_lengthlist__44c6_s_long[] = {
  132373. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132374. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132375. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132376. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132377. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132378. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132379. 11,10,10,12,
  132380. };
  132381. static static_codebook _huff_book__44c6_s_long = {
  132382. 2, 100,
  132383. _huff_lengthlist__44c6_s_long,
  132384. 0, 0, 0, 0, 0,
  132385. NULL,
  132386. NULL,
  132387. NULL,
  132388. NULL,
  132389. 0
  132390. };
  132391. static long _vq_quantlist__44c6_s_p1_0[] = {
  132392. 1,
  132393. 0,
  132394. 2,
  132395. };
  132396. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132397. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132398. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132399. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132400. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132401. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132402. 8,
  132403. };
  132404. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132405. -0.5, 0.5,
  132406. };
  132407. static long _vq_quantmap__44c6_s_p1_0[] = {
  132408. 1, 0, 2,
  132409. };
  132410. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132411. _vq_quantthresh__44c6_s_p1_0,
  132412. _vq_quantmap__44c6_s_p1_0,
  132413. 3,
  132414. 3
  132415. };
  132416. static static_codebook _44c6_s_p1_0 = {
  132417. 4, 81,
  132418. _vq_lengthlist__44c6_s_p1_0,
  132419. 1, -535822336, 1611661312, 2, 0,
  132420. _vq_quantlist__44c6_s_p1_0,
  132421. NULL,
  132422. &_vq_auxt__44c6_s_p1_0,
  132423. NULL,
  132424. 0
  132425. };
  132426. static long _vq_quantlist__44c6_s_p2_0[] = {
  132427. 2,
  132428. 1,
  132429. 3,
  132430. 0,
  132431. 4,
  132432. };
  132433. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132434. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132435. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132436. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132437. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132438. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132439. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132440. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132441. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132443. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132444. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132445. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132446. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132447. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132448. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132449. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132451. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132452. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132453. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132454. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132455. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132456. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132457. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132459. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132460. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132461. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132462. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132463. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132464. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132465. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132470. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132471. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132472. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132473. 13,
  132474. };
  132475. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132476. -1.5, -0.5, 0.5, 1.5,
  132477. };
  132478. static long _vq_quantmap__44c6_s_p2_0[] = {
  132479. 3, 1, 0, 2, 4,
  132480. };
  132481. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132482. _vq_quantthresh__44c6_s_p2_0,
  132483. _vq_quantmap__44c6_s_p2_0,
  132484. 5,
  132485. 5
  132486. };
  132487. static static_codebook _44c6_s_p2_0 = {
  132488. 4, 625,
  132489. _vq_lengthlist__44c6_s_p2_0,
  132490. 1, -533725184, 1611661312, 3, 0,
  132491. _vq_quantlist__44c6_s_p2_0,
  132492. NULL,
  132493. &_vq_auxt__44c6_s_p2_0,
  132494. NULL,
  132495. 0
  132496. };
  132497. static long _vq_quantlist__44c6_s_p3_0[] = {
  132498. 4,
  132499. 3,
  132500. 5,
  132501. 2,
  132502. 6,
  132503. 1,
  132504. 7,
  132505. 0,
  132506. 8,
  132507. };
  132508. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132509. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132510. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132511. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132512. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132514. 0,
  132515. };
  132516. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132517. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132518. };
  132519. static long _vq_quantmap__44c6_s_p3_0[] = {
  132520. 7, 5, 3, 1, 0, 2, 4, 6,
  132521. 8,
  132522. };
  132523. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132524. _vq_quantthresh__44c6_s_p3_0,
  132525. _vq_quantmap__44c6_s_p3_0,
  132526. 9,
  132527. 9
  132528. };
  132529. static static_codebook _44c6_s_p3_0 = {
  132530. 2, 81,
  132531. _vq_lengthlist__44c6_s_p3_0,
  132532. 1, -531628032, 1611661312, 4, 0,
  132533. _vq_quantlist__44c6_s_p3_0,
  132534. NULL,
  132535. &_vq_auxt__44c6_s_p3_0,
  132536. NULL,
  132537. 0
  132538. };
  132539. static long _vq_quantlist__44c6_s_p4_0[] = {
  132540. 8,
  132541. 7,
  132542. 9,
  132543. 6,
  132544. 10,
  132545. 5,
  132546. 11,
  132547. 4,
  132548. 12,
  132549. 3,
  132550. 13,
  132551. 2,
  132552. 14,
  132553. 1,
  132554. 15,
  132555. 0,
  132556. 16,
  132557. };
  132558. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132559. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132560. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132561. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132562. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132563. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132564. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132565. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132566. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132567. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132568. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132577. 0,
  132578. };
  132579. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132580. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132581. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132582. };
  132583. static long _vq_quantmap__44c6_s_p4_0[] = {
  132584. 15, 13, 11, 9, 7, 5, 3, 1,
  132585. 0, 2, 4, 6, 8, 10, 12, 14,
  132586. 16,
  132587. };
  132588. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132589. _vq_quantthresh__44c6_s_p4_0,
  132590. _vq_quantmap__44c6_s_p4_0,
  132591. 17,
  132592. 17
  132593. };
  132594. static static_codebook _44c6_s_p4_0 = {
  132595. 2, 289,
  132596. _vq_lengthlist__44c6_s_p4_0,
  132597. 1, -529530880, 1611661312, 5, 0,
  132598. _vq_quantlist__44c6_s_p4_0,
  132599. NULL,
  132600. &_vq_auxt__44c6_s_p4_0,
  132601. NULL,
  132602. 0
  132603. };
  132604. static long _vq_quantlist__44c6_s_p5_0[] = {
  132605. 1,
  132606. 0,
  132607. 2,
  132608. };
  132609. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132610. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132611. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132612. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132613. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132614. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132615. 12,
  132616. };
  132617. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132618. -5.5, 5.5,
  132619. };
  132620. static long _vq_quantmap__44c6_s_p5_0[] = {
  132621. 1, 0, 2,
  132622. };
  132623. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132624. _vq_quantthresh__44c6_s_p5_0,
  132625. _vq_quantmap__44c6_s_p5_0,
  132626. 3,
  132627. 3
  132628. };
  132629. static static_codebook _44c6_s_p5_0 = {
  132630. 4, 81,
  132631. _vq_lengthlist__44c6_s_p5_0,
  132632. 1, -529137664, 1618345984, 2, 0,
  132633. _vq_quantlist__44c6_s_p5_0,
  132634. NULL,
  132635. &_vq_auxt__44c6_s_p5_0,
  132636. NULL,
  132637. 0
  132638. };
  132639. static long _vq_quantlist__44c6_s_p5_1[] = {
  132640. 5,
  132641. 4,
  132642. 6,
  132643. 3,
  132644. 7,
  132645. 2,
  132646. 8,
  132647. 1,
  132648. 9,
  132649. 0,
  132650. 10,
  132651. };
  132652. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132653. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132654. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132655. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132656. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132657. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132658. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132659. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132660. 11,10,10, 7, 7, 8, 8, 8, 8,
  132661. };
  132662. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132663. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132664. 3.5, 4.5,
  132665. };
  132666. static long _vq_quantmap__44c6_s_p5_1[] = {
  132667. 9, 7, 5, 3, 1, 0, 2, 4,
  132668. 6, 8, 10,
  132669. };
  132670. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132671. _vq_quantthresh__44c6_s_p5_1,
  132672. _vq_quantmap__44c6_s_p5_1,
  132673. 11,
  132674. 11
  132675. };
  132676. static static_codebook _44c6_s_p5_1 = {
  132677. 2, 121,
  132678. _vq_lengthlist__44c6_s_p5_1,
  132679. 1, -531365888, 1611661312, 4, 0,
  132680. _vq_quantlist__44c6_s_p5_1,
  132681. NULL,
  132682. &_vq_auxt__44c6_s_p5_1,
  132683. NULL,
  132684. 0
  132685. };
  132686. static long _vq_quantlist__44c6_s_p6_0[] = {
  132687. 6,
  132688. 5,
  132689. 7,
  132690. 4,
  132691. 8,
  132692. 3,
  132693. 9,
  132694. 2,
  132695. 10,
  132696. 1,
  132697. 11,
  132698. 0,
  132699. 12,
  132700. };
  132701. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132702. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132703. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132704. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132705. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132706. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132707. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132712. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132713. };
  132714. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132715. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132716. 12.5, 17.5, 22.5, 27.5,
  132717. };
  132718. static long _vq_quantmap__44c6_s_p6_0[] = {
  132719. 11, 9, 7, 5, 3, 1, 0, 2,
  132720. 4, 6, 8, 10, 12,
  132721. };
  132722. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132723. _vq_quantthresh__44c6_s_p6_0,
  132724. _vq_quantmap__44c6_s_p6_0,
  132725. 13,
  132726. 13
  132727. };
  132728. static static_codebook _44c6_s_p6_0 = {
  132729. 2, 169,
  132730. _vq_lengthlist__44c6_s_p6_0,
  132731. 1, -526516224, 1616117760, 4, 0,
  132732. _vq_quantlist__44c6_s_p6_0,
  132733. NULL,
  132734. &_vq_auxt__44c6_s_p6_0,
  132735. NULL,
  132736. 0
  132737. };
  132738. static long _vq_quantlist__44c6_s_p6_1[] = {
  132739. 2,
  132740. 1,
  132741. 3,
  132742. 0,
  132743. 4,
  132744. };
  132745. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132746. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132747. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132748. };
  132749. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132750. -1.5, -0.5, 0.5, 1.5,
  132751. };
  132752. static long _vq_quantmap__44c6_s_p6_1[] = {
  132753. 3, 1, 0, 2, 4,
  132754. };
  132755. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132756. _vq_quantthresh__44c6_s_p6_1,
  132757. _vq_quantmap__44c6_s_p6_1,
  132758. 5,
  132759. 5
  132760. };
  132761. static static_codebook _44c6_s_p6_1 = {
  132762. 2, 25,
  132763. _vq_lengthlist__44c6_s_p6_1,
  132764. 1, -533725184, 1611661312, 3, 0,
  132765. _vq_quantlist__44c6_s_p6_1,
  132766. NULL,
  132767. &_vq_auxt__44c6_s_p6_1,
  132768. NULL,
  132769. 0
  132770. };
  132771. static long _vq_quantlist__44c6_s_p7_0[] = {
  132772. 6,
  132773. 5,
  132774. 7,
  132775. 4,
  132776. 8,
  132777. 3,
  132778. 9,
  132779. 2,
  132780. 10,
  132781. 1,
  132782. 11,
  132783. 0,
  132784. 12,
  132785. };
  132786. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132787. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132788. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132789. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132790. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132791. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132792. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132793. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132794. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132795. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132796. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132797. 20,13,13,13,13,13,13,14,14,
  132798. };
  132799. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132800. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132801. 27.5, 38.5, 49.5, 60.5,
  132802. };
  132803. static long _vq_quantmap__44c6_s_p7_0[] = {
  132804. 11, 9, 7, 5, 3, 1, 0, 2,
  132805. 4, 6, 8, 10, 12,
  132806. };
  132807. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132808. _vq_quantthresh__44c6_s_p7_0,
  132809. _vq_quantmap__44c6_s_p7_0,
  132810. 13,
  132811. 13
  132812. };
  132813. static static_codebook _44c6_s_p7_0 = {
  132814. 2, 169,
  132815. _vq_lengthlist__44c6_s_p7_0,
  132816. 1, -523206656, 1618345984, 4, 0,
  132817. _vq_quantlist__44c6_s_p7_0,
  132818. NULL,
  132819. &_vq_auxt__44c6_s_p7_0,
  132820. NULL,
  132821. 0
  132822. };
  132823. static long _vq_quantlist__44c6_s_p7_1[] = {
  132824. 5,
  132825. 4,
  132826. 6,
  132827. 3,
  132828. 7,
  132829. 2,
  132830. 8,
  132831. 1,
  132832. 9,
  132833. 0,
  132834. 10,
  132835. };
  132836. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132837. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132838. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132839. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132840. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132841. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132842. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132843. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132844. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132845. };
  132846. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132847. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132848. 3.5, 4.5,
  132849. };
  132850. static long _vq_quantmap__44c6_s_p7_1[] = {
  132851. 9, 7, 5, 3, 1, 0, 2, 4,
  132852. 6, 8, 10,
  132853. };
  132854. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132855. _vq_quantthresh__44c6_s_p7_1,
  132856. _vq_quantmap__44c6_s_p7_1,
  132857. 11,
  132858. 11
  132859. };
  132860. static static_codebook _44c6_s_p7_1 = {
  132861. 2, 121,
  132862. _vq_lengthlist__44c6_s_p7_1,
  132863. 1, -531365888, 1611661312, 4, 0,
  132864. _vq_quantlist__44c6_s_p7_1,
  132865. NULL,
  132866. &_vq_auxt__44c6_s_p7_1,
  132867. NULL,
  132868. 0
  132869. };
  132870. static long _vq_quantlist__44c6_s_p8_0[] = {
  132871. 7,
  132872. 6,
  132873. 8,
  132874. 5,
  132875. 9,
  132876. 4,
  132877. 10,
  132878. 3,
  132879. 11,
  132880. 2,
  132881. 12,
  132882. 1,
  132883. 13,
  132884. 0,
  132885. 14,
  132886. };
  132887. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132888. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132889. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132890. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132891. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132892. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132893. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132894. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132895. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132896. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132897. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132898. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132899. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132900. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132901. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132902. 14,
  132903. };
  132904. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132905. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132906. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132907. };
  132908. static long _vq_quantmap__44c6_s_p8_0[] = {
  132909. 13, 11, 9, 7, 5, 3, 1, 0,
  132910. 2, 4, 6, 8, 10, 12, 14,
  132911. };
  132912. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132913. _vq_quantthresh__44c6_s_p8_0,
  132914. _vq_quantmap__44c6_s_p8_0,
  132915. 15,
  132916. 15
  132917. };
  132918. static static_codebook _44c6_s_p8_0 = {
  132919. 2, 225,
  132920. _vq_lengthlist__44c6_s_p8_0,
  132921. 1, -520986624, 1620377600, 4, 0,
  132922. _vq_quantlist__44c6_s_p8_0,
  132923. NULL,
  132924. &_vq_auxt__44c6_s_p8_0,
  132925. NULL,
  132926. 0
  132927. };
  132928. static long _vq_quantlist__44c6_s_p8_1[] = {
  132929. 10,
  132930. 9,
  132931. 11,
  132932. 8,
  132933. 12,
  132934. 7,
  132935. 13,
  132936. 6,
  132937. 14,
  132938. 5,
  132939. 15,
  132940. 4,
  132941. 16,
  132942. 3,
  132943. 17,
  132944. 2,
  132945. 18,
  132946. 1,
  132947. 19,
  132948. 0,
  132949. 20,
  132950. };
  132951. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132952. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132953. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132954. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132955. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132956. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132957. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132958. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132959. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132960. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132961. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132962. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132963. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132964. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132965. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132966. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132967. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132968. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132969. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132970. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132971. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132972. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132973. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132974. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132975. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132976. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132977. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132978. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132979. 10,10,10,10,10,10,10,10,10,
  132980. };
  132981. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132982. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132983. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132984. 6.5, 7.5, 8.5, 9.5,
  132985. };
  132986. static long _vq_quantmap__44c6_s_p8_1[] = {
  132987. 19, 17, 15, 13, 11, 9, 7, 5,
  132988. 3, 1, 0, 2, 4, 6, 8, 10,
  132989. 12, 14, 16, 18, 20,
  132990. };
  132991. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132992. _vq_quantthresh__44c6_s_p8_1,
  132993. _vq_quantmap__44c6_s_p8_1,
  132994. 21,
  132995. 21
  132996. };
  132997. static static_codebook _44c6_s_p8_1 = {
  132998. 2, 441,
  132999. _vq_lengthlist__44c6_s_p8_1,
  133000. 1, -529268736, 1611661312, 5, 0,
  133001. _vq_quantlist__44c6_s_p8_1,
  133002. NULL,
  133003. &_vq_auxt__44c6_s_p8_1,
  133004. NULL,
  133005. 0
  133006. };
  133007. static long _vq_quantlist__44c6_s_p9_0[] = {
  133008. 6,
  133009. 5,
  133010. 7,
  133011. 4,
  133012. 8,
  133013. 3,
  133014. 9,
  133015. 2,
  133016. 10,
  133017. 1,
  133018. 11,
  133019. 0,
  133020. 12,
  133021. };
  133022. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133023. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133024. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133025. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133026. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133027. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133028. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133029. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133030. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133031. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133032. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133033. 10,10,10,10,10,10,10,10,10,
  133034. };
  133035. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133036. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133037. 1592.5, 2229.5, 2866.5, 3503.5,
  133038. };
  133039. static long _vq_quantmap__44c6_s_p9_0[] = {
  133040. 11, 9, 7, 5, 3, 1, 0, 2,
  133041. 4, 6, 8, 10, 12,
  133042. };
  133043. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133044. _vq_quantthresh__44c6_s_p9_0,
  133045. _vq_quantmap__44c6_s_p9_0,
  133046. 13,
  133047. 13
  133048. };
  133049. static static_codebook _44c6_s_p9_0 = {
  133050. 2, 169,
  133051. _vq_lengthlist__44c6_s_p9_0,
  133052. 1, -511845376, 1630791680, 4, 0,
  133053. _vq_quantlist__44c6_s_p9_0,
  133054. NULL,
  133055. &_vq_auxt__44c6_s_p9_0,
  133056. NULL,
  133057. 0
  133058. };
  133059. static long _vq_quantlist__44c6_s_p9_1[] = {
  133060. 6,
  133061. 5,
  133062. 7,
  133063. 4,
  133064. 8,
  133065. 3,
  133066. 9,
  133067. 2,
  133068. 10,
  133069. 1,
  133070. 11,
  133071. 0,
  133072. 12,
  133073. };
  133074. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133075. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133076. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133077. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133078. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133079. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133080. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133081. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133082. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133083. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133084. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133085. 15,12,10,11,11,13,11,12,13,
  133086. };
  133087. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133088. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133089. 122.5, 171.5, 220.5, 269.5,
  133090. };
  133091. static long _vq_quantmap__44c6_s_p9_1[] = {
  133092. 11, 9, 7, 5, 3, 1, 0, 2,
  133093. 4, 6, 8, 10, 12,
  133094. };
  133095. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133096. _vq_quantthresh__44c6_s_p9_1,
  133097. _vq_quantmap__44c6_s_p9_1,
  133098. 13,
  133099. 13
  133100. };
  133101. static static_codebook _44c6_s_p9_1 = {
  133102. 2, 169,
  133103. _vq_lengthlist__44c6_s_p9_1,
  133104. 1, -518889472, 1622704128, 4, 0,
  133105. _vq_quantlist__44c6_s_p9_1,
  133106. NULL,
  133107. &_vq_auxt__44c6_s_p9_1,
  133108. NULL,
  133109. 0
  133110. };
  133111. static long _vq_quantlist__44c6_s_p9_2[] = {
  133112. 24,
  133113. 23,
  133114. 25,
  133115. 22,
  133116. 26,
  133117. 21,
  133118. 27,
  133119. 20,
  133120. 28,
  133121. 19,
  133122. 29,
  133123. 18,
  133124. 30,
  133125. 17,
  133126. 31,
  133127. 16,
  133128. 32,
  133129. 15,
  133130. 33,
  133131. 14,
  133132. 34,
  133133. 13,
  133134. 35,
  133135. 12,
  133136. 36,
  133137. 11,
  133138. 37,
  133139. 10,
  133140. 38,
  133141. 9,
  133142. 39,
  133143. 8,
  133144. 40,
  133145. 7,
  133146. 41,
  133147. 6,
  133148. 42,
  133149. 5,
  133150. 43,
  133151. 4,
  133152. 44,
  133153. 3,
  133154. 45,
  133155. 2,
  133156. 46,
  133157. 1,
  133158. 47,
  133159. 0,
  133160. 48,
  133161. };
  133162. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133163. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133164. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133165. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133166. 7,
  133167. };
  133168. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133169. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133170. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133171. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133172. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133173. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133174. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133175. };
  133176. static long _vq_quantmap__44c6_s_p9_2[] = {
  133177. 47, 45, 43, 41, 39, 37, 35, 33,
  133178. 31, 29, 27, 25, 23, 21, 19, 17,
  133179. 15, 13, 11, 9, 7, 5, 3, 1,
  133180. 0, 2, 4, 6, 8, 10, 12, 14,
  133181. 16, 18, 20, 22, 24, 26, 28, 30,
  133182. 32, 34, 36, 38, 40, 42, 44, 46,
  133183. 48,
  133184. };
  133185. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133186. _vq_quantthresh__44c6_s_p9_2,
  133187. _vq_quantmap__44c6_s_p9_2,
  133188. 49,
  133189. 49
  133190. };
  133191. static static_codebook _44c6_s_p9_2 = {
  133192. 1, 49,
  133193. _vq_lengthlist__44c6_s_p9_2,
  133194. 1, -526909440, 1611661312, 6, 0,
  133195. _vq_quantlist__44c6_s_p9_2,
  133196. NULL,
  133197. &_vq_auxt__44c6_s_p9_2,
  133198. NULL,
  133199. 0
  133200. };
  133201. static long _huff_lengthlist__44c6_s_short[] = {
  133202. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133203. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133204. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133205. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133206. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133207. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133208. 9,10,17,18,
  133209. };
  133210. static static_codebook _huff_book__44c6_s_short = {
  133211. 2, 100,
  133212. _huff_lengthlist__44c6_s_short,
  133213. 0, 0, 0, 0, 0,
  133214. NULL,
  133215. NULL,
  133216. NULL,
  133217. NULL,
  133218. 0
  133219. };
  133220. static long _huff_lengthlist__44c7_s_long[] = {
  133221. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133222. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133223. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133224. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133225. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133226. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133227. 11,10,10,12,
  133228. };
  133229. static static_codebook _huff_book__44c7_s_long = {
  133230. 2, 100,
  133231. _huff_lengthlist__44c7_s_long,
  133232. 0, 0, 0, 0, 0,
  133233. NULL,
  133234. NULL,
  133235. NULL,
  133236. NULL,
  133237. 0
  133238. };
  133239. static long _vq_quantlist__44c7_s_p1_0[] = {
  133240. 1,
  133241. 0,
  133242. 2,
  133243. };
  133244. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133245. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133246. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133247. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133248. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133249. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133250. 8,
  133251. };
  133252. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133253. -0.5, 0.5,
  133254. };
  133255. static long _vq_quantmap__44c7_s_p1_0[] = {
  133256. 1, 0, 2,
  133257. };
  133258. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133259. _vq_quantthresh__44c7_s_p1_0,
  133260. _vq_quantmap__44c7_s_p1_0,
  133261. 3,
  133262. 3
  133263. };
  133264. static static_codebook _44c7_s_p1_0 = {
  133265. 4, 81,
  133266. _vq_lengthlist__44c7_s_p1_0,
  133267. 1, -535822336, 1611661312, 2, 0,
  133268. _vq_quantlist__44c7_s_p1_0,
  133269. NULL,
  133270. &_vq_auxt__44c7_s_p1_0,
  133271. NULL,
  133272. 0
  133273. };
  133274. static long _vq_quantlist__44c7_s_p2_0[] = {
  133275. 2,
  133276. 1,
  133277. 3,
  133278. 0,
  133279. 4,
  133280. };
  133281. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133282. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133283. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133284. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133285. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133286. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133287. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133288. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133289. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133291. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133292. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133293. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133294. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133295. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133296. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133297. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133299. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133300. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133301. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133302. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133303. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133304. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133305. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133307. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133308. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133309. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133310. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133311. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133312. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133313. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133318. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133319. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133320. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133321. 13,
  133322. };
  133323. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133324. -1.5, -0.5, 0.5, 1.5,
  133325. };
  133326. static long _vq_quantmap__44c7_s_p2_0[] = {
  133327. 3, 1, 0, 2, 4,
  133328. };
  133329. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133330. _vq_quantthresh__44c7_s_p2_0,
  133331. _vq_quantmap__44c7_s_p2_0,
  133332. 5,
  133333. 5
  133334. };
  133335. static static_codebook _44c7_s_p2_0 = {
  133336. 4, 625,
  133337. _vq_lengthlist__44c7_s_p2_0,
  133338. 1, -533725184, 1611661312, 3, 0,
  133339. _vq_quantlist__44c7_s_p2_0,
  133340. NULL,
  133341. &_vq_auxt__44c7_s_p2_0,
  133342. NULL,
  133343. 0
  133344. };
  133345. static long _vq_quantlist__44c7_s_p3_0[] = {
  133346. 4,
  133347. 3,
  133348. 5,
  133349. 2,
  133350. 6,
  133351. 1,
  133352. 7,
  133353. 0,
  133354. 8,
  133355. };
  133356. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133357. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133358. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133359. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133360. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133362. 0,
  133363. };
  133364. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133365. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133366. };
  133367. static long _vq_quantmap__44c7_s_p3_0[] = {
  133368. 7, 5, 3, 1, 0, 2, 4, 6,
  133369. 8,
  133370. };
  133371. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133372. _vq_quantthresh__44c7_s_p3_0,
  133373. _vq_quantmap__44c7_s_p3_0,
  133374. 9,
  133375. 9
  133376. };
  133377. static static_codebook _44c7_s_p3_0 = {
  133378. 2, 81,
  133379. _vq_lengthlist__44c7_s_p3_0,
  133380. 1, -531628032, 1611661312, 4, 0,
  133381. _vq_quantlist__44c7_s_p3_0,
  133382. NULL,
  133383. &_vq_auxt__44c7_s_p3_0,
  133384. NULL,
  133385. 0
  133386. };
  133387. static long _vq_quantlist__44c7_s_p4_0[] = {
  133388. 8,
  133389. 7,
  133390. 9,
  133391. 6,
  133392. 10,
  133393. 5,
  133394. 11,
  133395. 4,
  133396. 12,
  133397. 3,
  133398. 13,
  133399. 2,
  133400. 14,
  133401. 1,
  133402. 15,
  133403. 0,
  133404. 16,
  133405. };
  133406. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133407. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133408. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133409. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133410. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133411. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133412. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133413. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133414. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133415. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133416. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133425. 0,
  133426. };
  133427. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133428. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133429. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133430. };
  133431. static long _vq_quantmap__44c7_s_p4_0[] = {
  133432. 15, 13, 11, 9, 7, 5, 3, 1,
  133433. 0, 2, 4, 6, 8, 10, 12, 14,
  133434. 16,
  133435. };
  133436. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133437. _vq_quantthresh__44c7_s_p4_0,
  133438. _vq_quantmap__44c7_s_p4_0,
  133439. 17,
  133440. 17
  133441. };
  133442. static static_codebook _44c7_s_p4_0 = {
  133443. 2, 289,
  133444. _vq_lengthlist__44c7_s_p4_0,
  133445. 1, -529530880, 1611661312, 5, 0,
  133446. _vq_quantlist__44c7_s_p4_0,
  133447. NULL,
  133448. &_vq_auxt__44c7_s_p4_0,
  133449. NULL,
  133450. 0
  133451. };
  133452. static long _vq_quantlist__44c7_s_p5_0[] = {
  133453. 1,
  133454. 0,
  133455. 2,
  133456. };
  133457. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133458. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133459. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133460. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133461. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133462. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133463. 12,
  133464. };
  133465. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133466. -5.5, 5.5,
  133467. };
  133468. static long _vq_quantmap__44c7_s_p5_0[] = {
  133469. 1, 0, 2,
  133470. };
  133471. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133472. _vq_quantthresh__44c7_s_p5_0,
  133473. _vq_quantmap__44c7_s_p5_0,
  133474. 3,
  133475. 3
  133476. };
  133477. static static_codebook _44c7_s_p5_0 = {
  133478. 4, 81,
  133479. _vq_lengthlist__44c7_s_p5_0,
  133480. 1, -529137664, 1618345984, 2, 0,
  133481. _vq_quantlist__44c7_s_p5_0,
  133482. NULL,
  133483. &_vq_auxt__44c7_s_p5_0,
  133484. NULL,
  133485. 0
  133486. };
  133487. static long _vq_quantlist__44c7_s_p5_1[] = {
  133488. 5,
  133489. 4,
  133490. 6,
  133491. 3,
  133492. 7,
  133493. 2,
  133494. 8,
  133495. 1,
  133496. 9,
  133497. 0,
  133498. 10,
  133499. };
  133500. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133501. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133502. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133503. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133504. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133505. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133506. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133507. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133508. 11,11,11, 7, 7, 8, 8, 8, 8,
  133509. };
  133510. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133511. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133512. 3.5, 4.5,
  133513. };
  133514. static long _vq_quantmap__44c7_s_p5_1[] = {
  133515. 9, 7, 5, 3, 1, 0, 2, 4,
  133516. 6, 8, 10,
  133517. };
  133518. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133519. _vq_quantthresh__44c7_s_p5_1,
  133520. _vq_quantmap__44c7_s_p5_1,
  133521. 11,
  133522. 11
  133523. };
  133524. static static_codebook _44c7_s_p5_1 = {
  133525. 2, 121,
  133526. _vq_lengthlist__44c7_s_p5_1,
  133527. 1, -531365888, 1611661312, 4, 0,
  133528. _vq_quantlist__44c7_s_p5_1,
  133529. NULL,
  133530. &_vq_auxt__44c7_s_p5_1,
  133531. NULL,
  133532. 0
  133533. };
  133534. static long _vq_quantlist__44c7_s_p6_0[] = {
  133535. 6,
  133536. 5,
  133537. 7,
  133538. 4,
  133539. 8,
  133540. 3,
  133541. 9,
  133542. 2,
  133543. 10,
  133544. 1,
  133545. 11,
  133546. 0,
  133547. 12,
  133548. };
  133549. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133550. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133551. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133552. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133553. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133554. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133555. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133560. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133561. };
  133562. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133563. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133564. 12.5, 17.5, 22.5, 27.5,
  133565. };
  133566. static long _vq_quantmap__44c7_s_p6_0[] = {
  133567. 11, 9, 7, 5, 3, 1, 0, 2,
  133568. 4, 6, 8, 10, 12,
  133569. };
  133570. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133571. _vq_quantthresh__44c7_s_p6_0,
  133572. _vq_quantmap__44c7_s_p6_0,
  133573. 13,
  133574. 13
  133575. };
  133576. static static_codebook _44c7_s_p6_0 = {
  133577. 2, 169,
  133578. _vq_lengthlist__44c7_s_p6_0,
  133579. 1, -526516224, 1616117760, 4, 0,
  133580. _vq_quantlist__44c7_s_p6_0,
  133581. NULL,
  133582. &_vq_auxt__44c7_s_p6_0,
  133583. NULL,
  133584. 0
  133585. };
  133586. static long _vq_quantlist__44c7_s_p6_1[] = {
  133587. 2,
  133588. 1,
  133589. 3,
  133590. 0,
  133591. 4,
  133592. };
  133593. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133594. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133595. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133596. };
  133597. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133598. -1.5, -0.5, 0.5, 1.5,
  133599. };
  133600. static long _vq_quantmap__44c7_s_p6_1[] = {
  133601. 3, 1, 0, 2, 4,
  133602. };
  133603. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133604. _vq_quantthresh__44c7_s_p6_1,
  133605. _vq_quantmap__44c7_s_p6_1,
  133606. 5,
  133607. 5
  133608. };
  133609. static static_codebook _44c7_s_p6_1 = {
  133610. 2, 25,
  133611. _vq_lengthlist__44c7_s_p6_1,
  133612. 1, -533725184, 1611661312, 3, 0,
  133613. _vq_quantlist__44c7_s_p6_1,
  133614. NULL,
  133615. &_vq_auxt__44c7_s_p6_1,
  133616. NULL,
  133617. 0
  133618. };
  133619. static long _vq_quantlist__44c7_s_p7_0[] = {
  133620. 6,
  133621. 5,
  133622. 7,
  133623. 4,
  133624. 8,
  133625. 3,
  133626. 9,
  133627. 2,
  133628. 10,
  133629. 1,
  133630. 11,
  133631. 0,
  133632. 12,
  133633. };
  133634. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133635. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133636. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133637. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133638. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133639. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133640. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133641. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133642. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133643. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133644. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133645. 19,13,13,13,13,14,14,15,15,
  133646. };
  133647. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133648. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133649. 27.5, 38.5, 49.5, 60.5,
  133650. };
  133651. static long _vq_quantmap__44c7_s_p7_0[] = {
  133652. 11, 9, 7, 5, 3, 1, 0, 2,
  133653. 4, 6, 8, 10, 12,
  133654. };
  133655. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133656. _vq_quantthresh__44c7_s_p7_0,
  133657. _vq_quantmap__44c7_s_p7_0,
  133658. 13,
  133659. 13
  133660. };
  133661. static static_codebook _44c7_s_p7_0 = {
  133662. 2, 169,
  133663. _vq_lengthlist__44c7_s_p7_0,
  133664. 1, -523206656, 1618345984, 4, 0,
  133665. _vq_quantlist__44c7_s_p7_0,
  133666. NULL,
  133667. &_vq_auxt__44c7_s_p7_0,
  133668. NULL,
  133669. 0
  133670. };
  133671. static long _vq_quantlist__44c7_s_p7_1[] = {
  133672. 5,
  133673. 4,
  133674. 6,
  133675. 3,
  133676. 7,
  133677. 2,
  133678. 8,
  133679. 1,
  133680. 9,
  133681. 0,
  133682. 10,
  133683. };
  133684. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133685. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133686. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133687. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133688. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133689. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133690. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133691. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133692. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133693. };
  133694. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133695. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133696. 3.5, 4.5,
  133697. };
  133698. static long _vq_quantmap__44c7_s_p7_1[] = {
  133699. 9, 7, 5, 3, 1, 0, 2, 4,
  133700. 6, 8, 10,
  133701. };
  133702. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133703. _vq_quantthresh__44c7_s_p7_1,
  133704. _vq_quantmap__44c7_s_p7_1,
  133705. 11,
  133706. 11
  133707. };
  133708. static static_codebook _44c7_s_p7_1 = {
  133709. 2, 121,
  133710. _vq_lengthlist__44c7_s_p7_1,
  133711. 1, -531365888, 1611661312, 4, 0,
  133712. _vq_quantlist__44c7_s_p7_1,
  133713. NULL,
  133714. &_vq_auxt__44c7_s_p7_1,
  133715. NULL,
  133716. 0
  133717. };
  133718. static long _vq_quantlist__44c7_s_p8_0[] = {
  133719. 7,
  133720. 6,
  133721. 8,
  133722. 5,
  133723. 9,
  133724. 4,
  133725. 10,
  133726. 3,
  133727. 11,
  133728. 2,
  133729. 12,
  133730. 1,
  133731. 13,
  133732. 0,
  133733. 14,
  133734. };
  133735. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133736. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133737. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133738. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133739. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133740. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133741. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133742. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133743. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133744. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133745. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133746. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133747. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133748. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133749. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133750. 14,
  133751. };
  133752. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133753. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133754. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133755. };
  133756. static long _vq_quantmap__44c7_s_p8_0[] = {
  133757. 13, 11, 9, 7, 5, 3, 1, 0,
  133758. 2, 4, 6, 8, 10, 12, 14,
  133759. };
  133760. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133761. _vq_quantthresh__44c7_s_p8_0,
  133762. _vq_quantmap__44c7_s_p8_0,
  133763. 15,
  133764. 15
  133765. };
  133766. static static_codebook _44c7_s_p8_0 = {
  133767. 2, 225,
  133768. _vq_lengthlist__44c7_s_p8_0,
  133769. 1, -520986624, 1620377600, 4, 0,
  133770. _vq_quantlist__44c7_s_p8_0,
  133771. NULL,
  133772. &_vq_auxt__44c7_s_p8_0,
  133773. NULL,
  133774. 0
  133775. };
  133776. static long _vq_quantlist__44c7_s_p8_1[] = {
  133777. 10,
  133778. 9,
  133779. 11,
  133780. 8,
  133781. 12,
  133782. 7,
  133783. 13,
  133784. 6,
  133785. 14,
  133786. 5,
  133787. 15,
  133788. 4,
  133789. 16,
  133790. 3,
  133791. 17,
  133792. 2,
  133793. 18,
  133794. 1,
  133795. 19,
  133796. 0,
  133797. 20,
  133798. };
  133799. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133800. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133801. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133802. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133803. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133804. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133805. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133806. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133807. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133808. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133809. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133810. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133811. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133812. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133813. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133814. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133815. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133816. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133817. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133818. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133819. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133820. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133821. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133822. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133823. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133824. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133825. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133826. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133827. 10,10,10,10,10,10,10,10,10,
  133828. };
  133829. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133830. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133831. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133832. 6.5, 7.5, 8.5, 9.5,
  133833. };
  133834. static long _vq_quantmap__44c7_s_p8_1[] = {
  133835. 19, 17, 15, 13, 11, 9, 7, 5,
  133836. 3, 1, 0, 2, 4, 6, 8, 10,
  133837. 12, 14, 16, 18, 20,
  133838. };
  133839. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133840. _vq_quantthresh__44c7_s_p8_1,
  133841. _vq_quantmap__44c7_s_p8_1,
  133842. 21,
  133843. 21
  133844. };
  133845. static static_codebook _44c7_s_p8_1 = {
  133846. 2, 441,
  133847. _vq_lengthlist__44c7_s_p8_1,
  133848. 1, -529268736, 1611661312, 5, 0,
  133849. _vq_quantlist__44c7_s_p8_1,
  133850. NULL,
  133851. &_vq_auxt__44c7_s_p8_1,
  133852. NULL,
  133853. 0
  133854. };
  133855. static long _vq_quantlist__44c7_s_p9_0[] = {
  133856. 6,
  133857. 5,
  133858. 7,
  133859. 4,
  133860. 8,
  133861. 3,
  133862. 9,
  133863. 2,
  133864. 10,
  133865. 1,
  133866. 11,
  133867. 0,
  133868. 12,
  133869. };
  133870. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133871. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133872. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133874. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133875. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133876. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133877. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133878. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133880. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133881. 11,11,11,11,11,11,11,11,11,
  133882. };
  133883. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133884. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133885. 1592.5, 2229.5, 2866.5, 3503.5,
  133886. };
  133887. static long _vq_quantmap__44c7_s_p9_0[] = {
  133888. 11, 9, 7, 5, 3, 1, 0, 2,
  133889. 4, 6, 8, 10, 12,
  133890. };
  133891. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133892. _vq_quantthresh__44c7_s_p9_0,
  133893. _vq_quantmap__44c7_s_p9_0,
  133894. 13,
  133895. 13
  133896. };
  133897. static static_codebook _44c7_s_p9_0 = {
  133898. 2, 169,
  133899. _vq_lengthlist__44c7_s_p9_0,
  133900. 1, -511845376, 1630791680, 4, 0,
  133901. _vq_quantlist__44c7_s_p9_0,
  133902. NULL,
  133903. &_vq_auxt__44c7_s_p9_0,
  133904. NULL,
  133905. 0
  133906. };
  133907. static long _vq_quantlist__44c7_s_p9_1[] = {
  133908. 6,
  133909. 5,
  133910. 7,
  133911. 4,
  133912. 8,
  133913. 3,
  133914. 9,
  133915. 2,
  133916. 10,
  133917. 1,
  133918. 11,
  133919. 0,
  133920. 12,
  133921. };
  133922. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133923. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133924. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133925. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133926. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133927. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133928. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133929. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133930. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133931. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133932. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133933. 15,11,11,10,10,12,12,12,12,
  133934. };
  133935. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133936. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133937. 122.5, 171.5, 220.5, 269.5,
  133938. };
  133939. static long _vq_quantmap__44c7_s_p9_1[] = {
  133940. 11, 9, 7, 5, 3, 1, 0, 2,
  133941. 4, 6, 8, 10, 12,
  133942. };
  133943. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133944. _vq_quantthresh__44c7_s_p9_1,
  133945. _vq_quantmap__44c7_s_p9_1,
  133946. 13,
  133947. 13
  133948. };
  133949. static static_codebook _44c7_s_p9_1 = {
  133950. 2, 169,
  133951. _vq_lengthlist__44c7_s_p9_1,
  133952. 1, -518889472, 1622704128, 4, 0,
  133953. _vq_quantlist__44c7_s_p9_1,
  133954. NULL,
  133955. &_vq_auxt__44c7_s_p9_1,
  133956. NULL,
  133957. 0
  133958. };
  133959. static long _vq_quantlist__44c7_s_p9_2[] = {
  133960. 24,
  133961. 23,
  133962. 25,
  133963. 22,
  133964. 26,
  133965. 21,
  133966. 27,
  133967. 20,
  133968. 28,
  133969. 19,
  133970. 29,
  133971. 18,
  133972. 30,
  133973. 17,
  133974. 31,
  133975. 16,
  133976. 32,
  133977. 15,
  133978. 33,
  133979. 14,
  133980. 34,
  133981. 13,
  133982. 35,
  133983. 12,
  133984. 36,
  133985. 11,
  133986. 37,
  133987. 10,
  133988. 38,
  133989. 9,
  133990. 39,
  133991. 8,
  133992. 40,
  133993. 7,
  133994. 41,
  133995. 6,
  133996. 42,
  133997. 5,
  133998. 43,
  133999. 4,
  134000. 44,
  134001. 3,
  134002. 45,
  134003. 2,
  134004. 46,
  134005. 1,
  134006. 47,
  134007. 0,
  134008. 48,
  134009. };
  134010. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134011. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134012. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134013. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134014. 7,
  134015. };
  134016. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134017. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134018. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134019. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134020. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134021. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134022. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134023. };
  134024. static long _vq_quantmap__44c7_s_p9_2[] = {
  134025. 47, 45, 43, 41, 39, 37, 35, 33,
  134026. 31, 29, 27, 25, 23, 21, 19, 17,
  134027. 15, 13, 11, 9, 7, 5, 3, 1,
  134028. 0, 2, 4, 6, 8, 10, 12, 14,
  134029. 16, 18, 20, 22, 24, 26, 28, 30,
  134030. 32, 34, 36, 38, 40, 42, 44, 46,
  134031. 48,
  134032. };
  134033. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134034. _vq_quantthresh__44c7_s_p9_2,
  134035. _vq_quantmap__44c7_s_p9_2,
  134036. 49,
  134037. 49
  134038. };
  134039. static static_codebook _44c7_s_p9_2 = {
  134040. 1, 49,
  134041. _vq_lengthlist__44c7_s_p9_2,
  134042. 1, -526909440, 1611661312, 6, 0,
  134043. _vq_quantlist__44c7_s_p9_2,
  134044. NULL,
  134045. &_vq_auxt__44c7_s_p9_2,
  134046. NULL,
  134047. 0
  134048. };
  134049. static long _huff_lengthlist__44c7_s_short[] = {
  134050. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134051. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134052. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134053. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134054. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134055. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134056. 10, 9,11,14,
  134057. };
  134058. static static_codebook _huff_book__44c7_s_short = {
  134059. 2, 100,
  134060. _huff_lengthlist__44c7_s_short,
  134061. 0, 0, 0, 0, 0,
  134062. NULL,
  134063. NULL,
  134064. NULL,
  134065. NULL,
  134066. 0
  134067. };
  134068. static long _huff_lengthlist__44c8_s_long[] = {
  134069. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134070. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134071. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134072. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134073. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134074. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134075. 11, 9, 9,10,
  134076. };
  134077. static static_codebook _huff_book__44c8_s_long = {
  134078. 2, 100,
  134079. _huff_lengthlist__44c8_s_long,
  134080. 0, 0, 0, 0, 0,
  134081. NULL,
  134082. NULL,
  134083. NULL,
  134084. NULL,
  134085. 0
  134086. };
  134087. static long _vq_quantlist__44c8_s_p1_0[] = {
  134088. 1,
  134089. 0,
  134090. 2,
  134091. };
  134092. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134093. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134094. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134095. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134096. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134097. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134098. 8,
  134099. };
  134100. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134101. -0.5, 0.5,
  134102. };
  134103. static long _vq_quantmap__44c8_s_p1_0[] = {
  134104. 1, 0, 2,
  134105. };
  134106. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134107. _vq_quantthresh__44c8_s_p1_0,
  134108. _vq_quantmap__44c8_s_p1_0,
  134109. 3,
  134110. 3
  134111. };
  134112. static static_codebook _44c8_s_p1_0 = {
  134113. 4, 81,
  134114. _vq_lengthlist__44c8_s_p1_0,
  134115. 1, -535822336, 1611661312, 2, 0,
  134116. _vq_quantlist__44c8_s_p1_0,
  134117. NULL,
  134118. &_vq_auxt__44c8_s_p1_0,
  134119. NULL,
  134120. 0
  134121. };
  134122. static long _vq_quantlist__44c8_s_p2_0[] = {
  134123. 2,
  134124. 1,
  134125. 3,
  134126. 0,
  134127. 4,
  134128. };
  134129. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134130. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134131. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134132. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134133. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134134. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134135. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134136. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134137. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134139. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134140. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134141. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134142. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134143. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134144. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134145. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134147. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134148. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134149. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134150. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134151. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134152. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134153. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134155. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134156. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134157. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134158. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134159. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134160. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134161. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134166. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134167. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134168. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134169. 13,
  134170. };
  134171. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134172. -1.5, -0.5, 0.5, 1.5,
  134173. };
  134174. static long _vq_quantmap__44c8_s_p2_0[] = {
  134175. 3, 1, 0, 2, 4,
  134176. };
  134177. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134178. _vq_quantthresh__44c8_s_p2_0,
  134179. _vq_quantmap__44c8_s_p2_0,
  134180. 5,
  134181. 5
  134182. };
  134183. static static_codebook _44c8_s_p2_0 = {
  134184. 4, 625,
  134185. _vq_lengthlist__44c8_s_p2_0,
  134186. 1, -533725184, 1611661312, 3, 0,
  134187. _vq_quantlist__44c8_s_p2_0,
  134188. NULL,
  134189. &_vq_auxt__44c8_s_p2_0,
  134190. NULL,
  134191. 0
  134192. };
  134193. static long _vq_quantlist__44c8_s_p3_0[] = {
  134194. 4,
  134195. 3,
  134196. 5,
  134197. 2,
  134198. 6,
  134199. 1,
  134200. 7,
  134201. 0,
  134202. 8,
  134203. };
  134204. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134205. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134206. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134207. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134208. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134210. 0,
  134211. };
  134212. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134213. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134214. };
  134215. static long _vq_quantmap__44c8_s_p3_0[] = {
  134216. 7, 5, 3, 1, 0, 2, 4, 6,
  134217. 8,
  134218. };
  134219. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134220. _vq_quantthresh__44c8_s_p3_0,
  134221. _vq_quantmap__44c8_s_p3_0,
  134222. 9,
  134223. 9
  134224. };
  134225. static static_codebook _44c8_s_p3_0 = {
  134226. 2, 81,
  134227. _vq_lengthlist__44c8_s_p3_0,
  134228. 1, -531628032, 1611661312, 4, 0,
  134229. _vq_quantlist__44c8_s_p3_0,
  134230. NULL,
  134231. &_vq_auxt__44c8_s_p3_0,
  134232. NULL,
  134233. 0
  134234. };
  134235. static long _vq_quantlist__44c8_s_p4_0[] = {
  134236. 8,
  134237. 7,
  134238. 9,
  134239. 6,
  134240. 10,
  134241. 5,
  134242. 11,
  134243. 4,
  134244. 12,
  134245. 3,
  134246. 13,
  134247. 2,
  134248. 14,
  134249. 1,
  134250. 15,
  134251. 0,
  134252. 16,
  134253. };
  134254. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134255. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134256. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134257. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134258. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134259. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134260. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134261. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134262. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134263. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134264. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134273. 0,
  134274. };
  134275. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134276. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134277. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134278. };
  134279. static long _vq_quantmap__44c8_s_p4_0[] = {
  134280. 15, 13, 11, 9, 7, 5, 3, 1,
  134281. 0, 2, 4, 6, 8, 10, 12, 14,
  134282. 16,
  134283. };
  134284. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134285. _vq_quantthresh__44c8_s_p4_0,
  134286. _vq_quantmap__44c8_s_p4_0,
  134287. 17,
  134288. 17
  134289. };
  134290. static static_codebook _44c8_s_p4_0 = {
  134291. 2, 289,
  134292. _vq_lengthlist__44c8_s_p4_0,
  134293. 1, -529530880, 1611661312, 5, 0,
  134294. _vq_quantlist__44c8_s_p4_0,
  134295. NULL,
  134296. &_vq_auxt__44c8_s_p4_0,
  134297. NULL,
  134298. 0
  134299. };
  134300. static long _vq_quantlist__44c8_s_p5_0[] = {
  134301. 1,
  134302. 0,
  134303. 2,
  134304. };
  134305. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134306. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134307. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134308. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134309. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134310. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134311. 12,
  134312. };
  134313. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134314. -5.5, 5.5,
  134315. };
  134316. static long _vq_quantmap__44c8_s_p5_0[] = {
  134317. 1, 0, 2,
  134318. };
  134319. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134320. _vq_quantthresh__44c8_s_p5_0,
  134321. _vq_quantmap__44c8_s_p5_0,
  134322. 3,
  134323. 3
  134324. };
  134325. static static_codebook _44c8_s_p5_0 = {
  134326. 4, 81,
  134327. _vq_lengthlist__44c8_s_p5_0,
  134328. 1, -529137664, 1618345984, 2, 0,
  134329. _vq_quantlist__44c8_s_p5_0,
  134330. NULL,
  134331. &_vq_auxt__44c8_s_p5_0,
  134332. NULL,
  134333. 0
  134334. };
  134335. static long _vq_quantlist__44c8_s_p5_1[] = {
  134336. 5,
  134337. 4,
  134338. 6,
  134339. 3,
  134340. 7,
  134341. 2,
  134342. 8,
  134343. 1,
  134344. 9,
  134345. 0,
  134346. 10,
  134347. };
  134348. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134349. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134350. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134351. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134352. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134353. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134354. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134355. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134356. 11,11,11, 7, 7, 7, 7, 8, 8,
  134357. };
  134358. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134359. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134360. 3.5, 4.5,
  134361. };
  134362. static long _vq_quantmap__44c8_s_p5_1[] = {
  134363. 9, 7, 5, 3, 1, 0, 2, 4,
  134364. 6, 8, 10,
  134365. };
  134366. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134367. _vq_quantthresh__44c8_s_p5_1,
  134368. _vq_quantmap__44c8_s_p5_1,
  134369. 11,
  134370. 11
  134371. };
  134372. static static_codebook _44c8_s_p5_1 = {
  134373. 2, 121,
  134374. _vq_lengthlist__44c8_s_p5_1,
  134375. 1, -531365888, 1611661312, 4, 0,
  134376. _vq_quantlist__44c8_s_p5_1,
  134377. NULL,
  134378. &_vq_auxt__44c8_s_p5_1,
  134379. NULL,
  134380. 0
  134381. };
  134382. static long _vq_quantlist__44c8_s_p6_0[] = {
  134383. 6,
  134384. 5,
  134385. 7,
  134386. 4,
  134387. 8,
  134388. 3,
  134389. 9,
  134390. 2,
  134391. 10,
  134392. 1,
  134393. 11,
  134394. 0,
  134395. 12,
  134396. };
  134397. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134398. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134399. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134400. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134401. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134402. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134403. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134408. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134409. };
  134410. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134411. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134412. 12.5, 17.5, 22.5, 27.5,
  134413. };
  134414. static long _vq_quantmap__44c8_s_p6_0[] = {
  134415. 11, 9, 7, 5, 3, 1, 0, 2,
  134416. 4, 6, 8, 10, 12,
  134417. };
  134418. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134419. _vq_quantthresh__44c8_s_p6_0,
  134420. _vq_quantmap__44c8_s_p6_0,
  134421. 13,
  134422. 13
  134423. };
  134424. static static_codebook _44c8_s_p6_0 = {
  134425. 2, 169,
  134426. _vq_lengthlist__44c8_s_p6_0,
  134427. 1, -526516224, 1616117760, 4, 0,
  134428. _vq_quantlist__44c8_s_p6_0,
  134429. NULL,
  134430. &_vq_auxt__44c8_s_p6_0,
  134431. NULL,
  134432. 0
  134433. };
  134434. static long _vq_quantlist__44c8_s_p6_1[] = {
  134435. 2,
  134436. 1,
  134437. 3,
  134438. 0,
  134439. 4,
  134440. };
  134441. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134442. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134443. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134444. };
  134445. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134446. -1.5, -0.5, 0.5, 1.5,
  134447. };
  134448. static long _vq_quantmap__44c8_s_p6_1[] = {
  134449. 3, 1, 0, 2, 4,
  134450. };
  134451. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134452. _vq_quantthresh__44c8_s_p6_1,
  134453. _vq_quantmap__44c8_s_p6_1,
  134454. 5,
  134455. 5
  134456. };
  134457. static static_codebook _44c8_s_p6_1 = {
  134458. 2, 25,
  134459. _vq_lengthlist__44c8_s_p6_1,
  134460. 1, -533725184, 1611661312, 3, 0,
  134461. _vq_quantlist__44c8_s_p6_1,
  134462. NULL,
  134463. &_vq_auxt__44c8_s_p6_1,
  134464. NULL,
  134465. 0
  134466. };
  134467. static long _vq_quantlist__44c8_s_p7_0[] = {
  134468. 6,
  134469. 5,
  134470. 7,
  134471. 4,
  134472. 8,
  134473. 3,
  134474. 9,
  134475. 2,
  134476. 10,
  134477. 1,
  134478. 11,
  134479. 0,
  134480. 12,
  134481. };
  134482. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134483. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134484. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134485. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134486. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134487. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134488. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134489. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134490. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134491. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134492. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134493. 20,13,13,13,13,14,13,15,15,
  134494. };
  134495. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134496. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134497. 27.5, 38.5, 49.5, 60.5,
  134498. };
  134499. static long _vq_quantmap__44c8_s_p7_0[] = {
  134500. 11, 9, 7, 5, 3, 1, 0, 2,
  134501. 4, 6, 8, 10, 12,
  134502. };
  134503. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134504. _vq_quantthresh__44c8_s_p7_0,
  134505. _vq_quantmap__44c8_s_p7_0,
  134506. 13,
  134507. 13
  134508. };
  134509. static static_codebook _44c8_s_p7_0 = {
  134510. 2, 169,
  134511. _vq_lengthlist__44c8_s_p7_0,
  134512. 1, -523206656, 1618345984, 4, 0,
  134513. _vq_quantlist__44c8_s_p7_0,
  134514. NULL,
  134515. &_vq_auxt__44c8_s_p7_0,
  134516. NULL,
  134517. 0
  134518. };
  134519. static long _vq_quantlist__44c8_s_p7_1[] = {
  134520. 5,
  134521. 4,
  134522. 6,
  134523. 3,
  134524. 7,
  134525. 2,
  134526. 8,
  134527. 1,
  134528. 9,
  134529. 0,
  134530. 10,
  134531. };
  134532. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134533. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134534. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134535. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134536. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134537. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134538. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134539. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134540. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134541. };
  134542. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134543. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134544. 3.5, 4.5,
  134545. };
  134546. static long _vq_quantmap__44c8_s_p7_1[] = {
  134547. 9, 7, 5, 3, 1, 0, 2, 4,
  134548. 6, 8, 10,
  134549. };
  134550. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134551. _vq_quantthresh__44c8_s_p7_1,
  134552. _vq_quantmap__44c8_s_p7_1,
  134553. 11,
  134554. 11
  134555. };
  134556. static static_codebook _44c8_s_p7_1 = {
  134557. 2, 121,
  134558. _vq_lengthlist__44c8_s_p7_1,
  134559. 1, -531365888, 1611661312, 4, 0,
  134560. _vq_quantlist__44c8_s_p7_1,
  134561. NULL,
  134562. &_vq_auxt__44c8_s_p7_1,
  134563. NULL,
  134564. 0
  134565. };
  134566. static long _vq_quantlist__44c8_s_p8_0[] = {
  134567. 7,
  134568. 6,
  134569. 8,
  134570. 5,
  134571. 9,
  134572. 4,
  134573. 10,
  134574. 3,
  134575. 11,
  134576. 2,
  134577. 12,
  134578. 1,
  134579. 13,
  134580. 0,
  134581. 14,
  134582. };
  134583. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134584. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134585. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134586. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134587. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134588. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134589. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134590. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134591. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134592. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134593. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134594. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134595. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134596. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134597. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134598. 15,
  134599. };
  134600. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134601. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134602. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134603. };
  134604. static long _vq_quantmap__44c8_s_p8_0[] = {
  134605. 13, 11, 9, 7, 5, 3, 1, 0,
  134606. 2, 4, 6, 8, 10, 12, 14,
  134607. };
  134608. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134609. _vq_quantthresh__44c8_s_p8_0,
  134610. _vq_quantmap__44c8_s_p8_0,
  134611. 15,
  134612. 15
  134613. };
  134614. static static_codebook _44c8_s_p8_0 = {
  134615. 2, 225,
  134616. _vq_lengthlist__44c8_s_p8_0,
  134617. 1, -520986624, 1620377600, 4, 0,
  134618. _vq_quantlist__44c8_s_p8_0,
  134619. NULL,
  134620. &_vq_auxt__44c8_s_p8_0,
  134621. NULL,
  134622. 0
  134623. };
  134624. static long _vq_quantlist__44c8_s_p8_1[] = {
  134625. 10,
  134626. 9,
  134627. 11,
  134628. 8,
  134629. 12,
  134630. 7,
  134631. 13,
  134632. 6,
  134633. 14,
  134634. 5,
  134635. 15,
  134636. 4,
  134637. 16,
  134638. 3,
  134639. 17,
  134640. 2,
  134641. 18,
  134642. 1,
  134643. 19,
  134644. 0,
  134645. 20,
  134646. };
  134647. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134648. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134649. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134650. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134651. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134652. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134653. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134654. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134655. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134656. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134657. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134658. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134659. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134660. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134661. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134662. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134663. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134664. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134665. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134666. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134667. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134668. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134669. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134670. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134671. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134672. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134673. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134674. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134675. 10, 9, 9,10,10, 9,10, 9, 9,
  134676. };
  134677. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134678. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134679. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134680. 6.5, 7.5, 8.5, 9.5,
  134681. };
  134682. static long _vq_quantmap__44c8_s_p8_1[] = {
  134683. 19, 17, 15, 13, 11, 9, 7, 5,
  134684. 3, 1, 0, 2, 4, 6, 8, 10,
  134685. 12, 14, 16, 18, 20,
  134686. };
  134687. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134688. _vq_quantthresh__44c8_s_p8_1,
  134689. _vq_quantmap__44c8_s_p8_1,
  134690. 21,
  134691. 21
  134692. };
  134693. static static_codebook _44c8_s_p8_1 = {
  134694. 2, 441,
  134695. _vq_lengthlist__44c8_s_p8_1,
  134696. 1, -529268736, 1611661312, 5, 0,
  134697. _vq_quantlist__44c8_s_p8_1,
  134698. NULL,
  134699. &_vq_auxt__44c8_s_p8_1,
  134700. NULL,
  134701. 0
  134702. };
  134703. static long _vq_quantlist__44c8_s_p9_0[] = {
  134704. 8,
  134705. 7,
  134706. 9,
  134707. 6,
  134708. 10,
  134709. 5,
  134710. 11,
  134711. 4,
  134712. 12,
  134713. 3,
  134714. 13,
  134715. 2,
  134716. 14,
  134717. 1,
  134718. 15,
  134719. 0,
  134720. 16,
  134721. };
  134722. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134723. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134724. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134725. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134733. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134737. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134738. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134739. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134740. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134741. 10,
  134742. };
  134743. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134744. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134745. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134746. };
  134747. static long _vq_quantmap__44c8_s_p9_0[] = {
  134748. 15, 13, 11, 9, 7, 5, 3, 1,
  134749. 0, 2, 4, 6, 8, 10, 12, 14,
  134750. 16,
  134751. };
  134752. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134753. _vq_quantthresh__44c8_s_p9_0,
  134754. _vq_quantmap__44c8_s_p9_0,
  134755. 17,
  134756. 17
  134757. };
  134758. static static_codebook _44c8_s_p9_0 = {
  134759. 2, 289,
  134760. _vq_lengthlist__44c8_s_p9_0,
  134761. 1, -509798400, 1631393792, 5, 0,
  134762. _vq_quantlist__44c8_s_p9_0,
  134763. NULL,
  134764. &_vq_auxt__44c8_s_p9_0,
  134765. NULL,
  134766. 0
  134767. };
  134768. static long _vq_quantlist__44c8_s_p9_1[] = {
  134769. 9,
  134770. 8,
  134771. 10,
  134772. 7,
  134773. 11,
  134774. 6,
  134775. 12,
  134776. 5,
  134777. 13,
  134778. 4,
  134779. 14,
  134780. 3,
  134781. 15,
  134782. 2,
  134783. 16,
  134784. 1,
  134785. 17,
  134786. 0,
  134787. 18,
  134788. };
  134789. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134790. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134791. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134792. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134793. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134794. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134795. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134796. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134797. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134798. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134799. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134800. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134801. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134802. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134803. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134804. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134805. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134806. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134807. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134808. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134809. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134810. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134811. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134812. 14,13,13,14,14,15,14,15,14,
  134813. };
  134814. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134815. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134816. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134817. 367.5, 416.5,
  134818. };
  134819. static long _vq_quantmap__44c8_s_p9_1[] = {
  134820. 17, 15, 13, 11, 9, 7, 5, 3,
  134821. 1, 0, 2, 4, 6, 8, 10, 12,
  134822. 14, 16, 18,
  134823. };
  134824. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134825. _vq_quantthresh__44c8_s_p9_1,
  134826. _vq_quantmap__44c8_s_p9_1,
  134827. 19,
  134828. 19
  134829. };
  134830. static static_codebook _44c8_s_p9_1 = {
  134831. 2, 361,
  134832. _vq_lengthlist__44c8_s_p9_1,
  134833. 1, -518287360, 1622704128, 5, 0,
  134834. _vq_quantlist__44c8_s_p9_1,
  134835. NULL,
  134836. &_vq_auxt__44c8_s_p9_1,
  134837. NULL,
  134838. 0
  134839. };
  134840. static long _vq_quantlist__44c8_s_p9_2[] = {
  134841. 24,
  134842. 23,
  134843. 25,
  134844. 22,
  134845. 26,
  134846. 21,
  134847. 27,
  134848. 20,
  134849. 28,
  134850. 19,
  134851. 29,
  134852. 18,
  134853. 30,
  134854. 17,
  134855. 31,
  134856. 16,
  134857. 32,
  134858. 15,
  134859. 33,
  134860. 14,
  134861. 34,
  134862. 13,
  134863. 35,
  134864. 12,
  134865. 36,
  134866. 11,
  134867. 37,
  134868. 10,
  134869. 38,
  134870. 9,
  134871. 39,
  134872. 8,
  134873. 40,
  134874. 7,
  134875. 41,
  134876. 6,
  134877. 42,
  134878. 5,
  134879. 43,
  134880. 4,
  134881. 44,
  134882. 3,
  134883. 45,
  134884. 2,
  134885. 46,
  134886. 1,
  134887. 47,
  134888. 0,
  134889. 48,
  134890. };
  134891. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134892. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134893. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134894. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134895. 7,
  134896. };
  134897. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134898. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134899. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134900. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134901. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134902. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134903. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134904. };
  134905. static long _vq_quantmap__44c8_s_p9_2[] = {
  134906. 47, 45, 43, 41, 39, 37, 35, 33,
  134907. 31, 29, 27, 25, 23, 21, 19, 17,
  134908. 15, 13, 11, 9, 7, 5, 3, 1,
  134909. 0, 2, 4, 6, 8, 10, 12, 14,
  134910. 16, 18, 20, 22, 24, 26, 28, 30,
  134911. 32, 34, 36, 38, 40, 42, 44, 46,
  134912. 48,
  134913. };
  134914. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134915. _vq_quantthresh__44c8_s_p9_2,
  134916. _vq_quantmap__44c8_s_p9_2,
  134917. 49,
  134918. 49
  134919. };
  134920. static static_codebook _44c8_s_p9_2 = {
  134921. 1, 49,
  134922. _vq_lengthlist__44c8_s_p9_2,
  134923. 1, -526909440, 1611661312, 6, 0,
  134924. _vq_quantlist__44c8_s_p9_2,
  134925. NULL,
  134926. &_vq_auxt__44c8_s_p9_2,
  134927. NULL,
  134928. 0
  134929. };
  134930. static long _huff_lengthlist__44c8_s_short[] = {
  134931. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134932. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134933. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134934. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134935. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134936. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134937. 10, 9,11,14,
  134938. };
  134939. static static_codebook _huff_book__44c8_s_short = {
  134940. 2, 100,
  134941. _huff_lengthlist__44c8_s_short,
  134942. 0, 0, 0, 0, 0,
  134943. NULL,
  134944. NULL,
  134945. NULL,
  134946. NULL,
  134947. 0
  134948. };
  134949. static long _huff_lengthlist__44c9_s_long[] = {
  134950. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134951. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134952. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134953. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134954. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134955. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134956. 10, 9, 8, 9,
  134957. };
  134958. static static_codebook _huff_book__44c9_s_long = {
  134959. 2, 100,
  134960. _huff_lengthlist__44c9_s_long,
  134961. 0, 0, 0, 0, 0,
  134962. NULL,
  134963. NULL,
  134964. NULL,
  134965. NULL,
  134966. 0
  134967. };
  134968. static long _vq_quantlist__44c9_s_p1_0[] = {
  134969. 1,
  134970. 0,
  134971. 2,
  134972. };
  134973. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134974. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134975. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134976. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134977. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134978. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134979. 7,
  134980. };
  134981. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134982. -0.5, 0.5,
  134983. };
  134984. static long _vq_quantmap__44c9_s_p1_0[] = {
  134985. 1, 0, 2,
  134986. };
  134987. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134988. _vq_quantthresh__44c9_s_p1_0,
  134989. _vq_quantmap__44c9_s_p1_0,
  134990. 3,
  134991. 3
  134992. };
  134993. static static_codebook _44c9_s_p1_0 = {
  134994. 4, 81,
  134995. _vq_lengthlist__44c9_s_p1_0,
  134996. 1, -535822336, 1611661312, 2, 0,
  134997. _vq_quantlist__44c9_s_p1_0,
  134998. NULL,
  134999. &_vq_auxt__44c9_s_p1_0,
  135000. NULL,
  135001. 0
  135002. };
  135003. static long _vq_quantlist__44c9_s_p2_0[] = {
  135004. 2,
  135005. 1,
  135006. 3,
  135007. 0,
  135008. 4,
  135009. };
  135010. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135011. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135012. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135013. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135014. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135015. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135016. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135017. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135018. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  135019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135020. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135021. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135022. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135023. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135024. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135025. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135026. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  135027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135028. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135029. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135030. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135031. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135032. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135033. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135034. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135036. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135037. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135038. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135039. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135040. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135041. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135042. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135047. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135048. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135049. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135050. 12,
  135051. };
  135052. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135053. -1.5, -0.5, 0.5, 1.5,
  135054. };
  135055. static long _vq_quantmap__44c9_s_p2_0[] = {
  135056. 3, 1, 0, 2, 4,
  135057. };
  135058. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135059. _vq_quantthresh__44c9_s_p2_0,
  135060. _vq_quantmap__44c9_s_p2_0,
  135061. 5,
  135062. 5
  135063. };
  135064. static static_codebook _44c9_s_p2_0 = {
  135065. 4, 625,
  135066. _vq_lengthlist__44c9_s_p2_0,
  135067. 1, -533725184, 1611661312, 3, 0,
  135068. _vq_quantlist__44c9_s_p2_0,
  135069. NULL,
  135070. &_vq_auxt__44c9_s_p2_0,
  135071. NULL,
  135072. 0
  135073. };
  135074. static long _vq_quantlist__44c9_s_p3_0[] = {
  135075. 4,
  135076. 3,
  135077. 5,
  135078. 2,
  135079. 6,
  135080. 1,
  135081. 7,
  135082. 0,
  135083. 8,
  135084. };
  135085. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135086. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135087. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135088. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135089. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135091. 0,
  135092. };
  135093. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135094. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135095. };
  135096. static long _vq_quantmap__44c9_s_p3_0[] = {
  135097. 7, 5, 3, 1, 0, 2, 4, 6,
  135098. 8,
  135099. };
  135100. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135101. _vq_quantthresh__44c9_s_p3_0,
  135102. _vq_quantmap__44c9_s_p3_0,
  135103. 9,
  135104. 9
  135105. };
  135106. static static_codebook _44c9_s_p3_0 = {
  135107. 2, 81,
  135108. _vq_lengthlist__44c9_s_p3_0,
  135109. 1, -531628032, 1611661312, 4, 0,
  135110. _vq_quantlist__44c9_s_p3_0,
  135111. NULL,
  135112. &_vq_auxt__44c9_s_p3_0,
  135113. NULL,
  135114. 0
  135115. };
  135116. static long _vq_quantlist__44c9_s_p4_0[] = {
  135117. 8,
  135118. 7,
  135119. 9,
  135120. 6,
  135121. 10,
  135122. 5,
  135123. 11,
  135124. 4,
  135125. 12,
  135126. 3,
  135127. 13,
  135128. 2,
  135129. 14,
  135130. 1,
  135131. 15,
  135132. 0,
  135133. 16,
  135134. };
  135135. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135136. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135137. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135138. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135139. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135140. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135141. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135142. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135143. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135144. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135145. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135154. 0,
  135155. };
  135156. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135157. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135158. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135159. };
  135160. static long _vq_quantmap__44c9_s_p4_0[] = {
  135161. 15, 13, 11, 9, 7, 5, 3, 1,
  135162. 0, 2, 4, 6, 8, 10, 12, 14,
  135163. 16,
  135164. };
  135165. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135166. _vq_quantthresh__44c9_s_p4_0,
  135167. _vq_quantmap__44c9_s_p4_0,
  135168. 17,
  135169. 17
  135170. };
  135171. static static_codebook _44c9_s_p4_0 = {
  135172. 2, 289,
  135173. _vq_lengthlist__44c9_s_p4_0,
  135174. 1, -529530880, 1611661312, 5, 0,
  135175. _vq_quantlist__44c9_s_p4_0,
  135176. NULL,
  135177. &_vq_auxt__44c9_s_p4_0,
  135178. NULL,
  135179. 0
  135180. };
  135181. static long _vq_quantlist__44c9_s_p5_0[] = {
  135182. 1,
  135183. 0,
  135184. 2,
  135185. };
  135186. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135187. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135188. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135189. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135190. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135191. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135192. 12,
  135193. };
  135194. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135195. -5.5, 5.5,
  135196. };
  135197. static long _vq_quantmap__44c9_s_p5_0[] = {
  135198. 1, 0, 2,
  135199. };
  135200. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135201. _vq_quantthresh__44c9_s_p5_0,
  135202. _vq_quantmap__44c9_s_p5_0,
  135203. 3,
  135204. 3
  135205. };
  135206. static static_codebook _44c9_s_p5_0 = {
  135207. 4, 81,
  135208. _vq_lengthlist__44c9_s_p5_0,
  135209. 1, -529137664, 1618345984, 2, 0,
  135210. _vq_quantlist__44c9_s_p5_0,
  135211. NULL,
  135212. &_vq_auxt__44c9_s_p5_0,
  135213. NULL,
  135214. 0
  135215. };
  135216. static long _vq_quantlist__44c9_s_p5_1[] = {
  135217. 5,
  135218. 4,
  135219. 6,
  135220. 3,
  135221. 7,
  135222. 2,
  135223. 8,
  135224. 1,
  135225. 9,
  135226. 0,
  135227. 10,
  135228. };
  135229. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135230. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135231. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135232. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135233. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135234. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135235. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135236. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135237. 11,11,11, 7, 7, 7, 7, 7, 7,
  135238. };
  135239. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135240. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135241. 3.5, 4.5,
  135242. };
  135243. static long _vq_quantmap__44c9_s_p5_1[] = {
  135244. 9, 7, 5, 3, 1, 0, 2, 4,
  135245. 6, 8, 10,
  135246. };
  135247. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135248. _vq_quantthresh__44c9_s_p5_1,
  135249. _vq_quantmap__44c9_s_p5_1,
  135250. 11,
  135251. 11
  135252. };
  135253. static static_codebook _44c9_s_p5_1 = {
  135254. 2, 121,
  135255. _vq_lengthlist__44c9_s_p5_1,
  135256. 1, -531365888, 1611661312, 4, 0,
  135257. _vq_quantlist__44c9_s_p5_1,
  135258. NULL,
  135259. &_vq_auxt__44c9_s_p5_1,
  135260. NULL,
  135261. 0
  135262. };
  135263. static long _vq_quantlist__44c9_s_p6_0[] = {
  135264. 6,
  135265. 5,
  135266. 7,
  135267. 4,
  135268. 8,
  135269. 3,
  135270. 9,
  135271. 2,
  135272. 10,
  135273. 1,
  135274. 11,
  135275. 0,
  135276. 12,
  135277. };
  135278. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135279. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135280. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135281. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135282. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135283. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135284. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135289. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135290. };
  135291. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135292. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135293. 12.5, 17.5, 22.5, 27.5,
  135294. };
  135295. static long _vq_quantmap__44c9_s_p6_0[] = {
  135296. 11, 9, 7, 5, 3, 1, 0, 2,
  135297. 4, 6, 8, 10, 12,
  135298. };
  135299. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135300. _vq_quantthresh__44c9_s_p6_0,
  135301. _vq_quantmap__44c9_s_p6_0,
  135302. 13,
  135303. 13
  135304. };
  135305. static static_codebook _44c9_s_p6_0 = {
  135306. 2, 169,
  135307. _vq_lengthlist__44c9_s_p6_0,
  135308. 1, -526516224, 1616117760, 4, 0,
  135309. _vq_quantlist__44c9_s_p6_0,
  135310. NULL,
  135311. &_vq_auxt__44c9_s_p6_0,
  135312. NULL,
  135313. 0
  135314. };
  135315. static long _vq_quantlist__44c9_s_p6_1[] = {
  135316. 2,
  135317. 1,
  135318. 3,
  135319. 0,
  135320. 4,
  135321. };
  135322. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135323. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135324. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135325. };
  135326. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135327. -1.5, -0.5, 0.5, 1.5,
  135328. };
  135329. static long _vq_quantmap__44c9_s_p6_1[] = {
  135330. 3, 1, 0, 2, 4,
  135331. };
  135332. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135333. _vq_quantthresh__44c9_s_p6_1,
  135334. _vq_quantmap__44c9_s_p6_1,
  135335. 5,
  135336. 5
  135337. };
  135338. static static_codebook _44c9_s_p6_1 = {
  135339. 2, 25,
  135340. _vq_lengthlist__44c9_s_p6_1,
  135341. 1, -533725184, 1611661312, 3, 0,
  135342. _vq_quantlist__44c9_s_p6_1,
  135343. NULL,
  135344. &_vq_auxt__44c9_s_p6_1,
  135345. NULL,
  135346. 0
  135347. };
  135348. static long _vq_quantlist__44c9_s_p7_0[] = {
  135349. 6,
  135350. 5,
  135351. 7,
  135352. 4,
  135353. 8,
  135354. 3,
  135355. 9,
  135356. 2,
  135357. 10,
  135358. 1,
  135359. 11,
  135360. 0,
  135361. 12,
  135362. };
  135363. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135364. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135365. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135366. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135367. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135368. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135369. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135370. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135371. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135372. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135373. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135374. 19,12,12,12,12,13,13,14,14,
  135375. };
  135376. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135377. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135378. 27.5, 38.5, 49.5, 60.5,
  135379. };
  135380. static long _vq_quantmap__44c9_s_p7_0[] = {
  135381. 11, 9, 7, 5, 3, 1, 0, 2,
  135382. 4, 6, 8, 10, 12,
  135383. };
  135384. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135385. _vq_quantthresh__44c9_s_p7_0,
  135386. _vq_quantmap__44c9_s_p7_0,
  135387. 13,
  135388. 13
  135389. };
  135390. static static_codebook _44c9_s_p7_0 = {
  135391. 2, 169,
  135392. _vq_lengthlist__44c9_s_p7_0,
  135393. 1, -523206656, 1618345984, 4, 0,
  135394. _vq_quantlist__44c9_s_p7_0,
  135395. NULL,
  135396. &_vq_auxt__44c9_s_p7_0,
  135397. NULL,
  135398. 0
  135399. };
  135400. static long _vq_quantlist__44c9_s_p7_1[] = {
  135401. 5,
  135402. 4,
  135403. 6,
  135404. 3,
  135405. 7,
  135406. 2,
  135407. 8,
  135408. 1,
  135409. 9,
  135410. 0,
  135411. 10,
  135412. };
  135413. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135414. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135415. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135416. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135417. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135418. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135419. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135420. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135421. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135422. };
  135423. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135424. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135425. 3.5, 4.5,
  135426. };
  135427. static long _vq_quantmap__44c9_s_p7_1[] = {
  135428. 9, 7, 5, 3, 1, 0, 2, 4,
  135429. 6, 8, 10,
  135430. };
  135431. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135432. _vq_quantthresh__44c9_s_p7_1,
  135433. _vq_quantmap__44c9_s_p7_1,
  135434. 11,
  135435. 11
  135436. };
  135437. static static_codebook _44c9_s_p7_1 = {
  135438. 2, 121,
  135439. _vq_lengthlist__44c9_s_p7_1,
  135440. 1, -531365888, 1611661312, 4, 0,
  135441. _vq_quantlist__44c9_s_p7_1,
  135442. NULL,
  135443. &_vq_auxt__44c9_s_p7_1,
  135444. NULL,
  135445. 0
  135446. };
  135447. static long _vq_quantlist__44c9_s_p8_0[] = {
  135448. 7,
  135449. 6,
  135450. 8,
  135451. 5,
  135452. 9,
  135453. 4,
  135454. 10,
  135455. 3,
  135456. 11,
  135457. 2,
  135458. 12,
  135459. 1,
  135460. 13,
  135461. 0,
  135462. 14,
  135463. };
  135464. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135465. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135466. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135467. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135468. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135469. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135470. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135471. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135472. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135473. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135474. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135475. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135476. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135477. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135478. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135479. 14,
  135480. };
  135481. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135482. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135483. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135484. };
  135485. static long _vq_quantmap__44c9_s_p8_0[] = {
  135486. 13, 11, 9, 7, 5, 3, 1, 0,
  135487. 2, 4, 6, 8, 10, 12, 14,
  135488. };
  135489. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135490. _vq_quantthresh__44c9_s_p8_0,
  135491. _vq_quantmap__44c9_s_p8_0,
  135492. 15,
  135493. 15
  135494. };
  135495. static static_codebook _44c9_s_p8_0 = {
  135496. 2, 225,
  135497. _vq_lengthlist__44c9_s_p8_0,
  135498. 1, -520986624, 1620377600, 4, 0,
  135499. _vq_quantlist__44c9_s_p8_0,
  135500. NULL,
  135501. &_vq_auxt__44c9_s_p8_0,
  135502. NULL,
  135503. 0
  135504. };
  135505. static long _vq_quantlist__44c9_s_p8_1[] = {
  135506. 10,
  135507. 9,
  135508. 11,
  135509. 8,
  135510. 12,
  135511. 7,
  135512. 13,
  135513. 6,
  135514. 14,
  135515. 5,
  135516. 15,
  135517. 4,
  135518. 16,
  135519. 3,
  135520. 17,
  135521. 2,
  135522. 18,
  135523. 1,
  135524. 19,
  135525. 0,
  135526. 20,
  135527. };
  135528. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135529. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135530. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135531. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135532. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135533. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135534. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135535. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135536. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135537. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135538. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135539. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135540. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135541. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135542. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135543. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135544. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135545. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135546. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135547. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135548. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135549. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135550. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135551. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135552. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135553. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135554. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135555. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135556. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135557. };
  135558. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135559. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135560. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135561. 6.5, 7.5, 8.5, 9.5,
  135562. };
  135563. static long _vq_quantmap__44c9_s_p8_1[] = {
  135564. 19, 17, 15, 13, 11, 9, 7, 5,
  135565. 3, 1, 0, 2, 4, 6, 8, 10,
  135566. 12, 14, 16, 18, 20,
  135567. };
  135568. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135569. _vq_quantthresh__44c9_s_p8_1,
  135570. _vq_quantmap__44c9_s_p8_1,
  135571. 21,
  135572. 21
  135573. };
  135574. static static_codebook _44c9_s_p8_1 = {
  135575. 2, 441,
  135576. _vq_lengthlist__44c9_s_p8_1,
  135577. 1, -529268736, 1611661312, 5, 0,
  135578. _vq_quantlist__44c9_s_p8_1,
  135579. NULL,
  135580. &_vq_auxt__44c9_s_p8_1,
  135581. NULL,
  135582. 0
  135583. };
  135584. static long _vq_quantlist__44c9_s_p9_0[] = {
  135585. 9,
  135586. 8,
  135587. 10,
  135588. 7,
  135589. 11,
  135590. 6,
  135591. 12,
  135592. 5,
  135593. 13,
  135594. 4,
  135595. 14,
  135596. 3,
  135597. 15,
  135598. 2,
  135599. 16,
  135600. 1,
  135601. 17,
  135602. 0,
  135603. 18,
  135604. };
  135605. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135606. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135607. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135608. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135609. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135610. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135611. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135612. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135613. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135614. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135615. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135616. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135617. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135618. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135619. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135620. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135621. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135622. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135623. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135624. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135625. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135626. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135627. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135628. 11,11,11,11,11,11,11,11,11,
  135629. };
  135630. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135631. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135632. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135633. 6982.5, 7913.5,
  135634. };
  135635. static long _vq_quantmap__44c9_s_p9_0[] = {
  135636. 17, 15, 13, 11, 9, 7, 5, 3,
  135637. 1, 0, 2, 4, 6, 8, 10, 12,
  135638. 14, 16, 18,
  135639. };
  135640. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135641. _vq_quantthresh__44c9_s_p9_0,
  135642. _vq_quantmap__44c9_s_p9_0,
  135643. 19,
  135644. 19
  135645. };
  135646. static static_codebook _44c9_s_p9_0 = {
  135647. 2, 361,
  135648. _vq_lengthlist__44c9_s_p9_0,
  135649. 1, -508535424, 1631393792, 5, 0,
  135650. _vq_quantlist__44c9_s_p9_0,
  135651. NULL,
  135652. &_vq_auxt__44c9_s_p9_0,
  135653. NULL,
  135654. 0
  135655. };
  135656. static long _vq_quantlist__44c9_s_p9_1[] = {
  135657. 9,
  135658. 8,
  135659. 10,
  135660. 7,
  135661. 11,
  135662. 6,
  135663. 12,
  135664. 5,
  135665. 13,
  135666. 4,
  135667. 14,
  135668. 3,
  135669. 15,
  135670. 2,
  135671. 16,
  135672. 1,
  135673. 17,
  135674. 0,
  135675. 18,
  135676. };
  135677. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135678. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135679. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135680. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135681. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135682. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135683. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135684. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135685. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135686. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135687. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135688. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135689. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135690. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135691. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135692. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135693. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135694. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135695. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135696. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135697. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135698. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135699. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135700. 13,13,13,14,13,14,15,15,15,
  135701. };
  135702. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135703. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135704. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135705. 367.5, 416.5,
  135706. };
  135707. static long _vq_quantmap__44c9_s_p9_1[] = {
  135708. 17, 15, 13, 11, 9, 7, 5, 3,
  135709. 1, 0, 2, 4, 6, 8, 10, 12,
  135710. 14, 16, 18,
  135711. };
  135712. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135713. _vq_quantthresh__44c9_s_p9_1,
  135714. _vq_quantmap__44c9_s_p9_1,
  135715. 19,
  135716. 19
  135717. };
  135718. static static_codebook _44c9_s_p9_1 = {
  135719. 2, 361,
  135720. _vq_lengthlist__44c9_s_p9_1,
  135721. 1, -518287360, 1622704128, 5, 0,
  135722. _vq_quantlist__44c9_s_p9_1,
  135723. NULL,
  135724. &_vq_auxt__44c9_s_p9_1,
  135725. NULL,
  135726. 0
  135727. };
  135728. static long _vq_quantlist__44c9_s_p9_2[] = {
  135729. 24,
  135730. 23,
  135731. 25,
  135732. 22,
  135733. 26,
  135734. 21,
  135735. 27,
  135736. 20,
  135737. 28,
  135738. 19,
  135739. 29,
  135740. 18,
  135741. 30,
  135742. 17,
  135743. 31,
  135744. 16,
  135745. 32,
  135746. 15,
  135747. 33,
  135748. 14,
  135749. 34,
  135750. 13,
  135751. 35,
  135752. 12,
  135753. 36,
  135754. 11,
  135755. 37,
  135756. 10,
  135757. 38,
  135758. 9,
  135759. 39,
  135760. 8,
  135761. 40,
  135762. 7,
  135763. 41,
  135764. 6,
  135765. 42,
  135766. 5,
  135767. 43,
  135768. 4,
  135769. 44,
  135770. 3,
  135771. 45,
  135772. 2,
  135773. 46,
  135774. 1,
  135775. 47,
  135776. 0,
  135777. 48,
  135778. };
  135779. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135780. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135781. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135782. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135783. 7,
  135784. };
  135785. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135786. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135787. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135788. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135789. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135790. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135791. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135792. };
  135793. static long _vq_quantmap__44c9_s_p9_2[] = {
  135794. 47, 45, 43, 41, 39, 37, 35, 33,
  135795. 31, 29, 27, 25, 23, 21, 19, 17,
  135796. 15, 13, 11, 9, 7, 5, 3, 1,
  135797. 0, 2, 4, 6, 8, 10, 12, 14,
  135798. 16, 18, 20, 22, 24, 26, 28, 30,
  135799. 32, 34, 36, 38, 40, 42, 44, 46,
  135800. 48,
  135801. };
  135802. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135803. _vq_quantthresh__44c9_s_p9_2,
  135804. _vq_quantmap__44c9_s_p9_2,
  135805. 49,
  135806. 49
  135807. };
  135808. static static_codebook _44c9_s_p9_2 = {
  135809. 1, 49,
  135810. _vq_lengthlist__44c9_s_p9_2,
  135811. 1, -526909440, 1611661312, 6, 0,
  135812. _vq_quantlist__44c9_s_p9_2,
  135813. NULL,
  135814. &_vq_auxt__44c9_s_p9_2,
  135815. NULL,
  135816. 0
  135817. };
  135818. static long _huff_lengthlist__44c9_s_short[] = {
  135819. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135820. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135821. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135822. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135823. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135824. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135825. 9, 8,10,13,
  135826. };
  135827. static static_codebook _huff_book__44c9_s_short = {
  135828. 2, 100,
  135829. _huff_lengthlist__44c9_s_short,
  135830. 0, 0, 0, 0, 0,
  135831. NULL,
  135832. NULL,
  135833. NULL,
  135834. NULL,
  135835. 0
  135836. };
  135837. static long _huff_lengthlist__44c0_s_long[] = {
  135838. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135839. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135840. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135841. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135842. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135843. 12,
  135844. };
  135845. static static_codebook _huff_book__44c0_s_long = {
  135846. 2, 81,
  135847. _huff_lengthlist__44c0_s_long,
  135848. 0, 0, 0, 0, 0,
  135849. NULL,
  135850. NULL,
  135851. NULL,
  135852. NULL,
  135853. 0
  135854. };
  135855. static long _vq_quantlist__44c0_s_p1_0[] = {
  135856. 1,
  135857. 0,
  135858. 2,
  135859. };
  135860. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135861. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135862. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135867. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135872. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135907. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135912. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135917. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135953. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135958. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135963. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0,
  136272. };
  136273. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136274. -0.5, 0.5,
  136275. };
  136276. static long _vq_quantmap__44c0_s_p1_0[] = {
  136277. 1, 0, 2,
  136278. };
  136279. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136280. _vq_quantthresh__44c0_s_p1_0,
  136281. _vq_quantmap__44c0_s_p1_0,
  136282. 3,
  136283. 3
  136284. };
  136285. static static_codebook _44c0_s_p1_0 = {
  136286. 8, 6561,
  136287. _vq_lengthlist__44c0_s_p1_0,
  136288. 1, -535822336, 1611661312, 2, 0,
  136289. _vq_quantlist__44c0_s_p1_0,
  136290. NULL,
  136291. &_vq_auxt__44c0_s_p1_0,
  136292. NULL,
  136293. 0
  136294. };
  136295. static long _vq_quantlist__44c0_s_p2_0[] = {
  136296. 2,
  136297. 1,
  136298. 3,
  136299. 0,
  136300. 4,
  136301. };
  136302. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136303. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  136343. };
  136344. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136345. -1.5, -0.5, 0.5, 1.5,
  136346. };
  136347. static long _vq_quantmap__44c0_s_p2_0[] = {
  136348. 3, 1, 0, 2, 4,
  136349. };
  136350. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136351. _vq_quantthresh__44c0_s_p2_0,
  136352. _vq_quantmap__44c0_s_p2_0,
  136353. 5,
  136354. 5
  136355. };
  136356. static static_codebook _44c0_s_p2_0 = {
  136357. 4, 625,
  136358. _vq_lengthlist__44c0_s_p2_0,
  136359. 1, -533725184, 1611661312, 3, 0,
  136360. _vq_quantlist__44c0_s_p2_0,
  136361. NULL,
  136362. &_vq_auxt__44c0_s_p2_0,
  136363. NULL,
  136364. 0
  136365. };
  136366. static long _vq_quantlist__44c0_s_p3_0[] = {
  136367. 4,
  136368. 3,
  136369. 5,
  136370. 2,
  136371. 6,
  136372. 1,
  136373. 7,
  136374. 0,
  136375. 8,
  136376. };
  136377. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136378. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136379. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136380. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136381. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136382. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0,
  136384. };
  136385. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136386. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136387. };
  136388. static long _vq_quantmap__44c0_s_p3_0[] = {
  136389. 7, 5, 3, 1, 0, 2, 4, 6,
  136390. 8,
  136391. };
  136392. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136393. _vq_quantthresh__44c0_s_p3_0,
  136394. _vq_quantmap__44c0_s_p3_0,
  136395. 9,
  136396. 9
  136397. };
  136398. static static_codebook _44c0_s_p3_0 = {
  136399. 2, 81,
  136400. _vq_lengthlist__44c0_s_p3_0,
  136401. 1, -531628032, 1611661312, 4, 0,
  136402. _vq_quantlist__44c0_s_p3_0,
  136403. NULL,
  136404. &_vq_auxt__44c0_s_p3_0,
  136405. NULL,
  136406. 0
  136407. };
  136408. static long _vq_quantlist__44c0_s_p4_0[] = {
  136409. 4,
  136410. 3,
  136411. 5,
  136412. 2,
  136413. 6,
  136414. 1,
  136415. 7,
  136416. 0,
  136417. 8,
  136418. };
  136419. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136420. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136421. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136422. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136423. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136424. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136425. 10,
  136426. };
  136427. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136428. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136429. };
  136430. static long _vq_quantmap__44c0_s_p4_0[] = {
  136431. 7, 5, 3, 1, 0, 2, 4, 6,
  136432. 8,
  136433. };
  136434. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136435. _vq_quantthresh__44c0_s_p4_0,
  136436. _vq_quantmap__44c0_s_p4_0,
  136437. 9,
  136438. 9
  136439. };
  136440. static static_codebook _44c0_s_p4_0 = {
  136441. 2, 81,
  136442. _vq_lengthlist__44c0_s_p4_0,
  136443. 1, -531628032, 1611661312, 4, 0,
  136444. _vq_quantlist__44c0_s_p4_0,
  136445. NULL,
  136446. &_vq_auxt__44c0_s_p4_0,
  136447. NULL,
  136448. 0
  136449. };
  136450. static long _vq_quantlist__44c0_s_p5_0[] = {
  136451. 8,
  136452. 7,
  136453. 9,
  136454. 6,
  136455. 10,
  136456. 5,
  136457. 11,
  136458. 4,
  136459. 12,
  136460. 3,
  136461. 13,
  136462. 2,
  136463. 14,
  136464. 1,
  136465. 15,
  136466. 0,
  136467. 16,
  136468. };
  136469. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136470. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136471. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136472. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136473. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136474. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136475. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136476. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136477. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136478. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136479. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136480. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136481. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136482. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136483. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136484. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136485. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136486. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136487. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136488. 14,
  136489. };
  136490. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136491. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136492. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136493. };
  136494. static long _vq_quantmap__44c0_s_p5_0[] = {
  136495. 15, 13, 11, 9, 7, 5, 3, 1,
  136496. 0, 2, 4, 6, 8, 10, 12, 14,
  136497. 16,
  136498. };
  136499. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136500. _vq_quantthresh__44c0_s_p5_0,
  136501. _vq_quantmap__44c0_s_p5_0,
  136502. 17,
  136503. 17
  136504. };
  136505. static static_codebook _44c0_s_p5_0 = {
  136506. 2, 289,
  136507. _vq_lengthlist__44c0_s_p5_0,
  136508. 1, -529530880, 1611661312, 5, 0,
  136509. _vq_quantlist__44c0_s_p5_0,
  136510. NULL,
  136511. &_vq_auxt__44c0_s_p5_0,
  136512. NULL,
  136513. 0
  136514. };
  136515. static long _vq_quantlist__44c0_s_p6_0[] = {
  136516. 1,
  136517. 0,
  136518. 2,
  136519. };
  136520. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136521. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136522. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136523. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136524. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136525. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136526. 10,
  136527. };
  136528. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136529. -5.5, 5.5,
  136530. };
  136531. static long _vq_quantmap__44c0_s_p6_0[] = {
  136532. 1, 0, 2,
  136533. };
  136534. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136535. _vq_quantthresh__44c0_s_p6_0,
  136536. _vq_quantmap__44c0_s_p6_0,
  136537. 3,
  136538. 3
  136539. };
  136540. static static_codebook _44c0_s_p6_0 = {
  136541. 4, 81,
  136542. _vq_lengthlist__44c0_s_p6_0,
  136543. 1, -529137664, 1618345984, 2, 0,
  136544. _vq_quantlist__44c0_s_p6_0,
  136545. NULL,
  136546. &_vq_auxt__44c0_s_p6_0,
  136547. NULL,
  136548. 0
  136549. };
  136550. static long _vq_quantlist__44c0_s_p6_1[] = {
  136551. 5,
  136552. 4,
  136553. 6,
  136554. 3,
  136555. 7,
  136556. 2,
  136557. 8,
  136558. 1,
  136559. 9,
  136560. 0,
  136561. 10,
  136562. };
  136563. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136564. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136565. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136566. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136567. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136568. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136569. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136570. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136571. 10,10,10, 8, 8, 8, 8, 8, 8,
  136572. };
  136573. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136574. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136575. 3.5, 4.5,
  136576. };
  136577. static long _vq_quantmap__44c0_s_p6_1[] = {
  136578. 9, 7, 5, 3, 1, 0, 2, 4,
  136579. 6, 8, 10,
  136580. };
  136581. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136582. _vq_quantthresh__44c0_s_p6_1,
  136583. _vq_quantmap__44c0_s_p6_1,
  136584. 11,
  136585. 11
  136586. };
  136587. static static_codebook _44c0_s_p6_1 = {
  136588. 2, 121,
  136589. _vq_lengthlist__44c0_s_p6_1,
  136590. 1, -531365888, 1611661312, 4, 0,
  136591. _vq_quantlist__44c0_s_p6_1,
  136592. NULL,
  136593. &_vq_auxt__44c0_s_p6_1,
  136594. NULL,
  136595. 0
  136596. };
  136597. static long _vq_quantlist__44c0_s_p7_0[] = {
  136598. 6,
  136599. 5,
  136600. 7,
  136601. 4,
  136602. 8,
  136603. 3,
  136604. 9,
  136605. 2,
  136606. 10,
  136607. 1,
  136608. 11,
  136609. 0,
  136610. 12,
  136611. };
  136612. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136613. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136614. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136615. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136616. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136617. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136618. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136619. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136620. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136621. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136622. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136623. 0,12,12,11,11,12,12,13,13,
  136624. };
  136625. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136626. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136627. 12.5, 17.5, 22.5, 27.5,
  136628. };
  136629. static long _vq_quantmap__44c0_s_p7_0[] = {
  136630. 11, 9, 7, 5, 3, 1, 0, 2,
  136631. 4, 6, 8, 10, 12,
  136632. };
  136633. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136634. _vq_quantthresh__44c0_s_p7_0,
  136635. _vq_quantmap__44c0_s_p7_0,
  136636. 13,
  136637. 13
  136638. };
  136639. static static_codebook _44c0_s_p7_0 = {
  136640. 2, 169,
  136641. _vq_lengthlist__44c0_s_p7_0,
  136642. 1, -526516224, 1616117760, 4, 0,
  136643. _vq_quantlist__44c0_s_p7_0,
  136644. NULL,
  136645. &_vq_auxt__44c0_s_p7_0,
  136646. NULL,
  136647. 0
  136648. };
  136649. static long _vq_quantlist__44c0_s_p7_1[] = {
  136650. 2,
  136651. 1,
  136652. 3,
  136653. 0,
  136654. 4,
  136655. };
  136656. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136657. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136658. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136659. };
  136660. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136661. -1.5, -0.5, 0.5, 1.5,
  136662. };
  136663. static long _vq_quantmap__44c0_s_p7_1[] = {
  136664. 3, 1, 0, 2, 4,
  136665. };
  136666. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136667. _vq_quantthresh__44c0_s_p7_1,
  136668. _vq_quantmap__44c0_s_p7_1,
  136669. 5,
  136670. 5
  136671. };
  136672. static static_codebook _44c0_s_p7_1 = {
  136673. 2, 25,
  136674. _vq_lengthlist__44c0_s_p7_1,
  136675. 1, -533725184, 1611661312, 3, 0,
  136676. _vq_quantlist__44c0_s_p7_1,
  136677. NULL,
  136678. &_vq_auxt__44c0_s_p7_1,
  136679. NULL,
  136680. 0
  136681. };
  136682. static long _vq_quantlist__44c0_s_p8_0[] = {
  136683. 2,
  136684. 1,
  136685. 3,
  136686. 0,
  136687. 4,
  136688. };
  136689. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136690. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136691. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136692. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136693. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136694. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136695. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136696. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136697. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136698. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136699. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136700. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136701. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136702. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136705. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136716. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136718. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136729. 11,
  136730. };
  136731. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136732. -331.5, -110.5, 110.5, 331.5,
  136733. };
  136734. static long _vq_quantmap__44c0_s_p8_0[] = {
  136735. 3, 1, 0, 2, 4,
  136736. };
  136737. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136738. _vq_quantthresh__44c0_s_p8_0,
  136739. _vq_quantmap__44c0_s_p8_0,
  136740. 5,
  136741. 5
  136742. };
  136743. static static_codebook _44c0_s_p8_0 = {
  136744. 4, 625,
  136745. _vq_lengthlist__44c0_s_p8_0,
  136746. 1, -518283264, 1627103232, 3, 0,
  136747. _vq_quantlist__44c0_s_p8_0,
  136748. NULL,
  136749. &_vq_auxt__44c0_s_p8_0,
  136750. NULL,
  136751. 0
  136752. };
  136753. static long _vq_quantlist__44c0_s_p8_1[] = {
  136754. 6,
  136755. 5,
  136756. 7,
  136757. 4,
  136758. 8,
  136759. 3,
  136760. 9,
  136761. 2,
  136762. 10,
  136763. 1,
  136764. 11,
  136765. 0,
  136766. 12,
  136767. };
  136768. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136769. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136770. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136771. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136772. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136773. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136774. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136775. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136776. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136777. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136778. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136779. 16,13,13,12,12,14,14,15,13,
  136780. };
  136781. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136782. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136783. 42.5, 59.5, 76.5, 93.5,
  136784. };
  136785. static long _vq_quantmap__44c0_s_p8_1[] = {
  136786. 11, 9, 7, 5, 3, 1, 0, 2,
  136787. 4, 6, 8, 10, 12,
  136788. };
  136789. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136790. _vq_quantthresh__44c0_s_p8_1,
  136791. _vq_quantmap__44c0_s_p8_1,
  136792. 13,
  136793. 13
  136794. };
  136795. static static_codebook _44c0_s_p8_1 = {
  136796. 2, 169,
  136797. _vq_lengthlist__44c0_s_p8_1,
  136798. 1, -522616832, 1620115456, 4, 0,
  136799. _vq_quantlist__44c0_s_p8_1,
  136800. NULL,
  136801. &_vq_auxt__44c0_s_p8_1,
  136802. NULL,
  136803. 0
  136804. };
  136805. static long _vq_quantlist__44c0_s_p8_2[] = {
  136806. 8,
  136807. 7,
  136808. 9,
  136809. 6,
  136810. 10,
  136811. 5,
  136812. 11,
  136813. 4,
  136814. 12,
  136815. 3,
  136816. 13,
  136817. 2,
  136818. 14,
  136819. 1,
  136820. 15,
  136821. 0,
  136822. 16,
  136823. };
  136824. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136825. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136826. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136827. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136828. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136829. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136830. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136831. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136832. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136833. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136834. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136835. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136836. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136837. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136838. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136839. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136840. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136841. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136842. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136843. 10,
  136844. };
  136845. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136846. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136847. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136848. };
  136849. static long _vq_quantmap__44c0_s_p8_2[] = {
  136850. 15, 13, 11, 9, 7, 5, 3, 1,
  136851. 0, 2, 4, 6, 8, 10, 12, 14,
  136852. 16,
  136853. };
  136854. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136855. _vq_quantthresh__44c0_s_p8_2,
  136856. _vq_quantmap__44c0_s_p8_2,
  136857. 17,
  136858. 17
  136859. };
  136860. static static_codebook _44c0_s_p8_2 = {
  136861. 2, 289,
  136862. _vq_lengthlist__44c0_s_p8_2,
  136863. 1, -529530880, 1611661312, 5, 0,
  136864. _vq_quantlist__44c0_s_p8_2,
  136865. NULL,
  136866. &_vq_auxt__44c0_s_p8_2,
  136867. NULL,
  136868. 0
  136869. };
  136870. static long _huff_lengthlist__44c0_s_short[] = {
  136871. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136872. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136873. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136874. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136875. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136876. 12,
  136877. };
  136878. static static_codebook _huff_book__44c0_s_short = {
  136879. 2, 81,
  136880. _huff_lengthlist__44c0_s_short,
  136881. 0, 0, 0, 0, 0,
  136882. NULL,
  136883. NULL,
  136884. NULL,
  136885. NULL,
  136886. 0
  136887. };
  136888. static long _huff_lengthlist__44c0_sm_long[] = {
  136889. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136890. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136891. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136892. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136893. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136894. 13,
  136895. };
  136896. static static_codebook _huff_book__44c0_sm_long = {
  136897. 2, 81,
  136898. _huff_lengthlist__44c0_sm_long,
  136899. 0, 0, 0, 0, 0,
  136900. NULL,
  136901. NULL,
  136902. NULL,
  136903. NULL,
  136904. 0
  136905. };
  136906. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136907. 1,
  136908. 0,
  136909. 2,
  136910. };
  136911. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136912. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136913. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136918. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136923. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136958. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136963. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136968. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137004. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137009. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137014. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0,
  137323. };
  137324. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137325. -0.5, 0.5,
  137326. };
  137327. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137328. 1, 0, 2,
  137329. };
  137330. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137331. _vq_quantthresh__44c0_sm_p1_0,
  137332. _vq_quantmap__44c0_sm_p1_0,
  137333. 3,
  137334. 3
  137335. };
  137336. static static_codebook _44c0_sm_p1_0 = {
  137337. 8, 6561,
  137338. _vq_lengthlist__44c0_sm_p1_0,
  137339. 1, -535822336, 1611661312, 2, 0,
  137340. _vq_quantlist__44c0_sm_p1_0,
  137341. NULL,
  137342. &_vq_auxt__44c0_sm_p1_0,
  137343. NULL,
  137344. 0
  137345. };
  137346. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137347. 2,
  137348. 1,
  137349. 3,
  137350. 0,
  137351. 4,
  137352. };
  137353. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137354. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  137394. };
  137395. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137396. -1.5, -0.5, 0.5, 1.5,
  137397. };
  137398. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137399. 3, 1, 0, 2, 4,
  137400. };
  137401. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137402. _vq_quantthresh__44c0_sm_p2_0,
  137403. _vq_quantmap__44c0_sm_p2_0,
  137404. 5,
  137405. 5
  137406. };
  137407. static static_codebook _44c0_sm_p2_0 = {
  137408. 4, 625,
  137409. _vq_lengthlist__44c0_sm_p2_0,
  137410. 1, -533725184, 1611661312, 3, 0,
  137411. _vq_quantlist__44c0_sm_p2_0,
  137412. NULL,
  137413. &_vq_auxt__44c0_sm_p2_0,
  137414. NULL,
  137415. 0
  137416. };
  137417. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137418. 4,
  137419. 3,
  137420. 5,
  137421. 2,
  137422. 6,
  137423. 1,
  137424. 7,
  137425. 0,
  137426. 8,
  137427. };
  137428. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137429. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137430. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137431. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137432. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137433. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0,
  137435. };
  137436. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137437. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137438. };
  137439. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137440. 7, 5, 3, 1, 0, 2, 4, 6,
  137441. 8,
  137442. };
  137443. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137444. _vq_quantthresh__44c0_sm_p3_0,
  137445. _vq_quantmap__44c0_sm_p3_0,
  137446. 9,
  137447. 9
  137448. };
  137449. static static_codebook _44c0_sm_p3_0 = {
  137450. 2, 81,
  137451. _vq_lengthlist__44c0_sm_p3_0,
  137452. 1, -531628032, 1611661312, 4, 0,
  137453. _vq_quantlist__44c0_sm_p3_0,
  137454. NULL,
  137455. &_vq_auxt__44c0_sm_p3_0,
  137456. NULL,
  137457. 0
  137458. };
  137459. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137460. 4,
  137461. 3,
  137462. 5,
  137463. 2,
  137464. 6,
  137465. 1,
  137466. 7,
  137467. 0,
  137468. 8,
  137469. };
  137470. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137471. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137472. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137473. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137474. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137475. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137476. 11,
  137477. };
  137478. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137479. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137480. };
  137481. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137482. 7, 5, 3, 1, 0, 2, 4, 6,
  137483. 8,
  137484. };
  137485. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137486. _vq_quantthresh__44c0_sm_p4_0,
  137487. _vq_quantmap__44c0_sm_p4_0,
  137488. 9,
  137489. 9
  137490. };
  137491. static static_codebook _44c0_sm_p4_0 = {
  137492. 2, 81,
  137493. _vq_lengthlist__44c0_sm_p4_0,
  137494. 1, -531628032, 1611661312, 4, 0,
  137495. _vq_quantlist__44c0_sm_p4_0,
  137496. NULL,
  137497. &_vq_auxt__44c0_sm_p4_0,
  137498. NULL,
  137499. 0
  137500. };
  137501. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137502. 8,
  137503. 7,
  137504. 9,
  137505. 6,
  137506. 10,
  137507. 5,
  137508. 11,
  137509. 4,
  137510. 12,
  137511. 3,
  137512. 13,
  137513. 2,
  137514. 14,
  137515. 1,
  137516. 15,
  137517. 0,
  137518. 16,
  137519. };
  137520. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137521. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137522. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137523. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137524. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137525. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137526. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137527. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137528. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137529. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137530. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137531. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137532. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137533. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137534. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137535. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137536. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137537. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137538. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137539. 14,
  137540. };
  137541. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137542. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137543. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137544. };
  137545. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137546. 15, 13, 11, 9, 7, 5, 3, 1,
  137547. 0, 2, 4, 6, 8, 10, 12, 14,
  137548. 16,
  137549. };
  137550. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137551. _vq_quantthresh__44c0_sm_p5_0,
  137552. _vq_quantmap__44c0_sm_p5_0,
  137553. 17,
  137554. 17
  137555. };
  137556. static static_codebook _44c0_sm_p5_0 = {
  137557. 2, 289,
  137558. _vq_lengthlist__44c0_sm_p5_0,
  137559. 1, -529530880, 1611661312, 5, 0,
  137560. _vq_quantlist__44c0_sm_p5_0,
  137561. NULL,
  137562. &_vq_auxt__44c0_sm_p5_0,
  137563. NULL,
  137564. 0
  137565. };
  137566. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137567. 1,
  137568. 0,
  137569. 2,
  137570. };
  137571. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137572. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137573. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137574. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137575. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137576. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137577. 11,
  137578. };
  137579. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137580. -5.5, 5.5,
  137581. };
  137582. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137583. 1, 0, 2,
  137584. };
  137585. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137586. _vq_quantthresh__44c0_sm_p6_0,
  137587. _vq_quantmap__44c0_sm_p6_0,
  137588. 3,
  137589. 3
  137590. };
  137591. static static_codebook _44c0_sm_p6_0 = {
  137592. 4, 81,
  137593. _vq_lengthlist__44c0_sm_p6_0,
  137594. 1, -529137664, 1618345984, 2, 0,
  137595. _vq_quantlist__44c0_sm_p6_0,
  137596. NULL,
  137597. &_vq_auxt__44c0_sm_p6_0,
  137598. NULL,
  137599. 0
  137600. };
  137601. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137602. 5,
  137603. 4,
  137604. 6,
  137605. 3,
  137606. 7,
  137607. 2,
  137608. 8,
  137609. 1,
  137610. 9,
  137611. 0,
  137612. 10,
  137613. };
  137614. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137615. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137616. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137617. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137618. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137619. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137620. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137621. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137622. 10,10,10, 8, 8, 8, 8, 8, 8,
  137623. };
  137624. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137625. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137626. 3.5, 4.5,
  137627. };
  137628. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137629. 9, 7, 5, 3, 1, 0, 2, 4,
  137630. 6, 8, 10,
  137631. };
  137632. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137633. _vq_quantthresh__44c0_sm_p6_1,
  137634. _vq_quantmap__44c0_sm_p6_1,
  137635. 11,
  137636. 11
  137637. };
  137638. static static_codebook _44c0_sm_p6_1 = {
  137639. 2, 121,
  137640. _vq_lengthlist__44c0_sm_p6_1,
  137641. 1, -531365888, 1611661312, 4, 0,
  137642. _vq_quantlist__44c0_sm_p6_1,
  137643. NULL,
  137644. &_vq_auxt__44c0_sm_p6_1,
  137645. NULL,
  137646. 0
  137647. };
  137648. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137649. 6,
  137650. 5,
  137651. 7,
  137652. 4,
  137653. 8,
  137654. 3,
  137655. 9,
  137656. 2,
  137657. 10,
  137658. 1,
  137659. 11,
  137660. 0,
  137661. 12,
  137662. };
  137663. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137664. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137665. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137666. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137667. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137668. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137669. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137670. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137671. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137672. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137673. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137674. 0,12,12,11,11,13,12,14,14,
  137675. };
  137676. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137677. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137678. 12.5, 17.5, 22.5, 27.5,
  137679. };
  137680. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137681. 11, 9, 7, 5, 3, 1, 0, 2,
  137682. 4, 6, 8, 10, 12,
  137683. };
  137684. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137685. _vq_quantthresh__44c0_sm_p7_0,
  137686. _vq_quantmap__44c0_sm_p7_0,
  137687. 13,
  137688. 13
  137689. };
  137690. static static_codebook _44c0_sm_p7_0 = {
  137691. 2, 169,
  137692. _vq_lengthlist__44c0_sm_p7_0,
  137693. 1, -526516224, 1616117760, 4, 0,
  137694. _vq_quantlist__44c0_sm_p7_0,
  137695. NULL,
  137696. &_vq_auxt__44c0_sm_p7_0,
  137697. NULL,
  137698. 0
  137699. };
  137700. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137701. 2,
  137702. 1,
  137703. 3,
  137704. 0,
  137705. 4,
  137706. };
  137707. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137708. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137709. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137710. };
  137711. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137712. -1.5, -0.5, 0.5, 1.5,
  137713. };
  137714. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137715. 3, 1, 0, 2, 4,
  137716. };
  137717. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137718. _vq_quantthresh__44c0_sm_p7_1,
  137719. _vq_quantmap__44c0_sm_p7_1,
  137720. 5,
  137721. 5
  137722. };
  137723. static static_codebook _44c0_sm_p7_1 = {
  137724. 2, 25,
  137725. _vq_lengthlist__44c0_sm_p7_1,
  137726. 1, -533725184, 1611661312, 3, 0,
  137727. _vq_quantlist__44c0_sm_p7_1,
  137728. NULL,
  137729. &_vq_auxt__44c0_sm_p7_1,
  137730. NULL,
  137731. 0
  137732. };
  137733. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137734. 4,
  137735. 3,
  137736. 5,
  137737. 2,
  137738. 6,
  137739. 1,
  137740. 7,
  137741. 0,
  137742. 8,
  137743. };
  137744. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137745. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137746. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137748. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137749. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137750. 12,
  137751. };
  137752. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137753. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137754. };
  137755. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137756. 7, 5, 3, 1, 0, 2, 4, 6,
  137757. 8,
  137758. };
  137759. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137760. _vq_quantthresh__44c0_sm_p8_0,
  137761. _vq_quantmap__44c0_sm_p8_0,
  137762. 9,
  137763. 9
  137764. };
  137765. static static_codebook _44c0_sm_p8_0 = {
  137766. 2, 81,
  137767. _vq_lengthlist__44c0_sm_p8_0,
  137768. 1, -516186112, 1627103232, 4, 0,
  137769. _vq_quantlist__44c0_sm_p8_0,
  137770. NULL,
  137771. &_vq_auxt__44c0_sm_p8_0,
  137772. NULL,
  137773. 0
  137774. };
  137775. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137776. 6,
  137777. 5,
  137778. 7,
  137779. 4,
  137780. 8,
  137781. 3,
  137782. 9,
  137783. 2,
  137784. 10,
  137785. 1,
  137786. 11,
  137787. 0,
  137788. 12,
  137789. };
  137790. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137791. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137792. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137793. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137794. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137795. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137796. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137797. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137798. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137799. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137800. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137801. 20,13,13,12,12,16,13,15,13,
  137802. };
  137803. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137804. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137805. 42.5, 59.5, 76.5, 93.5,
  137806. };
  137807. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137808. 11, 9, 7, 5, 3, 1, 0, 2,
  137809. 4, 6, 8, 10, 12,
  137810. };
  137811. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137812. _vq_quantthresh__44c0_sm_p8_1,
  137813. _vq_quantmap__44c0_sm_p8_1,
  137814. 13,
  137815. 13
  137816. };
  137817. static static_codebook _44c0_sm_p8_1 = {
  137818. 2, 169,
  137819. _vq_lengthlist__44c0_sm_p8_1,
  137820. 1, -522616832, 1620115456, 4, 0,
  137821. _vq_quantlist__44c0_sm_p8_1,
  137822. NULL,
  137823. &_vq_auxt__44c0_sm_p8_1,
  137824. NULL,
  137825. 0
  137826. };
  137827. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137828. 8,
  137829. 7,
  137830. 9,
  137831. 6,
  137832. 10,
  137833. 5,
  137834. 11,
  137835. 4,
  137836. 12,
  137837. 3,
  137838. 13,
  137839. 2,
  137840. 14,
  137841. 1,
  137842. 15,
  137843. 0,
  137844. 16,
  137845. };
  137846. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137847. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137848. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137849. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137850. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137851. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137852. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137853. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137854. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137855. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137856. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137857. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137858. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137859. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137860. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137861. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137862. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137863. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137864. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137865. 9,
  137866. };
  137867. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137868. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137869. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137870. };
  137871. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137872. 15, 13, 11, 9, 7, 5, 3, 1,
  137873. 0, 2, 4, 6, 8, 10, 12, 14,
  137874. 16,
  137875. };
  137876. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137877. _vq_quantthresh__44c0_sm_p8_2,
  137878. _vq_quantmap__44c0_sm_p8_2,
  137879. 17,
  137880. 17
  137881. };
  137882. static static_codebook _44c0_sm_p8_2 = {
  137883. 2, 289,
  137884. _vq_lengthlist__44c0_sm_p8_2,
  137885. 1, -529530880, 1611661312, 5, 0,
  137886. _vq_quantlist__44c0_sm_p8_2,
  137887. NULL,
  137888. &_vq_auxt__44c0_sm_p8_2,
  137889. NULL,
  137890. 0
  137891. };
  137892. static long _huff_lengthlist__44c0_sm_short[] = {
  137893. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137894. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137895. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137896. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137897. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137898. 12,
  137899. };
  137900. static static_codebook _huff_book__44c0_sm_short = {
  137901. 2, 81,
  137902. _huff_lengthlist__44c0_sm_short,
  137903. 0, 0, 0, 0, 0,
  137904. NULL,
  137905. NULL,
  137906. NULL,
  137907. NULL,
  137908. 0
  137909. };
  137910. static long _huff_lengthlist__44c1_s_long[] = {
  137911. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137912. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137913. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137914. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137915. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137916. 11,
  137917. };
  137918. static static_codebook _huff_book__44c1_s_long = {
  137919. 2, 81,
  137920. _huff_lengthlist__44c1_s_long,
  137921. 0, 0, 0, 0, 0,
  137922. NULL,
  137923. NULL,
  137924. NULL,
  137925. NULL,
  137926. 0
  137927. };
  137928. static long _vq_quantlist__44c1_s_p1_0[] = {
  137929. 1,
  137930. 0,
  137931. 2,
  137932. };
  137933. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137934. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137935. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137939. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137940. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137945. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137980. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137985. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137990. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138026. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138031. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138036. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0,
  138345. };
  138346. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138347. -0.5, 0.5,
  138348. };
  138349. static long _vq_quantmap__44c1_s_p1_0[] = {
  138350. 1, 0, 2,
  138351. };
  138352. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138353. _vq_quantthresh__44c1_s_p1_0,
  138354. _vq_quantmap__44c1_s_p1_0,
  138355. 3,
  138356. 3
  138357. };
  138358. static static_codebook _44c1_s_p1_0 = {
  138359. 8, 6561,
  138360. _vq_lengthlist__44c1_s_p1_0,
  138361. 1, -535822336, 1611661312, 2, 0,
  138362. _vq_quantlist__44c1_s_p1_0,
  138363. NULL,
  138364. &_vq_auxt__44c1_s_p1_0,
  138365. NULL,
  138366. 0
  138367. };
  138368. static long _vq_quantlist__44c1_s_p2_0[] = {
  138369. 2,
  138370. 1,
  138371. 3,
  138372. 0,
  138373. 4,
  138374. };
  138375. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138376. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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,
  138416. };
  138417. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138418. -1.5, -0.5, 0.5, 1.5,
  138419. };
  138420. static long _vq_quantmap__44c1_s_p2_0[] = {
  138421. 3, 1, 0, 2, 4,
  138422. };
  138423. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138424. _vq_quantthresh__44c1_s_p2_0,
  138425. _vq_quantmap__44c1_s_p2_0,
  138426. 5,
  138427. 5
  138428. };
  138429. static static_codebook _44c1_s_p2_0 = {
  138430. 4, 625,
  138431. _vq_lengthlist__44c1_s_p2_0,
  138432. 1, -533725184, 1611661312, 3, 0,
  138433. _vq_quantlist__44c1_s_p2_0,
  138434. NULL,
  138435. &_vq_auxt__44c1_s_p2_0,
  138436. NULL,
  138437. 0
  138438. };
  138439. static long _vq_quantlist__44c1_s_p3_0[] = {
  138440. 4,
  138441. 3,
  138442. 5,
  138443. 2,
  138444. 6,
  138445. 1,
  138446. 7,
  138447. 0,
  138448. 8,
  138449. };
  138450. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138451. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138452. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138453. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138454. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138455. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0,
  138457. };
  138458. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138459. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138460. };
  138461. static long _vq_quantmap__44c1_s_p3_0[] = {
  138462. 7, 5, 3, 1, 0, 2, 4, 6,
  138463. 8,
  138464. };
  138465. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138466. _vq_quantthresh__44c1_s_p3_0,
  138467. _vq_quantmap__44c1_s_p3_0,
  138468. 9,
  138469. 9
  138470. };
  138471. static static_codebook _44c1_s_p3_0 = {
  138472. 2, 81,
  138473. _vq_lengthlist__44c1_s_p3_0,
  138474. 1, -531628032, 1611661312, 4, 0,
  138475. _vq_quantlist__44c1_s_p3_0,
  138476. NULL,
  138477. &_vq_auxt__44c1_s_p3_0,
  138478. NULL,
  138479. 0
  138480. };
  138481. static long _vq_quantlist__44c1_s_p4_0[] = {
  138482. 4,
  138483. 3,
  138484. 5,
  138485. 2,
  138486. 6,
  138487. 1,
  138488. 7,
  138489. 0,
  138490. 8,
  138491. };
  138492. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138493. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138494. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138495. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138496. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138497. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138498. 11,
  138499. };
  138500. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138501. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138502. };
  138503. static long _vq_quantmap__44c1_s_p4_0[] = {
  138504. 7, 5, 3, 1, 0, 2, 4, 6,
  138505. 8,
  138506. };
  138507. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138508. _vq_quantthresh__44c1_s_p4_0,
  138509. _vq_quantmap__44c1_s_p4_0,
  138510. 9,
  138511. 9
  138512. };
  138513. static static_codebook _44c1_s_p4_0 = {
  138514. 2, 81,
  138515. _vq_lengthlist__44c1_s_p4_0,
  138516. 1, -531628032, 1611661312, 4, 0,
  138517. _vq_quantlist__44c1_s_p4_0,
  138518. NULL,
  138519. &_vq_auxt__44c1_s_p4_0,
  138520. NULL,
  138521. 0
  138522. };
  138523. static long _vq_quantlist__44c1_s_p5_0[] = {
  138524. 8,
  138525. 7,
  138526. 9,
  138527. 6,
  138528. 10,
  138529. 5,
  138530. 11,
  138531. 4,
  138532. 12,
  138533. 3,
  138534. 13,
  138535. 2,
  138536. 14,
  138537. 1,
  138538. 15,
  138539. 0,
  138540. 16,
  138541. };
  138542. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138543. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138544. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138545. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138546. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138547. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138548. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138549. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138550. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138551. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138552. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138553. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138554. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138555. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138556. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138557. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138558. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138559. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138560. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138561. 14,
  138562. };
  138563. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138564. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138565. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138566. };
  138567. static long _vq_quantmap__44c1_s_p5_0[] = {
  138568. 15, 13, 11, 9, 7, 5, 3, 1,
  138569. 0, 2, 4, 6, 8, 10, 12, 14,
  138570. 16,
  138571. };
  138572. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138573. _vq_quantthresh__44c1_s_p5_0,
  138574. _vq_quantmap__44c1_s_p5_0,
  138575. 17,
  138576. 17
  138577. };
  138578. static static_codebook _44c1_s_p5_0 = {
  138579. 2, 289,
  138580. _vq_lengthlist__44c1_s_p5_0,
  138581. 1, -529530880, 1611661312, 5, 0,
  138582. _vq_quantlist__44c1_s_p5_0,
  138583. NULL,
  138584. &_vq_auxt__44c1_s_p5_0,
  138585. NULL,
  138586. 0
  138587. };
  138588. static long _vq_quantlist__44c1_s_p6_0[] = {
  138589. 1,
  138590. 0,
  138591. 2,
  138592. };
  138593. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138594. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138595. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138596. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138597. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138598. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138599. 11,
  138600. };
  138601. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138602. -5.5, 5.5,
  138603. };
  138604. static long _vq_quantmap__44c1_s_p6_0[] = {
  138605. 1, 0, 2,
  138606. };
  138607. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138608. _vq_quantthresh__44c1_s_p6_0,
  138609. _vq_quantmap__44c1_s_p6_0,
  138610. 3,
  138611. 3
  138612. };
  138613. static static_codebook _44c1_s_p6_0 = {
  138614. 4, 81,
  138615. _vq_lengthlist__44c1_s_p6_0,
  138616. 1, -529137664, 1618345984, 2, 0,
  138617. _vq_quantlist__44c1_s_p6_0,
  138618. NULL,
  138619. &_vq_auxt__44c1_s_p6_0,
  138620. NULL,
  138621. 0
  138622. };
  138623. static long _vq_quantlist__44c1_s_p6_1[] = {
  138624. 5,
  138625. 4,
  138626. 6,
  138627. 3,
  138628. 7,
  138629. 2,
  138630. 8,
  138631. 1,
  138632. 9,
  138633. 0,
  138634. 10,
  138635. };
  138636. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138637. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138638. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138639. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138640. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138641. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138642. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138643. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138644. 10,10,10, 8, 8, 8, 8, 8, 8,
  138645. };
  138646. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138647. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138648. 3.5, 4.5,
  138649. };
  138650. static long _vq_quantmap__44c1_s_p6_1[] = {
  138651. 9, 7, 5, 3, 1, 0, 2, 4,
  138652. 6, 8, 10,
  138653. };
  138654. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138655. _vq_quantthresh__44c1_s_p6_1,
  138656. _vq_quantmap__44c1_s_p6_1,
  138657. 11,
  138658. 11
  138659. };
  138660. static static_codebook _44c1_s_p6_1 = {
  138661. 2, 121,
  138662. _vq_lengthlist__44c1_s_p6_1,
  138663. 1, -531365888, 1611661312, 4, 0,
  138664. _vq_quantlist__44c1_s_p6_1,
  138665. NULL,
  138666. &_vq_auxt__44c1_s_p6_1,
  138667. NULL,
  138668. 0
  138669. };
  138670. static long _vq_quantlist__44c1_s_p7_0[] = {
  138671. 6,
  138672. 5,
  138673. 7,
  138674. 4,
  138675. 8,
  138676. 3,
  138677. 9,
  138678. 2,
  138679. 10,
  138680. 1,
  138681. 11,
  138682. 0,
  138683. 12,
  138684. };
  138685. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138686. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138687. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138688. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138689. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138690. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138691. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138692. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138693. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138694. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138695. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138696. 0,12,11,11,11,13,10,14,13,
  138697. };
  138698. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138699. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138700. 12.5, 17.5, 22.5, 27.5,
  138701. };
  138702. static long _vq_quantmap__44c1_s_p7_0[] = {
  138703. 11, 9, 7, 5, 3, 1, 0, 2,
  138704. 4, 6, 8, 10, 12,
  138705. };
  138706. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138707. _vq_quantthresh__44c1_s_p7_0,
  138708. _vq_quantmap__44c1_s_p7_0,
  138709. 13,
  138710. 13
  138711. };
  138712. static static_codebook _44c1_s_p7_0 = {
  138713. 2, 169,
  138714. _vq_lengthlist__44c1_s_p7_0,
  138715. 1, -526516224, 1616117760, 4, 0,
  138716. _vq_quantlist__44c1_s_p7_0,
  138717. NULL,
  138718. &_vq_auxt__44c1_s_p7_0,
  138719. NULL,
  138720. 0
  138721. };
  138722. static long _vq_quantlist__44c1_s_p7_1[] = {
  138723. 2,
  138724. 1,
  138725. 3,
  138726. 0,
  138727. 4,
  138728. };
  138729. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138730. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138731. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138732. };
  138733. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138734. -1.5, -0.5, 0.5, 1.5,
  138735. };
  138736. static long _vq_quantmap__44c1_s_p7_1[] = {
  138737. 3, 1, 0, 2, 4,
  138738. };
  138739. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138740. _vq_quantthresh__44c1_s_p7_1,
  138741. _vq_quantmap__44c1_s_p7_1,
  138742. 5,
  138743. 5
  138744. };
  138745. static static_codebook _44c1_s_p7_1 = {
  138746. 2, 25,
  138747. _vq_lengthlist__44c1_s_p7_1,
  138748. 1, -533725184, 1611661312, 3, 0,
  138749. _vq_quantlist__44c1_s_p7_1,
  138750. NULL,
  138751. &_vq_auxt__44c1_s_p7_1,
  138752. NULL,
  138753. 0
  138754. };
  138755. static long _vq_quantlist__44c1_s_p8_0[] = {
  138756. 6,
  138757. 5,
  138758. 7,
  138759. 4,
  138760. 8,
  138761. 3,
  138762. 9,
  138763. 2,
  138764. 10,
  138765. 1,
  138766. 11,
  138767. 0,
  138768. 12,
  138769. };
  138770. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138771. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138772. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138773. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138774. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138776. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138777. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138778. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138779. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138780. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138781. 10,10,10,10,10,10,10,10,10,
  138782. };
  138783. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138784. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138785. 552.5, 773.5, 994.5, 1215.5,
  138786. };
  138787. static long _vq_quantmap__44c1_s_p8_0[] = {
  138788. 11, 9, 7, 5, 3, 1, 0, 2,
  138789. 4, 6, 8, 10, 12,
  138790. };
  138791. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138792. _vq_quantthresh__44c1_s_p8_0,
  138793. _vq_quantmap__44c1_s_p8_0,
  138794. 13,
  138795. 13
  138796. };
  138797. static static_codebook _44c1_s_p8_0 = {
  138798. 2, 169,
  138799. _vq_lengthlist__44c1_s_p8_0,
  138800. 1, -514541568, 1627103232, 4, 0,
  138801. _vq_quantlist__44c1_s_p8_0,
  138802. NULL,
  138803. &_vq_auxt__44c1_s_p8_0,
  138804. NULL,
  138805. 0
  138806. };
  138807. static long _vq_quantlist__44c1_s_p8_1[] = {
  138808. 6,
  138809. 5,
  138810. 7,
  138811. 4,
  138812. 8,
  138813. 3,
  138814. 9,
  138815. 2,
  138816. 10,
  138817. 1,
  138818. 11,
  138819. 0,
  138820. 12,
  138821. };
  138822. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138823. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138824. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138825. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138826. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138827. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138828. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138829. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138830. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138831. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138832. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138833. 16,13,12,12,11,14,12,15,13,
  138834. };
  138835. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138836. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138837. 42.5, 59.5, 76.5, 93.5,
  138838. };
  138839. static long _vq_quantmap__44c1_s_p8_1[] = {
  138840. 11, 9, 7, 5, 3, 1, 0, 2,
  138841. 4, 6, 8, 10, 12,
  138842. };
  138843. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138844. _vq_quantthresh__44c1_s_p8_1,
  138845. _vq_quantmap__44c1_s_p8_1,
  138846. 13,
  138847. 13
  138848. };
  138849. static static_codebook _44c1_s_p8_1 = {
  138850. 2, 169,
  138851. _vq_lengthlist__44c1_s_p8_1,
  138852. 1, -522616832, 1620115456, 4, 0,
  138853. _vq_quantlist__44c1_s_p8_1,
  138854. NULL,
  138855. &_vq_auxt__44c1_s_p8_1,
  138856. NULL,
  138857. 0
  138858. };
  138859. static long _vq_quantlist__44c1_s_p8_2[] = {
  138860. 8,
  138861. 7,
  138862. 9,
  138863. 6,
  138864. 10,
  138865. 5,
  138866. 11,
  138867. 4,
  138868. 12,
  138869. 3,
  138870. 13,
  138871. 2,
  138872. 14,
  138873. 1,
  138874. 15,
  138875. 0,
  138876. 16,
  138877. };
  138878. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138879. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138880. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138881. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138882. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138883. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138884. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138885. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138886. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138887. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138888. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138889. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138890. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138891. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138892. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138893. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138894. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138895. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138896. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138897. 9,
  138898. };
  138899. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138900. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138901. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138902. };
  138903. static long _vq_quantmap__44c1_s_p8_2[] = {
  138904. 15, 13, 11, 9, 7, 5, 3, 1,
  138905. 0, 2, 4, 6, 8, 10, 12, 14,
  138906. 16,
  138907. };
  138908. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138909. _vq_quantthresh__44c1_s_p8_2,
  138910. _vq_quantmap__44c1_s_p8_2,
  138911. 17,
  138912. 17
  138913. };
  138914. static static_codebook _44c1_s_p8_2 = {
  138915. 2, 289,
  138916. _vq_lengthlist__44c1_s_p8_2,
  138917. 1, -529530880, 1611661312, 5, 0,
  138918. _vq_quantlist__44c1_s_p8_2,
  138919. NULL,
  138920. &_vq_auxt__44c1_s_p8_2,
  138921. NULL,
  138922. 0
  138923. };
  138924. static long _huff_lengthlist__44c1_s_short[] = {
  138925. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138926. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138927. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138928. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138929. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138930. 11,
  138931. };
  138932. static static_codebook _huff_book__44c1_s_short = {
  138933. 2, 81,
  138934. _huff_lengthlist__44c1_s_short,
  138935. 0, 0, 0, 0, 0,
  138936. NULL,
  138937. NULL,
  138938. NULL,
  138939. NULL,
  138940. 0
  138941. };
  138942. static long _huff_lengthlist__44c1_sm_long[] = {
  138943. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138944. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138945. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138946. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138947. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138948. 11,
  138949. };
  138950. static static_codebook _huff_book__44c1_sm_long = {
  138951. 2, 81,
  138952. _huff_lengthlist__44c1_sm_long,
  138953. 0, 0, 0, 0, 0,
  138954. NULL,
  138955. NULL,
  138956. NULL,
  138957. NULL,
  138958. 0
  138959. };
  138960. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138961. 1,
  138962. 0,
  138963. 2,
  138964. };
  138965. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138966. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138967. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138971. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138972. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138977. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  139012. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139017. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  139022. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139058. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139063. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139068. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0,
  139377. };
  139378. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139379. -0.5, 0.5,
  139380. };
  139381. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139382. 1, 0, 2,
  139383. };
  139384. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139385. _vq_quantthresh__44c1_sm_p1_0,
  139386. _vq_quantmap__44c1_sm_p1_0,
  139387. 3,
  139388. 3
  139389. };
  139390. static static_codebook _44c1_sm_p1_0 = {
  139391. 8, 6561,
  139392. _vq_lengthlist__44c1_sm_p1_0,
  139393. 1, -535822336, 1611661312, 2, 0,
  139394. _vq_quantlist__44c1_sm_p1_0,
  139395. NULL,
  139396. &_vq_auxt__44c1_sm_p1_0,
  139397. NULL,
  139398. 0
  139399. };
  139400. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139401. 2,
  139402. 1,
  139403. 3,
  139404. 0,
  139405. 4,
  139406. };
  139407. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139408. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  139448. };
  139449. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139450. -1.5, -0.5, 0.5, 1.5,
  139451. };
  139452. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139453. 3, 1, 0, 2, 4,
  139454. };
  139455. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139456. _vq_quantthresh__44c1_sm_p2_0,
  139457. _vq_quantmap__44c1_sm_p2_0,
  139458. 5,
  139459. 5
  139460. };
  139461. static static_codebook _44c1_sm_p2_0 = {
  139462. 4, 625,
  139463. _vq_lengthlist__44c1_sm_p2_0,
  139464. 1, -533725184, 1611661312, 3, 0,
  139465. _vq_quantlist__44c1_sm_p2_0,
  139466. NULL,
  139467. &_vq_auxt__44c1_sm_p2_0,
  139468. NULL,
  139469. 0
  139470. };
  139471. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139472. 4,
  139473. 3,
  139474. 5,
  139475. 2,
  139476. 6,
  139477. 1,
  139478. 7,
  139479. 0,
  139480. 8,
  139481. };
  139482. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139483. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139484. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139485. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139486. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139487. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139488. 0,
  139489. };
  139490. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139491. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139492. };
  139493. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139494. 7, 5, 3, 1, 0, 2, 4, 6,
  139495. 8,
  139496. };
  139497. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139498. _vq_quantthresh__44c1_sm_p3_0,
  139499. _vq_quantmap__44c1_sm_p3_0,
  139500. 9,
  139501. 9
  139502. };
  139503. static static_codebook _44c1_sm_p3_0 = {
  139504. 2, 81,
  139505. _vq_lengthlist__44c1_sm_p3_0,
  139506. 1, -531628032, 1611661312, 4, 0,
  139507. _vq_quantlist__44c1_sm_p3_0,
  139508. NULL,
  139509. &_vq_auxt__44c1_sm_p3_0,
  139510. NULL,
  139511. 0
  139512. };
  139513. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139514. 4,
  139515. 3,
  139516. 5,
  139517. 2,
  139518. 6,
  139519. 1,
  139520. 7,
  139521. 0,
  139522. 8,
  139523. };
  139524. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139525. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139526. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139527. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139528. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139529. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139530. 11,
  139531. };
  139532. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139533. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139534. };
  139535. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139536. 7, 5, 3, 1, 0, 2, 4, 6,
  139537. 8,
  139538. };
  139539. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139540. _vq_quantthresh__44c1_sm_p4_0,
  139541. _vq_quantmap__44c1_sm_p4_0,
  139542. 9,
  139543. 9
  139544. };
  139545. static static_codebook _44c1_sm_p4_0 = {
  139546. 2, 81,
  139547. _vq_lengthlist__44c1_sm_p4_0,
  139548. 1, -531628032, 1611661312, 4, 0,
  139549. _vq_quantlist__44c1_sm_p4_0,
  139550. NULL,
  139551. &_vq_auxt__44c1_sm_p4_0,
  139552. NULL,
  139553. 0
  139554. };
  139555. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139556. 8,
  139557. 7,
  139558. 9,
  139559. 6,
  139560. 10,
  139561. 5,
  139562. 11,
  139563. 4,
  139564. 12,
  139565. 3,
  139566. 13,
  139567. 2,
  139568. 14,
  139569. 1,
  139570. 15,
  139571. 0,
  139572. 16,
  139573. };
  139574. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139575. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139576. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139577. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139578. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139579. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139580. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139581. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139582. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139583. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139584. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139585. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139586. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139587. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139588. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139589. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139590. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139591. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139592. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139593. 14,
  139594. };
  139595. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139596. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139597. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139598. };
  139599. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139600. 15, 13, 11, 9, 7, 5, 3, 1,
  139601. 0, 2, 4, 6, 8, 10, 12, 14,
  139602. 16,
  139603. };
  139604. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139605. _vq_quantthresh__44c1_sm_p5_0,
  139606. _vq_quantmap__44c1_sm_p5_0,
  139607. 17,
  139608. 17
  139609. };
  139610. static static_codebook _44c1_sm_p5_0 = {
  139611. 2, 289,
  139612. _vq_lengthlist__44c1_sm_p5_0,
  139613. 1, -529530880, 1611661312, 5, 0,
  139614. _vq_quantlist__44c1_sm_p5_0,
  139615. NULL,
  139616. &_vq_auxt__44c1_sm_p5_0,
  139617. NULL,
  139618. 0
  139619. };
  139620. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139621. 1,
  139622. 0,
  139623. 2,
  139624. };
  139625. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139626. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139627. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139628. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139629. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139630. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139631. 11,
  139632. };
  139633. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139634. -5.5, 5.5,
  139635. };
  139636. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139637. 1, 0, 2,
  139638. };
  139639. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139640. _vq_quantthresh__44c1_sm_p6_0,
  139641. _vq_quantmap__44c1_sm_p6_0,
  139642. 3,
  139643. 3
  139644. };
  139645. static static_codebook _44c1_sm_p6_0 = {
  139646. 4, 81,
  139647. _vq_lengthlist__44c1_sm_p6_0,
  139648. 1, -529137664, 1618345984, 2, 0,
  139649. _vq_quantlist__44c1_sm_p6_0,
  139650. NULL,
  139651. &_vq_auxt__44c1_sm_p6_0,
  139652. NULL,
  139653. 0
  139654. };
  139655. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139656. 5,
  139657. 4,
  139658. 6,
  139659. 3,
  139660. 7,
  139661. 2,
  139662. 8,
  139663. 1,
  139664. 9,
  139665. 0,
  139666. 10,
  139667. };
  139668. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139669. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139670. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139671. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139672. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139673. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139674. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139675. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139676. 10,10,10, 8, 8, 8, 8, 8, 8,
  139677. };
  139678. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139679. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139680. 3.5, 4.5,
  139681. };
  139682. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139683. 9, 7, 5, 3, 1, 0, 2, 4,
  139684. 6, 8, 10,
  139685. };
  139686. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139687. _vq_quantthresh__44c1_sm_p6_1,
  139688. _vq_quantmap__44c1_sm_p6_1,
  139689. 11,
  139690. 11
  139691. };
  139692. static static_codebook _44c1_sm_p6_1 = {
  139693. 2, 121,
  139694. _vq_lengthlist__44c1_sm_p6_1,
  139695. 1, -531365888, 1611661312, 4, 0,
  139696. _vq_quantlist__44c1_sm_p6_1,
  139697. NULL,
  139698. &_vq_auxt__44c1_sm_p6_1,
  139699. NULL,
  139700. 0
  139701. };
  139702. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139703. 6,
  139704. 5,
  139705. 7,
  139706. 4,
  139707. 8,
  139708. 3,
  139709. 9,
  139710. 2,
  139711. 10,
  139712. 1,
  139713. 11,
  139714. 0,
  139715. 12,
  139716. };
  139717. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139718. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139719. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139720. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139721. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139722. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139723. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139724. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139725. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139726. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139727. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139728. 0,12,12,11,11,13,12,14,13,
  139729. };
  139730. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139731. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139732. 12.5, 17.5, 22.5, 27.5,
  139733. };
  139734. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139735. 11, 9, 7, 5, 3, 1, 0, 2,
  139736. 4, 6, 8, 10, 12,
  139737. };
  139738. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139739. _vq_quantthresh__44c1_sm_p7_0,
  139740. _vq_quantmap__44c1_sm_p7_0,
  139741. 13,
  139742. 13
  139743. };
  139744. static static_codebook _44c1_sm_p7_0 = {
  139745. 2, 169,
  139746. _vq_lengthlist__44c1_sm_p7_0,
  139747. 1, -526516224, 1616117760, 4, 0,
  139748. _vq_quantlist__44c1_sm_p7_0,
  139749. NULL,
  139750. &_vq_auxt__44c1_sm_p7_0,
  139751. NULL,
  139752. 0
  139753. };
  139754. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139755. 2,
  139756. 1,
  139757. 3,
  139758. 0,
  139759. 4,
  139760. };
  139761. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139762. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139763. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139764. };
  139765. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139766. -1.5, -0.5, 0.5, 1.5,
  139767. };
  139768. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139769. 3, 1, 0, 2, 4,
  139770. };
  139771. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139772. _vq_quantthresh__44c1_sm_p7_1,
  139773. _vq_quantmap__44c1_sm_p7_1,
  139774. 5,
  139775. 5
  139776. };
  139777. static static_codebook _44c1_sm_p7_1 = {
  139778. 2, 25,
  139779. _vq_lengthlist__44c1_sm_p7_1,
  139780. 1, -533725184, 1611661312, 3, 0,
  139781. _vq_quantlist__44c1_sm_p7_1,
  139782. NULL,
  139783. &_vq_auxt__44c1_sm_p7_1,
  139784. NULL,
  139785. 0
  139786. };
  139787. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139788. 6,
  139789. 5,
  139790. 7,
  139791. 4,
  139792. 8,
  139793. 3,
  139794. 9,
  139795. 2,
  139796. 10,
  139797. 1,
  139798. 11,
  139799. 0,
  139800. 12,
  139801. };
  139802. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139803. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139804. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139805. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139806. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139807. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139808. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139809. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139810. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139811. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139812. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139813. 13,13,13,13,13,13,13,13,13,
  139814. };
  139815. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139816. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139817. 552.5, 773.5, 994.5, 1215.5,
  139818. };
  139819. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139820. 11, 9, 7, 5, 3, 1, 0, 2,
  139821. 4, 6, 8, 10, 12,
  139822. };
  139823. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139824. _vq_quantthresh__44c1_sm_p8_0,
  139825. _vq_quantmap__44c1_sm_p8_0,
  139826. 13,
  139827. 13
  139828. };
  139829. static static_codebook _44c1_sm_p8_0 = {
  139830. 2, 169,
  139831. _vq_lengthlist__44c1_sm_p8_0,
  139832. 1, -514541568, 1627103232, 4, 0,
  139833. _vq_quantlist__44c1_sm_p8_0,
  139834. NULL,
  139835. &_vq_auxt__44c1_sm_p8_0,
  139836. NULL,
  139837. 0
  139838. };
  139839. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139840. 6,
  139841. 5,
  139842. 7,
  139843. 4,
  139844. 8,
  139845. 3,
  139846. 9,
  139847. 2,
  139848. 10,
  139849. 1,
  139850. 11,
  139851. 0,
  139852. 12,
  139853. };
  139854. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139855. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139856. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139857. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139858. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139859. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139860. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139861. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139862. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139863. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139864. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139865. 20,13,12,12,12,14,12,14,13,
  139866. };
  139867. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139868. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139869. 42.5, 59.5, 76.5, 93.5,
  139870. };
  139871. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139872. 11, 9, 7, 5, 3, 1, 0, 2,
  139873. 4, 6, 8, 10, 12,
  139874. };
  139875. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139876. _vq_quantthresh__44c1_sm_p8_1,
  139877. _vq_quantmap__44c1_sm_p8_1,
  139878. 13,
  139879. 13
  139880. };
  139881. static static_codebook _44c1_sm_p8_1 = {
  139882. 2, 169,
  139883. _vq_lengthlist__44c1_sm_p8_1,
  139884. 1, -522616832, 1620115456, 4, 0,
  139885. _vq_quantlist__44c1_sm_p8_1,
  139886. NULL,
  139887. &_vq_auxt__44c1_sm_p8_1,
  139888. NULL,
  139889. 0
  139890. };
  139891. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139892. 8,
  139893. 7,
  139894. 9,
  139895. 6,
  139896. 10,
  139897. 5,
  139898. 11,
  139899. 4,
  139900. 12,
  139901. 3,
  139902. 13,
  139903. 2,
  139904. 14,
  139905. 1,
  139906. 15,
  139907. 0,
  139908. 16,
  139909. };
  139910. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139911. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139912. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139913. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139914. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139915. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139916. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139917. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139918. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139919. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139920. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139921. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139922. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139923. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139924. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139925. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139926. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139927. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139928. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139929. 9,
  139930. };
  139931. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139932. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139933. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139934. };
  139935. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139936. 15, 13, 11, 9, 7, 5, 3, 1,
  139937. 0, 2, 4, 6, 8, 10, 12, 14,
  139938. 16,
  139939. };
  139940. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139941. _vq_quantthresh__44c1_sm_p8_2,
  139942. _vq_quantmap__44c1_sm_p8_2,
  139943. 17,
  139944. 17
  139945. };
  139946. static static_codebook _44c1_sm_p8_2 = {
  139947. 2, 289,
  139948. _vq_lengthlist__44c1_sm_p8_2,
  139949. 1, -529530880, 1611661312, 5, 0,
  139950. _vq_quantlist__44c1_sm_p8_2,
  139951. NULL,
  139952. &_vq_auxt__44c1_sm_p8_2,
  139953. NULL,
  139954. 0
  139955. };
  139956. static long _huff_lengthlist__44c1_sm_short[] = {
  139957. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139958. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139959. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139960. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139961. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139962. 11,
  139963. };
  139964. static static_codebook _huff_book__44c1_sm_short = {
  139965. 2, 81,
  139966. _huff_lengthlist__44c1_sm_short,
  139967. 0, 0, 0, 0, 0,
  139968. NULL,
  139969. NULL,
  139970. NULL,
  139971. NULL,
  139972. 0
  139973. };
  139974. static long _huff_lengthlist__44cn1_s_long[] = {
  139975. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139976. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139977. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139978. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139979. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139980. 20,
  139981. };
  139982. static static_codebook _huff_book__44cn1_s_long = {
  139983. 2, 81,
  139984. _huff_lengthlist__44cn1_s_long,
  139985. 0, 0, 0, 0, 0,
  139986. NULL,
  139987. NULL,
  139988. NULL,
  139989. NULL,
  139990. 0
  139991. };
  139992. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139993. 1,
  139994. 0,
  139995. 2,
  139996. };
  139997. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139998. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139999. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140003. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140004. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140009. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140044. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  140045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  140049. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  140054. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140090. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140095. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140100. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0,
  140409. };
  140410. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140411. -0.5, 0.5,
  140412. };
  140413. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140414. 1, 0, 2,
  140415. };
  140416. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140417. _vq_quantthresh__44cn1_s_p1_0,
  140418. _vq_quantmap__44cn1_s_p1_0,
  140419. 3,
  140420. 3
  140421. };
  140422. static static_codebook _44cn1_s_p1_0 = {
  140423. 8, 6561,
  140424. _vq_lengthlist__44cn1_s_p1_0,
  140425. 1, -535822336, 1611661312, 2, 0,
  140426. _vq_quantlist__44cn1_s_p1_0,
  140427. NULL,
  140428. &_vq_auxt__44cn1_s_p1_0,
  140429. NULL,
  140430. 0
  140431. };
  140432. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140433. 2,
  140434. 1,
  140435. 3,
  140436. 0,
  140437. 4,
  140438. };
  140439. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140440. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  140480. };
  140481. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140482. -1.5, -0.5, 0.5, 1.5,
  140483. };
  140484. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140485. 3, 1, 0, 2, 4,
  140486. };
  140487. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140488. _vq_quantthresh__44cn1_s_p2_0,
  140489. _vq_quantmap__44cn1_s_p2_0,
  140490. 5,
  140491. 5
  140492. };
  140493. static static_codebook _44cn1_s_p2_0 = {
  140494. 4, 625,
  140495. _vq_lengthlist__44cn1_s_p2_0,
  140496. 1, -533725184, 1611661312, 3, 0,
  140497. _vq_quantlist__44cn1_s_p2_0,
  140498. NULL,
  140499. &_vq_auxt__44cn1_s_p2_0,
  140500. NULL,
  140501. 0
  140502. };
  140503. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140504. 4,
  140505. 3,
  140506. 5,
  140507. 2,
  140508. 6,
  140509. 1,
  140510. 7,
  140511. 0,
  140512. 8,
  140513. };
  140514. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140515. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140516. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140517. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140518. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140519. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140520. 0,
  140521. };
  140522. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140523. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140524. };
  140525. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140526. 7, 5, 3, 1, 0, 2, 4, 6,
  140527. 8,
  140528. };
  140529. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140530. _vq_quantthresh__44cn1_s_p3_0,
  140531. _vq_quantmap__44cn1_s_p3_0,
  140532. 9,
  140533. 9
  140534. };
  140535. static static_codebook _44cn1_s_p3_0 = {
  140536. 2, 81,
  140537. _vq_lengthlist__44cn1_s_p3_0,
  140538. 1, -531628032, 1611661312, 4, 0,
  140539. _vq_quantlist__44cn1_s_p3_0,
  140540. NULL,
  140541. &_vq_auxt__44cn1_s_p3_0,
  140542. NULL,
  140543. 0
  140544. };
  140545. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140546. 4,
  140547. 3,
  140548. 5,
  140549. 2,
  140550. 6,
  140551. 1,
  140552. 7,
  140553. 0,
  140554. 8,
  140555. };
  140556. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140557. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140558. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140559. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140560. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140561. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140562. 11,
  140563. };
  140564. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140565. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140566. };
  140567. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140568. 7, 5, 3, 1, 0, 2, 4, 6,
  140569. 8,
  140570. };
  140571. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140572. _vq_quantthresh__44cn1_s_p4_0,
  140573. _vq_quantmap__44cn1_s_p4_0,
  140574. 9,
  140575. 9
  140576. };
  140577. static static_codebook _44cn1_s_p4_0 = {
  140578. 2, 81,
  140579. _vq_lengthlist__44cn1_s_p4_0,
  140580. 1, -531628032, 1611661312, 4, 0,
  140581. _vq_quantlist__44cn1_s_p4_0,
  140582. NULL,
  140583. &_vq_auxt__44cn1_s_p4_0,
  140584. NULL,
  140585. 0
  140586. };
  140587. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140588. 8,
  140589. 7,
  140590. 9,
  140591. 6,
  140592. 10,
  140593. 5,
  140594. 11,
  140595. 4,
  140596. 12,
  140597. 3,
  140598. 13,
  140599. 2,
  140600. 14,
  140601. 1,
  140602. 15,
  140603. 0,
  140604. 16,
  140605. };
  140606. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140607. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140608. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140609. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140610. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140611. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140612. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140613. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140614. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140615. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140616. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140617. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140618. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140619. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140620. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140621. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140622. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140623. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140624. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140625. 14,
  140626. };
  140627. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140628. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140629. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140630. };
  140631. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140632. 15, 13, 11, 9, 7, 5, 3, 1,
  140633. 0, 2, 4, 6, 8, 10, 12, 14,
  140634. 16,
  140635. };
  140636. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140637. _vq_quantthresh__44cn1_s_p5_0,
  140638. _vq_quantmap__44cn1_s_p5_0,
  140639. 17,
  140640. 17
  140641. };
  140642. static static_codebook _44cn1_s_p5_0 = {
  140643. 2, 289,
  140644. _vq_lengthlist__44cn1_s_p5_0,
  140645. 1, -529530880, 1611661312, 5, 0,
  140646. _vq_quantlist__44cn1_s_p5_0,
  140647. NULL,
  140648. &_vq_auxt__44cn1_s_p5_0,
  140649. NULL,
  140650. 0
  140651. };
  140652. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140653. 1,
  140654. 0,
  140655. 2,
  140656. };
  140657. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140658. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140659. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140660. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140661. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140662. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140663. 10,
  140664. };
  140665. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140666. -5.5, 5.5,
  140667. };
  140668. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140669. 1, 0, 2,
  140670. };
  140671. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140672. _vq_quantthresh__44cn1_s_p6_0,
  140673. _vq_quantmap__44cn1_s_p6_0,
  140674. 3,
  140675. 3
  140676. };
  140677. static static_codebook _44cn1_s_p6_0 = {
  140678. 4, 81,
  140679. _vq_lengthlist__44cn1_s_p6_0,
  140680. 1, -529137664, 1618345984, 2, 0,
  140681. _vq_quantlist__44cn1_s_p6_0,
  140682. NULL,
  140683. &_vq_auxt__44cn1_s_p6_0,
  140684. NULL,
  140685. 0
  140686. };
  140687. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140688. 5,
  140689. 4,
  140690. 6,
  140691. 3,
  140692. 7,
  140693. 2,
  140694. 8,
  140695. 1,
  140696. 9,
  140697. 0,
  140698. 10,
  140699. };
  140700. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140701. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140702. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140703. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140704. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140705. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140706. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140707. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140708. 10,10,10, 9, 9, 9, 9, 9, 9,
  140709. };
  140710. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140711. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140712. 3.5, 4.5,
  140713. };
  140714. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140715. 9, 7, 5, 3, 1, 0, 2, 4,
  140716. 6, 8, 10,
  140717. };
  140718. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140719. _vq_quantthresh__44cn1_s_p6_1,
  140720. _vq_quantmap__44cn1_s_p6_1,
  140721. 11,
  140722. 11
  140723. };
  140724. static static_codebook _44cn1_s_p6_1 = {
  140725. 2, 121,
  140726. _vq_lengthlist__44cn1_s_p6_1,
  140727. 1, -531365888, 1611661312, 4, 0,
  140728. _vq_quantlist__44cn1_s_p6_1,
  140729. NULL,
  140730. &_vq_auxt__44cn1_s_p6_1,
  140731. NULL,
  140732. 0
  140733. };
  140734. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140735. 6,
  140736. 5,
  140737. 7,
  140738. 4,
  140739. 8,
  140740. 3,
  140741. 9,
  140742. 2,
  140743. 10,
  140744. 1,
  140745. 11,
  140746. 0,
  140747. 12,
  140748. };
  140749. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140750. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140751. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140752. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140753. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140754. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140755. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140756. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140757. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140758. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140759. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140760. 0,13,13,12,12,13,13,13,14,
  140761. };
  140762. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140763. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140764. 12.5, 17.5, 22.5, 27.5,
  140765. };
  140766. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140767. 11, 9, 7, 5, 3, 1, 0, 2,
  140768. 4, 6, 8, 10, 12,
  140769. };
  140770. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140771. _vq_quantthresh__44cn1_s_p7_0,
  140772. _vq_quantmap__44cn1_s_p7_0,
  140773. 13,
  140774. 13
  140775. };
  140776. static static_codebook _44cn1_s_p7_0 = {
  140777. 2, 169,
  140778. _vq_lengthlist__44cn1_s_p7_0,
  140779. 1, -526516224, 1616117760, 4, 0,
  140780. _vq_quantlist__44cn1_s_p7_0,
  140781. NULL,
  140782. &_vq_auxt__44cn1_s_p7_0,
  140783. NULL,
  140784. 0
  140785. };
  140786. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140787. 2,
  140788. 1,
  140789. 3,
  140790. 0,
  140791. 4,
  140792. };
  140793. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140794. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140795. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140796. };
  140797. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140798. -1.5, -0.5, 0.5, 1.5,
  140799. };
  140800. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140801. 3, 1, 0, 2, 4,
  140802. };
  140803. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140804. _vq_quantthresh__44cn1_s_p7_1,
  140805. _vq_quantmap__44cn1_s_p7_1,
  140806. 5,
  140807. 5
  140808. };
  140809. static static_codebook _44cn1_s_p7_1 = {
  140810. 2, 25,
  140811. _vq_lengthlist__44cn1_s_p7_1,
  140812. 1, -533725184, 1611661312, 3, 0,
  140813. _vq_quantlist__44cn1_s_p7_1,
  140814. NULL,
  140815. &_vq_auxt__44cn1_s_p7_1,
  140816. NULL,
  140817. 0
  140818. };
  140819. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140820. 2,
  140821. 1,
  140822. 3,
  140823. 0,
  140824. 4,
  140825. };
  140826. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140827. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140828. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140829. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140830. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140831. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140832. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140833. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140834. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140835. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140836. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140837. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140838. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140839. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140840. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140841. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140842. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140852. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140853. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140854. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140855. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140856. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140857. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140858. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140859. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140860. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140861. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140862. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140863. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140864. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140865. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140866. 12,
  140867. };
  140868. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140869. -331.5, -110.5, 110.5, 331.5,
  140870. };
  140871. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140872. 3, 1, 0, 2, 4,
  140873. };
  140874. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140875. _vq_quantthresh__44cn1_s_p8_0,
  140876. _vq_quantmap__44cn1_s_p8_0,
  140877. 5,
  140878. 5
  140879. };
  140880. static static_codebook _44cn1_s_p8_0 = {
  140881. 4, 625,
  140882. _vq_lengthlist__44cn1_s_p8_0,
  140883. 1, -518283264, 1627103232, 3, 0,
  140884. _vq_quantlist__44cn1_s_p8_0,
  140885. NULL,
  140886. &_vq_auxt__44cn1_s_p8_0,
  140887. NULL,
  140888. 0
  140889. };
  140890. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140891. 6,
  140892. 5,
  140893. 7,
  140894. 4,
  140895. 8,
  140896. 3,
  140897. 9,
  140898. 2,
  140899. 10,
  140900. 1,
  140901. 11,
  140902. 0,
  140903. 12,
  140904. };
  140905. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140906. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140907. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140908. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140909. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140910. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140911. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140912. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140913. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140914. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140915. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140916. 15,12,12,11,11,14,12,13,14,
  140917. };
  140918. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140919. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140920. 42.5, 59.5, 76.5, 93.5,
  140921. };
  140922. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140923. 11, 9, 7, 5, 3, 1, 0, 2,
  140924. 4, 6, 8, 10, 12,
  140925. };
  140926. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140927. _vq_quantthresh__44cn1_s_p8_1,
  140928. _vq_quantmap__44cn1_s_p8_1,
  140929. 13,
  140930. 13
  140931. };
  140932. static static_codebook _44cn1_s_p8_1 = {
  140933. 2, 169,
  140934. _vq_lengthlist__44cn1_s_p8_1,
  140935. 1, -522616832, 1620115456, 4, 0,
  140936. _vq_quantlist__44cn1_s_p8_1,
  140937. NULL,
  140938. &_vq_auxt__44cn1_s_p8_1,
  140939. NULL,
  140940. 0
  140941. };
  140942. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140943. 8,
  140944. 7,
  140945. 9,
  140946. 6,
  140947. 10,
  140948. 5,
  140949. 11,
  140950. 4,
  140951. 12,
  140952. 3,
  140953. 13,
  140954. 2,
  140955. 14,
  140956. 1,
  140957. 15,
  140958. 0,
  140959. 16,
  140960. };
  140961. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140962. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140963. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140964. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140965. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140966. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140967. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140968. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140969. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140970. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140971. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140972. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140973. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140974. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140975. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140976. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140977. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140978. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140979. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140980. 9,
  140981. };
  140982. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140983. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140984. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140985. };
  140986. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140987. 15, 13, 11, 9, 7, 5, 3, 1,
  140988. 0, 2, 4, 6, 8, 10, 12, 14,
  140989. 16,
  140990. };
  140991. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140992. _vq_quantthresh__44cn1_s_p8_2,
  140993. _vq_quantmap__44cn1_s_p8_2,
  140994. 17,
  140995. 17
  140996. };
  140997. static static_codebook _44cn1_s_p8_2 = {
  140998. 2, 289,
  140999. _vq_lengthlist__44cn1_s_p8_2,
  141000. 1, -529530880, 1611661312, 5, 0,
  141001. _vq_quantlist__44cn1_s_p8_2,
  141002. NULL,
  141003. &_vq_auxt__44cn1_s_p8_2,
  141004. NULL,
  141005. 0
  141006. };
  141007. static long _huff_lengthlist__44cn1_s_short[] = {
  141008. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141009. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141010. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141011. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141012. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141013. 10,
  141014. };
  141015. static static_codebook _huff_book__44cn1_s_short = {
  141016. 2, 81,
  141017. _huff_lengthlist__44cn1_s_short,
  141018. 0, 0, 0, 0, 0,
  141019. NULL,
  141020. NULL,
  141021. NULL,
  141022. NULL,
  141023. 0
  141024. };
  141025. static long _huff_lengthlist__44cn1_sm_long[] = {
  141026. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141027. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141028. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141029. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141030. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141031. 17,
  141032. };
  141033. static static_codebook _huff_book__44cn1_sm_long = {
  141034. 2, 81,
  141035. _huff_lengthlist__44cn1_sm_long,
  141036. 0, 0, 0, 0, 0,
  141037. NULL,
  141038. NULL,
  141039. NULL,
  141040. NULL,
  141041. 0
  141042. };
  141043. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141044. 1,
  141045. 0,
  141046. 2,
  141047. };
  141048. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141049. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141050. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141054. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141055. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141059. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141060. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  141095. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  141100. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  141105. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  141106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141141. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141146. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141150. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141151. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141459. 0,
  141460. };
  141461. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141462. -0.5, 0.5,
  141463. };
  141464. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141465. 1, 0, 2,
  141466. };
  141467. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141468. _vq_quantthresh__44cn1_sm_p1_0,
  141469. _vq_quantmap__44cn1_sm_p1_0,
  141470. 3,
  141471. 3
  141472. };
  141473. static static_codebook _44cn1_sm_p1_0 = {
  141474. 8, 6561,
  141475. _vq_lengthlist__44cn1_sm_p1_0,
  141476. 1, -535822336, 1611661312, 2, 0,
  141477. _vq_quantlist__44cn1_sm_p1_0,
  141478. NULL,
  141479. &_vq_auxt__44cn1_sm_p1_0,
  141480. NULL,
  141481. 0
  141482. };
  141483. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141484. 2,
  141485. 1,
  141486. 3,
  141487. 0,
  141488. 4,
  141489. };
  141490. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141491. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141494. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141497. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  141531. };
  141532. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141533. -1.5, -0.5, 0.5, 1.5,
  141534. };
  141535. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141536. 3, 1, 0, 2, 4,
  141537. };
  141538. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141539. _vq_quantthresh__44cn1_sm_p2_0,
  141540. _vq_quantmap__44cn1_sm_p2_0,
  141541. 5,
  141542. 5
  141543. };
  141544. static static_codebook _44cn1_sm_p2_0 = {
  141545. 4, 625,
  141546. _vq_lengthlist__44cn1_sm_p2_0,
  141547. 1, -533725184, 1611661312, 3, 0,
  141548. _vq_quantlist__44cn1_sm_p2_0,
  141549. NULL,
  141550. &_vq_auxt__44cn1_sm_p2_0,
  141551. NULL,
  141552. 0
  141553. };
  141554. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141555. 4,
  141556. 3,
  141557. 5,
  141558. 2,
  141559. 6,
  141560. 1,
  141561. 7,
  141562. 0,
  141563. 8,
  141564. };
  141565. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141566. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141567. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141568. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141569. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141570. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141571. 0,
  141572. };
  141573. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141574. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141575. };
  141576. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141577. 7, 5, 3, 1, 0, 2, 4, 6,
  141578. 8,
  141579. };
  141580. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141581. _vq_quantthresh__44cn1_sm_p3_0,
  141582. _vq_quantmap__44cn1_sm_p3_0,
  141583. 9,
  141584. 9
  141585. };
  141586. static static_codebook _44cn1_sm_p3_0 = {
  141587. 2, 81,
  141588. _vq_lengthlist__44cn1_sm_p3_0,
  141589. 1, -531628032, 1611661312, 4, 0,
  141590. _vq_quantlist__44cn1_sm_p3_0,
  141591. NULL,
  141592. &_vq_auxt__44cn1_sm_p3_0,
  141593. NULL,
  141594. 0
  141595. };
  141596. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141597. 4,
  141598. 3,
  141599. 5,
  141600. 2,
  141601. 6,
  141602. 1,
  141603. 7,
  141604. 0,
  141605. 8,
  141606. };
  141607. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141608. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141609. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141610. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141611. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141612. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141613. 11,
  141614. };
  141615. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141616. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141617. };
  141618. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141619. 7, 5, 3, 1, 0, 2, 4, 6,
  141620. 8,
  141621. };
  141622. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141623. _vq_quantthresh__44cn1_sm_p4_0,
  141624. _vq_quantmap__44cn1_sm_p4_0,
  141625. 9,
  141626. 9
  141627. };
  141628. static static_codebook _44cn1_sm_p4_0 = {
  141629. 2, 81,
  141630. _vq_lengthlist__44cn1_sm_p4_0,
  141631. 1, -531628032, 1611661312, 4, 0,
  141632. _vq_quantlist__44cn1_sm_p4_0,
  141633. NULL,
  141634. &_vq_auxt__44cn1_sm_p4_0,
  141635. NULL,
  141636. 0
  141637. };
  141638. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141639. 8,
  141640. 7,
  141641. 9,
  141642. 6,
  141643. 10,
  141644. 5,
  141645. 11,
  141646. 4,
  141647. 12,
  141648. 3,
  141649. 13,
  141650. 2,
  141651. 14,
  141652. 1,
  141653. 15,
  141654. 0,
  141655. 16,
  141656. };
  141657. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141658. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141659. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141660. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141661. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141662. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141663. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141664. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141665. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141666. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141667. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141668. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141669. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141670. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141671. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141672. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141673. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141674. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141675. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141676. 14,
  141677. };
  141678. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141679. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141680. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141681. };
  141682. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141683. 15, 13, 11, 9, 7, 5, 3, 1,
  141684. 0, 2, 4, 6, 8, 10, 12, 14,
  141685. 16,
  141686. };
  141687. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141688. _vq_quantthresh__44cn1_sm_p5_0,
  141689. _vq_quantmap__44cn1_sm_p5_0,
  141690. 17,
  141691. 17
  141692. };
  141693. static static_codebook _44cn1_sm_p5_0 = {
  141694. 2, 289,
  141695. _vq_lengthlist__44cn1_sm_p5_0,
  141696. 1, -529530880, 1611661312, 5, 0,
  141697. _vq_quantlist__44cn1_sm_p5_0,
  141698. NULL,
  141699. &_vq_auxt__44cn1_sm_p5_0,
  141700. NULL,
  141701. 0
  141702. };
  141703. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141704. 1,
  141705. 0,
  141706. 2,
  141707. };
  141708. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141709. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141710. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141711. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141712. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141713. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141714. 10,
  141715. };
  141716. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141717. -5.5, 5.5,
  141718. };
  141719. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141720. 1, 0, 2,
  141721. };
  141722. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141723. _vq_quantthresh__44cn1_sm_p6_0,
  141724. _vq_quantmap__44cn1_sm_p6_0,
  141725. 3,
  141726. 3
  141727. };
  141728. static static_codebook _44cn1_sm_p6_0 = {
  141729. 4, 81,
  141730. _vq_lengthlist__44cn1_sm_p6_0,
  141731. 1, -529137664, 1618345984, 2, 0,
  141732. _vq_quantlist__44cn1_sm_p6_0,
  141733. NULL,
  141734. &_vq_auxt__44cn1_sm_p6_0,
  141735. NULL,
  141736. 0
  141737. };
  141738. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141739. 5,
  141740. 4,
  141741. 6,
  141742. 3,
  141743. 7,
  141744. 2,
  141745. 8,
  141746. 1,
  141747. 9,
  141748. 0,
  141749. 10,
  141750. };
  141751. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141752. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141753. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141754. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141755. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141756. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141757. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141758. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141759. 10,10,10, 8, 9, 8, 8, 9, 8,
  141760. };
  141761. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141762. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141763. 3.5, 4.5,
  141764. };
  141765. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141766. 9, 7, 5, 3, 1, 0, 2, 4,
  141767. 6, 8, 10,
  141768. };
  141769. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141770. _vq_quantthresh__44cn1_sm_p6_1,
  141771. _vq_quantmap__44cn1_sm_p6_1,
  141772. 11,
  141773. 11
  141774. };
  141775. static static_codebook _44cn1_sm_p6_1 = {
  141776. 2, 121,
  141777. _vq_lengthlist__44cn1_sm_p6_1,
  141778. 1, -531365888, 1611661312, 4, 0,
  141779. _vq_quantlist__44cn1_sm_p6_1,
  141780. NULL,
  141781. &_vq_auxt__44cn1_sm_p6_1,
  141782. NULL,
  141783. 0
  141784. };
  141785. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141786. 6,
  141787. 5,
  141788. 7,
  141789. 4,
  141790. 8,
  141791. 3,
  141792. 9,
  141793. 2,
  141794. 10,
  141795. 1,
  141796. 11,
  141797. 0,
  141798. 12,
  141799. };
  141800. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141801. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141802. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141803. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141804. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141805. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141806. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141807. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141808. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141809. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141810. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141811. 0,13,12,12,12,13,13,13,14,
  141812. };
  141813. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141814. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141815. 12.5, 17.5, 22.5, 27.5,
  141816. };
  141817. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141818. 11, 9, 7, 5, 3, 1, 0, 2,
  141819. 4, 6, 8, 10, 12,
  141820. };
  141821. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141822. _vq_quantthresh__44cn1_sm_p7_0,
  141823. _vq_quantmap__44cn1_sm_p7_0,
  141824. 13,
  141825. 13
  141826. };
  141827. static static_codebook _44cn1_sm_p7_0 = {
  141828. 2, 169,
  141829. _vq_lengthlist__44cn1_sm_p7_0,
  141830. 1, -526516224, 1616117760, 4, 0,
  141831. _vq_quantlist__44cn1_sm_p7_0,
  141832. NULL,
  141833. &_vq_auxt__44cn1_sm_p7_0,
  141834. NULL,
  141835. 0
  141836. };
  141837. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141838. 2,
  141839. 1,
  141840. 3,
  141841. 0,
  141842. 4,
  141843. };
  141844. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141845. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141846. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141847. };
  141848. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141849. -1.5, -0.5, 0.5, 1.5,
  141850. };
  141851. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141852. 3, 1, 0, 2, 4,
  141853. };
  141854. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141855. _vq_quantthresh__44cn1_sm_p7_1,
  141856. _vq_quantmap__44cn1_sm_p7_1,
  141857. 5,
  141858. 5
  141859. };
  141860. static static_codebook _44cn1_sm_p7_1 = {
  141861. 2, 25,
  141862. _vq_lengthlist__44cn1_sm_p7_1,
  141863. 1, -533725184, 1611661312, 3, 0,
  141864. _vq_quantlist__44cn1_sm_p7_1,
  141865. NULL,
  141866. &_vq_auxt__44cn1_sm_p7_1,
  141867. NULL,
  141868. 0
  141869. };
  141870. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141871. 4,
  141872. 3,
  141873. 5,
  141874. 2,
  141875. 6,
  141876. 1,
  141877. 7,
  141878. 0,
  141879. 8,
  141880. };
  141881. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141882. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141883. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141884. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141885. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141886. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141887. 14,
  141888. };
  141889. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141890. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141891. };
  141892. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141893. 7, 5, 3, 1, 0, 2, 4, 6,
  141894. 8,
  141895. };
  141896. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141897. _vq_quantthresh__44cn1_sm_p8_0,
  141898. _vq_quantmap__44cn1_sm_p8_0,
  141899. 9,
  141900. 9
  141901. };
  141902. static static_codebook _44cn1_sm_p8_0 = {
  141903. 2, 81,
  141904. _vq_lengthlist__44cn1_sm_p8_0,
  141905. 1, -516186112, 1627103232, 4, 0,
  141906. _vq_quantlist__44cn1_sm_p8_0,
  141907. NULL,
  141908. &_vq_auxt__44cn1_sm_p8_0,
  141909. NULL,
  141910. 0
  141911. };
  141912. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141913. 6,
  141914. 5,
  141915. 7,
  141916. 4,
  141917. 8,
  141918. 3,
  141919. 9,
  141920. 2,
  141921. 10,
  141922. 1,
  141923. 11,
  141924. 0,
  141925. 12,
  141926. };
  141927. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141928. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141929. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141930. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141931. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141932. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141933. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141934. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141935. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141936. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141937. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141938. 17,12,12,11,10,13,11,13,13,
  141939. };
  141940. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141941. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141942. 42.5, 59.5, 76.5, 93.5,
  141943. };
  141944. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141945. 11, 9, 7, 5, 3, 1, 0, 2,
  141946. 4, 6, 8, 10, 12,
  141947. };
  141948. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141949. _vq_quantthresh__44cn1_sm_p8_1,
  141950. _vq_quantmap__44cn1_sm_p8_1,
  141951. 13,
  141952. 13
  141953. };
  141954. static static_codebook _44cn1_sm_p8_1 = {
  141955. 2, 169,
  141956. _vq_lengthlist__44cn1_sm_p8_1,
  141957. 1, -522616832, 1620115456, 4, 0,
  141958. _vq_quantlist__44cn1_sm_p8_1,
  141959. NULL,
  141960. &_vq_auxt__44cn1_sm_p8_1,
  141961. NULL,
  141962. 0
  141963. };
  141964. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141965. 8,
  141966. 7,
  141967. 9,
  141968. 6,
  141969. 10,
  141970. 5,
  141971. 11,
  141972. 4,
  141973. 12,
  141974. 3,
  141975. 13,
  141976. 2,
  141977. 14,
  141978. 1,
  141979. 15,
  141980. 0,
  141981. 16,
  141982. };
  141983. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141984. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141985. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141986. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141987. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141988. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141989. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141990. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141991. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141992. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141993. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141994. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141995. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141996. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141997. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141998. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141999. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142000. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142001. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142002. 9,
  142003. };
  142004. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142005. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142006. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142007. };
  142008. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142009. 15, 13, 11, 9, 7, 5, 3, 1,
  142010. 0, 2, 4, 6, 8, 10, 12, 14,
  142011. 16,
  142012. };
  142013. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142014. _vq_quantthresh__44cn1_sm_p8_2,
  142015. _vq_quantmap__44cn1_sm_p8_2,
  142016. 17,
  142017. 17
  142018. };
  142019. static static_codebook _44cn1_sm_p8_2 = {
  142020. 2, 289,
  142021. _vq_lengthlist__44cn1_sm_p8_2,
  142022. 1, -529530880, 1611661312, 5, 0,
  142023. _vq_quantlist__44cn1_sm_p8_2,
  142024. NULL,
  142025. &_vq_auxt__44cn1_sm_p8_2,
  142026. NULL,
  142027. 0
  142028. };
  142029. static long _huff_lengthlist__44cn1_sm_short[] = {
  142030. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142031. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142032. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142033. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142034. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142035. 9,
  142036. };
  142037. static static_codebook _huff_book__44cn1_sm_short = {
  142038. 2, 81,
  142039. _huff_lengthlist__44cn1_sm_short,
  142040. 0, 0, 0, 0, 0,
  142041. NULL,
  142042. NULL,
  142043. NULL,
  142044. NULL,
  142045. 0
  142046. };
  142047. /*** End of inlined file: res_books_stereo.h ***/
  142048. /***** residue backends *********************************************/
  142049. static vorbis_info_residue0 _residue_44_low={
  142050. 0,-1, -1, 9,-1,
  142051. /* 0 1 2 3 4 5 6 7 */
  142052. {0},
  142053. {-1},
  142054. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142055. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142056. };
  142057. static vorbis_info_residue0 _residue_44_mid={
  142058. 0,-1, -1, 10,-1,
  142059. /* 0 1 2 3 4 5 6 7 8 */
  142060. {0},
  142061. {-1},
  142062. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142063. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142064. };
  142065. static vorbis_info_residue0 _residue_44_high={
  142066. 0,-1, -1, 10,-1,
  142067. /* 0 1 2 3 4 5 6 7 8 */
  142068. {0},
  142069. {-1},
  142070. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142071. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142072. };
  142073. static static_bookblock _resbook_44s_n1={
  142074. {
  142075. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142076. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142077. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142078. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142079. }
  142080. };
  142081. static static_bookblock _resbook_44sm_n1={
  142082. {
  142083. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142084. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142085. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142086. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142087. }
  142088. };
  142089. static static_bookblock _resbook_44s_0={
  142090. {
  142091. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142092. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142093. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142094. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142095. }
  142096. };
  142097. static static_bookblock _resbook_44sm_0={
  142098. {
  142099. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142100. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142101. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142102. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142103. }
  142104. };
  142105. static static_bookblock _resbook_44s_1={
  142106. {
  142107. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142108. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142109. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142110. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142111. }
  142112. };
  142113. static static_bookblock _resbook_44sm_1={
  142114. {
  142115. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142116. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142117. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142118. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142119. }
  142120. };
  142121. static static_bookblock _resbook_44s_2={
  142122. {
  142123. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142124. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142125. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142126. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142127. }
  142128. };
  142129. static static_bookblock _resbook_44s_3={
  142130. {
  142131. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142132. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142133. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142134. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142135. }
  142136. };
  142137. static static_bookblock _resbook_44s_4={
  142138. {
  142139. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142140. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142141. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142142. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142143. }
  142144. };
  142145. static static_bookblock _resbook_44s_5={
  142146. {
  142147. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142148. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142149. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142150. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142151. }
  142152. };
  142153. static static_bookblock _resbook_44s_6={
  142154. {
  142155. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142156. {0,0,&_44c6_s_p4_0},
  142157. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142158. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142159. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142160. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142161. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142162. }
  142163. };
  142164. static static_bookblock _resbook_44s_7={
  142165. {
  142166. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142167. {0,0,&_44c7_s_p4_0},
  142168. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142169. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142170. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142171. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142172. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142173. }
  142174. };
  142175. static static_bookblock _resbook_44s_8={
  142176. {
  142177. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142178. {0,0,&_44c8_s_p4_0},
  142179. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142180. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142181. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142182. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142183. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142184. }
  142185. };
  142186. static static_bookblock _resbook_44s_9={
  142187. {
  142188. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142189. {0,0,&_44c9_s_p4_0},
  142190. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142191. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142192. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142193. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142194. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142195. }
  142196. };
  142197. static vorbis_residue_template _res_44s_n1[]={
  142198. {2,0, &_residue_44_low,
  142199. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142200. &_resbook_44s_n1,&_resbook_44sm_n1},
  142201. {2,0, &_residue_44_low,
  142202. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142203. &_resbook_44s_n1,&_resbook_44sm_n1}
  142204. };
  142205. static vorbis_residue_template _res_44s_0[]={
  142206. {2,0, &_residue_44_low,
  142207. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142208. &_resbook_44s_0,&_resbook_44sm_0},
  142209. {2,0, &_residue_44_low,
  142210. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142211. &_resbook_44s_0,&_resbook_44sm_0}
  142212. };
  142213. static vorbis_residue_template _res_44s_1[]={
  142214. {2,0, &_residue_44_low,
  142215. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142216. &_resbook_44s_1,&_resbook_44sm_1},
  142217. {2,0, &_residue_44_low,
  142218. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142219. &_resbook_44s_1,&_resbook_44sm_1}
  142220. };
  142221. static vorbis_residue_template _res_44s_2[]={
  142222. {2,0, &_residue_44_mid,
  142223. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142224. &_resbook_44s_2,&_resbook_44s_2},
  142225. {2,0, &_residue_44_mid,
  142226. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142227. &_resbook_44s_2,&_resbook_44s_2}
  142228. };
  142229. static vorbis_residue_template _res_44s_3[]={
  142230. {2,0, &_residue_44_mid,
  142231. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142232. &_resbook_44s_3,&_resbook_44s_3},
  142233. {2,0, &_residue_44_mid,
  142234. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142235. &_resbook_44s_3,&_resbook_44s_3}
  142236. };
  142237. static vorbis_residue_template _res_44s_4[]={
  142238. {2,0, &_residue_44_mid,
  142239. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142240. &_resbook_44s_4,&_resbook_44s_4},
  142241. {2,0, &_residue_44_mid,
  142242. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142243. &_resbook_44s_4,&_resbook_44s_4}
  142244. };
  142245. static vorbis_residue_template _res_44s_5[]={
  142246. {2,0, &_residue_44_mid,
  142247. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142248. &_resbook_44s_5,&_resbook_44s_5},
  142249. {2,0, &_residue_44_mid,
  142250. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142251. &_resbook_44s_5,&_resbook_44s_5}
  142252. };
  142253. static vorbis_residue_template _res_44s_6[]={
  142254. {2,0, &_residue_44_high,
  142255. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142256. &_resbook_44s_6,&_resbook_44s_6},
  142257. {2,0, &_residue_44_high,
  142258. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142259. &_resbook_44s_6,&_resbook_44s_6}
  142260. };
  142261. static vorbis_residue_template _res_44s_7[]={
  142262. {2,0, &_residue_44_high,
  142263. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142264. &_resbook_44s_7,&_resbook_44s_7},
  142265. {2,0, &_residue_44_high,
  142266. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142267. &_resbook_44s_7,&_resbook_44s_7}
  142268. };
  142269. static vorbis_residue_template _res_44s_8[]={
  142270. {2,0, &_residue_44_high,
  142271. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142272. &_resbook_44s_8,&_resbook_44s_8},
  142273. {2,0, &_residue_44_high,
  142274. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142275. &_resbook_44s_8,&_resbook_44s_8}
  142276. };
  142277. static vorbis_residue_template _res_44s_9[]={
  142278. {2,0, &_residue_44_high,
  142279. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142280. &_resbook_44s_9,&_resbook_44s_9},
  142281. {2,0, &_residue_44_high,
  142282. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142283. &_resbook_44s_9,&_resbook_44s_9}
  142284. };
  142285. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142286. { _map_nominal, _res_44s_n1 }, /* -1 */
  142287. { _map_nominal, _res_44s_0 }, /* 0 */
  142288. { _map_nominal, _res_44s_1 }, /* 1 */
  142289. { _map_nominal, _res_44s_2 }, /* 2 */
  142290. { _map_nominal, _res_44s_3 }, /* 3 */
  142291. { _map_nominal, _res_44s_4 }, /* 4 */
  142292. { _map_nominal, _res_44s_5 }, /* 5 */
  142293. { _map_nominal, _res_44s_6 }, /* 6 */
  142294. { _map_nominal, _res_44s_7 }, /* 7 */
  142295. { _map_nominal, _res_44s_8 }, /* 8 */
  142296. { _map_nominal, _res_44s_9 }, /* 9 */
  142297. };
  142298. /*** End of inlined file: residue_44.h ***/
  142299. /*** Start of inlined file: psych_44.h ***/
  142300. /* preecho trigger settings *****************************************/
  142301. static vorbis_info_psy_global _psy_global_44[5]={
  142302. {8, /* lines per eighth octave */
  142303. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142304. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142305. -6.f,
  142306. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142307. },
  142308. {8, /* lines per eighth octave */
  142309. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142310. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142311. -6.f,
  142312. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142313. },
  142314. {8, /* lines per eighth octave */
  142315. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142316. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142317. -6.f,
  142318. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142319. },
  142320. {8, /* lines per eighth octave */
  142321. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142322. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142323. -6.f,
  142324. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142325. },
  142326. {8, /* lines per eighth octave */
  142327. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142328. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142329. -6.f,
  142330. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142331. },
  142332. };
  142333. /* noise compander lookups * low, mid, high quality ****************/
  142334. static compandblock _psy_compand_44[6]={
  142335. /* sub-mode Z short */
  142336. {{
  142337. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142338. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142339. 16,17,18,19,20,21,22, 23, /* 23dB */
  142340. 24,25,26,27,28,29,30, 31, /* 31dB */
  142341. 32,33,34,35,36,37,38, 39, /* 39dB */
  142342. }},
  142343. /* mode_Z nominal short */
  142344. {{
  142345. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142346. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142347. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142348. 15,16,17,17,17,18,18, 19, /* 31dB */
  142349. 19,19,20,21,22,23,24, 25, /* 39dB */
  142350. }},
  142351. /* mode A short */
  142352. {{
  142353. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142354. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142355. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142356. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142357. 11,12,13,14,15,16,17, 18, /* 39dB */
  142358. }},
  142359. /* sub-mode Z long */
  142360. {{
  142361. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142362. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142363. 16,17,18,19,20,21,22, 23, /* 23dB */
  142364. 24,25,26,27,28,29,30, 31, /* 31dB */
  142365. 32,33,34,35,36,37,38, 39, /* 39dB */
  142366. }},
  142367. /* mode_Z nominal long */
  142368. {{
  142369. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142370. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142371. 13,14,14,14,15,15,15, 15, /* 23dB */
  142372. 16,16,17,17,17,18,18, 19, /* 31dB */
  142373. 19,19,20,21,22,23,24, 25, /* 39dB */
  142374. }},
  142375. /* mode A long */
  142376. {{
  142377. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142378. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142379. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142380. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142381. 11,12,13,14,15,16,17, 18, /* 39dB */
  142382. }}
  142383. };
  142384. /* tonal masking curve level adjustments *************************/
  142385. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142386. /* 63 125 250 500 1 2 4 8 16 */
  142387. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142388. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142389. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142390. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142391. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142392. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142393. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142394. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142395. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142396. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142397. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142398. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142399. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142400. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142401. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142402. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142403. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142404. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142405. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142406. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142407. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142408. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142409. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142410. };
  142411. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142412. /* 63 125 250 500 1 2 4 8 16 */
  142413. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142414. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142415. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142416. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142417. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142418. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142419. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142420. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142421. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142422. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142423. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142424. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142425. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142426. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142427. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142428. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142429. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142430. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142431. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142432. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142433. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142434. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142435. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142436. };
  142437. /* noise bias (transition block) */
  142438. static noise3 _psy_noisebias_trans[12]={
  142439. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142440. /* -1 */
  142441. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142442. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142443. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142444. /* 0
  142445. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142446. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142447. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142448. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142449. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142450. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142451. /* 1
  142452. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142453. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142454. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142455. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142456. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142457. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142458. /* 2
  142459. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142460. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142461. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142462. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142463. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142464. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142465. /* 3
  142466. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142467. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142468. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142469. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142470. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142471. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142472. /* 4
  142473. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142474. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142475. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142476. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142477. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142478. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142479. /* 5
  142480. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142481. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142482. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142483. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142484. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142485. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142486. /* 6
  142487. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142488. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142489. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142490. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142491. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142492. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142493. /* 7
  142494. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142495. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142496. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142497. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142498. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142499. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142500. /* 8
  142501. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142502. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142503. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142504. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142505. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142506. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142507. /* 9
  142508. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142509. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142510. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142511. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142512. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142513. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142514. /* 10 */
  142515. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142516. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142517. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142518. };
  142519. /* noise bias (long block) */
  142520. static noise3 _psy_noisebias_long[12]={
  142521. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142522. /* -1 */
  142523. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142524. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142525. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142526. /* 0 */
  142527. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142528. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142529. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142530. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142531. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142532. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142533. /* 1 */
  142534. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142535. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142536. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142537. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142538. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142539. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142540. /* 2 */
  142541. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142542. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142543. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142544. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142545. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142546. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142547. /* 3 */
  142548. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142549. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142550. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142551. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142552. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142553. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142554. /* 4 */
  142555. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142556. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142557. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142558. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142559. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142560. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142561. /* 5 */
  142562. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142563. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142564. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142565. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142566. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142567. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142568. /* 6 */
  142569. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142570. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142571. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142572. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142573. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142574. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142575. /* 7 */
  142576. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142577. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142578. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142579. /* 8 */
  142580. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142581. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142582. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142583. /* 9 */
  142584. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142585. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142586. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142587. /* 10 */
  142588. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142589. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142590. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142591. };
  142592. /* noise bias (impulse block) */
  142593. static noise3 _psy_noisebias_impulse[12]={
  142594. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142595. /* -1 */
  142596. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142597. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142598. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142599. /* 0 */
  142600. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142601. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142602. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142603. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142604. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142605. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142606. /* 1 */
  142607. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142608. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142609. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142610. /* 2 */
  142611. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142612. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142613. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142614. /* 3 */
  142615. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142616. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142617. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142618. /* 4 */
  142619. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142620. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142621. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142622. /* 5 */
  142623. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142624. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142625. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142626. /* 6
  142627. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142628. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142629. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142630. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142631. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142632. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142633. /* 7 */
  142634. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142635. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142636. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142637. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142638. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142639. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142640. /* 8 */
  142641. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142642. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142643. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142644. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142645. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142646. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142647. /* 9 */
  142648. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142649. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142650. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142651. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142652. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142653. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142654. /* 10 */
  142655. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142656. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142657. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142658. };
  142659. /* noise bias (padding block) */
  142660. static noise3 _psy_noisebias_padding[12]={
  142661. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142662. /* -1 */
  142663. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142664. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142665. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142666. /* 0 */
  142667. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142668. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142669. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142670. /* 1 */
  142671. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142672. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142673. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142674. /* 2 */
  142675. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142676. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142677. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142678. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142679. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142680. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142681. /* 3 */
  142682. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142683. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142684. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142685. /* 4 */
  142686. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142687. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142688. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142689. /* 5 */
  142690. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142691. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142692. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142693. /* 6 */
  142694. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142695. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142696. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142697. /* 7 */
  142698. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142699. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142700. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142701. /* 8 */
  142702. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142703. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142704. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142705. /* 9 */
  142706. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142707. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142708. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142709. /* 10 */
  142710. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142711. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142712. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142713. };
  142714. static noiseguard _psy_noiseguards_44[4]={
  142715. {3,3,15},
  142716. {3,3,15},
  142717. {10,10,100},
  142718. {10,10,100},
  142719. };
  142720. static int _psy_tone_suppress[12]={
  142721. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142722. };
  142723. static int _psy_tone_0dB[12]={
  142724. 90,90,95,95,95,95,105,105,105,105,105,105,
  142725. };
  142726. static int _psy_noise_suppress[12]={
  142727. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142728. };
  142729. static vorbis_info_psy _psy_info_template={
  142730. /* blockflag */
  142731. -1,
  142732. /* ath_adjatt, ath_maxatt */
  142733. -140.,-140.,
  142734. /* tonemask att boost/decay,suppr,curves */
  142735. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142736. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142737. 1, -0.f, .5f, .5f, 0,0,0,
  142738. /* noiseoffset*3, noisecompand, max_curve_dB */
  142739. {{-1},{-1},{-1}},{-1},105.f,
  142740. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142741. 0,0,-1,-1,0.,
  142742. };
  142743. /* ath ****************/
  142744. static int _psy_ath_floater[12]={
  142745. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142746. };
  142747. static int _psy_ath_abs[12]={
  142748. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142749. };
  142750. /* stereo setup. These don't map directly to quality level, there's
  142751. an additional indirection as several of the below may be used in a
  142752. single bitmanaged stream
  142753. ****************/
  142754. /* various stereo possibilities */
  142755. /* stereo mode by base quality level */
  142756. static adj_stereo _psy_stereo_modes_44[12]={
  142757. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142758. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142759. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142760. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142761. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142762. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142763. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142764. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142765. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142766. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142767. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142768. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142769. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142770. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142771. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142772. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142773. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142774. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142775. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142776. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142777. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142778. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142779. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142780. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142781. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142782. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142783. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142784. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142785. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142786. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142787. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142788. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142789. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142790. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142791. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142792. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142793. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142794. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142795. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142796. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142797. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142798. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142799. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142800. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142801. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142802. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142803. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142804. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142805. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142806. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142807. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142808. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142809. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142810. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142811. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142812. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142813. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142814. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142815. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142816. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142817. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142818. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142819. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142820. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142821. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142822. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142823. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142824. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142825. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142826. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142827. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142828. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142829. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142830. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142831. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142832. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142833. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142834. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142835. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142836. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142837. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142838. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142839. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142840. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142841. };
  142842. /* tone master attenuation by base quality mode and bitrate tweak */
  142843. static att3 _psy_tone_masteratt_44[12]={
  142844. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142845. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142846. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142847. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142848. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142849. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142850. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142851. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142852. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142853. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142854. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142855. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142856. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142857. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142858. };
  142859. /* lowpass by mode **************/
  142860. static double _psy_lowpass_44[12]={
  142861. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142862. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142863. };
  142864. /* noise normalization **********/
  142865. static int _noise_start_short_44[11]={
  142866. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142867. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142868. };
  142869. static int _noise_start_long_44[11]={
  142870. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142871. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142872. };
  142873. static int _noise_part_short_44[11]={
  142874. 8,8,8,8,8,8,8,8,8,8,8
  142875. };
  142876. static int _noise_part_long_44[11]={
  142877. 32,32,32,32,32,32,32,32,32,32,32
  142878. };
  142879. static double _noise_thresh_44[11]={
  142880. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142881. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142882. };
  142883. static double _noise_thresh_5only[2]={
  142884. .5,.5,
  142885. };
  142886. /*** End of inlined file: psych_44.h ***/
  142887. static double rate_mapping_44_stereo[12]={
  142888. 22500.,32000.,40000.,48000.,56000.,64000.,
  142889. 80000.,96000.,112000.,128000.,160000.,250001.
  142890. };
  142891. static double quality_mapping_44[12]={
  142892. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142893. };
  142894. static int blocksize_short_44[11]={
  142895. 512,256,256,256,256,256,256,256,256,256,256
  142896. };
  142897. static int blocksize_long_44[11]={
  142898. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142899. };
  142900. static double _psy_compand_short_mapping[12]={
  142901. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142902. };
  142903. static double _psy_compand_long_mapping[12]={
  142904. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142905. };
  142906. static double _global_mapping_44[12]={
  142907. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142908. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142909. };
  142910. static int _floor_short_mapping_44[11]={
  142911. 1,0,0,2,2,4,5,5,5,5,5
  142912. };
  142913. static int _floor_long_mapping_44[11]={
  142914. 8,7,7,7,7,7,7,7,7,7,7
  142915. };
  142916. ve_setup_data_template ve_setup_44_stereo={
  142917. 11,
  142918. rate_mapping_44_stereo,
  142919. quality_mapping_44,
  142920. 2,
  142921. 40000,
  142922. 50000,
  142923. blocksize_short_44,
  142924. blocksize_long_44,
  142925. _psy_tone_masteratt_44,
  142926. _psy_tone_0dB,
  142927. _psy_tone_suppress,
  142928. _vp_tonemask_adj_otherblock,
  142929. _vp_tonemask_adj_longblock,
  142930. _vp_tonemask_adj_otherblock,
  142931. _psy_noiseguards_44,
  142932. _psy_noisebias_impulse,
  142933. _psy_noisebias_padding,
  142934. _psy_noisebias_trans,
  142935. _psy_noisebias_long,
  142936. _psy_noise_suppress,
  142937. _psy_compand_44,
  142938. _psy_compand_short_mapping,
  142939. _psy_compand_long_mapping,
  142940. {_noise_start_short_44,_noise_start_long_44},
  142941. {_noise_part_short_44,_noise_part_long_44},
  142942. _noise_thresh_44,
  142943. _psy_ath_floater,
  142944. _psy_ath_abs,
  142945. _psy_lowpass_44,
  142946. _psy_global_44,
  142947. _global_mapping_44,
  142948. _psy_stereo_modes_44,
  142949. _floor_books,
  142950. _floor,
  142951. _floor_short_mapping_44,
  142952. _floor_long_mapping_44,
  142953. _mapres_template_44_stereo
  142954. };
  142955. /*** End of inlined file: setup_44.h ***/
  142956. /*** Start of inlined file: setup_44u.h ***/
  142957. /*** Start of inlined file: residue_44u.h ***/
  142958. /*** Start of inlined file: res_books_uncoupled.h ***/
  142959. static long _vq_quantlist__16u0__p1_0[] = {
  142960. 1,
  142961. 0,
  142962. 2,
  142963. };
  142964. static long _vq_lengthlist__16u0__p1_0[] = {
  142965. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142966. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142967. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142968. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142969. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142970. 12,
  142971. };
  142972. static float _vq_quantthresh__16u0__p1_0[] = {
  142973. -0.5, 0.5,
  142974. };
  142975. static long _vq_quantmap__16u0__p1_0[] = {
  142976. 1, 0, 2,
  142977. };
  142978. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142979. _vq_quantthresh__16u0__p1_0,
  142980. _vq_quantmap__16u0__p1_0,
  142981. 3,
  142982. 3
  142983. };
  142984. static static_codebook _16u0__p1_0 = {
  142985. 4, 81,
  142986. _vq_lengthlist__16u0__p1_0,
  142987. 1, -535822336, 1611661312, 2, 0,
  142988. _vq_quantlist__16u0__p1_0,
  142989. NULL,
  142990. &_vq_auxt__16u0__p1_0,
  142991. NULL,
  142992. 0
  142993. };
  142994. static long _vq_quantlist__16u0__p2_0[] = {
  142995. 1,
  142996. 0,
  142997. 2,
  142998. };
  142999. static long _vq_lengthlist__16u0__p2_0[] = {
  143000. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143001. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143002. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143003. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143004. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143005. 8,
  143006. };
  143007. static float _vq_quantthresh__16u0__p2_0[] = {
  143008. -0.5, 0.5,
  143009. };
  143010. static long _vq_quantmap__16u0__p2_0[] = {
  143011. 1, 0, 2,
  143012. };
  143013. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143014. _vq_quantthresh__16u0__p2_0,
  143015. _vq_quantmap__16u0__p2_0,
  143016. 3,
  143017. 3
  143018. };
  143019. static static_codebook _16u0__p2_0 = {
  143020. 4, 81,
  143021. _vq_lengthlist__16u0__p2_0,
  143022. 1, -535822336, 1611661312, 2, 0,
  143023. _vq_quantlist__16u0__p2_0,
  143024. NULL,
  143025. &_vq_auxt__16u0__p2_0,
  143026. NULL,
  143027. 0
  143028. };
  143029. static long _vq_quantlist__16u0__p3_0[] = {
  143030. 2,
  143031. 1,
  143032. 3,
  143033. 0,
  143034. 4,
  143035. };
  143036. static long _vq_lengthlist__16u0__p3_0[] = {
  143037. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143038. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143039. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143040. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143041. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143042. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143043. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143044. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143045. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143046. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143047. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143048. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143049. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143050. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143051. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143052. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143053. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143054. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143055. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143056. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143057. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143058. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143059. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143060. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143061. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143062. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143063. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143064. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143065. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143066. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143067. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143068. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143069. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143070. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143071. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143072. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143073. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143074. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143075. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143076. 18,
  143077. };
  143078. static float _vq_quantthresh__16u0__p3_0[] = {
  143079. -1.5, -0.5, 0.5, 1.5,
  143080. };
  143081. static long _vq_quantmap__16u0__p3_0[] = {
  143082. 3, 1, 0, 2, 4,
  143083. };
  143084. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143085. _vq_quantthresh__16u0__p3_0,
  143086. _vq_quantmap__16u0__p3_0,
  143087. 5,
  143088. 5
  143089. };
  143090. static static_codebook _16u0__p3_0 = {
  143091. 4, 625,
  143092. _vq_lengthlist__16u0__p3_0,
  143093. 1, -533725184, 1611661312, 3, 0,
  143094. _vq_quantlist__16u0__p3_0,
  143095. NULL,
  143096. &_vq_auxt__16u0__p3_0,
  143097. NULL,
  143098. 0
  143099. };
  143100. static long _vq_quantlist__16u0__p4_0[] = {
  143101. 2,
  143102. 1,
  143103. 3,
  143104. 0,
  143105. 4,
  143106. };
  143107. static long _vq_lengthlist__16u0__p4_0[] = {
  143108. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143109. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143110. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143111. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143112. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143113. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143114. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143115. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143116. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143117. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143118. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143119. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143120. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143121. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143122. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143123. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143124. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143125. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143126. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143127. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143128. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143129. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143130. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143131. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143132. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143133. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143134. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143135. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143136. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143137. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143138. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143139. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143140. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143141. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143142. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143143. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143144. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143145. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143146. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143147. 11,
  143148. };
  143149. static float _vq_quantthresh__16u0__p4_0[] = {
  143150. -1.5, -0.5, 0.5, 1.5,
  143151. };
  143152. static long _vq_quantmap__16u0__p4_0[] = {
  143153. 3, 1, 0, 2, 4,
  143154. };
  143155. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143156. _vq_quantthresh__16u0__p4_0,
  143157. _vq_quantmap__16u0__p4_0,
  143158. 5,
  143159. 5
  143160. };
  143161. static static_codebook _16u0__p4_0 = {
  143162. 4, 625,
  143163. _vq_lengthlist__16u0__p4_0,
  143164. 1, -533725184, 1611661312, 3, 0,
  143165. _vq_quantlist__16u0__p4_0,
  143166. NULL,
  143167. &_vq_auxt__16u0__p4_0,
  143168. NULL,
  143169. 0
  143170. };
  143171. static long _vq_quantlist__16u0__p5_0[] = {
  143172. 4,
  143173. 3,
  143174. 5,
  143175. 2,
  143176. 6,
  143177. 1,
  143178. 7,
  143179. 0,
  143180. 8,
  143181. };
  143182. static long _vq_lengthlist__16u0__p5_0[] = {
  143183. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143184. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143185. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143186. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143187. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143188. 12,
  143189. };
  143190. static float _vq_quantthresh__16u0__p5_0[] = {
  143191. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143192. };
  143193. static long _vq_quantmap__16u0__p5_0[] = {
  143194. 7, 5, 3, 1, 0, 2, 4, 6,
  143195. 8,
  143196. };
  143197. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143198. _vq_quantthresh__16u0__p5_0,
  143199. _vq_quantmap__16u0__p5_0,
  143200. 9,
  143201. 9
  143202. };
  143203. static static_codebook _16u0__p5_0 = {
  143204. 2, 81,
  143205. _vq_lengthlist__16u0__p5_0,
  143206. 1, -531628032, 1611661312, 4, 0,
  143207. _vq_quantlist__16u0__p5_0,
  143208. NULL,
  143209. &_vq_auxt__16u0__p5_0,
  143210. NULL,
  143211. 0
  143212. };
  143213. static long _vq_quantlist__16u0__p6_0[] = {
  143214. 6,
  143215. 5,
  143216. 7,
  143217. 4,
  143218. 8,
  143219. 3,
  143220. 9,
  143221. 2,
  143222. 10,
  143223. 1,
  143224. 11,
  143225. 0,
  143226. 12,
  143227. };
  143228. static long _vq_lengthlist__16u0__p6_0[] = {
  143229. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143230. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143231. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143232. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143233. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143234. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143235. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143236. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143237. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143238. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143239. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143240. };
  143241. static float _vq_quantthresh__16u0__p6_0[] = {
  143242. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143243. 12.5, 17.5, 22.5, 27.5,
  143244. };
  143245. static long _vq_quantmap__16u0__p6_0[] = {
  143246. 11, 9, 7, 5, 3, 1, 0, 2,
  143247. 4, 6, 8, 10, 12,
  143248. };
  143249. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143250. _vq_quantthresh__16u0__p6_0,
  143251. _vq_quantmap__16u0__p6_0,
  143252. 13,
  143253. 13
  143254. };
  143255. static static_codebook _16u0__p6_0 = {
  143256. 2, 169,
  143257. _vq_lengthlist__16u0__p6_0,
  143258. 1, -526516224, 1616117760, 4, 0,
  143259. _vq_quantlist__16u0__p6_0,
  143260. NULL,
  143261. &_vq_auxt__16u0__p6_0,
  143262. NULL,
  143263. 0
  143264. };
  143265. static long _vq_quantlist__16u0__p6_1[] = {
  143266. 2,
  143267. 1,
  143268. 3,
  143269. 0,
  143270. 4,
  143271. };
  143272. static long _vq_lengthlist__16u0__p6_1[] = {
  143273. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143274. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143275. };
  143276. static float _vq_quantthresh__16u0__p6_1[] = {
  143277. -1.5, -0.5, 0.5, 1.5,
  143278. };
  143279. static long _vq_quantmap__16u0__p6_1[] = {
  143280. 3, 1, 0, 2, 4,
  143281. };
  143282. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143283. _vq_quantthresh__16u0__p6_1,
  143284. _vq_quantmap__16u0__p6_1,
  143285. 5,
  143286. 5
  143287. };
  143288. static static_codebook _16u0__p6_1 = {
  143289. 2, 25,
  143290. _vq_lengthlist__16u0__p6_1,
  143291. 1, -533725184, 1611661312, 3, 0,
  143292. _vq_quantlist__16u0__p6_1,
  143293. NULL,
  143294. &_vq_auxt__16u0__p6_1,
  143295. NULL,
  143296. 0
  143297. };
  143298. static long _vq_quantlist__16u0__p7_0[] = {
  143299. 1,
  143300. 0,
  143301. 2,
  143302. };
  143303. static long _vq_lengthlist__16u0__p7_0[] = {
  143304. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143305. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143306. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143307. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143308. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143309. 7,
  143310. };
  143311. static float _vq_quantthresh__16u0__p7_0[] = {
  143312. -157.5, 157.5,
  143313. };
  143314. static long _vq_quantmap__16u0__p7_0[] = {
  143315. 1, 0, 2,
  143316. };
  143317. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143318. _vq_quantthresh__16u0__p7_0,
  143319. _vq_quantmap__16u0__p7_0,
  143320. 3,
  143321. 3
  143322. };
  143323. static static_codebook _16u0__p7_0 = {
  143324. 4, 81,
  143325. _vq_lengthlist__16u0__p7_0,
  143326. 1, -518803456, 1628680192, 2, 0,
  143327. _vq_quantlist__16u0__p7_0,
  143328. NULL,
  143329. &_vq_auxt__16u0__p7_0,
  143330. NULL,
  143331. 0
  143332. };
  143333. static long _vq_quantlist__16u0__p7_1[] = {
  143334. 7,
  143335. 6,
  143336. 8,
  143337. 5,
  143338. 9,
  143339. 4,
  143340. 10,
  143341. 3,
  143342. 11,
  143343. 2,
  143344. 12,
  143345. 1,
  143346. 13,
  143347. 0,
  143348. 14,
  143349. };
  143350. static long _vq_lengthlist__16u0__p7_1[] = {
  143351. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143352. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143353. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143354. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143355. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143356. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143357. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143358. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143359. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143360. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143361. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143362. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143363. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143364. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143365. 10,
  143366. };
  143367. static float _vq_quantthresh__16u0__p7_1[] = {
  143368. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143369. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143370. };
  143371. static long _vq_quantmap__16u0__p7_1[] = {
  143372. 13, 11, 9, 7, 5, 3, 1, 0,
  143373. 2, 4, 6, 8, 10, 12, 14,
  143374. };
  143375. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143376. _vq_quantthresh__16u0__p7_1,
  143377. _vq_quantmap__16u0__p7_1,
  143378. 15,
  143379. 15
  143380. };
  143381. static static_codebook _16u0__p7_1 = {
  143382. 2, 225,
  143383. _vq_lengthlist__16u0__p7_1,
  143384. 1, -520986624, 1620377600, 4, 0,
  143385. _vq_quantlist__16u0__p7_1,
  143386. NULL,
  143387. &_vq_auxt__16u0__p7_1,
  143388. NULL,
  143389. 0
  143390. };
  143391. static long _vq_quantlist__16u0__p7_2[] = {
  143392. 10,
  143393. 9,
  143394. 11,
  143395. 8,
  143396. 12,
  143397. 7,
  143398. 13,
  143399. 6,
  143400. 14,
  143401. 5,
  143402. 15,
  143403. 4,
  143404. 16,
  143405. 3,
  143406. 17,
  143407. 2,
  143408. 18,
  143409. 1,
  143410. 19,
  143411. 0,
  143412. 20,
  143413. };
  143414. static long _vq_lengthlist__16u0__p7_2[] = {
  143415. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143416. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143417. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143418. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143419. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143420. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143421. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143422. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143423. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143424. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143425. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143426. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143427. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143428. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143429. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143430. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143431. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143432. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143433. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143434. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143435. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143436. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143437. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143438. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143439. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143440. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143441. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143442. 10,10,12,11,10,11,11,11,10,
  143443. };
  143444. static float _vq_quantthresh__16u0__p7_2[] = {
  143445. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143446. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143447. 6.5, 7.5, 8.5, 9.5,
  143448. };
  143449. static long _vq_quantmap__16u0__p7_2[] = {
  143450. 19, 17, 15, 13, 11, 9, 7, 5,
  143451. 3, 1, 0, 2, 4, 6, 8, 10,
  143452. 12, 14, 16, 18, 20,
  143453. };
  143454. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143455. _vq_quantthresh__16u0__p7_2,
  143456. _vq_quantmap__16u0__p7_2,
  143457. 21,
  143458. 21
  143459. };
  143460. static static_codebook _16u0__p7_2 = {
  143461. 2, 441,
  143462. _vq_lengthlist__16u0__p7_2,
  143463. 1, -529268736, 1611661312, 5, 0,
  143464. _vq_quantlist__16u0__p7_2,
  143465. NULL,
  143466. &_vq_auxt__16u0__p7_2,
  143467. NULL,
  143468. 0
  143469. };
  143470. static long _huff_lengthlist__16u0__single[] = {
  143471. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143472. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143473. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143474. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143475. };
  143476. static static_codebook _huff_book__16u0__single = {
  143477. 2, 64,
  143478. _huff_lengthlist__16u0__single,
  143479. 0, 0, 0, 0, 0,
  143480. NULL,
  143481. NULL,
  143482. NULL,
  143483. NULL,
  143484. 0
  143485. };
  143486. static long _huff_lengthlist__16u1__long[] = {
  143487. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143488. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143489. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143490. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143491. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143492. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143493. 16,13,16,18,
  143494. };
  143495. static static_codebook _huff_book__16u1__long = {
  143496. 2, 100,
  143497. _huff_lengthlist__16u1__long,
  143498. 0, 0, 0, 0, 0,
  143499. NULL,
  143500. NULL,
  143501. NULL,
  143502. NULL,
  143503. 0
  143504. };
  143505. static long _vq_quantlist__16u1__p1_0[] = {
  143506. 1,
  143507. 0,
  143508. 2,
  143509. };
  143510. static long _vq_lengthlist__16u1__p1_0[] = {
  143511. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143512. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143513. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143514. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143515. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143516. 11,
  143517. };
  143518. static float _vq_quantthresh__16u1__p1_0[] = {
  143519. -0.5, 0.5,
  143520. };
  143521. static long _vq_quantmap__16u1__p1_0[] = {
  143522. 1, 0, 2,
  143523. };
  143524. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143525. _vq_quantthresh__16u1__p1_0,
  143526. _vq_quantmap__16u1__p1_0,
  143527. 3,
  143528. 3
  143529. };
  143530. static static_codebook _16u1__p1_0 = {
  143531. 4, 81,
  143532. _vq_lengthlist__16u1__p1_0,
  143533. 1, -535822336, 1611661312, 2, 0,
  143534. _vq_quantlist__16u1__p1_0,
  143535. NULL,
  143536. &_vq_auxt__16u1__p1_0,
  143537. NULL,
  143538. 0
  143539. };
  143540. static long _vq_quantlist__16u1__p2_0[] = {
  143541. 1,
  143542. 0,
  143543. 2,
  143544. };
  143545. static long _vq_lengthlist__16u1__p2_0[] = {
  143546. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143547. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143548. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143549. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143550. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143551. 8,
  143552. };
  143553. static float _vq_quantthresh__16u1__p2_0[] = {
  143554. -0.5, 0.5,
  143555. };
  143556. static long _vq_quantmap__16u1__p2_0[] = {
  143557. 1, 0, 2,
  143558. };
  143559. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143560. _vq_quantthresh__16u1__p2_0,
  143561. _vq_quantmap__16u1__p2_0,
  143562. 3,
  143563. 3
  143564. };
  143565. static static_codebook _16u1__p2_0 = {
  143566. 4, 81,
  143567. _vq_lengthlist__16u1__p2_0,
  143568. 1, -535822336, 1611661312, 2, 0,
  143569. _vq_quantlist__16u1__p2_0,
  143570. NULL,
  143571. &_vq_auxt__16u1__p2_0,
  143572. NULL,
  143573. 0
  143574. };
  143575. static long _vq_quantlist__16u1__p3_0[] = {
  143576. 2,
  143577. 1,
  143578. 3,
  143579. 0,
  143580. 4,
  143581. };
  143582. static long _vq_lengthlist__16u1__p3_0[] = {
  143583. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143584. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143585. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143586. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143587. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143588. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143589. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143590. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143591. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143592. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143593. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143594. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143595. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143596. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143597. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143598. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143599. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143600. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143601. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143602. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143603. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143604. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143605. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143606. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143607. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143608. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143609. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143610. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143611. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143612. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143613. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143614. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143615. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143616. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143617. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143618. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143619. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143620. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143621. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143622. 16,
  143623. };
  143624. static float _vq_quantthresh__16u1__p3_0[] = {
  143625. -1.5, -0.5, 0.5, 1.5,
  143626. };
  143627. static long _vq_quantmap__16u1__p3_0[] = {
  143628. 3, 1, 0, 2, 4,
  143629. };
  143630. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143631. _vq_quantthresh__16u1__p3_0,
  143632. _vq_quantmap__16u1__p3_0,
  143633. 5,
  143634. 5
  143635. };
  143636. static static_codebook _16u1__p3_0 = {
  143637. 4, 625,
  143638. _vq_lengthlist__16u1__p3_0,
  143639. 1, -533725184, 1611661312, 3, 0,
  143640. _vq_quantlist__16u1__p3_0,
  143641. NULL,
  143642. &_vq_auxt__16u1__p3_0,
  143643. NULL,
  143644. 0
  143645. };
  143646. static long _vq_quantlist__16u1__p4_0[] = {
  143647. 2,
  143648. 1,
  143649. 3,
  143650. 0,
  143651. 4,
  143652. };
  143653. static long _vq_lengthlist__16u1__p4_0[] = {
  143654. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143655. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143656. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143657. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143658. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143659. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143660. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143661. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143662. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143663. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143664. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143665. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143666. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143667. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143668. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143669. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143670. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143671. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143672. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143673. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143674. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143675. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143676. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143677. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143678. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143679. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143680. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143681. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143682. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143683. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143684. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143685. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143686. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143687. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143688. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143689. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143690. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143691. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143692. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143693. 11,
  143694. };
  143695. static float _vq_quantthresh__16u1__p4_0[] = {
  143696. -1.5, -0.5, 0.5, 1.5,
  143697. };
  143698. static long _vq_quantmap__16u1__p4_0[] = {
  143699. 3, 1, 0, 2, 4,
  143700. };
  143701. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143702. _vq_quantthresh__16u1__p4_0,
  143703. _vq_quantmap__16u1__p4_0,
  143704. 5,
  143705. 5
  143706. };
  143707. static static_codebook _16u1__p4_0 = {
  143708. 4, 625,
  143709. _vq_lengthlist__16u1__p4_0,
  143710. 1, -533725184, 1611661312, 3, 0,
  143711. _vq_quantlist__16u1__p4_0,
  143712. NULL,
  143713. &_vq_auxt__16u1__p4_0,
  143714. NULL,
  143715. 0
  143716. };
  143717. static long _vq_quantlist__16u1__p5_0[] = {
  143718. 4,
  143719. 3,
  143720. 5,
  143721. 2,
  143722. 6,
  143723. 1,
  143724. 7,
  143725. 0,
  143726. 8,
  143727. };
  143728. static long _vq_lengthlist__16u1__p5_0[] = {
  143729. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143730. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143731. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143732. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143733. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143734. 13,
  143735. };
  143736. static float _vq_quantthresh__16u1__p5_0[] = {
  143737. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143738. };
  143739. static long _vq_quantmap__16u1__p5_0[] = {
  143740. 7, 5, 3, 1, 0, 2, 4, 6,
  143741. 8,
  143742. };
  143743. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143744. _vq_quantthresh__16u1__p5_0,
  143745. _vq_quantmap__16u1__p5_0,
  143746. 9,
  143747. 9
  143748. };
  143749. static static_codebook _16u1__p5_0 = {
  143750. 2, 81,
  143751. _vq_lengthlist__16u1__p5_0,
  143752. 1, -531628032, 1611661312, 4, 0,
  143753. _vq_quantlist__16u1__p5_0,
  143754. NULL,
  143755. &_vq_auxt__16u1__p5_0,
  143756. NULL,
  143757. 0
  143758. };
  143759. static long _vq_quantlist__16u1__p6_0[] = {
  143760. 4,
  143761. 3,
  143762. 5,
  143763. 2,
  143764. 6,
  143765. 1,
  143766. 7,
  143767. 0,
  143768. 8,
  143769. };
  143770. static long _vq_lengthlist__16u1__p6_0[] = {
  143771. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143772. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143773. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143774. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143775. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143776. 11,
  143777. };
  143778. static float _vq_quantthresh__16u1__p6_0[] = {
  143779. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143780. };
  143781. static long _vq_quantmap__16u1__p6_0[] = {
  143782. 7, 5, 3, 1, 0, 2, 4, 6,
  143783. 8,
  143784. };
  143785. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143786. _vq_quantthresh__16u1__p6_0,
  143787. _vq_quantmap__16u1__p6_0,
  143788. 9,
  143789. 9
  143790. };
  143791. static static_codebook _16u1__p6_0 = {
  143792. 2, 81,
  143793. _vq_lengthlist__16u1__p6_0,
  143794. 1, -531628032, 1611661312, 4, 0,
  143795. _vq_quantlist__16u1__p6_0,
  143796. NULL,
  143797. &_vq_auxt__16u1__p6_0,
  143798. NULL,
  143799. 0
  143800. };
  143801. static long _vq_quantlist__16u1__p7_0[] = {
  143802. 1,
  143803. 0,
  143804. 2,
  143805. };
  143806. static long _vq_lengthlist__16u1__p7_0[] = {
  143807. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143808. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143809. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143810. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143811. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143812. 13,
  143813. };
  143814. static float _vq_quantthresh__16u1__p7_0[] = {
  143815. -5.5, 5.5,
  143816. };
  143817. static long _vq_quantmap__16u1__p7_0[] = {
  143818. 1, 0, 2,
  143819. };
  143820. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143821. _vq_quantthresh__16u1__p7_0,
  143822. _vq_quantmap__16u1__p7_0,
  143823. 3,
  143824. 3
  143825. };
  143826. static static_codebook _16u1__p7_0 = {
  143827. 4, 81,
  143828. _vq_lengthlist__16u1__p7_0,
  143829. 1, -529137664, 1618345984, 2, 0,
  143830. _vq_quantlist__16u1__p7_0,
  143831. NULL,
  143832. &_vq_auxt__16u1__p7_0,
  143833. NULL,
  143834. 0
  143835. };
  143836. static long _vq_quantlist__16u1__p7_1[] = {
  143837. 5,
  143838. 4,
  143839. 6,
  143840. 3,
  143841. 7,
  143842. 2,
  143843. 8,
  143844. 1,
  143845. 9,
  143846. 0,
  143847. 10,
  143848. };
  143849. static long _vq_lengthlist__16u1__p7_1[] = {
  143850. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143851. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143852. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143853. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143854. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143855. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143856. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143857. 8, 9, 9,10,10,10,10,10,10,
  143858. };
  143859. static float _vq_quantthresh__16u1__p7_1[] = {
  143860. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143861. 3.5, 4.5,
  143862. };
  143863. static long _vq_quantmap__16u1__p7_1[] = {
  143864. 9, 7, 5, 3, 1, 0, 2, 4,
  143865. 6, 8, 10,
  143866. };
  143867. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143868. _vq_quantthresh__16u1__p7_1,
  143869. _vq_quantmap__16u1__p7_1,
  143870. 11,
  143871. 11
  143872. };
  143873. static static_codebook _16u1__p7_1 = {
  143874. 2, 121,
  143875. _vq_lengthlist__16u1__p7_1,
  143876. 1, -531365888, 1611661312, 4, 0,
  143877. _vq_quantlist__16u1__p7_1,
  143878. NULL,
  143879. &_vq_auxt__16u1__p7_1,
  143880. NULL,
  143881. 0
  143882. };
  143883. static long _vq_quantlist__16u1__p8_0[] = {
  143884. 5,
  143885. 4,
  143886. 6,
  143887. 3,
  143888. 7,
  143889. 2,
  143890. 8,
  143891. 1,
  143892. 9,
  143893. 0,
  143894. 10,
  143895. };
  143896. static long _vq_lengthlist__16u1__p8_0[] = {
  143897. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143898. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143899. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143900. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143901. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143902. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143903. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143904. 13,14,14,15,15,16,16,15,16,
  143905. };
  143906. static float _vq_quantthresh__16u1__p8_0[] = {
  143907. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143908. 38.5, 49.5,
  143909. };
  143910. static long _vq_quantmap__16u1__p8_0[] = {
  143911. 9, 7, 5, 3, 1, 0, 2, 4,
  143912. 6, 8, 10,
  143913. };
  143914. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143915. _vq_quantthresh__16u1__p8_0,
  143916. _vq_quantmap__16u1__p8_0,
  143917. 11,
  143918. 11
  143919. };
  143920. static static_codebook _16u1__p8_0 = {
  143921. 2, 121,
  143922. _vq_lengthlist__16u1__p8_0,
  143923. 1, -524582912, 1618345984, 4, 0,
  143924. _vq_quantlist__16u1__p8_0,
  143925. NULL,
  143926. &_vq_auxt__16u1__p8_0,
  143927. NULL,
  143928. 0
  143929. };
  143930. static long _vq_quantlist__16u1__p8_1[] = {
  143931. 5,
  143932. 4,
  143933. 6,
  143934. 3,
  143935. 7,
  143936. 2,
  143937. 8,
  143938. 1,
  143939. 9,
  143940. 0,
  143941. 10,
  143942. };
  143943. static long _vq_lengthlist__16u1__p8_1[] = {
  143944. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143945. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143946. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143947. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143948. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143949. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143950. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143951. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143952. };
  143953. static float _vq_quantthresh__16u1__p8_1[] = {
  143954. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143955. 3.5, 4.5,
  143956. };
  143957. static long _vq_quantmap__16u1__p8_1[] = {
  143958. 9, 7, 5, 3, 1, 0, 2, 4,
  143959. 6, 8, 10,
  143960. };
  143961. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143962. _vq_quantthresh__16u1__p8_1,
  143963. _vq_quantmap__16u1__p8_1,
  143964. 11,
  143965. 11
  143966. };
  143967. static static_codebook _16u1__p8_1 = {
  143968. 2, 121,
  143969. _vq_lengthlist__16u1__p8_1,
  143970. 1, -531365888, 1611661312, 4, 0,
  143971. _vq_quantlist__16u1__p8_1,
  143972. NULL,
  143973. &_vq_auxt__16u1__p8_1,
  143974. NULL,
  143975. 0
  143976. };
  143977. static long _vq_quantlist__16u1__p9_0[] = {
  143978. 7,
  143979. 6,
  143980. 8,
  143981. 5,
  143982. 9,
  143983. 4,
  143984. 10,
  143985. 3,
  143986. 11,
  143987. 2,
  143988. 12,
  143989. 1,
  143990. 13,
  143991. 0,
  143992. 14,
  143993. };
  143994. static long _vq_lengthlist__16u1__p9_0[] = {
  143995. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143996. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143997. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143998. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143999. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144000. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144001. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144002. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144003. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144004. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144005. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144006. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144007. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144008. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144009. 8,
  144010. };
  144011. static float _vq_quantthresh__16u1__p9_0[] = {
  144012. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144013. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144014. };
  144015. static long _vq_quantmap__16u1__p9_0[] = {
  144016. 13, 11, 9, 7, 5, 3, 1, 0,
  144017. 2, 4, 6, 8, 10, 12, 14,
  144018. };
  144019. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144020. _vq_quantthresh__16u1__p9_0,
  144021. _vq_quantmap__16u1__p9_0,
  144022. 15,
  144023. 15
  144024. };
  144025. static static_codebook _16u1__p9_0 = {
  144026. 2, 225,
  144027. _vq_lengthlist__16u1__p9_0,
  144028. 1, -514071552, 1627381760, 4, 0,
  144029. _vq_quantlist__16u1__p9_0,
  144030. NULL,
  144031. &_vq_auxt__16u1__p9_0,
  144032. NULL,
  144033. 0
  144034. };
  144035. static long _vq_quantlist__16u1__p9_1[] = {
  144036. 7,
  144037. 6,
  144038. 8,
  144039. 5,
  144040. 9,
  144041. 4,
  144042. 10,
  144043. 3,
  144044. 11,
  144045. 2,
  144046. 12,
  144047. 1,
  144048. 13,
  144049. 0,
  144050. 14,
  144051. };
  144052. static long _vq_lengthlist__16u1__p9_1[] = {
  144053. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144054. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144055. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144056. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144057. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144058. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144059. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144060. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144061. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144062. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144063. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144064. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144065. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144066. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144067. 9,
  144068. };
  144069. static float _vq_quantthresh__16u1__p9_1[] = {
  144070. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144071. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144072. };
  144073. static long _vq_quantmap__16u1__p9_1[] = {
  144074. 13, 11, 9, 7, 5, 3, 1, 0,
  144075. 2, 4, 6, 8, 10, 12, 14,
  144076. };
  144077. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144078. _vq_quantthresh__16u1__p9_1,
  144079. _vq_quantmap__16u1__p9_1,
  144080. 15,
  144081. 15
  144082. };
  144083. static static_codebook _16u1__p9_1 = {
  144084. 2, 225,
  144085. _vq_lengthlist__16u1__p9_1,
  144086. 1, -522338304, 1620115456, 4, 0,
  144087. _vq_quantlist__16u1__p9_1,
  144088. NULL,
  144089. &_vq_auxt__16u1__p9_1,
  144090. NULL,
  144091. 0
  144092. };
  144093. static long _vq_quantlist__16u1__p9_2[] = {
  144094. 8,
  144095. 7,
  144096. 9,
  144097. 6,
  144098. 10,
  144099. 5,
  144100. 11,
  144101. 4,
  144102. 12,
  144103. 3,
  144104. 13,
  144105. 2,
  144106. 14,
  144107. 1,
  144108. 15,
  144109. 0,
  144110. 16,
  144111. };
  144112. static long _vq_lengthlist__16u1__p9_2[] = {
  144113. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144114. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144115. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144116. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144117. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144118. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144119. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144120. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144121. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144122. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144123. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144124. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144125. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144126. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144127. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144128. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144129. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144130. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144131. 10,
  144132. };
  144133. static float _vq_quantthresh__16u1__p9_2[] = {
  144134. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144135. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144136. };
  144137. static long _vq_quantmap__16u1__p9_2[] = {
  144138. 15, 13, 11, 9, 7, 5, 3, 1,
  144139. 0, 2, 4, 6, 8, 10, 12, 14,
  144140. 16,
  144141. };
  144142. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144143. _vq_quantthresh__16u1__p9_2,
  144144. _vq_quantmap__16u1__p9_2,
  144145. 17,
  144146. 17
  144147. };
  144148. static static_codebook _16u1__p9_2 = {
  144149. 2, 289,
  144150. _vq_lengthlist__16u1__p9_2,
  144151. 1, -529530880, 1611661312, 5, 0,
  144152. _vq_quantlist__16u1__p9_2,
  144153. NULL,
  144154. &_vq_auxt__16u1__p9_2,
  144155. NULL,
  144156. 0
  144157. };
  144158. static long _huff_lengthlist__16u1__short[] = {
  144159. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144160. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144161. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144162. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144163. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144164. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144165. 16,16,16,16,
  144166. };
  144167. static static_codebook _huff_book__16u1__short = {
  144168. 2, 100,
  144169. _huff_lengthlist__16u1__short,
  144170. 0, 0, 0, 0, 0,
  144171. NULL,
  144172. NULL,
  144173. NULL,
  144174. NULL,
  144175. 0
  144176. };
  144177. static long _huff_lengthlist__16u2__long[] = {
  144178. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144179. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144180. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144181. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144182. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144183. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144184. 13,14,18,18,
  144185. };
  144186. static static_codebook _huff_book__16u2__long = {
  144187. 2, 100,
  144188. _huff_lengthlist__16u2__long,
  144189. 0, 0, 0, 0, 0,
  144190. NULL,
  144191. NULL,
  144192. NULL,
  144193. NULL,
  144194. 0
  144195. };
  144196. static long _huff_lengthlist__16u2__short[] = {
  144197. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144198. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144199. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144200. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144201. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144202. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144203. 16,16,16,16,
  144204. };
  144205. static static_codebook _huff_book__16u2__short = {
  144206. 2, 100,
  144207. _huff_lengthlist__16u2__short,
  144208. 0, 0, 0, 0, 0,
  144209. NULL,
  144210. NULL,
  144211. NULL,
  144212. NULL,
  144213. 0
  144214. };
  144215. static long _vq_quantlist__16u2_p1_0[] = {
  144216. 1,
  144217. 0,
  144218. 2,
  144219. };
  144220. static long _vq_lengthlist__16u2_p1_0[] = {
  144221. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144222. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144223. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144224. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144225. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144226. 10,
  144227. };
  144228. static float _vq_quantthresh__16u2_p1_0[] = {
  144229. -0.5, 0.5,
  144230. };
  144231. static long _vq_quantmap__16u2_p1_0[] = {
  144232. 1, 0, 2,
  144233. };
  144234. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144235. _vq_quantthresh__16u2_p1_0,
  144236. _vq_quantmap__16u2_p1_0,
  144237. 3,
  144238. 3
  144239. };
  144240. static static_codebook _16u2_p1_0 = {
  144241. 4, 81,
  144242. _vq_lengthlist__16u2_p1_0,
  144243. 1, -535822336, 1611661312, 2, 0,
  144244. _vq_quantlist__16u2_p1_0,
  144245. NULL,
  144246. &_vq_auxt__16u2_p1_0,
  144247. NULL,
  144248. 0
  144249. };
  144250. static long _vq_quantlist__16u2_p2_0[] = {
  144251. 2,
  144252. 1,
  144253. 3,
  144254. 0,
  144255. 4,
  144256. };
  144257. static long _vq_lengthlist__16u2_p2_0[] = {
  144258. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144259. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144260. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144261. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144262. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144263. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144264. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144265. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144266. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144267. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144268. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144269. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144270. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144271. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144272. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144273. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144274. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144275. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144276. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144277. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144278. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144279. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144280. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144281. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144282. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144283. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144284. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144285. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144286. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144287. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144288. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144289. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144290. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144291. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144292. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144293. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144294. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144295. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144296. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144297. 13,
  144298. };
  144299. static float _vq_quantthresh__16u2_p2_0[] = {
  144300. -1.5, -0.5, 0.5, 1.5,
  144301. };
  144302. static long _vq_quantmap__16u2_p2_0[] = {
  144303. 3, 1, 0, 2, 4,
  144304. };
  144305. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144306. _vq_quantthresh__16u2_p2_0,
  144307. _vq_quantmap__16u2_p2_0,
  144308. 5,
  144309. 5
  144310. };
  144311. static static_codebook _16u2_p2_0 = {
  144312. 4, 625,
  144313. _vq_lengthlist__16u2_p2_0,
  144314. 1, -533725184, 1611661312, 3, 0,
  144315. _vq_quantlist__16u2_p2_0,
  144316. NULL,
  144317. &_vq_auxt__16u2_p2_0,
  144318. NULL,
  144319. 0
  144320. };
  144321. static long _vq_quantlist__16u2_p3_0[] = {
  144322. 4,
  144323. 3,
  144324. 5,
  144325. 2,
  144326. 6,
  144327. 1,
  144328. 7,
  144329. 0,
  144330. 8,
  144331. };
  144332. static long _vq_lengthlist__16u2_p3_0[] = {
  144333. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144334. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144335. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144336. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144337. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144338. 11,
  144339. };
  144340. static float _vq_quantthresh__16u2_p3_0[] = {
  144341. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144342. };
  144343. static long _vq_quantmap__16u2_p3_0[] = {
  144344. 7, 5, 3, 1, 0, 2, 4, 6,
  144345. 8,
  144346. };
  144347. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144348. _vq_quantthresh__16u2_p3_0,
  144349. _vq_quantmap__16u2_p3_0,
  144350. 9,
  144351. 9
  144352. };
  144353. static static_codebook _16u2_p3_0 = {
  144354. 2, 81,
  144355. _vq_lengthlist__16u2_p3_0,
  144356. 1, -531628032, 1611661312, 4, 0,
  144357. _vq_quantlist__16u2_p3_0,
  144358. NULL,
  144359. &_vq_auxt__16u2_p3_0,
  144360. NULL,
  144361. 0
  144362. };
  144363. static long _vq_quantlist__16u2_p4_0[] = {
  144364. 8,
  144365. 7,
  144366. 9,
  144367. 6,
  144368. 10,
  144369. 5,
  144370. 11,
  144371. 4,
  144372. 12,
  144373. 3,
  144374. 13,
  144375. 2,
  144376. 14,
  144377. 1,
  144378. 15,
  144379. 0,
  144380. 16,
  144381. };
  144382. static long _vq_lengthlist__16u2_p4_0[] = {
  144383. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144384. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144385. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144386. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144387. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144388. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144389. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144390. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144391. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144392. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144393. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144394. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144395. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144396. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144397. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144398. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144399. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144400. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144401. 14,
  144402. };
  144403. static float _vq_quantthresh__16u2_p4_0[] = {
  144404. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144405. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144406. };
  144407. static long _vq_quantmap__16u2_p4_0[] = {
  144408. 15, 13, 11, 9, 7, 5, 3, 1,
  144409. 0, 2, 4, 6, 8, 10, 12, 14,
  144410. 16,
  144411. };
  144412. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144413. _vq_quantthresh__16u2_p4_0,
  144414. _vq_quantmap__16u2_p4_0,
  144415. 17,
  144416. 17
  144417. };
  144418. static static_codebook _16u2_p4_0 = {
  144419. 2, 289,
  144420. _vq_lengthlist__16u2_p4_0,
  144421. 1, -529530880, 1611661312, 5, 0,
  144422. _vq_quantlist__16u2_p4_0,
  144423. NULL,
  144424. &_vq_auxt__16u2_p4_0,
  144425. NULL,
  144426. 0
  144427. };
  144428. static long _vq_quantlist__16u2_p5_0[] = {
  144429. 1,
  144430. 0,
  144431. 2,
  144432. };
  144433. static long _vq_lengthlist__16u2_p5_0[] = {
  144434. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144435. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144436. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144437. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144438. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144439. 10,
  144440. };
  144441. static float _vq_quantthresh__16u2_p5_0[] = {
  144442. -5.5, 5.5,
  144443. };
  144444. static long _vq_quantmap__16u2_p5_0[] = {
  144445. 1, 0, 2,
  144446. };
  144447. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144448. _vq_quantthresh__16u2_p5_0,
  144449. _vq_quantmap__16u2_p5_0,
  144450. 3,
  144451. 3
  144452. };
  144453. static static_codebook _16u2_p5_0 = {
  144454. 4, 81,
  144455. _vq_lengthlist__16u2_p5_0,
  144456. 1, -529137664, 1618345984, 2, 0,
  144457. _vq_quantlist__16u2_p5_0,
  144458. NULL,
  144459. &_vq_auxt__16u2_p5_0,
  144460. NULL,
  144461. 0
  144462. };
  144463. static long _vq_quantlist__16u2_p5_1[] = {
  144464. 5,
  144465. 4,
  144466. 6,
  144467. 3,
  144468. 7,
  144469. 2,
  144470. 8,
  144471. 1,
  144472. 9,
  144473. 0,
  144474. 10,
  144475. };
  144476. static long _vq_lengthlist__16u2_p5_1[] = {
  144477. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144478. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144479. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144480. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144481. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144482. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144483. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144484. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144485. };
  144486. static float _vq_quantthresh__16u2_p5_1[] = {
  144487. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144488. 3.5, 4.5,
  144489. };
  144490. static long _vq_quantmap__16u2_p5_1[] = {
  144491. 9, 7, 5, 3, 1, 0, 2, 4,
  144492. 6, 8, 10,
  144493. };
  144494. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144495. _vq_quantthresh__16u2_p5_1,
  144496. _vq_quantmap__16u2_p5_1,
  144497. 11,
  144498. 11
  144499. };
  144500. static static_codebook _16u2_p5_1 = {
  144501. 2, 121,
  144502. _vq_lengthlist__16u2_p5_1,
  144503. 1, -531365888, 1611661312, 4, 0,
  144504. _vq_quantlist__16u2_p5_1,
  144505. NULL,
  144506. &_vq_auxt__16u2_p5_1,
  144507. NULL,
  144508. 0
  144509. };
  144510. static long _vq_quantlist__16u2_p6_0[] = {
  144511. 6,
  144512. 5,
  144513. 7,
  144514. 4,
  144515. 8,
  144516. 3,
  144517. 9,
  144518. 2,
  144519. 10,
  144520. 1,
  144521. 11,
  144522. 0,
  144523. 12,
  144524. };
  144525. static long _vq_lengthlist__16u2_p6_0[] = {
  144526. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144527. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144528. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144529. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144530. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144531. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144532. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144533. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144534. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144535. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144536. 12,13,13,14,14,14,14,15,15,
  144537. };
  144538. static float _vq_quantthresh__16u2_p6_0[] = {
  144539. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144540. 12.5, 17.5, 22.5, 27.5,
  144541. };
  144542. static long _vq_quantmap__16u2_p6_0[] = {
  144543. 11, 9, 7, 5, 3, 1, 0, 2,
  144544. 4, 6, 8, 10, 12,
  144545. };
  144546. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144547. _vq_quantthresh__16u2_p6_0,
  144548. _vq_quantmap__16u2_p6_0,
  144549. 13,
  144550. 13
  144551. };
  144552. static static_codebook _16u2_p6_0 = {
  144553. 2, 169,
  144554. _vq_lengthlist__16u2_p6_0,
  144555. 1, -526516224, 1616117760, 4, 0,
  144556. _vq_quantlist__16u2_p6_0,
  144557. NULL,
  144558. &_vq_auxt__16u2_p6_0,
  144559. NULL,
  144560. 0
  144561. };
  144562. static long _vq_quantlist__16u2_p6_1[] = {
  144563. 2,
  144564. 1,
  144565. 3,
  144566. 0,
  144567. 4,
  144568. };
  144569. static long _vq_lengthlist__16u2_p6_1[] = {
  144570. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144571. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144572. };
  144573. static float _vq_quantthresh__16u2_p6_1[] = {
  144574. -1.5, -0.5, 0.5, 1.5,
  144575. };
  144576. static long _vq_quantmap__16u2_p6_1[] = {
  144577. 3, 1, 0, 2, 4,
  144578. };
  144579. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144580. _vq_quantthresh__16u2_p6_1,
  144581. _vq_quantmap__16u2_p6_1,
  144582. 5,
  144583. 5
  144584. };
  144585. static static_codebook _16u2_p6_1 = {
  144586. 2, 25,
  144587. _vq_lengthlist__16u2_p6_1,
  144588. 1, -533725184, 1611661312, 3, 0,
  144589. _vq_quantlist__16u2_p6_1,
  144590. NULL,
  144591. &_vq_auxt__16u2_p6_1,
  144592. NULL,
  144593. 0
  144594. };
  144595. static long _vq_quantlist__16u2_p7_0[] = {
  144596. 6,
  144597. 5,
  144598. 7,
  144599. 4,
  144600. 8,
  144601. 3,
  144602. 9,
  144603. 2,
  144604. 10,
  144605. 1,
  144606. 11,
  144607. 0,
  144608. 12,
  144609. };
  144610. static long _vq_lengthlist__16u2_p7_0[] = {
  144611. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144612. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144613. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144614. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144615. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144616. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144617. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144618. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144619. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144620. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144621. 12,13,13,13,14,14,14,15,14,
  144622. };
  144623. static float _vq_quantthresh__16u2_p7_0[] = {
  144624. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144625. 27.5, 38.5, 49.5, 60.5,
  144626. };
  144627. static long _vq_quantmap__16u2_p7_0[] = {
  144628. 11, 9, 7, 5, 3, 1, 0, 2,
  144629. 4, 6, 8, 10, 12,
  144630. };
  144631. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144632. _vq_quantthresh__16u2_p7_0,
  144633. _vq_quantmap__16u2_p7_0,
  144634. 13,
  144635. 13
  144636. };
  144637. static static_codebook _16u2_p7_0 = {
  144638. 2, 169,
  144639. _vq_lengthlist__16u2_p7_0,
  144640. 1, -523206656, 1618345984, 4, 0,
  144641. _vq_quantlist__16u2_p7_0,
  144642. NULL,
  144643. &_vq_auxt__16u2_p7_0,
  144644. NULL,
  144645. 0
  144646. };
  144647. static long _vq_quantlist__16u2_p7_1[] = {
  144648. 5,
  144649. 4,
  144650. 6,
  144651. 3,
  144652. 7,
  144653. 2,
  144654. 8,
  144655. 1,
  144656. 9,
  144657. 0,
  144658. 10,
  144659. };
  144660. static long _vq_lengthlist__16u2_p7_1[] = {
  144661. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144662. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144663. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144664. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144665. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144666. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144667. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144668. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144669. };
  144670. static float _vq_quantthresh__16u2_p7_1[] = {
  144671. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144672. 3.5, 4.5,
  144673. };
  144674. static long _vq_quantmap__16u2_p7_1[] = {
  144675. 9, 7, 5, 3, 1, 0, 2, 4,
  144676. 6, 8, 10,
  144677. };
  144678. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144679. _vq_quantthresh__16u2_p7_1,
  144680. _vq_quantmap__16u2_p7_1,
  144681. 11,
  144682. 11
  144683. };
  144684. static static_codebook _16u2_p7_1 = {
  144685. 2, 121,
  144686. _vq_lengthlist__16u2_p7_1,
  144687. 1, -531365888, 1611661312, 4, 0,
  144688. _vq_quantlist__16u2_p7_1,
  144689. NULL,
  144690. &_vq_auxt__16u2_p7_1,
  144691. NULL,
  144692. 0
  144693. };
  144694. static long _vq_quantlist__16u2_p8_0[] = {
  144695. 7,
  144696. 6,
  144697. 8,
  144698. 5,
  144699. 9,
  144700. 4,
  144701. 10,
  144702. 3,
  144703. 11,
  144704. 2,
  144705. 12,
  144706. 1,
  144707. 13,
  144708. 0,
  144709. 14,
  144710. };
  144711. static long _vq_lengthlist__16u2_p8_0[] = {
  144712. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144713. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144714. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144715. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144716. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144717. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144718. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144719. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144720. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144721. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144722. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144723. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144724. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144725. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144726. 14,
  144727. };
  144728. static float _vq_quantthresh__16u2_p8_0[] = {
  144729. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144730. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144731. };
  144732. static long _vq_quantmap__16u2_p8_0[] = {
  144733. 13, 11, 9, 7, 5, 3, 1, 0,
  144734. 2, 4, 6, 8, 10, 12, 14,
  144735. };
  144736. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144737. _vq_quantthresh__16u2_p8_0,
  144738. _vq_quantmap__16u2_p8_0,
  144739. 15,
  144740. 15
  144741. };
  144742. static static_codebook _16u2_p8_0 = {
  144743. 2, 225,
  144744. _vq_lengthlist__16u2_p8_0,
  144745. 1, -520986624, 1620377600, 4, 0,
  144746. _vq_quantlist__16u2_p8_0,
  144747. NULL,
  144748. &_vq_auxt__16u2_p8_0,
  144749. NULL,
  144750. 0
  144751. };
  144752. static long _vq_quantlist__16u2_p8_1[] = {
  144753. 10,
  144754. 9,
  144755. 11,
  144756. 8,
  144757. 12,
  144758. 7,
  144759. 13,
  144760. 6,
  144761. 14,
  144762. 5,
  144763. 15,
  144764. 4,
  144765. 16,
  144766. 3,
  144767. 17,
  144768. 2,
  144769. 18,
  144770. 1,
  144771. 19,
  144772. 0,
  144773. 20,
  144774. };
  144775. static long _vq_lengthlist__16u2_p8_1[] = {
  144776. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144777. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144778. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144779. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144780. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144781. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144782. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144783. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144784. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144785. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144786. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144787. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144788. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144789. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144790. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144791. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144792. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144793. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144794. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144795. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144796. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144797. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144798. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144799. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144801. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144802. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144803. 11,11,10,11,11,11,10,11,11,
  144804. };
  144805. static float _vq_quantthresh__16u2_p8_1[] = {
  144806. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144807. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144808. 6.5, 7.5, 8.5, 9.5,
  144809. };
  144810. static long _vq_quantmap__16u2_p8_1[] = {
  144811. 19, 17, 15, 13, 11, 9, 7, 5,
  144812. 3, 1, 0, 2, 4, 6, 8, 10,
  144813. 12, 14, 16, 18, 20,
  144814. };
  144815. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144816. _vq_quantthresh__16u2_p8_1,
  144817. _vq_quantmap__16u2_p8_1,
  144818. 21,
  144819. 21
  144820. };
  144821. static static_codebook _16u2_p8_1 = {
  144822. 2, 441,
  144823. _vq_lengthlist__16u2_p8_1,
  144824. 1, -529268736, 1611661312, 5, 0,
  144825. _vq_quantlist__16u2_p8_1,
  144826. NULL,
  144827. &_vq_auxt__16u2_p8_1,
  144828. NULL,
  144829. 0
  144830. };
  144831. static long _vq_quantlist__16u2_p9_0[] = {
  144832. 5586,
  144833. 4655,
  144834. 6517,
  144835. 3724,
  144836. 7448,
  144837. 2793,
  144838. 8379,
  144839. 1862,
  144840. 9310,
  144841. 931,
  144842. 10241,
  144843. 0,
  144844. 11172,
  144845. 5521,
  144846. 5651,
  144847. };
  144848. static long _vq_lengthlist__16u2_p9_0[] = {
  144849. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144850. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144851. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144852. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144853. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144854. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144855. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144856. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144857. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144858. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144859. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144860. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144861. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144862. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144863. 5,
  144864. };
  144865. static float _vq_quantthresh__16u2_p9_0[] = {
  144866. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144867. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144868. };
  144869. static long _vq_quantmap__16u2_p9_0[] = {
  144870. 11, 9, 7, 5, 3, 1, 13, 0,
  144871. 14, 2, 4, 6, 8, 10, 12,
  144872. };
  144873. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144874. _vq_quantthresh__16u2_p9_0,
  144875. _vq_quantmap__16u2_p9_0,
  144876. 15,
  144877. 15
  144878. };
  144879. static static_codebook _16u2_p9_0 = {
  144880. 2, 225,
  144881. _vq_lengthlist__16u2_p9_0,
  144882. 1, -510275072, 1611661312, 14, 0,
  144883. _vq_quantlist__16u2_p9_0,
  144884. NULL,
  144885. &_vq_auxt__16u2_p9_0,
  144886. NULL,
  144887. 0
  144888. };
  144889. static long _vq_quantlist__16u2_p9_1[] = {
  144890. 392,
  144891. 343,
  144892. 441,
  144893. 294,
  144894. 490,
  144895. 245,
  144896. 539,
  144897. 196,
  144898. 588,
  144899. 147,
  144900. 637,
  144901. 98,
  144902. 686,
  144903. 49,
  144904. 735,
  144905. 0,
  144906. 784,
  144907. 388,
  144908. 396,
  144909. };
  144910. static long _vq_lengthlist__16u2_p9_1[] = {
  144911. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144912. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144913. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144914. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144915. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144916. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144917. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144918. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144919. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144920. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144921. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144922. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144923. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144924. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144925. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144926. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144928. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144929. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144930. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144931. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144932. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144933. 11,11,11,11,11,11,11, 5, 4,
  144934. };
  144935. static float _vq_quantthresh__16u2_p9_1[] = {
  144936. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144937. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144938. 318.5, 367.5,
  144939. };
  144940. static long _vq_quantmap__16u2_p9_1[] = {
  144941. 15, 13, 11, 9, 7, 5, 3, 1,
  144942. 17, 0, 18, 2, 4, 6, 8, 10,
  144943. 12, 14, 16,
  144944. };
  144945. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144946. _vq_quantthresh__16u2_p9_1,
  144947. _vq_quantmap__16u2_p9_1,
  144948. 19,
  144949. 19
  144950. };
  144951. static static_codebook _16u2_p9_1 = {
  144952. 2, 361,
  144953. _vq_lengthlist__16u2_p9_1,
  144954. 1, -518488064, 1611661312, 10, 0,
  144955. _vq_quantlist__16u2_p9_1,
  144956. NULL,
  144957. &_vq_auxt__16u2_p9_1,
  144958. NULL,
  144959. 0
  144960. };
  144961. static long _vq_quantlist__16u2_p9_2[] = {
  144962. 24,
  144963. 23,
  144964. 25,
  144965. 22,
  144966. 26,
  144967. 21,
  144968. 27,
  144969. 20,
  144970. 28,
  144971. 19,
  144972. 29,
  144973. 18,
  144974. 30,
  144975. 17,
  144976. 31,
  144977. 16,
  144978. 32,
  144979. 15,
  144980. 33,
  144981. 14,
  144982. 34,
  144983. 13,
  144984. 35,
  144985. 12,
  144986. 36,
  144987. 11,
  144988. 37,
  144989. 10,
  144990. 38,
  144991. 9,
  144992. 39,
  144993. 8,
  144994. 40,
  144995. 7,
  144996. 41,
  144997. 6,
  144998. 42,
  144999. 5,
  145000. 43,
  145001. 4,
  145002. 44,
  145003. 3,
  145004. 45,
  145005. 2,
  145006. 46,
  145007. 1,
  145008. 47,
  145009. 0,
  145010. 48,
  145011. };
  145012. static long _vq_lengthlist__16u2_p9_2[] = {
  145013. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145014. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145015. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145016. 11,
  145017. };
  145018. static float _vq_quantthresh__16u2_p9_2[] = {
  145019. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145020. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145021. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145022. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145023. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145024. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145025. };
  145026. static long _vq_quantmap__16u2_p9_2[] = {
  145027. 47, 45, 43, 41, 39, 37, 35, 33,
  145028. 31, 29, 27, 25, 23, 21, 19, 17,
  145029. 15, 13, 11, 9, 7, 5, 3, 1,
  145030. 0, 2, 4, 6, 8, 10, 12, 14,
  145031. 16, 18, 20, 22, 24, 26, 28, 30,
  145032. 32, 34, 36, 38, 40, 42, 44, 46,
  145033. 48,
  145034. };
  145035. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145036. _vq_quantthresh__16u2_p9_2,
  145037. _vq_quantmap__16u2_p9_2,
  145038. 49,
  145039. 49
  145040. };
  145041. static static_codebook _16u2_p9_2 = {
  145042. 1, 49,
  145043. _vq_lengthlist__16u2_p9_2,
  145044. 1, -526909440, 1611661312, 6, 0,
  145045. _vq_quantlist__16u2_p9_2,
  145046. NULL,
  145047. &_vq_auxt__16u2_p9_2,
  145048. NULL,
  145049. 0
  145050. };
  145051. static long _vq_quantlist__8u0__p1_0[] = {
  145052. 1,
  145053. 0,
  145054. 2,
  145055. };
  145056. static long _vq_lengthlist__8u0__p1_0[] = {
  145057. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145058. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145059. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145060. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145061. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145062. 11,
  145063. };
  145064. static float _vq_quantthresh__8u0__p1_0[] = {
  145065. -0.5, 0.5,
  145066. };
  145067. static long _vq_quantmap__8u0__p1_0[] = {
  145068. 1, 0, 2,
  145069. };
  145070. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145071. _vq_quantthresh__8u0__p1_0,
  145072. _vq_quantmap__8u0__p1_0,
  145073. 3,
  145074. 3
  145075. };
  145076. static static_codebook _8u0__p1_0 = {
  145077. 4, 81,
  145078. _vq_lengthlist__8u0__p1_0,
  145079. 1, -535822336, 1611661312, 2, 0,
  145080. _vq_quantlist__8u0__p1_0,
  145081. NULL,
  145082. &_vq_auxt__8u0__p1_0,
  145083. NULL,
  145084. 0
  145085. };
  145086. static long _vq_quantlist__8u0__p2_0[] = {
  145087. 1,
  145088. 0,
  145089. 2,
  145090. };
  145091. static long _vq_lengthlist__8u0__p2_0[] = {
  145092. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145093. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145094. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145095. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145096. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145097. 8,
  145098. };
  145099. static float _vq_quantthresh__8u0__p2_0[] = {
  145100. -0.5, 0.5,
  145101. };
  145102. static long _vq_quantmap__8u0__p2_0[] = {
  145103. 1, 0, 2,
  145104. };
  145105. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145106. _vq_quantthresh__8u0__p2_0,
  145107. _vq_quantmap__8u0__p2_0,
  145108. 3,
  145109. 3
  145110. };
  145111. static static_codebook _8u0__p2_0 = {
  145112. 4, 81,
  145113. _vq_lengthlist__8u0__p2_0,
  145114. 1, -535822336, 1611661312, 2, 0,
  145115. _vq_quantlist__8u0__p2_0,
  145116. NULL,
  145117. &_vq_auxt__8u0__p2_0,
  145118. NULL,
  145119. 0
  145120. };
  145121. static long _vq_quantlist__8u0__p3_0[] = {
  145122. 2,
  145123. 1,
  145124. 3,
  145125. 0,
  145126. 4,
  145127. };
  145128. static long _vq_lengthlist__8u0__p3_0[] = {
  145129. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145130. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145131. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145132. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145133. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145134. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145135. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145136. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145137. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145138. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145139. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145140. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145141. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145142. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145143. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145144. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145145. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145146. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145147. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145148. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145149. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145150. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145151. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145152. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145153. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145154. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145155. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145156. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145157. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145158. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145159. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145160. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145161. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145162. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145163. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145164. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145165. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145166. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145167. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145168. 16,
  145169. };
  145170. static float _vq_quantthresh__8u0__p3_0[] = {
  145171. -1.5, -0.5, 0.5, 1.5,
  145172. };
  145173. static long _vq_quantmap__8u0__p3_0[] = {
  145174. 3, 1, 0, 2, 4,
  145175. };
  145176. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145177. _vq_quantthresh__8u0__p3_0,
  145178. _vq_quantmap__8u0__p3_0,
  145179. 5,
  145180. 5
  145181. };
  145182. static static_codebook _8u0__p3_0 = {
  145183. 4, 625,
  145184. _vq_lengthlist__8u0__p3_0,
  145185. 1, -533725184, 1611661312, 3, 0,
  145186. _vq_quantlist__8u0__p3_0,
  145187. NULL,
  145188. &_vq_auxt__8u0__p3_0,
  145189. NULL,
  145190. 0
  145191. };
  145192. static long _vq_quantlist__8u0__p4_0[] = {
  145193. 2,
  145194. 1,
  145195. 3,
  145196. 0,
  145197. 4,
  145198. };
  145199. static long _vq_lengthlist__8u0__p4_0[] = {
  145200. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145201. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145202. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145203. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145204. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145205. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145206. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145207. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145208. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145209. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145210. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145211. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145212. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145213. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145214. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145215. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145216. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145217. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145218. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145219. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145220. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145221. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145222. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145223. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145224. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145225. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145226. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145227. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145228. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145229. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145230. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145231. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145232. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145233. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145234. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145235. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145236. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145237. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145238. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145239. 12,
  145240. };
  145241. static float _vq_quantthresh__8u0__p4_0[] = {
  145242. -1.5, -0.5, 0.5, 1.5,
  145243. };
  145244. static long _vq_quantmap__8u0__p4_0[] = {
  145245. 3, 1, 0, 2, 4,
  145246. };
  145247. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145248. _vq_quantthresh__8u0__p4_0,
  145249. _vq_quantmap__8u0__p4_0,
  145250. 5,
  145251. 5
  145252. };
  145253. static static_codebook _8u0__p4_0 = {
  145254. 4, 625,
  145255. _vq_lengthlist__8u0__p4_0,
  145256. 1, -533725184, 1611661312, 3, 0,
  145257. _vq_quantlist__8u0__p4_0,
  145258. NULL,
  145259. &_vq_auxt__8u0__p4_0,
  145260. NULL,
  145261. 0
  145262. };
  145263. static long _vq_quantlist__8u0__p5_0[] = {
  145264. 4,
  145265. 3,
  145266. 5,
  145267. 2,
  145268. 6,
  145269. 1,
  145270. 7,
  145271. 0,
  145272. 8,
  145273. };
  145274. static long _vq_lengthlist__8u0__p5_0[] = {
  145275. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145276. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145277. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145278. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145279. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145280. 12,
  145281. };
  145282. static float _vq_quantthresh__8u0__p5_0[] = {
  145283. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145284. };
  145285. static long _vq_quantmap__8u0__p5_0[] = {
  145286. 7, 5, 3, 1, 0, 2, 4, 6,
  145287. 8,
  145288. };
  145289. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145290. _vq_quantthresh__8u0__p5_0,
  145291. _vq_quantmap__8u0__p5_0,
  145292. 9,
  145293. 9
  145294. };
  145295. static static_codebook _8u0__p5_0 = {
  145296. 2, 81,
  145297. _vq_lengthlist__8u0__p5_0,
  145298. 1, -531628032, 1611661312, 4, 0,
  145299. _vq_quantlist__8u0__p5_0,
  145300. NULL,
  145301. &_vq_auxt__8u0__p5_0,
  145302. NULL,
  145303. 0
  145304. };
  145305. static long _vq_quantlist__8u0__p6_0[] = {
  145306. 6,
  145307. 5,
  145308. 7,
  145309. 4,
  145310. 8,
  145311. 3,
  145312. 9,
  145313. 2,
  145314. 10,
  145315. 1,
  145316. 11,
  145317. 0,
  145318. 12,
  145319. };
  145320. static long _vq_lengthlist__8u0__p6_0[] = {
  145321. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145322. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145323. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145324. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145325. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145326. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145327. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145328. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145329. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145330. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145331. 16, 0,15, 0,17, 0, 0, 0, 0,
  145332. };
  145333. static float _vq_quantthresh__8u0__p6_0[] = {
  145334. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145335. 12.5, 17.5, 22.5, 27.5,
  145336. };
  145337. static long _vq_quantmap__8u0__p6_0[] = {
  145338. 11, 9, 7, 5, 3, 1, 0, 2,
  145339. 4, 6, 8, 10, 12,
  145340. };
  145341. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145342. _vq_quantthresh__8u0__p6_0,
  145343. _vq_quantmap__8u0__p6_0,
  145344. 13,
  145345. 13
  145346. };
  145347. static static_codebook _8u0__p6_0 = {
  145348. 2, 169,
  145349. _vq_lengthlist__8u0__p6_0,
  145350. 1, -526516224, 1616117760, 4, 0,
  145351. _vq_quantlist__8u0__p6_0,
  145352. NULL,
  145353. &_vq_auxt__8u0__p6_0,
  145354. NULL,
  145355. 0
  145356. };
  145357. static long _vq_quantlist__8u0__p6_1[] = {
  145358. 2,
  145359. 1,
  145360. 3,
  145361. 0,
  145362. 4,
  145363. };
  145364. static long _vq_lengthlist__8u0__p6_1[] = {
  145365. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145366. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145367. };
  145368. static float _vq_quantthresh__8u0__p6_1[] = {
  145369. -1.5, -0.5, 0.5, 1.5,
  145370. };
  145371. static long _vq_quantmap__8u0__p6_1[] = {
  145372. 3, 1, 0, 2, 4,
  145373. };
  145374. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145375. _vq_quantthresh__8u0__p6_1,
  145376. _vq_quantmap__8u0__p6_1,
  145377. 5,
  145378. 5
  145379. };
  145380. static static_codebook _8u0__p6_1 = {
  145381. 2, 25,
  145382. _vq_lengthlist__8u0__p6_1,
  145383. 1, -533725184, 1611661312, 3, 0,
  145384. _vq_quantlist__8u0__p6_1,
  145385. NULL,
  145386. &_vq_auxt__8u0__p6_1,
  145387. NULL,
  145388. 0
  145389. };
  145390. static long _vq_quantlist__8u0__p7_0[] = {
  145391. 1,
  145392. 0,
  145393. 2,
  145394. };
  145395. static long _vq_lengthlist__8u0__p7_0[] = {
  145396. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145397. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145398. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145399. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145400. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145401. 7,
  145402. };
  145403. static float _vq_quantthresh__8u0__p7_0[] = {
  145404. -157.5, 157.5,
  145405. };
  145406. static long _vq_quantmap__8u0__p7_0[] = {
  145407. 1, 0, 2,
  145408. };
  145409. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145410. _vq_quantthresh__8u0__p7_0,
  145411. _vq_quantmap__8u0__p7_0,
  145412. 3,
  145413. 3
  145414. };
  145415. static static_codebook _8u0__p7_0 = {
  145416. 4, 81,
  145417. _vq_lengthlist__8u0__p7_0,
  145418. 1, -518803456, 1628680192, 2, 0,
  145419. _vq_quantlist__8u0__p7_0,
  145420. NULL,
  145421. &_vq_auxt__8u0__p7_0,
  145422. NULL,
  145423. 0
  145424. };
  145425. static long _vq_quantlist__8u0__p7_1[] = {
  145426. 7,
  145427. 6,
  145428. 8,
  145429. 5,
  145430. 9,
  145431. 4,
  145432. 10,
  145433. 3,
  145434. 11,
  145435. 2,
  145436. 12,
  145437. 1,
  145438. 13,
  145439. 0,
  145440. 14,
  145441. };
  145442. static long _vq_lengthlist__8u0__p7_1[] = {
  145443. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145444. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145445. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145446. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145447. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145448. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145449. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145450. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145451. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145452. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145453. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145454. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145455. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145456. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145457. 10,
  145458. };
  145459. static float _vq_quantthresh__8u0__p7_1[] = {
  145460. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145461. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145462. };
  145463. static long _vq_quantmap__8u0__p7_1[] = {
  145464. 13, 11, 9, 7, 5, 3, 1, 0,
  145465. 2, 4, 6, 8, 10, 12, 14,
  145466. };
  145467. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145468. _vq_quantthresh__8u0__p7_1,
  145469. _vq_quantmap__8u0__p7_1,
  145470. 15,
  145471. 15
  145472. };
  145473. static static_codebook _8u0__p7_1 = {
  145474. 2, 225,
  145475. _vq_lengthlist__8u0__p7_1,
  145476. 1, -520986624, 1620377600, 4, 0,
  145477. _vq_quantlist__8u0__p7_1,
  145478. NULL,
  145479. &_vq_auxt__8u0__p7_1,
  145480. NULL,
  145481. 0
  145482. };
  145483. static long _vq_quantlist__8u0__p7_2[] = {
  145484. 10,
  145485. 9,
  145486. 11,
  145487. 8,
  145488. 12,
  145489. 7,
  145490. 13,
  145491. 6,
  145492. 14,
  145493. 5,
  145494. 15,
  145495. 4,
  145496. 16,
  145497. 3,
  145498. 17,
  145499. 2,
  145500. 18,
  145501. 1,
  145502. 19,
  145503. 0,
  145504. 20,
  145505. };
  145506. static long _vq_lengthlist__8u0__p7_2[] = {
  145507. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145508. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145509. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145510. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145511. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145512. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145513. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145514. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145515. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145516. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145517. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145518. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145519. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145520. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145521. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145522. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145523. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145524. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145525. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145526. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145527. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145528. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145529. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145530. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145531. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145532. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145533. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145534. 11,12,11,11,11,10,10,11,11,
  145535. };
  145536. static float _vq_quantthresh__8u0__p7_2[] = {
  145537. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145538. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145539. 6.5, 7.5, 8.5, 9.5,
  145540. };
  145541. static long _vq_quantmap__8u0__p7_2[] = {
  145542. 19, 17, 15, 13, 11, 9, 7, 5,
  145543. 3, 1, 0, 2, 4, 6, 8, 10,
  145544. 12, 14, 16, 18, 20,
  145545. };
  145546. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145547. _vq_quantthresh__8u0__p7_2,
  145548. _vq_quantmap__8u0__p7_2,
  145549. 21,
  145550. 21
  145551. };
  145552. static static_codebook _8u0__p7_2 = {
  145553. 2, 441,
  145554. _vq_lengthlist__8u0__p7_2,
  145555. 1, -529268736, 1611661312, 5, 0,
  145556. _vq_quantlist__8u0__p7_2,
  145557. NULL,
  145558. &_vq_auxt__8u0__p7_2,
  145559. NULL,
  145560. 0
  145561. };
  145562. static long _huff_lengthlist__8u0__single[] = {
  145563. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145564. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145565. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145566. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145567. };
  145568. static static_codebook _huff_book__8u0__single = {
  145569. 2, 64,
  145570. _huff_lengthlist__8u0__single,
  145571. 0, 0, 0, 0, 0,
  145572. NULL,
  145573. NULL,
  145574. NULL,
  145575. NULL,
  145576. 0
  145577. };
  145578. static long _vq_quantlist__8u1__p1_0[] = {
  145579. 1,
  145580. 0,
  145581. 2,
  145582. };
  145583. static long _vq_lengthlist__8u1__p1_0[] = {
  145584. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145585. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145586. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145587. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145588. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145589. 10,
  145590. };
  145591. static float _vq_quantthresh__8u1__p1_0[] = {
  145592. -0.5, 0.5,
  145593. };
  145594. static long _vq_quantmap__8u1__p1_0[] = {
  145595. 1, 0, 2,
  145596. };
  145597. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145598. _vq_quantthresh__8u1__p1_0,
  145599. _vq_quantmap__8u1__p1_0,
  145600. 3,
  145601. 3
  145602. };
  145603. static static_codebook _8u1__p1_0 = {
  145604. 4, 81,
  145605. _vq_lengthlist__8u1__p1_0,
  145606. 1, -535822336, 1611661312, 2, 0,
  145607. _vq_quantlist__8u1__p1_0,
  145608. NULL,
  145609. &_vq_auxt__8u1__p1_0,
  145610. NULL,
  145611. 0
  145612. };
  145613. static long _vq_quantlist__8u1__p2_0[] = {
  145614. 1,
  145615. 0,
  145616. 2,
  145617. };
  145618. static long _vq_lengthlist__8u1__p2_0[] = {
  145619. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145620. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145621. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145622. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145623. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145624. 7,
  145625. };
  145626. static float _vq_quantthresh__8u1__p2_0[] = {
  145627. -0.5, 0.5,
  145628. };
  145629. static long _vq_quantmap__8u1__p2_0[] = {
  145630. 1, 0, 2,
  145631. };
  145632. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145633. _vq_quantthresh__8u1__p2_0,
  145634. _vq_quantmap__8u1__p2_0,
  145635. 3,
  145636. 3
  145637. };
  145638. static static_codebook _8u1__p2_0 = {
  145639. 4, 81,
  145640. _vq_lengthlist__8u1__p2_0,
  145641. 1, -535822336, 1611661312, 2, 0,
  145642. _vq_quantlist__8u1__p2_0,
  145643. NULL,
  145644. &_vq_auxt__8u1__p2_0,
  145645. NULL,
  145646. 0
  145647. };
  145648. static long _vq_quantlist__8u1__p3_0[] = {
  145649. 2,
  145650. 1,
  145651. 3,
  145652. 0,
  145653. 4,
  145654. };
  145655. static long _vq_lengthlist__8u1__p3_0[] = {
  145656. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145657. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145658. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145659. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145660. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145661. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145662. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145663. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145664. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145665. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145666. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145667. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145668. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145669. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145670. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145671. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145672. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145673. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145674. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145675. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145676. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145677. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145678. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145679. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145680. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145681. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145682. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145683. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145684. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145685. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145686. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145687. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145688. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145689. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145690. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145691. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145692. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145693. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145694. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145695. 16,
  145696. };
  145697. static float _vq_quantthresh__8u1__p3_0[] = {
  145698. -1.5, -0.5, 0.5, 1.5,
  145699. };
  145700. static long _vq_quantmap__8u1__p3_0[] = {
  145701. 3, 1, 0, 2, 4,
  145702. };
  145703. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145704. _vq_quantthresh__8u1__p3_0,
  145705. _vq_quantmap__8u1__p3_0,
  145706. 5,
  145707. 5
  145708. };
  145709. static static_codebook _8u1__p3_0 = {
  145710. 4, 625,
  145711. _vq_lengthlist__8u1__p3_0,
  145712. 1, -533725184, 1611661312, 3, 0,
  145713. _vq_quantlist__8u1__p3_0,
  145714. NULL,
  145715. &_vq_auxt__8u1__p3_0,
  145716. NULL,
  145717. 0
  145718. };
  145719. static long _vq_quantlist__8u1__p4_0[] = {
  145720. 2,
  145721. 1,
  145722. 3,
  145723. 0,
  145724. 4,
  145725. };
  145726. static long _vq_lengthlist__8u1__p4_0[] = {
  145727. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145728. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145729. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145730. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145731. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145732. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145733. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145734. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145735. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145736. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145737. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145738. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145739. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145740. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145741. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145742. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145743. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145744. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145745. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145746. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145747. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145748. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145749. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145750. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145751. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145752. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145753. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145754. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145755. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145756. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145757. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145758. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145759. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145760. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145761. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145762. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145763. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145764. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145765. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145766. 10,
  145767. };
  145768. static float _vq_quantthresh__8u1__p4_0[] = {
  145769. -1.5, -0.5, 0.5, 1.5,
  145770. };
  145771. static long _vq_quantmap__8u1__p4_0[] = {
  145772. 3, 1, 0, 2, 4,
  145773. };
  145774. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145775. _vq_quantthresh__8u1__p4_0,
  145776. _vq_quantmap__8u1__p4_0,
  145777. 5,
  145778. 5
  145779. };
  145780. static static_codebook _8u1__p4_0 = {
  145781. 4, 625,
  145782. _vq_lengthlist__8u1__p4_0,
  145783. 1, -533725184, 1611661312, 3, 0,
  145784. _vq_quantlist__8u1__p4_0,
  145785. NULL,
  145786. &_vq_auxt__8u1__p4_0,
  145787. NULL,
  145788. 0
  145789. };
  145790. static long _vq_quantlist__8u1__p5_0[] = {
  145791. 4,
  145792. 3,
  145793. 5,
  145794. 2,
  145795. 6,
  145796. 1,
  145797. 7,
  145798. 0,
  145799. 8,
  145800. };
  145801. static long _vq_lengthlist__8u1__p5_0[] = {
  145802. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145803. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145804. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145805. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145806. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145807. 13,
  145808. };
  145809. static float _vq_quantthresh__8u1__p5_0[] = {
  145810. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145811. };
  145812. static long _vq_quantmap__8u1__p5_0[] = {
  145813. 7, 5, 3, 1, 0, 2, 4, 6,
  145814. 8,
  145815. };
  145816. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145817. _vq_quantthresh__8u1__p5_0,
  145818. _vq_quantmap__8u1__p5_0,
  145819. 9,
  145820. 9
  145821. };
  145822. static static_codebook _8u1__p5_0 = {
  145823. 2, 81,
  145824. _vq_lengthlist__8u1__p5_0,
  145825. 1, -531628032, 1611661312, 4, 0,
  145826. _vq_quantlist__8u1__p5_0,
  145827. NULL,
  145828. &_vq_auxt__8u1__p5_0,
  145829. NULL,
  145830. 0
  145831. };
  145832. static long _vq_quantlist__8u1__p6_0[] = {
  145833. 4,
  145834. 3,
  145835. 5,
  145836. 2,
  145837. 6,
  145838. 1,
  145839. 7,
  145840. 0,
  145841. 8,
  145842. };
  145843. static long _vq_lengthlist__8u1__p6_0[] = {
  145844. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145845. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145846. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145847. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145848. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145849. 10,
  145850. };
  145851. static float _vq_quantthresh__8u1__p6_0[] = {
  145852. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145853. };
  145854. static long _vq_quantmap__8u1__p6_0[] = {
  145855. 7, 5, 3, 1, 0, 2, 4, 6,
  145856. 8,
  145857. };
  145858. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145859. _vq_quantthresh__8u1__p6_0,
  145860. _vq_quantmap__8u1__p6_0,
  145861. 9,
  145862. 9
  145863. };
  145864. static static_codebook _8u1__p6_0 = {
  145865. 2, 81,
  145866. _vq_lengthlist__8u1__p6_0,
  145867. 1, -531628032, 1611661312, 4, 0,
  145868. _vq_quantlist__8u1__p6_0,
  145869. NULL,
  145870. &_vq_auxt__8u1__p6_0,
  145871. NULL,
  145872. 0
  145873. };
  145874. static long _vq_quantlist__8u1__p7_0[] = {
  145875. 1,
  145876. 0,
  145877. 2,
  145878. };
  145879. static long _vq_lengthlist__8u1__p7_0[] = {
  145880. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145881. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145882. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145883. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145884. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145885. 11,
  145886. };
  145887. static float _vq_quantthresh__8u1__p7_0[] = {
  145888. -5.5, 5.5,
  145889. };
  145890. static long _vq_quantmap__8u1__p7_0[] = {
  145891. 1, 0, 2,
  145892. };
  145893. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145894. _vq_quantthresh__8u1__p7_0,
  145895. _vq_quantmap__8u1__p7_0,
  145896. 3,
  145897. 3
  145898. };
  145899. static static_codebook _8u1__p7_0 = {
  145900. 4, 81,
  145901. _vq_lengthlist__8u1__p7_0,
  145902. 1, -529137664, 1618345984, 2, 0,
  145903. _vq_quantlist__8u1__p7_0,
  145904. NULL,
  145905. &_vq_auxt__8u1__p7_0,
  145906. NULL,
  145907. 0
  145908. };
  145909. static long _vq_quantlist__8u1__p7_1[] = {
  145910. 5,
  145911. 4,
  145912. 6,
  145913. 3,
  145914. 7,
  145915. 2,
  145916. 8,
  145917. 1,
  145918. 9,
  145919. 0,
  145920. 10,
  145921. };
  145922. static long _vq_lengthlist__8u1__p7_1[] = {
  145923. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145924. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145925. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145926. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145927. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145928. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145929. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145930. 9, 9, 9, 9, 9,10,10,10,10,
  145931. };
  145932. static float _vq_quantthresh__8u1__p7_1[] = {
  145933. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145934. 3.5, 4.5,
  145935. };
  145936. static long _vq_quantmap__8u1__p7_1[] = {
  145937. 9, 7, 5, 3, 1, 0, 2, 4,
  145938. 6, 8, 10,
  145939. };
  145940. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145941. _vq_quantthresh__8u1__p7_1,
  145942. _vq_quantmap__8u1__p7_1,
  145943. 11,
  145944. 11
  145945. };
  145946. static static_codebook _8u1__p7_1 = {
  145947. 2, 121,
  145948. _vq_lengthlist__8u1__p7_1,
  145949. 1, -531365888, 1611661312, 4, 0,
  145950. _vq_quantlist__8u1__p7_1,
  145951. NULL,
  145952. &_vq_auxt__8u1__p7_1,
  145953. NULL,
  145954. 0
  145955. };
  145956. static long _vq_quantlist__8u1__p8_0[] = {
  145957. 5,
  145958. 4,
  145959. 6,
  145960. 3,
  145961. 7,
  145962. 2,
  145963. 8,
  145964. 1,
  145965. 9,
  145966. 0,
  145967. 10,
  145968. };
  145969. static long _vq_lengthlist__8u1__p8_0[] = {
  145970. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145971. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145972. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145973. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145974. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145975. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145976. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145977. 12,13,13,14,14,15,15,15,15,
  145978. };
  145979. static float _vq_quantthresh__8u1__p8_0[] = {
  145980. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145981. 38.5, 49.5,
  145982. };
  145983. static long _vq_quantmap__8u1__p8_0[] = {
  145984. 9, 7, 5, 3, 1, 0, 2, 4,
  145985. 6, 8, 10,
  145986. };
  145987. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145988. _vq_quantthresh__8u1__p8_0,
  145989. _vq_quantmap__8u1__p8_0,
  145990. 11,
  145991. 11
  145992. };
  145993. static static_codebook _8u1__p8_0 = {
  145994. 2, 121,
  145995. _vq_lengthlist__8u1__p8_0,
  145996. 1, -524582912, 1618345984, 4, 0,
  145997. _vq_quantlist__8u1__p8_0,
  145998. NULL,
  145999. &_vq_auxt__8u1__p8_0,
  146000. NULL,
  146001. 0
  146002. };
  146003. static long _vq_quantlist__8u1__p8_1[] = {
  146004. 5,
  146005. 4,
  146006. 6,
  146007. 3,
  146008. 7,
  146009. 2,
  146010. 8,
  146011. 1,
  146012. 9,
  146013. 0,
  146014. 10,
  146015. };
  146016. static long _vq_lengthlist__8u1__p8_1[] = {
  146017. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146018. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146019. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146020. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146021. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146022. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146023. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146024. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146025. };
  146026. static float _vq_quantthresh__8u1__p8_1[] = {
  146027. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146028. 3.5, 4.5,
  146029. };
  146030. static long _vq_quantmap__8u1__p8_1[] = {
  146031. 9, 7, 5, 3, 1, 0, 2, 4,
  146032. 6, 8, 10,
  146033. };
  146034. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146035. _vq_quantthresh__8u1__p8_1,
  146036. _vq_quantmap__8u1__p8_1,
  146037. 11,
  146038. 11
  146039. };
  146040. static static_codebook _8u1__p8_1 = {
  146041. 2, 121,
  146042. _vq_lengthlist__8u1__p8_1,
  146043. 1, -531365888, 1611661312, 4, 0,
  146044. _vq_quantlist__8u1__p8_1,
  146045. NULL,
  146046. &_vq_auxt__8u1__p8_1,
  146047. NULL,
  146048. 0
  146049. };
  146050. static long _vq_quantlist__8u1__p9_0[] = {
  146051. 7,
  146052. 6,
  146053. 8,
  146054. 5,
  146055. 9,
  146056. 4,
  146057. 10,
  146058. 3,
  146059. 11,
  146060. 2,
  146061. 12,
  146062. 1,
  146063. 13,
  146064. 0,
  146065. 14,
  146066. };
  146067. static long _vq_lengthlist__8u1__p9_0[] = {
  146068. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146069. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146070. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146071. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146072. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146073. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146074. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146075. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146076. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146077. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146078. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146079. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146080. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146081. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146082. 10,
  146083. };
  146084. static float _vq_quantthresh__8u1__p9_0[] = {
  146085. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146086. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146087. };
  146088. static long _vq_quantmap__8u1__p9_0[] = {
  146089. 13, 11, 9, 7, 5, 3, 1, 0,
  146090. 2, 4, 6, 8, 10, 12, 14,
  146091. };
  146092. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146093. _vq_quantthresh__8u1__p9_0,
  146094. _vq_quantmap__8u1__p9_0,
  146095. 15,
  146096. 15
  146097. };
  146098. static static_codebook _8u1__p9_0 = {
  146099. 2, 225,
  146100. _vq_lengthlist__8u1__p9_0,
  146101. 1, -514071552, 1627381760, 4, 0,
  146102. _vq_quantlist__8u1__p9_0,
  146103. NULL,
  146104. &_vq_auxt__8u1__p9_0,
  146105. NULL,
  146106. 0
  146107. };
  146108. static long _vq_quantlist__8u1__p9_1[] = {
  146109. 7,
  146110. 6,
  146111. 8,
  146112. 5,
  146113. 9,
  146114. 4,
  146115. 10,
  146116. 3,
  146117. 11,
  146118. 2,
  146119. 12,
  146120. 1,
  146121. 13,
  146122. 0,
  146123. 14,
  146124. };
  146125. static long _vq_lengthlist__8u1__p9_1[] = {
  146126. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146127. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146128. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146129. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146130. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146131. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146132. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146133. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146134. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146135. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146136. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146137. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146138. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146139. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146140. 13,
  146141. };
  146142. static float _vq_quantthresh__8u1__p9_1[] = {
  146143. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146144. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146145. };
  146146. static long _vq_quantmap__8u1__p9_1[] = {
  146147. 13, 11, 9, 7, 5, 3, 1, 0,
  146148. 2, 4, 6, 8, 10, 12, 14,
  146149. };
  146150. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146151. _vq_quantthresh__8u1__p9_1,
  146152. _vq_quantmap__8u1__p9_1,
  146153. 15,
  146154. 15
  146155. };
  146156. static static_codebook _8u1__p9_1 = {
  146157. 2, 225,
  146158. _vq_lengthlist__8u1__p9_1,
  146159. 1, -522338304, 1620115456, 4, 0,
  146160. _vq_quantlist__8u1__p9_1,
  146161. NULL,
  146162. &_vq_auxt__8u1__p9_1,
  146163. NULL,
  146164. 0
  146165. };
  146166. static long _vq_quantlist__8u1__p9_2[] = {
  146167. 8,
  146168. 7,
  146169. 9,
  146170. 6,
  146171. 10,
  146172. 5,
  146173. 11,
  146174. 4,
  146175. 12,
  146176. 3,
  146177. 13,
  146178. 2,
  146179. 14,
  146180. 1,
  146181. 15,
  146182. 0,
  146183. 16,
  146184. };
  146185. static long _vq_lengthlist__8u1__p9_2[] = {
  146186. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146187. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146188. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146189. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146190. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146191. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146192. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146193. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146194. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146195. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146196. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146197. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146198. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146199. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146200. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146201. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146202. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146203. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146204. 10,
  146205. };
  146206. static float _vq_quantthresh__8u1__p9_2[] = {
  146207. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146208. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146209. };
  146210. static long _vq_quantmap__8u1__p9_2[] = {
  146211. 15, 13, 11, 9, 7, 5, 3, 1,
  146212. 0, 2, 4, 6, 8, 10, 12, 14,
  146213. 16,
  146214. };
  146215. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146216. _vq_quantthresh__8u1__p9_2,
  146217. _vq_quantmap__8u1__p9_2,
  146218. 17,
  146219. 17
  146220. };
  146221. static static_codebook _8u1__p9_2 = {
  146222. 2, 289,
  146223. _vq_lengthlist__8u1__p9_2,
  146224. 1, -529530880, 1611661312, 5, 0,
  146225. _vq_quantlist__8u1__p9_2,
  146226. NULL,
  146227. &_vq_auxt__8u1__p9_2,
  146228. NULL,
  146229. 0
  146230. };
  146231. static long _huff_lengthlist__8u1__single[] = {
  146232. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146233. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146234. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146235. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146236. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146237. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146238. 13, 8, 8,15,
  146239. };
  146240. static static_codebook _huff_book__8u1__single = {
  146241. 2, 100,
  146242. _huff_lengthlist__8u1__single,
  146243. 0, 0, 0, 0, 0,
  146244. NULL,
  146245. NULL,
  146246. NULL,
  146247. NULL,
  146248. 0
  146249. };
  146250. static long _huff_lengthlist__44u0__long[] = {
  146251. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146252. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146253. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146254. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146255. };
  146256. static static_codebook _huff_book__44u0__long = {
  146257. 2, 64,
  146258. _huff_lengthlist__44u0__long,
  146259. 0, 0, 0, 0, 0,
  146260. NULL,
  146261. NULL,
  146262. NULL,
  146263. NULL,
  146264. 0
  146265. };
  146266. static long _vq_quantlist__44u0__p1_0[] = {
  146267. 1,
  146268. 0,
  146269. 2,
  146270. };
  146271. static long _vq_lengthlist__44u0__p1_0[] = {
  146272. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146273. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146274. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146275. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146276. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146277. 13,
  146278. };
  146279. static float _vq_quantthresh__44u0__p1_0[] = {
  146280. -0.5, 0.5,
  146281. };
  146282. static long _vq_quantmap__44u0__p1_0[] = {
  146283. 1, 0, 2,
  146284. };
  146285. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146286. _vq_quantthresh__44u0__p1_0,
  146287. _vq_quantmap__44u0__p1_0,
  146288. 3,
  146289. 3
  146290. };
  146291. static static_codebook _44u0__p1_0 = {
  146292. 4, 81,
  146293. _vq_lengthlist__44u0__p1_0,
  146294. 1, -535822336, 1611661312, 2, 0,
  146295. _vq_quantlist__44u0__p1_0,
  146296. NULL,
  146297. &_vq_auxt__44u0__p1_0,
  146298. NULL,
  146299. 0
  146300. };
  146301. static long _vq_quantlist__44u0__p2_0[] = {
  146302. 1,
  146303. 0,
  146304. 2,
  146305. };
  146306. static long _vq_lengthlist__44u0__p2_0[] = {
  146307. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146308. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146309. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146310. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146311. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146312. 9,
  146313. };
  146314. static float _vq_quantthresh__44u0__p2_0[] = {
  146315. -0.5, 0.5,
  146316. };
  146317. static long _vq_quantmap__44u0__p2_0[] = {
  146318. 1, 0, 2,
  146319. };
  146320. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146321. _vq_quantthresh__44u0__p2_0,
  146322. _vq_quantmap__44u0__p2_0,
  146323. 3,
  146324. 3
  146325. };
  146326. static static_codebook _44u0__p2_0 = {
  146327. 4, 81,
  146328. _vq_lengthlist__44u0__p2_0,
  146329. 1, -535822336, 1611661312, 2, 0,
  146330. _vq_quantlist__44u0__p2_0,
  146331. NULL,
  146332. &_vq_auxt__44u0__p2_0,
  146333. NULL,
  146334. 0
  146335. };
  146336. static long _vq_quantlist__44u0__p3_0[] = {
  146337. 2,
  146338. 1,
  146339. 3,
  146340. 0,
  146341. 4,
  146342. };
  146343. static long _vq_lengthlist__44u0__p3_0[] = {
  146344. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146345. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146346. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146347. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146348. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146349. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146350. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146351. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146352. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146353. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146354. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146355. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146356. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146357. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146358. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146359. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146360. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146361. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146362. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146363. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146364. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146365. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146366. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146367. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146368. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146369. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146370. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146371. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146372. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146373. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146374. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146375. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146376. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146377. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146378. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146379. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146380. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146381. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146382. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146383. 19,
  146384. };
  146385. static float _vq_quantthresh__44u0__p3_0[] = {
  146386. -1.5, -0.5, 0.5, 1.5,
  146387. };
  146388. static long _vq_quantmap__44u0__p3_0[] = {
  146389. 3, 1, 0, 2, 4,
  146390. };
  146391. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146392. _vq_quantthresh__44u0__p3_0,
  146393. _vq_quantmap__44u0__p3_0,
  146394. 5,
  146395. 5
  146396. };
  146397. static static_codebook _44u0__p3_0 = {
  146398. 4, 625,
  146399. _vq_lengthlist__44u0__p3_0,
  146400. 1, -533725184, 1611661312, 3, 0,
  146401. _vq_quantlist__44u0__p3_0,
  146402. NULL,
  146403. &_vq_auxt__44u0__p3_0,
  146404. NULL,
  146405. 0
  146406. };
  146407. static long _vq_quantlist__44u0__p4_0[] = {
  146408. 2,
  146409. 1,
  146410. 3,
  146411. 0,
  146412. 4,
  146413. };
  146414. static long _vq_lengthlist__44u0__p4_0[] = {
  146415. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146416. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146417. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146418. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146419. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146420. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146421. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146422. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146423. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146424. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146425. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146426. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146427. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146428. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146429. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146430. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146431. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146432. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146433. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146434. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146435. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146436. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146437. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146438. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146439. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146440. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146441. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146442. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146443. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146444. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146445. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146446. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146447. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146448. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146449. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146450. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146451. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146452. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146453. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146454. 12,
  146455. };
  146456. static float _vq_quantthresh__44u0__p4_0[] = {
  146457. -1.5, -0.5, 0.5, 1.5,
  146458. };
  146459. static long _vq_quantmap__44u0__p4_0[] = {
  146460. 3, 1, 0, 2, 4,
  146461. };
  146462. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146463. _vq_quantthresh__44u0__p4_0,
  146464. _vq_quantmap__44u0__p4_0,
  146465. 5,
  146466. 5
  146467. };
  146468. static static_codebook _44u0__p4_0 = {
  146469. 4, 625,
  146470. _vq_lengthlist__44u0__p4_0,
  146471. 1, -533725184, 1611661312, 3, 0,
  146472. _vq_quantlist__44u0__p4_0,
  146473. NULL,
  146474. &_vq_auxt__44u0__p4_0,
  146475. NULL,
  146476. 0
  146477. };
  146478. static long _vq_quantlist__44u0__p5_0[] = {
  146479. 4,
  146480. 3,
  146481. 5,
  146482. 2,
  146483. 6,
  146484. 1,
  146485. 7,
  146486. 0,
  146487. 8,
  146488. };
  146489. static long _vq_lengthlist__44u0__p5_0[] = {
  146490. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146491. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146492. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146493. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146494. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146495. 12,
  146496. };
  146497. static float _vq_quantthresh__44u0__p5_0[] = {
  146498. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146499. };
  146500. static long _vq_quantmap__44u0__p5_0[] = {
  146501. 7, 5, 3, 1, 0, 2, 4, 6,
  146502. 8,
  146503. };
  146504. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146505. _vq_quantthresh__44u0__p5_0,
  146506. _vq_quantmap__44u0__p5_0,
  146507. 9,
  146508. 9
  146509. };
  146510. static static_codebook _44u0__p5_0 = {
  146511. 2, 81,
  146512. _vq_lengthlist__44u0__p5_0,
  146513. 1, -531628032, 1611661312, 4, 0,
  146514. _vq_quantlist__44u0__p5_0,
  146515. NULL,
  146516. &_vq_auxt__44u0__p5_0,
  146517. NULL,
  146518. 0
  146519. };
  146520. static long _vq_quantlist__44u0__p6_0[] = {
  146521. 6,
  146522. 5,
  146523. 7,
  146524. 4,
  146525. 8,
  146526. 3,
  146527. 9,
  146528. 2,
  146529. 10,
  146530. 1,
  146531. 11,
  146532. 0,
  146533. 12,
  146534. };
  146535. static long _vq_lengthlist__44u0__p6_0[] = {
  146536. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146537. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146538. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146539. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146540. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146541. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146542. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146543. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146544. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146545. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146546. 15,17,16,17,18,17,17,18, 0,
  146547. };
  146548. static float _vq_quantthresh__44u0__p6_0[] = {
  146549. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146550. 12.5, 17.5, 22.5, 27.5,
  146551. };
  146552. static long _vq_quantmap__44u0__p6_0[] = {
  146553. 11, 9, 7, 5, 3, 1, 0, 2,
  146554. 4, 6, 8, 10, 12,
  146555. };
  146556. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146557. _vq_quantthresh__44u0__p6_0,
  146558. _vq_quantmap__44u0__p6_0,
  146559. 13,
  146560. 13
  146561. };
  146562. static static_codebook _44u0__p6_0 = {
  146563. 2, 169,
  146564. _vq_lengthlist__44u0__p6_0,
  146565. 1, -526516224, 1616117760, 4, 0,
  146566. _vq_quantlist__44u0__p6_0,
  146567. NULL,
  146568. &_vq_auxt__44u0__p6_0,
  146569. NULL,
  146570. 0
  146571. };
  146572. static long _vq_quantlist__44u0__p6_1[] = {
  146573. 2,
  146574. 1,
  146575. 3,
  146576. 0,
  146577. 4,
  146578. };
  146579. static long _vq_lengthlist__44u0__p6_1[] = {
  146580. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146581. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146582. };
  146583. static float _vq_quantthresh__44u0__p6_1[] = {
  146584. -1.5, -0.5, 0.5, 1.5,
  146585. };
  146586. static long _vq_quantmap__44u0__p6_1[] = {
  146587. 3, 1, 0, 2, 4,
  146588. };
  146589. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146590. _vq_quantthresh__44u0__p6_1,
  146591. _vq_quantmap__44u0__p6_1,
  146592. 5,
  146593. 5
  146594. };
  146595. static static_codebook _44u0__p6_1 = {
  146596. 2, 25,
  146597. _vq_lengthlist__44u0__p6_1,
  146598. 1, -533725184, 1611661312, 3, 0,
  146599. _vq_quantlist__44u0__p6_1,
  146600. NULL,
  146601. &_vq_auxt__44u0__p6_1,
  146602. NULL,
  146603. 0
  146604. };
  146605. static long _vq_quantlist__44u0__p7_0[] = {
  146606. 2,
  146607. 1,
  146608. 3,
  146609. 0,
  146610. 4,
  146611. };
  146612. static long _vq_lengthlist__44u0__p7_0[] = {
  146613. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146614. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146615. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146616. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146617. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146618. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146619. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146620. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146621. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146622. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146623. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146624. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146625. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146626. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146627. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146628. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146631. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146632. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146637. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146638. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146639. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146640. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146641. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146642. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146643. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146644. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146645. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146646. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146647. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146648. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146649. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146650. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146651. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146652. 10,
  146653. };
  146654. static float _vq_quantthresh__44u0__p7_0[] = {
  146655. -253.5, -84.5, 84.5, 253.5,
  146656. };
  146657. static long _vq_quantmap__44u0__p7_0[] = {
  146658. 3, 1, 0, 2, 4,
  146659. };
  146660. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146661. _vq_quantthresh__44u0__p7_0,
  146662. _vq_quantmap__44u0__p7_0,
  146663. 5,
  146664. 5
  146665. };
  146666. static static_codebook _44u0__p7_0 = {
  146667. 4, 625,
  146668. _vq_lengthlist__44u0__p7_0,
  146669. 1, -518709248, 1626677248, 3, 0,
  146670. _vq_quantlist__44u0__p7_0,
  146671. NULL,
  146672. &_vq_auxt__44u0__p7_0,
  146673. NULL,
  146674. 0
  146675. };
  146676. static long _vq_quantlist__44u0__p7_1[] = {
  146677. 6,
  146678. 5,
  146679. 7,
  146680. 4,
  146681. 8,
  146682. 3,
  146683. 9,
  146684. 2,
  146685. 10,
  146686. 1,
  146687. 11,
  146688. 0,
  146689. 12,
  146690. };
  146691. static long _vq_lengthlist__44u0__p7_1[] = {
  146692. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146693. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146694. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146695. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146696. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146697. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146698. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146699. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146700. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146701. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146702. 15,15,15,15,15,15,15,15,15,
  146703. };
  146704. static float _vq_quantthresh__44u0__p7_1[] = {
  146705. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146706. 32.5, 45.5, 58.5, 71.5,
  146707. };
  146708. static long _vq_quantmap__44u0__p7_1[] = {
  146709. 11, 9, 7, 5, 3, 1, 0, 2,
  146710. 4, 6, 8, 10, 12,
  146711. };
  146712. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146713. _vq_quantthresh__44u0__p7_1,
  146714. _vq_quantmap__44u0__p7_1,
  146715. 13,
  146716. 13
  146717. };
  146718. static static_codebook _44u0__p7_1 = {
  146719. 2, 169,
  146720. _vq_lengthlist__44u0__p7_1,
  146721. 1, -523010048, 1618608128, 4, 0,
  146722. _vq_quantlist__44u0__p7_1,
  146723. NULL,
  146724. &_vq_auxt__44u0__p7_1,
  146725. NULL,
  146726. 0
  146727. };
  146728. static long _vq_quantlist__44u0__p7_2[] = {
  146729. 6,
  146730. 5,
  146731. 7,
  146732. 4,
  146733. 8,
  146734. 3,
  146735. 9,
  146736. 2,
  146737. 10,
  146738. 1,
  146739. 11,
  146740. 0,
  146741. 12,
  146742. };
  146743. static long _vq_lengthlist__44u0__p7_2[] = {
  146744. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146745. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146746. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146747. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146748. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146749. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146750. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146751. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146752. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146753. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146754. 9, 9, 9,10, 9, 9,10,10, 9,
  146755. };
  146756. static float _vq_quantthresh__44u0__p7_2[] = {
  146757. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146758. 2.5, 3.5, 4.5, 5.5,
  146759. };
  146760. static long _vq_quantmap__44u0__p7_2[] = {
  146761. 11, 9, 7, 5, 3, 1, 0, 2,
  146762. 4, 6, 8, 10, 12,
  146763. };
  146764. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146765. _vq_quantthresh__44u0__p7_2,
  146766. _vq_quantmap__44u0__p7_2,
  146767. 13,
  146768. 13
  146769. };
  146770. static static_codebook _44u0__p7_2 = {
  146771. 2, 169,
  146772. _vq_lengthlist__44u0__p7_2,
  146773. 1, -531103744, 1611661312, 4, 0,
  146774. _vq_quantlist__44u0__p7_2,
  146775. NULL,
  146776. &_vq_auxt__44u0__p7_2,
  146777. NULL,
  146778. 0
  146779. };
  146780. static long _huff_lengthlist__44u0__short[] = {
  146781. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146782. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146783. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146784. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146785. };
  146786. static static_codebook _huff_book__44u0__short = {
  146787. 2, 64,
  146788. _huff_lengthlist__44u0__short,
  146789. 0, 0, 0, 0, 0,
  146790. NULL,
  146791. NULL,
  146792. NULL,
  146793. NULL,
  146794. 0
  146795. };
  146796. static long _huff_lengthlist__44u1__long[] = {
  146797. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146798. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146799. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146800. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146801. };
  146802. static static_codebook _huff_book__44u1__long = {
  146803. 2, 64,
  146804. _huff_lengthlist__44u1__long,
  146805. 0, 0, 0, 0, 0,
  146806. NULL,
  146807. NULL,
  146808. NULL,
  146809. NULL,
  146810. 0
  146811. };
  146812. static long _vq_quantlist__44u1__p1_0[] = {
  146813. 1,
  146814. 0,
  146815. 2,
  146816. };
  146817. static long _vq_lengthlist__44u1__p1_0[] = {
  146818. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146819. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146820. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146821. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146822. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146823. 13,
  146824. };
  146825. static float _vq_quantthresh__44u1__p1_0[] = {
  146826. -0.5, 0.5,
  146827. };
  146828. static long _vq_quantmap__44u1__p1_0[] = {
  146829. 1, 0, 2,
  146830. };
  146831. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146832. _vq_quantthresh__44u1__p1_0,
  146833. _vq_quantmap__44u1__p1_0,
  146834. 3,
  146835. 3
  146836. };
  146837. static static_codebook _44u1__p1_0 = {
  146838. 4, 81,
  146839. _vq_lengthlist__44u1__p1_0,
  146840. 1, -535822336, 1611661312, 2, 0,
  146841. _vq_quantlist__44u1__p1_0,
  146842. NULL,
  146843. &_vq_auxt__44u1__p1_0,
  146844. NULL,
  146845. 0
  146846. };
  146847. static long _vq_quantlist__44u1__p2_0[] = {
  146848. 1,
  146849. 0,
  146850. 2,
  146851. };
  146852. static long _vq_lengthlist__44u1__p2_0[] = {
  146853. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146854. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146855. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146856. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146857. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146858. 9,
  146859. };
  146860. static float _vq_quantthresh__44u1__p2_0[] = {
  146861. -0.5, 0.5,
  146862. };
  146863. static long _vq_quantmap__44u1__p2_0[] = {
  146864. 1, 0, 2,
  146865. };
  146866. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146867. _vq_quantthresh__44u1__p2_0,
  146868. _vq_quantmap__44u1__p2_0,
  146869. 3,
  146870. 3
  146871. };
  146872. static static_codebook _44u1__p2_0 = {
  146873. 4, 81,
  146874. _vq_lengthlist__44u1__p2_0,
  146875. 1, -535822336, 1611661312, 2, 0,
  146876. _vq_quantlist__44u1__p2_0,
  146877. NULL,
  146878. &_vq_auxt__44u1__p2_0,
  146879. NULL,
  146880. 0
  146881. };
  146882. static long _vq_quantlist__44u1__p3_0[] = {
  146883. 2,
  146884. 1,
  146885. 3,
  146886. 0,
  146887. 4,
  146888. };
  146889. static long _vq_lengthlist__44u1__p3_0[] = {
  146890. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146891. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146892. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146893. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146894. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146895. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146896. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146897. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146898. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146899. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146900. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146901. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146902. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146903. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146904. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146905. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146906. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146907. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146908. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146909. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146910. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146911. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146912. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146913. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146914. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146915. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146916. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146917. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146918. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146919. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146920. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146921. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146922. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146923. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146924. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146925. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146926. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146927. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146928. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146929. 19,
  146930. };
  146931. static float _vq_quantthresh__44u1__p3_0[] = {
  146932. -1.5, -0.5, 0.5, 1.5,
  146933. };
  146934. static long _vq_quantmap__44u1__p3_0[] = {
  146935. 3, 1, 0, 2, 4,
  146936. };
  146937. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146938. _vq_quantthresh__44u1__p3_0,
  146939. _vq_quantmap__44u1__p3_0,
  146940. 5,
  146941. 5
  146942. };
  146943. static static_codebook _44u1__p3_0 = {
  146944. 4, 625,
  146945. _vq_lengthlist__44u1__p3_0,
  146946. 1, -533725184, 1611661312, 3, 0,
  146947. _vq_quantlist__44u1__p3_0,
  146948. NULL,
  146949. &_vq_auxt__44u1__p3_0,
  146950. NULL,
  146951. 0
  146952. };
  146953. static long _vq_quantlist__44u1__p4_0[] = {
  146954. 2,
  146955. 1,
  146956. 3,
  146957. 0,
  146958. 4,
  146959. };
  146960. static long _vq_lengthlist__44u1__p4_0[] = {
  146961. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146962. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146963. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146964. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146965. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146966. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146967. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146968. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146969. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146970. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146971. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146972. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146973. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146974. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146975. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146976. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146977. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146978. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146979. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146980. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146981. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146982. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146983. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146984. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146985. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146986. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146987. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146988. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146989. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146990. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146991. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146992. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146993. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146994. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146995. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146996. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146997. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146998. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146999. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147000. 12,
  147001. };
  147002. static float _vq_quantthresh__44u1__p4_0[] = {
  147003. -1.5, -0.5, 0.5, 1.5,
  147004. };
  147005. static long _vq_quantmap__44u1__p4_0[] = {
  147006. 3, 1, 0, 2, 4,
  147007. };
  147008. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147009. _vq_quantthresh__44u1__p4_0,
  147010. _vq_quantmap__44u1__p4_0,
  147011. 5,
  147012. 5
  147013. };
  147014. static static_codebook _44u1__p4_0 = {
  147015. 4, 625,
  147016. _vq_lengthlist__44u1__p4_0,
  147017. 1, -533725184, 1611661312, 3, 0,
  147018. _vq_quantlist__44u1__p4_0,
  147019. NULL,
  147020. &_vq_auxt__44u1__p4_0,
  147021. NULL,
  147022. 0
  147023. };
  147024. static long _vq_quantlist__44u1__p5_0[] = {
  147025. 4,
  147026. 3,
  147027. 5,
  147028. 2,
  147029. 6,
  147030. 1,
  147031. 7,
  147032. 0,
  147033. 8,
  147034. };
  147035. static long _vq_lengthlist__44u1__p5_0[] = {
  147036. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147037. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147038. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147039. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147040. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147041. 12,
  147042. };
  147043. static float _vq_quantthresh__44u1__p5_0[] = {
  147044. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147045. };
  147046. static long _vq_quantmap__44u1__p5_0[] = {
  147047. 7, 5, 3, 1, 0, 2, 4, 6,
  147048. 8,
  147049. };
  147050. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147051. _vq_quantthresh__44u1__p5_0,
  147052. _vq_quantmap__44u1__p5_0,
  147053. 9,
  147054. 9
  147055. };
  147056. static static_codebook _44u1__p5_0 = {
  147057. 2, 81,
  147058. _vq_lengthlist__44u1__p5_0,
  147059. 1, -531628032, 1611661312, 4, 0,
  147060. _vq_quantlist__44u1__p5_0,
  147061. NULL,
  147062. &_vq_auxt__44u1__p5_0,
  147063. NULL,
  147064. 0
  147065. };
  147066. static long _vq_quantlist__44u1__p6_0[] = {
  147067. 6,
  147068. 5,
  147069. 7,
  147070. 4,
  147071. 8,
  147072. 3,
  147073. 9,
  147074. 2,
  147075. 10,
  147076. 1,
  147077. 11,
  147078. 0,
  147079. 12,
  147080. };
  147081. static long _vq_lengthlist__44u1__p6_0[] = {
  147082. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147083. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147084. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147085. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147086. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147087. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147088. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147089. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147090. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147091. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147092. 15,17,16,17,18,17,17,18, 0,
  147093. };
  147094. static float _vq_quantthresh__44u1__p6_0[] = {
  147095. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147096. 12.5, 17.5, 22.5, 27.5,
  147097. };
  147098. static long _vq_quantmap__44u1__p6_0[] = {
  147099. 11, 9, 7, 5, 3, 1, 0, 2,
  147100. 4, 6, 8, 10, 12,
  147101. };
  147102. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147103. _vq_quantthresh__44u1__p6_0,
  147104. _vq_quantmap__44u1__p6_0,
  147105. 13,
  147106. 13
  147107. };
  147108. static static_codebook _44u1__p6_0 = {
  147109. 2, 169,
  147110. _vq_lengthlist__44u1__p6_0,
  147111. 1, -526516224, 1616117760, 4, 0,
  147112. _vq_quantlist__44u1__p6_0,
  147113. NULL,
  147114. &_vq_auxt__44u1__p6_0,
  147115. NULL,
  147116. 0
  147117. };
  147118. static long _vq_quantlist__44u1__p6_1[] = {
  147119. 2,
  147120. 1,
  147121. 3,
  147122. 0,
  147123. 4,
  147124. };
  147125. static long _vq_lengthlist__44u1__p6_1[] = {
  147126. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147127. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147128. };
  147129. static float _vq_quantthresh__44u1__p6_1[] = {
  147130. -1.5, -0.5, 0.5, 1.5,
  147131. };
  147132. static long _vq_quantmap__44u1__p6_1[] = {
  147133. 3, 1, 0, 2, 4,
  147134. };
  147135. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147136. _vq_quantthresh__44u1__p6_1,
  147137. _vq_quantmap__44u1__p6_1,
  147138. 5,
  147139. 5
  147140. };
  147141. static static_codebook _44u1__p6_1 = {
  147142. 2, 25,
  147143. _vq_lengthlist__44u1__p6_1,
  147144. 1, -533725184, 1611661312, 3, 0,
  147145. _vq_quantlist__44u1__p6_1,
  147146. NULL,
  147147. &_vq_auxt__44u1__p6_1,
  147148. NULL,
  147149. 0
  147150. };
  147151. static long _vq_quantlist__44u1__p7_0[] = {
  147152. 3,
  147153. 2,
  147154. 4,
  147155. 1,
  147156. 5,
  147157. 0,
  147158. 6,
  147159. };
  147160. static long _vq_lengthlist__44u1__p7_0[] = {
  147161. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147162. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147163. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147164. 8,
  147165. };
  147166. static float _vq_quantthresh__44u1__p7_0[] = {
  147167. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147168. };
  147169. static long _vq_quantmap__44u1__p7_0[] = {
  147170. 5, 3, 1, 0, 2, 4, 6,
  147171. };
  147172. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147173. _vq_quantthresh__44u1__p7_0,
  147174. _vq_quantmap__44u1__p7_0,
  147175. 7,
  147176. 7
  147177. };
  147178. static static_codebook _44u1__p7_0 = {
  147179. 2, 49,
  147180. _vq_lengthlist__44u1__p7_0,
  147181. 1, -518017024, 1626677248, 3, 0,
  147182. _vq_quantlist__44u1__p7_0,
  147183. NULL,
  147184. &_vq_auxt__44u1__p7_0,
  147185. NULL,
  147186. 0
  147187. };
  147188. static long _vq_quantlist__44u1__p7_1[] = {
  147189. 6,
  147190. 5,
  147191. 7,
  147192. 4,
  147193. 8,
  147194. 3,
  147195. 9,
  147196. 2,
  147197. 10,
  147198. 1,
  147199. 11,
  147200. 0,
  147201. 12,
  147202. };
  147203. static long _vq_lengthlist__44u1__p7_1[] = {
  147204. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147205. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147206. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147207. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147208. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147209. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147210. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147211. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147212. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147213. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147214. 15,15,15,15,15,15,15,15,15,
  147215. };
  147216. static float _vq_quantthresh__44u1__p7_1[] = {
  147217. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147218. 32.5, 45.5, 58.5, 71.5,
  147219. };
  147220. static long _vq_quantmap__44u1__p7_1[] = {
  147221. 11, 9, 7, 5, 3, 1, 0, 2,
  147222. 4, 6, 8, 10, 12,
  147223. };
  147224. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147225. _vq_quantthresh__44u1__p7_1,
  147226. _vq_quantmap__44u1__p7_1,
  147227. 13,
  147228. 13
  147229. };
  147230. static static_codebook _44u1__p7_1 = {
  147231. 2, 169,
  147232. _vq_lengthlist__44u1__p7_1,
  147233. 1, -523010048, 1618608128, 4, 0,
  147234. _vq_quantlist__44u1__p7_1,
  147235. NULL,
  147236. &_vq_auxt__44u1__p7_1,
  147237. NULL,
  147238. 0
  147239. };
  147240. static long _vq_quantlist__44u1__p7_2[] = {
  147241. 6,
  147242. 5,
  147243. 7,
  147244. 4,
  147245. 8,
  147246. 3,
  147247. 9,
  147248. 2,
  147249. 10,
  147250. 1,
  147251. 11,
  147252. 0,
  147253. 12,
  147254. };
  147255. static long _vq_lengthlist__44u1__p7_2[] = {
  147256. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147257. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147258. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147259. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147260. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147261. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147262. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147263. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147264. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147265. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147266. 9, 9, 9,10, 9, 9,10,10, 9,
  147267. };
  147268. static float _vq_quantthresh__44u1__p7_2[] = {
  147269. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147270. 2.5, 3.5, 4.5, 5.5,
  147271. };
  147272. static long _vq_quantmap__44u1__p7_2[] = {
  147273. 11, 9, 7, 5, 3, 1, 0, 2,
  147274. 4, 6, 8, 10, 12,
  147275. };
  147276. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147277. _vq_quantthresh__44u1__p7_2,
  147278. _vq_quantmap__44u1__p7_2,
  147279. 13,
  147280. 13
  147281. };
  147282. static static_codebook _44u1__p7_2 = {
  147283. 2, 169,
  147284. _vq_lengthlist__44u1__p7_2,
  147285. 1, -531103744, 1611661312, 4, 0,
  147286. _vq_quantlist__44u1__p7_2,
  147287. NULL,
  147288. &_vq_auxt__44u1__p7_2,
  147289. NULL,
  147290. 0
  147291. };
  147292. static long _huff_lengthlist__44u1__short[] = {
  147293. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147294. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147295. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147296. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147297. };
  147298. static static_codebook _huff_book__44u1__short = {
  147299. 2, 64,
  147300. _huff_lengthlist__44u1__short,
  147301. 0, 0, 0, 0, 0,
  147302. NULL,
  147303. NULL,
  147304. NULL,
  147305. NULL,
  147306. 0
  147307. };
  147308. static long _huff_lengthlist__44u2__long[] = {
  147309. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147310. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147311. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147312. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147313. };
  147314. static static_codebook _huff_book__44u2__long = {
  147315. 2, 64,
  147316. _huff_lengthlist__44u2__long,
  147317. 0, 0, 0, 0, 0,
  147318. NULL,
  147319. NULL,
  147320. NULL,
  147321. NULL,
  147322. 0
  147323. };
  147324. static long _vq_quantlist__44u2__p1_0[] = {
  147325. 1,
  147326. 0,
  147327. 2,
  147328. };
  147329. static long _vq_lengthlist__44u2__p1_0[] = {
  147330. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147331. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147332. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147333. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147334. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147335. 13,
  147336. };
  147337. static float _vq_quantthresh__44u2__p1_0[] = {
  147338. -0.5, 0.5,
  147339. };
  147340. static long _vq_quantmap__44u2__p1_0[] = {
  147341. 1, 0, 2,
  147342. };
  147343. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147344. _vq_quantthresh__44u2__p1_0,
  147345. _vq_quantmap__44u2__p1_0,
  147346. 3,
  147347. 3
  147348. };
  147349. static static_codebook _44u2__p1_0 = {
  147350. 4, 81,
  147351. _vq_lengthlist__44u2__p1_0,
  147352. 1, -535822336, 1611661312, 2, 0,
  147353. _vq_quantlist__44u2__p1_0,
  147354. NULL,
  147355. &_vq_auxt__44u2__p1_0,
  147356. NULL,
  147357. 0
  147358. };
  147359. static long _vq_quantlist__44u2__p2_0[] = {
  147360. 1,
  147361. 0,
  147362. 2,
  147363. };
  147364. static long _vq_lengthlist__44u2__p2_0[] = {
  147365. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147366. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147367. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147368. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147369. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147370. 9,
  147371. };
  147372. static float _vq_quantthresh__44u2__p2_0[] = {
  147373. -0.5, 0.5,
  147374. };
  147375. static long _vq_quantmap__44u2__p2_0[] = {
  147376. 1, 0, 2,
  147377. };
  147378. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147379. _vq_quantthresh__44u2__p2_0,
  147380. _vq_quantmap__44u2__p2_0,
  147381. 3,
  147382. 3
  147383. };
  147384. static static_codebook _44u2__p2_0 = {
  147385. 4, 81,
  147386. _vq_lengthlist__44u2__p2_0,
  147387. 1, -535822336, 1611661312, 2, 0,
  147388. _vq_quantlist__44u2__p2_0,
  147389. NULL,
  147390. &_vq_auxt__44u2__p2_0,
  147391. NULL,
  147392. 0
  147393. };
  147394. static long _vq_quantlist__44u2__p3_0[] = {
  147395. 2,
  147396. 1,
  147397. 3,
  147398. 0,
  147399. 4,
  147400. };
  147401. static long _vq_lengthlist__44u2__p3_0[] = {
  147402. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147403. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147404. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147405. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147406. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147407. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147408. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147409. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147410. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147411. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147412. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147413. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147414. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147415. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147416. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147417. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147418. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147419. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147420. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147421. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147422. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147423. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147424. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147425. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147426. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147427. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147428. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147429. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147430. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147431. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147432. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147433. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147434. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147435. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147436. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147437. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147438. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147439. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147440. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147441. 0,
  147442. };
  147443. static float _vq_quantthresh__44u2__p3_0[] = {
  147444. -1.5, -0.5, 0.5, 1.5,
  147445. };
  147446. static long _vq_quantmap__44u2__p3_0[] = {
  147447. 3, 1, 0, 2, 4,
  147448. };
  147449. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147450. _vq_quantthresh__44u2__p3_0,
  147451. _vq_quantmap__44u2__p3_0,
  147452. 5,
  147453. 5
  147454. };
  147455. static static_codebook _44u2__p3_0 = {
  147456. 4, 625,
  147457. _vq_lengthlist__44u2__p3_0,
  147458. 1, -533725184, 1611661312, 3, 0,
  147459. _vq_quantlist__44u2__p3_0,
  147460. NULL,
  147461. &_vq_auxt__44u2__p3_0,
  147462. NULL,
  147463. 0
  147464. };
  147465. static long _vq_quantlist__44u2__p4_0[] = {
  147466. 2,
  147467. 1,
  147468. 3,
  147469. 0,
  147470. 4,
  147471. };
  147472. static long _vq_lengthlist__44u2__p4_0[] = {
  147473. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147474. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147475. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147476. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147477. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147478. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147479. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147480. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147481. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147482. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147483. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147484. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147485. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147486. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147487. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147488. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147489. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147490. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147491. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147492. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147493. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147494. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147495. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147496. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147497. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147498. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147499. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147500. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147501. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147502. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147503. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147504. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147505. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147506. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147507. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147508. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147509. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147510. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147511. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147512. 13,
  147513. };
  147514. static float _vq_quantthresh__44u2__p4_0[] = {
  147515. -1.5, -0.5, 0.5, 1.5,
  147516. };
  147517. static long _vq_quantmap__44u2__p4_0[] = {
  147518. 3, 1, 0, 2, 4,
  147519. };
  147520. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147521. _vq_quantthresh__44u2__p4_0,
  147522. _vq_quantmap__44u2__p4_0,
  147523. 5,
  147524. 5
  147525. };
  147526. static static_codebook _44u2__p4_0 = {
  147527. 4, 625,
  147528. _vq_lengthlist__44u2__p4_0,
  147529. 1, -533725184, 1611661312, 3, 0,
  147530. _vq_quantlist__44u2__p4_0,
  147531. NULL,
  147532. &_vq_auxt__44u2__p4_0,
  147533. NULL,
  147534. 0
  147535. };
  147536. static long _vq_quantlist__44u2__p5_0[] = {
  147537. 4,
  147538. 3,
  147539. 5,
  147540. 2,
  147541. 6,
  147542. 1,
  147543. 7,
  147544. 0,
  147545. 8,
  147546. };
  147547. static long _vq_lengthlist__44u2__p5_0[] = {
  147548. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147549. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147550. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147551. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147552. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147553. 13,
  147554. };
  147555. static float _vq_quantthresh__44u2__p5_0[] = {
  147556. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147557. };
  147558. static long _vq_quantmap__44u2__p5_0[] = {
  147559. 7, 5, 3, 1, 0, 2, 4, 6,
  147560. 8,
  147561. };
  147562. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147563. _vq_quantthresh__44u2__p5_0,
  147564. _vq_quantmap__44u2__p5_0,
  147565. 9,
  147566. 9
  147567. };
  147568. static static_codebook _44u2__p5_0 = {
  147569. 2, 81,
  147570. _vq_lengthlist__44u2__p5_0,
  147571. 1, -531628032, 1611661312, 4, 0,
  147572. _vq_quantlist__44u2__p5_0,
  147573. NULL,
  147574. &_vq_auxt__44u2__p5_0,
  147575. NULL,
  147576. 0
  147577. };
  147578. static long _vq_quantlist__44u2__p6_0[] = {
  147579. 6,
  147580. 5,
  147581. 7,
  147582. 4,
  147583. 8,
  147584. 3,
  147585. 9,
  147586. 2,
  147587. 10,
  147588. 1,
  147589. 11,
  147590. 0,
  147591. 12,
  147592. };
  147593. static long _vq_lengthlist__44u2__p6_0[] = {
  147594. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147595. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147596. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147597. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147598. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147599. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147600. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147601. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147602. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147603. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147604. 15,17,17,16,18,17,18, 0, 0,
  147605. };
  147606. static float _vq_quantthresh__44u2__p6_0[] = {
  147607. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147608. 12.5, 17.5, 22.5, 27.5,
  147609. };
  147610. static long _vq_quantmap__44u2__p6_0[] = {
  147611. 11, 9, 7, 5, 3, 1, 0, 2,
  147612. 4, 6, 8, 10, 12,
  147613. };
  147614. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147615. _vq_quantthresh__44u2__p6_0,
  147616. _vq_quantmap__44u2__p6_0,
  147617. 13,
  147618. 13
  147619. };
  147620. static static_codebook _44u2__p6_0 = {
  147621. 2, 169,
  147622. _vq_lengthlist__44u2__p6_0,
  147623. 1, -526516224, 1616117760, 4, 0,
  147624. _vq_quantlist__44u2__p6_0,
  147625. NULL,
  147626. &_vq_auxt__44u2__p6_0,
  147627. NULL,
  147628. 0
  147629. };
  147630. static long _vq_quantlist__44u2__p6_1[] = {
  147631. 2,
  147632. 1,
  147633. 3,
  147634. 0,
  147635. 4,
  147636. };
  147637. static long _vq_lengthlist__44u2__p6_1[] = {
  147638. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147639. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147640. };
  147641. static float _vq_quantthresh__44u2__p6_1[] = {
  147642. -1.5, -0.5, 0.5, 1.5,
  147643. };
  147644. static long _vq_quantmap__44u2__p6_1[] = {
  147645. 3, 1, 0, 2, 4,
  147646. };
  147647. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147648. _vq_quantthresh__44u2__p6_1,
  147649. _vq_quantmap__44u2__p6_1,
  147650. 5,
  147651. 5
  147652. };
  147653. static static_codebook _44u2__p6_1 = {
  147654. 2, 25,
  147655. _vq_lengthlist__44u2__p6_1,
  147656. 1, -533725184, 1611661312, 3, 0,
  147657. _vq_quantlist__44u2__p6_1,
  147658. NULL,
  147659. &_vq_auxt__44u2__p6_1,
  147660. NULL,
  147661. 0
  147662. };
  147663. static long _vq_quantlist__44u2__p7_0[] = {
  147664. 4,
  147665. 3,
  147666. 5,
  147667. 2,
  147668. 6,
  147669. 1,
  147670. 7,
  147671. 0,
  147672. 8,
  147673. };
  147674. static long _vq_lengthlist__44u2__p7_0[] = {
  147675. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147676. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147679. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147680. 11,
  147681. };
  147682. static float _vq_quantthresh__44u2__p7_0[] = {
  147683. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147684. };
  147685. static long _vq_quantmap__44u2__p7_0[] = {
  147686. 7, 5, 3, 1, 0, 2, 4, 6,
  147687. 8,
  147688. };
  147689. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147690. _vq_quantthresh__44u2__p7_0,
  147691. _vq_quantmap__44u2__p7_0,
  147692. 9,
  147693. 9
  147694. };
  147695. static static_codebook _44u2__p7_0 = {
  147696. 2, 81,
  147697. _vq_lengthlist__44u2__p7_0,
  147698. 1, -516612096, 1626677248, 4, 0,
  147699. _vq_quantlist__44u2__p7_0,
  147700. NULL,
  147701. &_vq_auxt__44u2__p7_0,
  147702. NULL,
  147703. 0
  147704. };
  147705. static long _vq_quantlist__44u2__p7_1[] = {
  147706. 6,
  147707. 5,
  147708. 7,
  147709. 4,
  147710. 8,
  147711. 3,
  147712. 9,
  147713. 2,
  147714. 10,
  147715. 1,
  147716. 11,
  147717. 0,
  147718. 12,
  147719. };
  147720. static long _vq_lengthlist__44u2__p7_1[] = {
  147721. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147722. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147723. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147724. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147725. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147726. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147727. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147728. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147729. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147730. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147731. 14,14,14,17,15,17,17,17,17,
  147732. };
  147733. static float _vq_quantthresh__44u2__p7_1[] = {
  147734. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147735. 32.5, 45.5, 58.5, 71.5,
  147736. };
  147737. static long _vq_quantmap__44u2__p7_1[] = {
  147738. 11, 9, 7, 5, 3, 1, 0, 2,
  147739. 4, 6, 8, 10, 12,
  147740. };
  147741. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147742. _vq_quantthresh__44u2__p7_1,
  147743. _vq_quantmap__44u2__p7_1,
  147744. 13,
  147745. 13
  147746. };
  147747. static static_codebook _44u2__p7_1 = {
  147748. 2, 169,
  147749. _vq_lengthlist__44u2__p7_1,
  147750. 1, -523010048, 1618608128, 4, 0,
  147751. _vq_quantlist__44u2__p7_1,
  147752. NULL,
  147753. &_vq_auxt__44u2__p7_1,
  147754. NULL,
  147755. 0
  147756. };
  147757. static long _vq_quantlist__44u2__p7_2[] = {
  147758. 6,
  147759. 5,
  147760. 7,
  147761. 4,
  147762. 8,
  147763. 3,
  147764. 9,
  147765. 2,
  147766. 10,
  147767. 1,
  147768. 11,
  147769. 0,
  147770. 12,
  147771. };
  147772. static long _vq_lengthlist__44u2__p7_2[] = {
  147773. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147774. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147775. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147776. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147777. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147778. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147779. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147780. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147781. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147782. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147783. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147784. };
  147785. static float _vq_quantthresh__44u2__p7_2[] = {
  147786. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147787. 2.5, 3.5, 4.5, 5.5,
  147788. };
  147789. static long _vq_quantmap__44u2__p7_2[] = {
  147790. 11, 9, 7, 5, 3, 1, 0, 2,
  147791. 4, 6, 8, 10, 12,
  147792. };
  147793. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147794. _vq_quantthresh__44u2__p7_2,
  147795. _vq_quantmap__44u2__p7_2,
  147796. 13,
  147797. 13
  147798. };
  147799. static static_codebook _44u2__p7_2 = {
  147800. 2, 169,
  147801. _vq_lengthlist__44u2__p7_2,
  147802. 1, -531103744, 1611661312, 4, 0,
  147803. _vq_quantlist__44u2__p7_2,
  147804. NULL,
  147805. &_vq_auxt__44u2__p7_2,
  147806. NULL,
  147807. 0
  147808. };
  147809. static long _huff_lengthlist__44u2__short[] = {
  147810. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147811. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147812. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147813. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147814. };
  147815. static static_codebook _huff_book__44u2__short = {
  147816. 2, 64,
  147817. _huff_lengthlist__44u2__short,
  147818. 0, 0, 0, 0, 0,
  147819. NULL,
  147820. NULL,
  147821. NULL,
  147822. NULL,
  147823. 0
  147824. };
  147825. static long _huff_lengthlist__44u3__long[] = {
  147826. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147827. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147828. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147829. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147830. };
  147831. static static_codebook _huff_book__44u3__long = {
  147832. 2, 64,
  147833. _huff_lengthlist__44u3__long,
  147834. 0, 0, 0, 0, 0,
  147835. NULL,
  147836. NULL,
  147837. NULL,
  147838. NULL,
  147839. 0
  147840. };
  147841. static long _vq_quantlist__44u3__p1_0[] = {
  147842. 1,
  147843. 0,
  147844. 2,
  147845. };
  147846. static long _vq_lengthlist__44u3__p1_0[] = {
  147847. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147848. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147849. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147850. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147851. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147852. 13,
  147853. };
  147854. static float _vq_quantthresh__44u3__p1_0[] = {
  147855. -0.5, 0.5,
  147856. };
  147857. static long _vq_quantmap__44u3__p1_0[] = {
  147858. 1, 0, 2,
  147859. };
  147860. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147861. _vq_quantthresh__44u3__p1_0,
  147862. _vq_quantmap__44u3__p1_0,
  147863. 3,
  147864. 3
  147865. };
  147866. static static_codebook _44u3__p1_0 = {
  147867. 4, 81,
  147868. _vq_lengthlist__44u3__p1_0,
  147869. 1, -535822336, 1611661312, 2, 0,
  147870. _vq_quantlist__44u3__p1_0,
  147871. NULL,
  147872. &_vq_auxt__44u3__p1_0,
  147873. NULL,
  147874. 0
  147875. };
  147876. static long _vq_quantlist__44u3__p2_0[] = {
  147877. 1,
  147878. 0,
  147879. 2,
  147880. };
  147881. static long _vq_lengthlist__44u3__p2_0[] = {
  147882. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147883. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147884. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147885. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147886. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147887. 9,
  147888. };
  147889. static float _vq_quantthresh__44u3__p2_0[] = {
  147890. -0.5, 0.5,
  147891. };
  147892. static long _vq_quantmap__44u3__p2_0[] = {
  147893. 1, 0, 2,
  147894. };
  147895. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147896. _vq_quantthresh__44u3__p2_0,
  147897. _vq_quantmap__44u3__p2_0,
  147898. 3,
  147899. 3
  147900. };
  147901. static static_codebook _44u3__p2_0 = {
  147902. 4, 81,
  147903. _vq_lengthlist__44u3__p2_0,
  147904. 1, -535822336, 1611661312, 2, 0,
  147905. _vq_quantlist__44u3__p2_0,
  147906. NULL,
  147907. &_vq_auxt__44u3__p2_0,
  147908. NULL,
  147909. 0
  147910. };
  147911. static long _vq_quantlist__44u3__p3_0[] = {
  147912. 2,
  147913. 1,
  147914. 3,
  147915. 0,
  147916. 4,
  147917. };
  147918. static long _vq_lengthlist__44u3__p3_0[] = {
  147919. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147920. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147921. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147922. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147923. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147924. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147925. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147926. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147927. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147928. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147929. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147930. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147931. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147932. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147933. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147934. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147935. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147936. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147937. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147938. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147939. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147940. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147941. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147942. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147943. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147944. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147945. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147946. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147947. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147948. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147949. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147950. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147951. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147952. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147953. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147954. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147955. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147956. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147957. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147958. 0,
  147959. };
  147960. static float _vq_quantthresh__44u3__p3_0[] = {
  147961. -1.5, -0.5, 0.5, 1.5,
  147962. };
  147963. static long _vq_quantmap__44u3__p3_0[] = {
  147964. 3, 1, 0, 2, 4,
  147965. };
  147966. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147967. _vq_quantthresh__44u3__p3_0,
  147968. _vq_quantmap__44u3__p3_0,
  147969. 5,
  147970. 5
  147971. };
  147972. static static_codebook _44u3__p3_0 = {
  147973. 4, 625,
  147974. _vq_lengthlist__44u3__p3_0,
  147975. 1, -533725184, 1611661312, 3, 0,
  147976. _vq_quantlist__44u3__p3_0,
  147977. NULL,
  147978. &_vq_auxt__44u3__p3_0,
  147979. NULL,
  147980. 0
  147981. };
  147982. static long _vq_quantlist__44u3__p4_0[] = {
  147983. 2,
  147984. 1,
  147985. 3,
  147986. 0,
  147987. 4,
  147988. };
  147989. static long _vq_lengthlist__44u3__p4_0[] = {
  147990. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147991. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147992. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147993. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147994. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147995. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147996. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147997. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147998. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147999. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148000. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148001. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148002. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148003. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148004. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148005. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148006. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148007. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148008. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148009. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148010. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148011. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148012. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148013. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148014. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148015. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148016. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148017. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148018. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148019. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148020. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148021. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148022. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148023. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148024. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148025. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148026. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148027. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148028. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148029. 13,
  148030. };
  148031. static float _vq_quantthresh__44u3__p4_0[] = {
  148032. -1.5, -0.5, 0.5, 1.5,
  148033. };
  148034. static long _vq_quantmap__44u3__p4_0[] = {
  148035. 3, 1, 0, 2, 4,
  148036. };
  148037. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148038. _vq_quantthresh__44u3__p4_0,
  148039. _vq_quantmap__44u3__p4_0,
  148040. 5,
  148041. 5
  148042. };
  148043. static static_codebook _44u3__p4_0 = {
  148044. 4, 625,
  148045. _vq_lengthlist__44u3__p4_0,
  148046. 1, -533725184, 1611661312, 3, 0,
  148047. _vq_quantlist__44u3__p4_0,
  148048. NULL,
  148049. &_vq_auxt__44u3__p4_0,
  148050. NULL,
  148051. 0
  148052. };
  148053. static long _vq_quantlist__44u3__p5_0[] = {
  148054. 4,
  148055. 3,
  148056. 5,
  148057. 2,
  148058. 6,
  148059. 1,
  148060. 7,
  148061. 0,
  148062. 8,
  148063. };
  148064. static long _vq_lengthlist__44u3__p5_0[] = {
  148065. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148066. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148067. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148068. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148069. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148070. 12,
  148071. };
  148072. static float _vq_quantthresh__44u3__p5_0[] = {
  148073. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148074. };
  148075. static long _vq_quantmap__44u3__p5_0[] = {
  148076. 7, 5, 3, 1, 0, 2, 4, 6,
  148077. 8,
  148078. };
  148079. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148080. _vq_quantthresh__44u3__p5_0,
  148081. _vq_quantmap__44u3__p5_0,
  148082. 9,
  148083. 9
  148084. };
  148085. static static_codebook _44u3__p5_0 = {
  148086. 2, 81,
  148087. _vq_lengthlist__44u3__p5_0,
  148088. 1, -531628032, 1611661312, 4, 0,
  148089. _vq_quantlist__44u3__p5_0,
  148090. NULL,
  148091. &_vq_auxt__44u3__p5_0,
  148092. NULL,
  148093. 0
  148094. };
  148095. static long _vq_quantlist__44u3__p6_0[] = {
  148096. 6,
  148097. 5,
  148098. 7,
  148099. 4,
  148100. 8,
  148101. 3,
  148102. 9,
  148103. 2,
  148104. 10,
  148105. 1,
  148106. 11,
  148107. 0,
  148108. 12,
  148109. };
  148110. static long _vq_lengthlist__44u3__p6_0[] = {
  148111. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148112. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148113. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148114. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148115. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148116. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148117. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148118. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148119. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148120. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148121. 15,16,16,16,17,18,16,20,18,
  148122. };
  148123. static float _vq_quantthresh__44u3__p6_0[] = {
  148124. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148125. 12.5, 17.5, 22.5, 27.5,
  148126. };
  148127. static long _vq_quantmap__44u3__p6_0[] = {
  148128. 11, 9, 7, 5, 3, 1, 0, 2,
  148129. 4, 6, 8, 10, 12,
  148130. };
  148131. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148132. _vq_quantthresh__44u3__p6_0,
  148133. _vq_quantmap__44u3__p6_0,
  148134. 13,
  148135. 13
  148136. };
  148137. static static_codebook _44u3__p6_0 = {
  148138. 2, 169,
  148139. _vq_lengthlist__44u3__p6_0,
  148140. 1, -526516224, 1616117760, 4, 0,
  148141. _vq_quantlist__44u3__p6_0,
  148142. NULL,
  148143. &_vq_auxt__44u3__p6_0,
  148144. NULL,
  148145. 0
  148146. };
  148147. static long _vq_quantlist__44u3__p6_1[] = {
  148148. 2,
  148149. 1,
  148150. 3,
  148151. 0,
  148152. 4,
  148153. };
  148154. static long _vq_lengthlist__44u3__p6_1[] = {
  148155. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148156. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148157. };
  148158. static float _vq_quantthresh__44u3__p6_1[] = {
  148159. -1.5, -0.5, 0.5, 1.5,
  148160. };
  148161. static long _vq_quantmap__44u3__p6_1[] = {
  148162. 3, 1, 0, 2, 4,
  148163. };
  148164. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148165. _vq_quantthresh__44u3__p6_1,
  148166. _vq_quantmap__44u3__p6_1,
  148167. 5,
  148168. 5
  148169. };
  148170. static static_codebook _44u3__p6_1 = {
  148171. 2, 25,
  148172. _vq_lengthlist__44u3__p6_1,
  148173. 1, -533725184, 1611661312, 3, 0,
  148174. _vq_quantlist__44u3__p6_1,
  148175. NULL,
  148176. &_vq_auxt__44u3__p6_1,
  148177. NULL,
  148178. 0
  148179. };
  148180. static long _vq_quantlist__44u3__p7_0[] = {
  148181. 4,
  148182. 3,
  148183. 5,
  148184. 2,
  148185. 6,
  148186. 1,
  148187. 7,
  148188. 0,
  148189. 8,
  148190. };
  148191. static long _vq_lengthlist__44u3__p7_0[] = {
  148192. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148193. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148194. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148195. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148196. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148197. 9,
  148198. };
  148199. static float _vq_quantthresh__44u3__p7_0[] = {
  148200. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148201. };
  148202. static long _vq_quantmap__44u3__p7_0[] = {
  148203. 7, 5, 3, 1, 0, 2, 4, 6,
  148204. 8,
  148205. };
  148206. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148207. _vq_quantthresh__44u3__p7_0,
  148208. _vq_quantmap__44u3__p7_0,
  148209. 9,
  148210. 9
  148211. };
  148212. static static_codebook _44u3__p7_0 = {
  148213. 2, 81,
  148214. _vq_lengthlist__44u3__p7_0,
  148215. 1, -515907584, 1627381760, 4, 0,
  148216. _vq_quantlist__44u3__p7_0,
  148217. NULL,
  148218. &_vq_auxt__44u3__p7_0,
  148219. NULL,
  148220. 0
  148221. };
  148222. static long _vq_quantlist__44u3__p7_1[] = {
  148223. 7,
  148224. 6,
  148225. 8,
  148226. 5,
  148227. 9,
  148228. 4,
  148229. 10,
  148230. 3,
  148231. 11,
  148232. 2,
  148233. 12,
  148234. 1,
  148235. 13,
  148236. 0,
  148237. 14,
  148238. };
  148239. static long _vq_lengthlist__44u3__p7_1[] = {
  148240. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148241. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148242. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148243. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148244. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148245. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148246. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148247. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148248. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148249. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148250. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148251. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148252. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148253. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148254. 17,
  148255. };
  148256. static float _vq_quantthresh__44u3__p7_1[] = {
  148257. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148258. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148259. };
  148260. static long _vq_quantmap__44u3__p7_1[] = {
  148261. 13, 11, 9, 7, 5, 3, 1, 0,
  148262. 2, 4, 6, 8, 10, 12, 14,
  148263. };
  148264. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148265. _vq_quantthresh__44u3__p7_1,
  148266. _vq_quantmap__44u3__p7_1,
  148267. 15,
  148268. 15
  148269. };
  148270. static static_codebook _44u3__p7_1 = {
  148271. 2, 225,
  148272. _vq_lengthlist__44u3__p7_1,
  148273. 1, -522338304, 1620115456, 4, 0,
  148274. _vq_quantlist__44u3__p7_1,
  148275. NULL,
  148276. &_vq_auxt__44u3__p7_1,
  148277. NULL,
  148278. 0
  148279. };
  148280. static long _vq_quantlist__44u3__p7_2[] = {
  148281. 8,
  148282. 7,
  148283. 9,
  148284. 6,
  148285. 10,
  148286. 5,
  148287. 11,
  148288. 4,
  148289. 12,
  148290. 3,
  148291. 13,
  148292. 2,
  148293. 14,
  148294. 1,
  148295. 15,
  148296. 0,
  148297. 16,
  148298. };
  148299. static long _vq_lengthlist__44u3__p7_2[] = {
  148300. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148301. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148302. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148303. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148304. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148305. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148306. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148307. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148308. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148309. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148310. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148311. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148312. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148313. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148314. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148315. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148316. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148317. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148318. 11,
  148319. };
  148320. static float _vq_quantthresh__44u3__p7_2[] = {
  148321. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148322. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148323. };
  148324. static long _vq_quantmap__44u3__p7_2[] = {
  148325. 15, 13, 11, 9, 7, 5, 3, 1,
  148326. 0, 2, 4, 6, 8, 10, 12, 14,
  148327. 16,
  148328. };
  148329. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148330. _vq_quantthresh__44u3__p7_2,
  148331. _vq_quantmap__44u3__p7_2,
  148332. 17,
  148333. 17
  148334. };
  148335. static static_codebook _44u3__p7_2 = {
  148336. 2, 289,
  148337. _vq_lengthlist__44u3__p7_2,
  148338. 1, -529530880, 1611661312, 5, 0,
  148339. _vq_quantlist__44u3__p7_2,
  148340. NULL,
  148341. &_vq_auxt__44u3__p7_2,
  148342. NULL,
  148343. 0
  148344. };
  148345. static long _huff_lengthlist__44u3__short[] = {
  148346. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148347. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148348. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148349. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148350. };
  148351. static static_codebook _huff_book__44u3__short = {
  148352. 2, 64,
  148353. _huff_lengthlist__44u3__short,
  148354. 0, 0, 0, 0, 0,
  148355. NULL,
  148356. NULL,
  148357. NULL,
  148358. NULL,
  148359. 0
  148360. };
  148361. static long _huff_lengthlist__44u4__long[] = {
  148362. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148363. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148364. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148365. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148366. };
  148367. static static_codebook _huff_book__44u4__long = {
  148368. 2, 64,
  148369. _huff_lengthlist__44u4__long,
  148370. 0, 0, 0, 0, 0,
  148371. NULL,
  148372. NULL,
  148373. NULL,
  148374. NULL,
  148375. 0
  148376. };
  148377. static long _vq_quantlist__44u4__p1_0[] = {
  148378. 1,
  148379. 0,
  148380. 2,
  148381. };
  148382. static long _vq_lengthlist__44u4__p1_0[] = {
  148383. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148384. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148385. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148386. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148387. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148388. 13,
  148389. };
  148390. static float _vq_quantthresh__44u4__p1_0[] = {
  148391. -0.5, 0.5,
  148392. };
  148393. static long _vq_quantmap__44u4__p1_0[] = {
  148394. 1, 0, 2,
  148395. };
  148396. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148397. _vq_quantthresh__44u4__p1_0,
  148398. _vq_quantmap__44u4__p1_0,
  148399. 3,
  148400. 3
  148401. };
  148402. static static_codebook _44u4__p1_0 = {
  148403. 4, 81,
  148404. _vq_lengthlist__44u4__p1_0,
  148405. 1, -535822336, 1611661312, 2, 0,
  148406. _vq_quantlist__44u4__p1_0,
  148407. NULL,
  148408. &_vq_auxt__44u4__p1_0,
  148409. NULL,
  148410. 0
  148411. };
  148412. static long _vq_quantlist__44u4__p2_0[] = {
  148413. 1,
  148414. 0,
  148415. 2,
  148416. };
  148417. static long _vq_lengthlist__44u4__p2_0[] = {
  148418. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148419. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148420. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148421. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148422. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148423. 9,
  148424. };
  148425. static float _vq_quantthresh__44u4__p2_0[] = {
  148426. -0.5, 0.5,
  148427. };
  148428. static long _vq_quantmap__44u4__p2_0[] = {
  148429. 1, 0, 2,
  148430. };
  148431. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148432. _vq_quantthresh__44u4__p2_0,
  148433. _vq_quantmap__44u4__p2_0,
  148434. 3,
  148435. 3
  148436. };
  148437. static static_codebook _44u4__p2_0 = {
  148438. 4, 81,
  148439. _vq_lengthlist__44u4__p2_0,
  148440. 1, -535822336, 1611661312, 2, 0,
  148441. _vq_quantlist__44u4__p2_0,
  148442. NULL,
  148443. &_vq_auxt__44u4__p2_0,
  148444. NULL,
  148445. 0
  148446. };
  148447. static long _vq_quantlist__44u4__p3_0[] = {
  148448. 2,
  148449. 1,
  148450. 3,
  148451. 0,
  148452. 4,
  148453. };
  148454. static long _vq_lengthlist__44u4__p3_0[] = {
  148455. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148456. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148457. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148458. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148459. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148460. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148461. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148462. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148463. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148464. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148465. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148466. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148467. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148468. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148469. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148470. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148471. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148472. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148473. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148474. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148475. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148476. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148477. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148478. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148479. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148480. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148481. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148482. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148483. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148484. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148485. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148486. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148487. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148488. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148489. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148490. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148491. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148492. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148493. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148494. 0,
  148495. };
  148496. static float _vq_quantthresh__44u4__p3_0[] = {
  148497. -1.5, -0.5, 0.5, 1.5,
  148498. };
  148499. static long _vq_quantmap__44u4__p3_0[] = {
  148500. 3, 1, 0, 2, 4,
  148501. };
  148502. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148503. _vq_quantthresh__44u4__p3_0,
  148504. _vq_quantmap__44u4__p3_0,
  148505. 5,
  148506. 5
  148507. };
  148508. static static_codebook _44u4__p3_0 = {
  148509. 4, 625,
  148510. _vq_lengthlist__44u4__p3_0,
  148511. 1, -533725184, 1611661312, 3, 0,
  148512. _vq_quantlist__44u4__p3_0,
  148513. NULL,
  148514. &_vq_auxt__44u4__p3_0,
  148515. NULL,
  148516. 0
  148517. };
  148518. static long _vq_quantlist__44u4__p4_0[] = {
  148519. 2,
  148520. 1,
  148521. 3,
  148522. 0,
  148523. 4,
  148524. };
  148525. static long _vq_lengthlist__44u4__p4_0[] = {
  148526. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148527. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148528. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148529. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148530. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148531. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148532. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148533. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148534. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148535. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148536. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148537. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148538. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148539. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148540. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148541. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148542. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148543. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148544. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148545. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148546. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148547. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148548. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148549. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148550. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148551. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148552. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148553. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148554. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148555. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148556. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148557. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148558. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148559. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148560. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148561. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148562. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148563. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148564. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148565. 13,
  148566. };
  148567. static float _vq_quantthresh__44u4__p4_0[] = {
  148568. -1.5, -0.5, 0.5, 1.5,
  148569. };
  148570. static long _vq_quantmap__44u4__p4_0[] = {
  148571. 3, 1, 0, 2, 4,
  148572. };
  148573. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148574. _vq_quantthresh__44u4__p4_0,
  148575. _vq_quantmap__44u4__p4_0,
  148576. 5,
  148577. 5
  148578. };
  148579. static static_codebook _44u4__p4_0 = {
  148580. 4, 625,
  148581. _vq_lengthlist__44u4__p4_0,
  148582. 1, -533725184, 1611661312, 3, 0,
  148583. _vq_quantlist__44u4__p4_0,
  148584. NULL,
  148585. &_vq_auxt__44u4__p4_0,
  148586. NULL,
  148587. 0
  148588. };
  148589. static long _vq_quantlist__44u4__p5_0[] = {
  148590. 4,
  148591. 3,
  148592. 5,
  148593. 2,
  148594. 6,
  148595. 1,
  148596. 7,
  148597. 0,
  148598. 8,
  148599. };
  148600. static long _vq_lengthlist__44u4__p5_0[] = {
  148601. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148602. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148603. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148604. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148605. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148606. 12,
  148607. };
  148608. static float _vq_quantthresh__44u4__p5_0[] = {
  148609. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148610. };
  148611. static long _vq_quantmap__44u4__p5_0[] = {
  148612. 7, 5, 3, 1, 0, 2, 4, 6,
  148613. 8,
  148614. };
  148615. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148616. _vq_quantthresh__44u4__p5_0,
  148617. _vq_quantmap__44u4__p5_0,
  148618. 9,
  148619. 9
  148620. };
  148621. static static_codebook _44u4__p5_0 = {
  148622. 2, 81,
  148623. _vq_lengthlist__44u4__p5_0,
  148624. 1, -531628032, 1611661312, 4, 0,
  148625. _vq_quantlist__44u4__p5_0,
  148626. NULL,
  148627. &_vq_auxt__44u4__p5_0,
  148628. NULL,
  148629. 0
  148630. };
  148631. static long _vq_quantlist__44u4__p6_0[] = {
  148632. 6,
  148633. 5,
  148634. 7,
  148635. 4,
  148636. 8,
  148637. 3,
  148638. 9,
  148639. 2,
  148640. 10,
  148641. 1,
  148642. 11,
  148643. 0,
  148644. 12,
  148645. };
  148646. static long _vq_lengthlist__44u4__p6_0[] = {
  148647. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148648. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148649. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148650. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148651. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148652. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148653. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148654. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148655. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148656. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148657. 16,16,16,17,17,18,17,20,21,
  148658. };
  148659. static float _vq_quantthresh__44u4__p6_0[] = {
  148660. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148661. 12.5, 17.5, 22.5, 27.5,
  148662. };
  148663. static long _vq_quantmap__44u4__p6_0[] = {
  148664. 11, 9, 7, 5, 3, 1, 0, 2,
  148665. 4, 6, 8, 10, 12,
  148666. };
  148667. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148668. _vq_quantthresh__44u4__p6_0,
  148669. _vq_quantmap__44u4__p6_0,
  148670. 13,
  148671. 13
  148672. };
  148673. static static_codebook _44u4__p6_0 = {
  148674. 2, 169,
  148675. _vq_lengthlist__44u4__p6_0,
  148676. 1, -526516224, 1616117760, 4, 0,
  148677. _vq_quantlist__44u4__p6_0,
  148678. NULL,
  148679. &_vq_auxt__44u4__p6_0,
  148680. NULL,
  148681. 0
  148682. };
  148683. static long _vq_quantlist__44u4__p6_1[] = {
  148684. 2,
  148685. 1,
  148686. 3,
  148687. 0,
  148688. 4,
  148689. };
  148690. static long _vq_lengthlist__44u4__p6_1[] = {
  148691. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148692. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148693. };
  148694. static float _vq_quantthresh__44u4__p6_1[] = {
  148695. -1.5, -0.5, 0.5, 1.5,
  148696. };
  148697. static long _vq_quantmap__44u4__p6_1[] = {
  148698. 3, 1, 0, 2, 4,
  148699. };
  148700. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148701. _vq_quantthresh__44u4__p6_1,
  148702. _vq_quantmap__44u4__p6_1,
  148703. 5,
  148704. 5
  148705. };
  148706. static static_codebook _44u4__p6_1 = {
  148707. 2, 25,
  148708. _vq_lengthlist__44u4__p6_1,
  148709. 1, -533725184, 1611661312, 3, 0,
  148710. _vq_quantlist__44u4__p6_1,
  148711. NULL,
  148712. &_vq_auxt__44u4__p6_1,
  148713. NULL,
  148714. 0
  148715. };
  148716. static long _vq_quantlist__44u4__p7_0[] = {
  148717. 6,
  148718. 5,
  148719. 7,
  148720. 4,
  148721. 8,
  148722. 3,
  148723. 9,
  148724. 2,
  148725. 10,
  148726. 1,
  148727. 11,
  148728. 0,
  148729. 12,
  148730. };
  148731. static long _vq_lengthlist__44u4__p7_0[] = {
  148732. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148733. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148734. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148735. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148736. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148737. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148742. 11,11,11,11,11,11,11,11,11,
  148743. };
  148744. static float _vq_quantthresh__44u4__p7_0[] = {
  148745. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148746. 637.5, 892.5, 1147.5, 1402.5,
  148747. };
  148748. static long _vq_quantmap__44u4__p7_0[] = {
  148749. 11, 9, 7, 5, 3, 1, 0, 2,
  148750. 4, 6, 8, 10, 12,
  148751. };
  148752. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148753. _vq_quantthresh__44u4__p7_0,
  148754. _vq_quantmap__44u4__p7_0,
  148755. 13,
  148756. 13
  148757. };
  148758. static static_codebook _44u4__p7_0 = {
  148759. 2, 169,
  148760. _vq_lengthlist__44u4__p7_0,
  148761. 1, -514332672, 1627381760, 4, 0,
  148762. _vq_quantlist__44u4__p7_0,
  148763. NULL,
  148764. &_vq_auxt__44u4__p7_0,
  148765. NULL,
  148766. 0
  148767. };
  148768. static long _vq_quantlist__44u4__p7_1[] = {
  148769. 7,
  148770. 6,
  148771. 8,
  148772. 5,
  148773. 9,
  148774. 4,
  148775. 10,
  148776. 3,
  148777. 11,
  148778. 2,
  148779. 12,
  148780. 1,
  148781. 13,
  148782. 0,
  148783. 14,
  148784. };
  148785. static long _vq_lengthlist__44u4__p7_1[] = {
  148786. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148787. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148788. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148789. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148790. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148791. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148792. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148793. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148794. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148795. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148796. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148797. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148798. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148799. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148800. 16,
  148801. };
  148802. static float _vq_quantthresh__44u4__p7_1[] = {
  148803. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148804. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148805. };
  148806. static long _vq_quantmap__44u4__p7_1[] = {
  148807. 13, 11, 9, 7, 5, 3, 1, 0,
  148808. 2, 4, 6, 8, 10, 12, 14,
  148809. };
  148810. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148811. _vq_quantthresh__44u4__p7_1,
  148812. _vq_quantmap__44u4__p7_1,
  148813. 15,
  148814. 15
  148815. };
  148816. static static_codebook _44u4__p7_1 = {
  148817. 2, 225,
  148818. _vq_lengthlist__44u4__p7_1,
  148819. 1, -522338304, 1620115456, 4, 0,
  148820. _vq_quantlist__44u4__p7_1,
  148821. NULL,
  148822. &_vq_auxt__44u4__p7_1,
  148823. NULL,
  148824. 0
  148825. };
  148826. static long _vq_quantlist__44u4__p7_2[] = {
  148827. 8,
  148828. 7,
  148829. 9,
  148830. 6,
  148831. 10,
  148832. 5,
  148833. 11,
  148834. 4,
  148835. 12,
  148836. 3,
  148837. 13,
  148838. 2,
  148839. 14,
  148840. 1,
  148841. 15,
  148842. 0,
  148843. 16,
  148844. };
  148845. static long _vq_lengthlist__44u4__p7_2[] = {
  148846. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148847. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148848. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148849. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148850. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148851. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148852. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148853. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148854. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148855. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148856. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148857. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148858. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148859. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148860. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148861. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148862. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148863. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148864. 10,
  148865. };
  148866. static float _vq_quantthresh__44u4__p7_2[] = {
  148867. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148868. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148869. };
  148870. static long _vq_quantmap__44u4__p7_2[] = {
  148871. 15, 13, 11, 9, 7, 5, 3, 1,
  148872. 0, 2, 4, 6, 8, 10, 12, 14,
  148873. 16,
  148874. };
  148875. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148876. _vq_quantthresh__44u4__p7_2,
  148877. _vq_quantmap__44u4__p7_2,
  148878. 17,
  148879. 17
  148880. };
  148881. static static_codebook _44u4__p7_2 = {
  148882. 2, 289,
  148883. _vq_lengthlist__44u4__p7_2,
  148884. 1, -529530880, 1611661312, 5, 0,
  148885. _vq_quantlist__44u4__p7_2,
  148886. NULL,
  148887. &_vq_auxt__44u4__p7_2,
  148888. NULL,
  148889. 0
  148890. };
  148891. static long _huff_lengthlist__44u4__short[] = {
  148892. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148893. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148894. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148895. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148896. };
  148897. static static_codebook _huff_book__44u4__short = {
  148898. 2, 64,
  148899. _huff_lengthlist__44u4__short,
  148900. 0, 0, 0, 0, 0,
  148901. NULL,
  148902. NULL,
  148903. NULL,
  148904. NULL,
  148905. 0
  148906. };
  148907. static long _huff_lengthlist__44u5__long[] = {
  148908. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148909. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148910. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148911. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148912. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148913. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148914. 14, 8, 7, 8,
  148915. };
  148916. static static_codebook _huff_book__44u5__long = {
  148917. 2, 100,
  148918. _huff_lengthlist__44u5__long,
  148919. 0, 0, 0, 0, 0,
  148920. NULL,
  148921. NULL,
  148922. NULL,
  148923. NULL,
  148924. 0
  148925. };
  148926. static long _vq_quantlist__44u5__p1_0[] = {
  148927. 1,
  148928. 0,
  148929. 2,
  148930. };
  148931. static long _vq_lengthlist__44u5__p1_0[] = {
  148932. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148933. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148934. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148935. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148936. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148937. 12,
  148938. };
  148939. static float _vq_quantthresh__44u5__p1_0[] = {
  148940. -0.5, 0.5,
  148941. };
  148942. static long _vq_quantmap__44u5__p1_0[] = {
  148943. 1, 0, 2,
  148944. };
  148945. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148946. _vq_quantthresh__44u5__p1_0,
  148947. _vq_quantmap__44u5__p1_0,
  148948. 3,
  148949. 3
  148950. };
  148951. static static_codebook _44u5__p1_0 = {
  148952. 4, 81,
  148953. _vq_lengthlist__44u5__p1_0,
  148954. 1, -535822336, 1611661312, 2, 0,
  148955. _vq_quantlist__44u5__p1_0,
  148956. NULL,
  148957. &_vq_auxt__44u5__p1_0,
  148958. NULL,
  148959. 0
  148960. };
  148961. static long _vq_quantlist__44u5__p2_0[] = {
  148962. 1,
  148963. 0,
  148964. 2,
  148965. };
  148966. static long _vq_lengthlist__44u5__p2_0[] = {
  148967. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148968. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148969. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148970. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148971. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148972. 9,
  148973. };
  148974. static float _vq_quantthresh__44u5__p2_0[] = {
  148975. -0.5, 0.5,
  148976. };
  148977. static long _vq_quantmap__44u5__p2_0[] = {
  148978. 1, 0, 2,
  148979. };
  148980. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148981. _vq_quantthresh__44u5__p2_0,
  148982. _vq_quantmap__44u5__p2_0,
  148983. 3,
  148984. 3
  148985. };
  148986. static static_codebook _44u5__p2_0 = {
  148987. 4, 81,
  148988. _vq_lengthlist__44u5__p2_0,
  148989. 1, -535822336, 1611661312, 2, 0,
  148990. _vq_quantlist__44u5__p2_0,
  148991. NULL,
  148992. &_vq_auxt__44u5__p2_0,
  148993. NULL,
  148994. 0
  148995. };
  148996. static long _vq_quantlist__44u5__p3_0[] = {
  148997. 2,
  148998. 1,
  148999. 3,
  149000. 0,
  149001. 4,
  149002. };
  149003. static long _vq_lengthlist__44u5__p3_0[] = {
  149004. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149005. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149006. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149007. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149008. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149009. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149010. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149011. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149012. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149013. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149014. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149015. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149016. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149017. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149018. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149019. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149020. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149021. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149022. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149023. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149024. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149025. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149026. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149027. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149028. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149029. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149030. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149031. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149032. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149033. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149034. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149035. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149036. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149037. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149038. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149039. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149040. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149041. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149042. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149043. 0,
  149044. };
  149045. static float _vq_quantthresh__44u5__p3_0[] = {
  149046. -1.5, -0.5, 0.5, 1.5,
  149047. };
  149048. static long _vq_quantmap__44u5__p3_0[] = {
  149049. 3, 1, 0, 2, 4,
  149050. };
  149051. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149052. _vq_quantthresh__44u5__p3_0,
  149053. _vq_quantmap__44u5__p3_0,
  149054. 5,
  149055. 5
  149056. };
  149057. static static_codebook _44u5__p3_0 = {
  149058. 4, 625,
  149059. _vq_lengthlist__44u5__p3_0,
  149060. 1, -533725184, 1611661312, 3, 0,
  149061. _vq_quantlist__44u5__p3_0,
  149062. NULL,
  149063. &_vq_auxt__44u5__p3_0,
  149064. NULL,
  149065. 0
  149066. };
  149067. static long _vq_quantlist__44u5__p4_0[] = {
  149068. 2,
  149069. 1,
  149070. 3,
  149071. 0,
  149072. 4,
  149073. };
  149074. static long _vq_lengthlist__44u5__p4_0[] = {
  149075. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149076. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149077. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149078. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149079. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149080. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149081. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149082. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149083. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149084. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149085. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149086. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149087. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149088. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149089. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149090. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149091. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149092. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149093. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149094. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149095. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149096. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149097. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149098. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149099. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149100. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149101. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149102. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149103. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149104. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149105. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149106. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149107. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149108. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149109. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149110. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149111. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149112. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149113. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149114. 12,
  149115. };
  149116. static float _vq_quantthresh__44u5__p4_0[] = {
  149117. -1.5, -0.5, 0.5, 1.5,
  149118. };
  149119. static long _vq_quantmap__44u5__p4_0[] = {
  149120. 3, 1, 0, 2, 4,
  149121. };
  149122. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149123. _vq_quantthresh__44u5__p4_0,
  149124. _vq_quantmap__44u5__p4_0,
  149125. 5,
  149126. 5
  149127. };
  149128. static static_codebook _44u5__p4_0 = {
  149129. 4, 625,
  149130. _vq_lengthlist__44u5__p4_0,
  149131. 1, -533725184, 1611661312, 3, 0,
  149132. _vq_quantlist__44u5__p4_0,
  149133. NULL,
  149134. &_vq_auxt__44u5__p4_0,
  149135. NULL,
  149136. 0
  149137. };
  149138. static long _vq_quantlist__44u5__p5_0[] = {
  149139. 4,
  149140. 3,
  149141. 5,
  149142. 2,
  149143. 6,
  149144. 1,
  149145. 7,
  149146. 0,
  149147. 8,
  149148. };
  149149. static long _vq_lengthlist__44u5__p5_0[] = {
  149150. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149151. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149152. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149153. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149154. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149155. 14,
  149156. };
  149157. static float _vq_quantthresh__44u5__p5_0[] = {
  149158. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149159. };
  149160. static long _vq_quantmap__44u5__p5_0[] = {
  149161. 7, 5, 3, 1, 0, 2, 4, 6,
  149162. 8,
  149163. };
  149164. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149165. _vq_quantthresh__44u5__p5_0,
  149166. _vq_quantmap__44u5__p5_0,
  149167. 9,
  149168. 9
  149169. };
  149170. static static_codebook _44u5__p5_0 = {
  149171. 2, 81,
  149172. _vq_lengthlist__44u5__p5_0,
  149173. 1, -531628032, 1611661312, 4, 0,
  149174. _vq_quantlist__44u5__p5_0,
  149175. NULL,
  149176. &_vq_auxt__44u5__p5_0,
  149177. NULL,
  149178. 0
  149179. };
  149180. static long _vq_quantlist__44u5__p6_0[] = {
  149181. 4,
  149182. 3,
  149183. 5,
  149184. 2,
  149185. 6,
  149186. 1,
  149187. 7,
  149188. 0,
  149189. 8,
  149190. };
  149191. static long _vq_lengthlist__44u5__p6_0[] = {
  149192. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149193. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149194. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149195. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149196. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149197. 11,
  149198. };
  149199. static float _vq_quantthresh__44u5__p6_0[] = {
  149200. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149201. };
  149202. static long _vq_quantmap__44u5__p6_0[] = {
  149203. 7, 5, 3, 1, 0, 2, 4, 6,
  149204. 8,
  149205. };
  149206. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149207. _vq_quantthresh__44u5__p6_0,
  149208. _vq_quantmap__44u5__p6_0,
  149209. 9,
  149210. 9
  149211. };
  149212. static static_codebook _44u5__p6_0 = {
  149213. 2, 81,
  149214. _vq_lengthlist__44u5__p6_0,
  149215. 1, -531628032, 1611661312, 4, 0,
  149216. _vq_quantlist__44u5__p6_0,
  149217. NULL,
  149218. &_vq_auxt__44u5__p6_0,
  149219. NULL,
  149220. 0
  149221. };
  149222. static long _vq_quantlist__44u5__p7_0[] = {
  149223. 1,
  149224. 0,
  149225. 2,
  149226. };
  149227. static long _vq_lengthlist__44u5__p7_0[] = {
  149228. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149229. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149230. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149231. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149232. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149233. 12,
  149234. };
  149235. static float _vq_quantthresh__44u5__p7_0[] = {
  149236. -5.5, 5.5,
  149237. };
  149238. static long _vq_quantmap__44u5__p7_0[] = {
  149239. 1, 0, 2,
  149240. };
  149241. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149242. _vq_quantthresh__44u5__p7_0,
  149243. _vq_quantmap__44u5__p7_0,
  149244. 3,
  149245. 3
  149246. };
  149247. static static_codebook _44u5__p7_0 = {
  149248. 4, 81,
  149249. _vq_lengthlist__44u5__p7_0,
  149250. 1, -529137664, 1618345984, 2, 0,
  149251. _vq_quantlist__44u5__p7_0,
  149252. NULL,
  149253. &_vq_auxt__44u5__p7_0,
  149254. NULL,
  149255. 0
  149256. };
  149257. static long _vq_quantlist__44u5__p7_1[] = {
  149258. 5,
  149259. 4,
  149260. 6,
  149261. 3,
  149262. 7,
  149263. 2,
  149264. 8,
  149265. 1,
  149266. 9,
  149267. 0,
  149268. 10,
  149269. };
  149270. static long _vq_lengthlist__44u5__p7_1[] = {
  149271. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149272. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149273. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149274. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149275. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149276. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149277. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149278. 9, 9, 9, 9, 9,10,10,10,10,
  149279. };
  149280. static float _vq_quantthresh__44u5__p7_1[] = {
  149281. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149282. 3.5, 4.5,
  149283. };
  149284. static long _vq_quantmap__44u5__p7_1[] = {
  149285. 9, 7, 5, 3, 1, 0, 2, 4,
  149286. 6, 8, 10,
  149287. };
  149288. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149289. _vq_quantthresh__44u5__p7_1,
  149290. _vq_quantmap__44u5__p7_1,
  149291. 11,
  149292. 11
  149293. };
  149294. static static_codebook _44u5__p7_1 = {
  149295. 2, 121,
  149296. _vq_lengthlist__44u5__p7_1,
  149297. 1, -531365888, 1611661312, 4, 0,
  149298. _vq_quantlist__44u5__p7_1,
  149299. NULL,
  149300. &_vq_auxt__44u5__p7_1,
  149301. NULL,
  149302. 0
  149303. };
  149304. static long _vq_quantlist__44u5__p8_0[] = {
  149305. 5,
  149306. 4,
  149307. 6,
  149308. 3,
  149309. 7,
  149310. 2,
  149311. 8,
  149312. 1,
  149313. 9,
  149314. 0,
  149315. 10,
  149316. };
  149317. static long _vq_lengthlist__44u5__p8_0[] = {
  149318. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149319. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149320. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149321. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149322. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149323. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149324. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149325. 12,13,13,14,14,14,14,15,15,
  149326. };
  149327. static float _vq_quantthresh__44u5__p8_0[] = {
  149328. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149329. 38.5, 49.5,
  149330. };
  149331. static long _vq_quantmap__44u5__p8_0[] = {
  149332. 9, 7, 5, 3, 1, 0, 2, 4,
  149333. 6, 8, 10,
  149334. };
  149335. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149336. _vq_quantthresh__44u5__p8_0,
  149337. _vq_quantmap__44u5__p8_0,
  149338. 11,
  149339. 11
  149340. };
  149341. static static_codebook _44u5__p8_0 = {
  149342. 2, 121,
  149343. _vq_lengthlist__44u5__p8_0,
  149344. 1, -524582912, 1618345984, 4, 0,
  149345. _vq_quantlist__44u5__p8_0,
  149346. NULL,
  149347. &_vq_auxt__44u5__p8_0,
  149348. NULL,
  149349. 0
  149350. };
  149351. static long _vq_quantlist__44u5__p8_1[] = {
  149352. 5,
  149353. 4,
  149354. 6,
  149355. 3,
  149356. 7,
  149357. 2,
  149358. 8,
  149359. 1,
  149360. 9,
  149361. 0,
  149362. 10,
  149363. };
  149364. static long _vq_lengthlist__44u5__p8_1[] = {
  149365. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149366. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149367. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149368. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149369. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149370. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149371. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149372. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149373. };
  149374. static float _vq_quantthresh__44u5__p8_1[] = {
  149375. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149376. 3.5, 4.5,
  149377. };
  149378. static long _vq_quantmap__44u5__p8_1[] = {
  149379. 9, 7, 5, 3, 1, 0, 2, 4,
  149380. 6, 8, 10,
  149381. };
  149382. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149383. _vq_quantthresh__44u5__p8_1,
  149384. _vq_quantmap__44u5__p8_1,
  149385. 11,
  149386. 11
  149387. };
  149388. static static_codebook _44u5__p8_1 = {
  149389. 2, 121,
  149390. _vq_lengthlist__44u5__p8_1,
  149391. 1, -531365888, 1611661312, 4, 0,
  149392. _vq_quantlist__44u5__p8_1,
  149393. NULL,
  149394. &_vq_auxt__44u5__p8_1,
  149395. NULL,
  149396. 0
  149397. };
  149398. static long _vq_quantlist__44u5__p9_0[] = {
  149399. 6,
  149400. 5,
  149401. 7,
  149402. 4,
  149403. 8,
  149404. 3,
  149405. 9,
  149406. 2,
  149407. 10,
  149408. 1,
  149409. 11,
  149410. 0,
  149411. 12,
  149412. };
  149413. static long _vq_lengthlist__44u5__p9_0[] = {
  149414. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149415. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149416. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149417. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149418. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149419. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149420. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149421. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149422. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149423. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149424. 12,12,12,12,12,12,12,12,12,
  149425. };
  149426. static float _vq_quantthresh__44u5__p9_0[] = {
  149427. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149428. 637.5, 892.5, 1147.5, 1402.5,
  149429. };
  149430. static long _vq_quantmap__44u5__p9_0[] = {
  149431. 11, 9, 7, 5, 3, 1, 0, 2,
  149432. 4, 6, 8, 10, 12,
  149433. };
  149434. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149435. _vq_quantthresh__44u5__p9_0,
  149436. _vq_quantmap__44u5__p9_0,
  149437. 13,
  149438. 13
  149439. };
  149440. static static_codebook _44u5__p9_0 = {
  149441. 2, 169,
  149442. _vq_lengthlist__44u5__p9_0,
  149443. 1, -514332672, 1627381760, 4, 0,
  149444. _vq_quantlist__44u5__p9_0,
  149445. NULL,
  149446. &_vq_auxt__44u5__p9_0,
  149447. NULL,
  149448. 0
  149449. };
  149450. static long _vq_quantlist__44u5__p9_1[] = {
  149451. 7,
  149452. 6,
  149453. 8,
  149454. 5,
  149455. 9,
  149456. 4,
  149457. 10,
  149458. 3,
  149459. 11,
  149460. 2,
  149461. 12,
  149462. 1,
  149463. 13,
  149464. 0,
  149465. 14,
  149466. };
  149467. static long _vq_lengthlist__44u5__p9_1[] = {
  149468. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149469. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149470. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149471. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149472. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149473. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149474. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149475. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149476. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149477. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149478. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149479. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149480. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149481. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149482. 14,
  149483. };
  149484. static float _vq_quantthresh__44u5__p9_1[] = {
  149485. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149486. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149487. };
  149488. static long _vq_quantmap__44u5__p9_1[] = {
  149489. 13, 11, 9, 7, 5, 3, 1, 0,
  149490. 2, 4, 6, 8, 10, 12, 14,
  149491. };
  149492. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149493. _vq_quantthresh__44u5__p9_1,
  149494. _vq_quantmap__44u5__p9_1,
  149495. 15,
  149496. 15
  149497. };
  149498. static static_codebook _44u5__p9_1 = {
  149499. 2, 225,
  149500. _vq_lengthlist__44u5__p9_1,
  149501. 1, -522338304, 1620115456, 4, 0,
  149502. _vq_quantlist__44u5__p9_1,
  149503. NULL,
  149504. &_vq_auxt__44u5__p9_1,
  149505. NULL,
  149506. 0
  149507. };
  149508. static long _vq_quantlist__44u5__p9_2[] = {
  149509. 8,
  149510. 7,
  149511. 9,
  149512. 6,
  149513. 10,
  149514. 5,
  149515. 11,
  149516. 4,
  149517. 12,
  149518. 3,
  149519. 13,
  149520. 2,
  149521. 14,
  149522. 1,
  149523. 15,
  149524. 0,
  149525. 16,
  149526. };
  149527. static long _vq_lengthlist__44u5__p9_2[] = {
  149528. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149529. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149530. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149531. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149532. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149533. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149534. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149535. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149536. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149537. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149538. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149539. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149540. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149541. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149542. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149543. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149544. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149545. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149546. 10,
  149547. };
  149548. static float _vq_quantthresh__44u5__p9_2[] = {
  149549. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149550. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149551. };
  149552. static long _vq_quantmap__44u5__p9_2[] = {
  149553. 15, 13, 11, 9, 7, 5, 3, 1,
  149554. 0, 2, 4, 6, 8, 10, 12, 14,
  149555. 16,
  149556. };
  149557. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149558. _vq_quantthresh__44u5__p9_2,
  149559. _vq_quantmap__44u5__p9_2,
  149560. 17,
  149561. 17
  149562. };
  149563. static static_codebook _44u5__p9_2 = {
  149564. 2, 289,
  149565. _vq_lengthlist__44u5__p9_2,
  149566. 1, -529530880, 1611661312, 5, 0,
  149567. _vq_quantlist__44u5__p9_2,
  149568. NULL,
  149569. &_vq_auxt__44u5__p9_2,
  149570. NULL,
  149571. 0
  149572. };
  149573. static long _huff_lengthlist__44u5__short[] = {
  149574. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149575. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149576. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149577. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149578. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149579. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149580. 6, 8,15,17,
  149581. };
  149582. static static_codebook _huff_book__44u5__short = {
  149583. 2, 100,
  149584. _huff_lengthlist__44u5__short,
  149585. 0, 0, 0, 0, 0,
  149586. NULL,
  149587. NULL,
  149588. NULL,
  149589. NULL,
  149590. 0
  149591. };
  149592. static long _huff_lengthlist__44u6__long[] = {
  149593. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149594. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149595. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149596. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149597. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149598. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149599. 13, 8, 7, 7,
  149600. };
  149601. static static_codebook _huff_book__44u6__long = {
  149602. 2, 100,
  149603. _huff_lengthlist__44u6__long,
  149604. 0, 0, 0, 0, 0,
  149605. NULL,
  149606. NULL,
  149607. NULL,
  149608. NULL,
  149609. 0
  149610. };
  149611. static long _vq_quantlist__44u6__p1_0[] = {
  149612. 1,
  149613. 0,
  149614. 2,
  149615. };
  149616. static long _vq_lengthlist__44u6__p1_0[] = {
  149617. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149618. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149619. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149620. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149621. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149622. 12,
  149623. };
  149624. static float _vq_quantthresh__44u6__p1_0[] = {
  149625. -0.5, 0.5,
  149626. };
  149627. static long _vq_quantmap__44u6__p1_0[] = {
  149628. 1, 0, 2,
  149629. };
  149630. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149631. _vq_quantthresh__44u6__p1_0,
  149632. _vq_quantmap__44u6__p1_0,
  149633. 3,
  149634. 3
  149635. };
  149636. static static_codebook _44u6__p1_0 = {
  149637. 4, 81,
  149638. _vq_lengthlist__44u6__p1_0,
  149639. 1, -535822336, 1611661312, 2, 0,
  149640. _vq_quantlist__44u6__p1_0,
  149641. NULL,
  149642. &_vq_auxt__44u6__p1_0,
  149643. NULL,
  149644. 0
  149645. };
  149646. static long _vq_quantlist__44u6__p2_0[] = {
  149647. 1,
  149648. 0,
  149649. 2,
  149650. };
  149651. static long _vq_lengthlist__44u6__p2_0[] = {
  149652. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149653. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149654. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149655. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149656. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149657. 9,
  149658. };
  149659. static float _vq_quantthresh__44u6__p2_0[] = {
  149660. -0.5, 0.5,
  149661. };
  149662. static long _vq_quantmap__44u6__p2_0[] = {
  149663. 1, 0, 2,
  149664. };
  149665. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149666. _vq_quantthresh__44u6__p2_0,
  149667. _vq_quantmap__44u6__p2_0,
  149668. 3,
  149669. 3
  149670. };
  149671. static static_codebook _44u6__p2_0 = {
  149672. 4, 81,
  149673. _vq_lengthlist__44u6__p2_0,
  149674. 1, -535822336, 1611661312, 2, 0,
  149675. _vq_quantlist__44u6__p2_0,
  149676. NULL,
  149677. &_vq_auxt__44u6__p2_0,
  149678. NULL,
  149679. 0
  149680. };
  149681. static long _vq_quantlist__44u6__p3_0[] = {
  149682. 2,
  149683. 1,
  149684. 3,
  149685. 0,
  149686. 4,
  149687. };
  149688. static long _vq_lengthlist__44u6__p3_0[] = {
  149689. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149690. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149691. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149692. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149693. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149694. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149695. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149696. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149697. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149698. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149699. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149700. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149701. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149702. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149703. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149704. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149705. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149706. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149707. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149708. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149709. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149710. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149711. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149712. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149713. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149714. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149715. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149716. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149717. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149718. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149719. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149720. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149721. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149722. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149723. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149724. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149725. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149726. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149727. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149728. 19,
  149729. };
  149730. static float _vq_quantthresh__44u6__p3_0[] = {
  149731. -1.5, -0.5, 0.5, 1.5,
  149732. };
  149733. static long _vq_quantmap__44u6__p3_0[] = {
  149734. 3, 1, 0, 2, 4,
  149735. };
  149736. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149737. _vq_quantthresh__44u6__p3_0,
  149738. _vq_quantmap__44u6__p3_0,
  149739. 5,
  149740. 5
  149741. };
  149742. static static_codebook _44u6__p3_0 = {
  149743. 4, 625,
  149744. _vq_lengthlist__44u6__p3_0,
  149745. 1, -533725184, 1611661312, 3, 0,
  149746. _vq_quantlist__44u6__p3_0,
  149747. NULL,
  149748. &_vq_auxt__44u6__p3_0,
  149749. NULL,
  149750. 0
  149751. };
  149752. static long _vq_quantlist__44u6__p4_0[] = {
  149753. 2,
  149754. 1,
  149755. 3,
  149756. 0,
  149757. 4,
  149758. };
  149759. static long _vq_lengthlist__44u6__p4_0[] = {
  149760. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149761. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149762. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149763. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149764. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149765. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149766. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149767. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149768. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149769. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149770. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149771. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149772. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149773. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149774. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149775. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149776. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149777. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149778. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149779. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149780. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149781. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149782. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149783. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149784. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149785. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149786. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149787. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149788. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149789. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149790. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149791. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149792. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149793. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149794. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149795. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149796. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149797. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149798. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149799. 13,
  149800. };
  149801. static float _vq_quantthresh__44u6__p4_0[] = {
  149802. -1.5, -0.5, 0.5, 1.5,
  149803. };
  149804. static long _vq_quantmap__44u6__p4_0[] = {
  149805. 3, 1, 0, 2, 4,
  149806. };
  149807. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149808. _vq_quantthresh__44u6__p4_0,
  149809. _vq_quantmap__44u6__p4_0,
  149810. 5,
  149811. 5
  149812. };
  149813. static static_codebook _44u6__p4_0 = {
  149814. 4, 625,
  149815. _vq_lengthlist__44u6__p4_0,
  149816. 1, -533725184, 1611661312, 3, 0,
  149817. _vq_quantlist__44u6__p4_0,
  149818. NULL,
  149819. &_vq_auxt__44u6__p4_0,
  149820. NULL,
  149821. 0
  149822. };
  149823. static long _vq_quantlist__44u6__p5_0[] = {
  149824. 4,
  149825. 3,
  149826. 5,
  149827. 2,
  149828. 6,
  149829. 1,
  149830. 7,
  149831. 0,
  149832. 8,
  149833. };
  149834. static long _vq_lengthlist__44u6__p5_0[] = {
  149835. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149836. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149837. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149838. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149839. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149840. 14,
  149841. };
  149842. static float _vq_quantthresh__44u6__p5_0[] = {
  149843. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149844. };
  149845. static long _vq_quantmap__44u6__p5_0[] = {
  149846. 7, 5, 3, 1, 0, 2, 4, 6,
  149847. 8,
  149848. };
  149849. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149850. _vq_quantthresh__44u6__p5_0,
  149851. _vq_quantmap__44u6__p5_0,
  149852. 9,
  149853. 9
  149854. };
  149855. static static_codebook _44u6__p5_0 = {
  149856. 2, 81,
  149857. _vq_lengthlist__44u6__p5_0,
  149858. 1, -531628032, 1611661312, 4, 0,
  149859. _vq_quantlist__44u6__p5_0,
  149860. NULL,
  149861. &_vq_auxt__44u6__p5_0,
  149862. NULL,
  149863. 0
  149864. };
  149865. static long _vq_quantlist__44u6__p6_0[] = {
  149866. 4,
  149867. 3,
  149868. 5,
  149869. 2,
  149870. 6,
  149871. 1,
  149872. 7,
  149873. 0,
  149874. 8,
  149875. };
  149876. static long _vq_lengthlist__44u6__p6_0[] = {
  149877. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149878. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149879. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149880. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149881. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149882. 12,
  149883. };
  149884. static float _vq_quantthresh__44u6__p6_0[] = {
  149885. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149886. };
  149887. static long _vq_quantmap__44u6__p6_0[] = {
  149888. 7, 5, 3, 1, 0, 2, 4, 6,
  149889. 8,
  149890. };
  149891. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149892. _vq_quantthresh__44u6__p6_0,
  149893. _vq_quantmap__44u6__p6_0,
  149894. 9,
  149895. 9
  149896. };
  149897. static static_codebook _44u6__p6_0 = {
  149898. 2, 81,
  149899. _vq_lengthlist__44u6__p6_0,
  149900. 1, -531628032, 1611661312, 4, 0,
  149901. _vq_quantlist__44u6__p6_0,
  149902. NULL,
  149903. &_vq_auxt__44u6__p6_0,
  149904. NULL,
  149905. 0
  149906. };
  149907. static long _vq_quantlist__44u6__p7_0[] = {
  149908. 1,
  149909. 0,
  149910. 2,
  149911. };
  149912. static long _vq_lengthlist__44u6__p7_0[] = {
  149913. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149914. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149915. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149916. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149917. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149918. 10,
  149919. };
  149920. static float _vq_quantthresh__44u6__p7_0[] = {
  149921. -5.5, 5.5,
  149922. };
  149923. static long _vq_quantmap__44u6__p7_0[] = {
  149924. 1, 0, 2,
  149925. };
  149926. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149927. _vq_quantthresh__44u6__p7_0,
  149928. _vq_quantmap__44u6__p7_0,
  149929. 3,
  149930. 3
  149931. };
  149932. static static_codebook _44u6__p7_0 = {
  149933. 4, 81,
  149934. _vq_lengthlist__44u6__p7_0,
  149935. 1, -529137664, 1618345984, 2, 0,
  149936. _vq_quantlist__44u6__p7_0,
  149937. NULL,
  149938. &_vq_auxt__44u6__p7_0,
  149939. NULL,
  149940. 0
  149941. };
  149942. static long _vq_quantlist__44u6__p7_1[] = {
  149943. 5,
  149944. 4,
  149945. 6,
  149946. 3,
  149947. 7,
  149948. 2,
  149949. 8,
  149950. 1,
  149951. 9,
  149952. 0,
  149953. 10,
  149954. };
  149955. static long _vq_lengthlist__44u6__p7_1[] = {
  149956. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149957. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149958. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149959. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149960. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149961. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149962. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149963. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149964. };
  149965. static float _vq_quantthresh__44u6__p7_1[] = {
  149966. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149967. 3.5, 4.5,
  149968. };
  149969. static long _vq_quantmap__44u6__p7_1[] = {
  149970. 9, 7, 5, 3, 1, 0, 2, 4,
  149971. 6, 8, 10,
  149972. };
  149973. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149974. _vq_quantthresh__44u6__p7_1,
  149975. _vq_quantmap__44u6__p7_1,
  149976. 11,
  149977. 11
  149978. };
  149979. static static_codebook _44u6__p7_1 = {
  149980. 2, 121,
  149981. _vq_lengthlist__44u6__p7_1,
  149982. 1, -531365888, 1611661312, 4, 0,
  149983. _vq_quantlist__44u6__p7_1,
  149984. NULL,
  149985. &_vq_auxt__44u6__p7_1,
  149986. NULL,
  149987. 0
  149988. };
  149989. static long _vq_quantlist__44u6__p8_0[] = {
  149990. 5,
  149991. 4,
  149992. 6,
  149993. 3,
  149994. 7,
  149995. 2,
  149996. 8,
  149997. 1,
  149998. 9,
  149999. 0,
  150000. 10,
  150001. };
  150002. static long _vq_lengthlist__44u6__p8_0[] = {
  150003. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150004. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150005. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150006. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150007. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150008. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150009. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150010. 12,13,13,14,14,14,15,15,15,
  150011. };
  150012. static float _vq_quantthresh__44u6__p8_0[] = {
  150013. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150014. 38.5, 49.5,
  150015. };
  150016. static long _vq_quantmap__44u6__p8_0[] = {
  150017. 9, 7, 5, 3, 1, 0, 2, 4,
  150018. 6, 8, 10,
  150019. };
  150020. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150021. _vq_quantthresh__44u6__p8_0,
  150022. _vq_quantmap__44u6__p8_0,
  150023. 11,
  150024. 11
  150025. };
  150026. static static_codebook _44u6__p8_0 = {
  150027. 2, 121,
  150028. _vq_lengthlist__44u6__p8_0,
  150029. 1, -524582912, 1618345984, 4, 0,
  150030. _vq_quantlist__44u6__p8_0,
  150031. NULL,
  150032. &_vq_auxt__44u6__p8_0,
  150033. NULL,
  150034. 0
  150035. };
  150036. static long _vq_quantlist__44u6__p8_1[] = {
  150037. 5,
  150038. 4,
  150039. 6,
  150040. 3,
  150041. 7,
  150042. 2,
  150043. 8,
  150044. 1,
  150045. 9,
  150046. 0,
  150047. 10,
  150048. };
  150049. static long _vq_lengthlist__44u6__p8_1[] = {
  150050. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150051. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150052. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150053. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150054. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150055. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150056. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150057. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150058. };
  150059. static float _vq_quantthresh__44u6__p8_1[] = {
  150060. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150061. 3.5, 4.5,
  150062. };
  150063. static long _vq_quantmap__44u6__p8_1[] = {
  150064. 9, 7, 5, 3, 1, 0, 2, 4,
  150065. 6, 8, 10,
  150066. };
  150067. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150068. _vq_quantthresh__44u6__p8_1,
  150069. _vq_quantmap__44u6__p8_1,
  150070. 11,
  150071. 11
  150072. };
  150073. static static_codebook _44u6__p8_1 = {
  150074. 2, 121,
  150075. _vq_lengthlist__44u6__p8_1,
  150076. 1, -531365888, 1611661312, 4, 0,
  150077. _vq_quantlist__44u6__p8_1,
  150078. NULL,
  150079. &_vq_auxt__44u6__p8_1,
  150080. NULL,
  150081. 0
  150082. };
  150083. static long _vq_quantlist__44u6__p9_0[] = {
  150084. 7,
  150085. 6,
  150086. 8,
  150087. 5,
  150088. 9,
  150089. 4,
  150090. 10,
  150091. 3,
  150092. 11,
  150093. 2,
  150094. 12,
  150095. 1,
  150096. 13,
  150097. 0,
  150098. 14,
  150099. };
  150100. static long _vq_lengthlist__44u6__p9_0[] = {
  150101. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150102. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150103. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150104. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150105. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150106. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150107. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150108. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150109. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150110. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150111. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150112. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150113. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150114. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150115. 14,
  150116. };
  150117. static float _vq_quantthresh__44u6__p9_0[] = {
  150118. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150119. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150120. };
  150121. static long _vq_quantmap__44u6__p9_0[] = {
  150122. 13, 11, 9, 7, 5, 3, 1, 0,
  150123. 2, 4, 6, 8, 10, 12, 14,
  150124. };
  150125. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150126. _vq_quantthresh__44u6__p9_0,
  150127. _vq_quantmap__44u6__p9_0,
  150128. 15,
  150129. 15
  150130. };
  150131. static static_codebook _44u6__p9_0 = {
  150132. 2, 225,
  150133. _vq_lengthlist__44u6__p9_0,
  150134. 1, -514071552, 1627381760, 4, 0,
  150135. _vq_quantlist__44u6__p9_0,
  150136. NULL,
  150137. &_vq_auxt__44u6__p9_0,
  150138. NULL,
  150139. 0
  150140. };
  150141. static long _vq_quantlist__44u6__p9_1[] = {
  150142. 7,
  150143. 6,
  150144. 8,
  150145. 5,
  150146. 9,
  150147. 4,
  150148. 10,
  150149. 3,
  150150. 11,
  150151. 2,
  150152. 12,
  150153. 1,
  150154. 13,
  150155. 0,
  150156. 14,
  150157. };
  150158. static long _vq_lengthlist__44u6__p9_1[] = {
  150159. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150160. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150161. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150162. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150163. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150164. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150165. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150166. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150167. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150168. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150169. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150170. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150171. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150172. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150173. 13,
  150174. };
  150175. static float _vq_quantthresh__44u6__p9_1[] = {
  150176. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150177. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150178. };
  150179. static long _vq_quantmap__44u6__p9_1[] = {
  150180. 13, 11, 9, 7, 5, 3, 1, 0,
  150181. 2, 4, 6, 8, 10, 12, 14,
  150182. };
  150183. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150184. _vq_quantthresh__44u6__p9_1,
  150185. _vq_quantmap__44u6__p9_1,
  150186. 15,
  150187. 15
  150188. };
  150189. static static_codebook _44u6__p9_1 = {
  150190. 2, 225,
  150191. _vq_lengthlist__44u6__p9_1,
  150192. 1, -522338304, 1620115456, 4, 0,
  150193. _vq_quantlist__44u6__p9_1,
  150194. NULL,
  150195. &_vq_auxt__44u6__p9_1,
  150196. NULL,
  150197. 0
  150198. };
  150199. static long _vq_quantlist__44u6__p9_2[] = {
  150200. 8,
  150201. 7,
  150202. 9,
  150203. 6,
  150204. 10,
  150205. 5,
  150206. 11,
  150207. 4,
  150208. 12,
  150209. 3,
  150210. 13,
  150211. 2,
  150212. 14,
  150213. 1,
  150214. 15,
  150215. 0,
  150216. 16,
  150217. };
  150218. static long _vq_lengthlist__44u6__p9_2[] = {
  150219. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150220. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150221. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150222. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150223. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150224. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150225. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150226. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150227. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150228. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150229. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150230. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150231. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150232. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150233. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150234. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150235. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150236. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150237. 10,
  150238. };
  150239. static float _vq_quantthresh__44u6__p9_2[] = {
  150240. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150241. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150242. };
  150243. static long _vq_quantmap__44u6__p9_2[] = {
  150244. 15, 13, 11, 9, 7, 5, 3, 1,
  150245. 0, 2, 4, 6, 8, 10, 12, 14,
  150246. 16,
  150247. };
  150248. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150249. _vq_quantthresh__44u6__p9_2,
  150250. _vq_quantmap__44u6__p9_2,
  150251. 17,
  150252. 17
  150253. };
  150254. static static_codebook _44u6__p9_2 = {
  150255. 2, 289,
  150256. _vq_lengthlist__44u6__p9_2,
  150257. 1, -529530880, 1611661312, 5, 0,
  150258. _vq_quantlist__44u6__p9_2,
  150259. NULL,
  150260. &_vq_auxt__44u6__p9_2,
  150261. NULL,
  150262. 0
  150263. };
  150264. static long _huff_lengthlist__44u6__short[] = {
  150265. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150266. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150267. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150268. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150269. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150270. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150271. 7, 6, 9,16,
  150272. };
  150273. static static_codebook _huff_book__44u6__short = {
  150274. 2, 100,
  150275. _huff_lengthlist__44u6__short,
  150276. 0, 0, 0, 0, 0,
  150277. NULL,
  150278. NULL,
  150279. NULL,
  150280. NULL,
  150281. 0
  150282. };
  150283. static long _huff_lengthlist__44u7__long[] = {
  150284. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150285. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150286. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150287. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150288. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150289. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150290. 12, 8, 6, 7,
  150291. };
  150292. static static_codebook _huff_book__44u7__long = {
  150293. 2, 100,
  150294. _huff_lengthlist__44u7__long,
  150295. 0, 0, 0, 0, 0,
  150296. NULL,
  150297. NULL,
  150298. NULL,
  150299. NULL,
  150300. 0
  150301. };
  150302. static long _vq_quantlist__44u7__p1_0[] = {
  150303. 1,
  150304. 0,
  150305. 2,
  150306. };
  150307. static long _vq_lengthlist__44u7__p1_0[] = {
  150308. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150309. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150310. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150311. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150312. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150313. 12,
  150314. };
  150315. static float _vq_quantthresh__44u7__p1_0[] = {
  150316. -0.5, 0.5,
  150317. };
  150318. static long _vq_quantmap__44u7__p1_0[] = {
  150319. 1, 0, 2,
  150320. };
  150321. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150322. _vq_quantthresh__44u7__p1_0,
  150323. _vq_quantmap__44u7__p1_0,
  150324. 3,
  150325. 3
  150326. };
  150327. static static_codebook _44u7__p1_0 = {
  150328. 4, 81,
  150329. _vq_lengthlist__44u7__p1_0,
  150330. 1, -535822336, 1611661312, 2, 0,
  150331. _vq_quantlist__44u7__p1_0,
  150332. NULL,
  150333. &_vq_auxt__44u7__p1_0,
  150334. NULL,
  150335. 0
  150336. };
  150337. static long _vq_quantlist__44u7__p2_0[] = {
  150338. 1,
  150339. 0,
  150340. 2,
  150341. };
  150342. static long _vq_lengthlist__44u7__p2_0[] = {
  150343. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150344. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150345. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150346. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150347. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150348. 9,
  150349. };
  150350. static float _vq_quantthresh__44u7__p2_0[] = {
  150351. -0.5, 0.5,
  150352. };
  150353. static long _vq_quantmap__44u7__p2_0[] = {
  150354. 1, 0, 2,
  150355. };
  150356. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150357. _vq_quantthresh__44u7__p2_0,
  150358. _vq_quantmap__44u7__p2_0,
  150359. 3,
  150360. 3
  150361. };
  150362. static static_codebook _44u7__p2_0 = {
  150363. 4, 81,
  150364. _vq_lengthlist__44u7__p2_0,
  150365. 1, -535822336, 1611661312, 2, 0,
  150366. _vq_quantlist__44u7__p2_0,
  150367. NULL,
  150368. &_vq_auxt__44u7__p2_0,
  150369. NULL,
  150370. 0
  150371. };
  150372. static long _vq_quantlist__44u7__p3_0[] = {
  150373. 2,
  150374. 1,
  150375. 3,
  150376. 0,
  150377. 4,
  150378. };
  150379. static long _vq_lengthlist__44u7__p3_0[] = {
  150380. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150381. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150382. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150383. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150384. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150385. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150386. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150387. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150388. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150389. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150390. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150391. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150392. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150393. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150394. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150395. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150396. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150397. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150398. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150399. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150400. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150401. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150402. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150403. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150404. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150405. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150406. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150407. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150408. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150409. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150410. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150411. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150412. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150413. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150414. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150415. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150416. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150417. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150418. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150419. 0,
  150420. };
  150421. static float _vq_quantthresh__44u7__p3_0[] = {
  150422. -1.5, -0.5, 0.5, 1.5,
  150423. };
  150424. static long _vq_quantmap__44u7__p3_0[] = {
  150425. 3, 1, 0, 2, 4,
  150426. };
  150427. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150428. _vq_quantthresh__44u7__p3_0,
  150429. _vq_quantmap__44u7__p3_0,
  150430. 5,
  150431. 5
  150432. };
  150433. static static_codebook _44u7__p3_0 = {
  150434. 4, 625,
  150435. _vq_lengthlist__44u7__p3_0,
  150436. 1, -533725184, 1611661312, 3, 0,
  150437. _vq_quantlist__44u7__p3_0,
  150438. NULL,
  150439. &_vq_auxt__44u7__p3_0,
  150440. NULL,
  150441. 0
  150442. };
  150443. static long _vq_quantlist__44u7__p4_0[] = {
  150444. 2,
  150445. 1,
  150446. 3,
  150447. 0,
  150448. 4,
  150449. };
  150450. static long _vq_lengthlist__44u7__p4_0[] = {
  150451. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150452. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150453. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150454. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150455. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150456. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150457. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150458. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150459. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150460. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150461. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150462. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150463. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150464. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150465. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150466. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150467. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150468. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150469. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150470. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150471. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150472. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150473. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150474. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150475. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150476. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150477. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150478. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150479. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150480. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150481. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150482. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150483. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150484. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150485. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150486. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150487. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150488. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150489. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150490. 14,
  150491. };
  150492. static float _vq_quantthresh__44u7__p4_0[] = {
  150493. -1.5, -0.5, 0.5, 1.5,
  150494. };
  150495. static long _vq_quantmap__44u7__p4_0[] = {
  150496. 3, 1, 0, 2, 4,
  150497. };
  150498. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150499. _vq_quantthresh__44u7__p4_0,
  150500. _vq_quantmap__44u7__p4_0,
  150501. 5,
  150502. 5
  150503. };
  150504. static static_codebook _44u7__p4_0 = {
  150505. 4, 625,
  150506. _vq_lengthlist__44u7__p4_0,
  150507. 1, -533725184, 1611661312, 3, 0,
  150508. _vq_quantlist__44u7__p4_0,
  150509. NULL,
  150510. &_vq_auxt__44u7__p4_0,
  150511. NULL,
  150512. 0
  150513. };
  150514. static long _vq_quantlist__44u7__p5_0[] = {
  150515. 4,
  150516. 3,
  150517. 5,
  150518. 2,
  150519. 6,
  150520. 1,
  150521. 7,
  150522. 0,
  150523. 8,
  150524. };
  150525. static long _vq_lengthlist__44u7__p5_0[] = {
  150526. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150527. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150528. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150529. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150530. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150531. 14,
  150532. };
  150533. static float _vq_quantthresh__44u7__p5_0[] = {
  150534. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150535. };
  150536. static long _vq_quantmap__44u7__p5_0[] = {
  150537. 7, 5, 3, 1, 0, 2, 4, 6,
  150538. 8,
  150539. };
  150540. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150541. _vq_quantthresh__44u7__p5_0,
  150542. _vq_quantmap__44u7__p5_0,
  150543. 9,
  150544. 9
  150545. };
  150546. static static_codebook _44u7__p5_0 = {
  150547. 2, 81,
  150548. _vq_lengthlist__44u7__p5_0,
  150549. 1, -531628032, 1611661312, 4, 0,
  150550. _vq_quantlist__44u7__p5_0,
  150551. NULL,
  150552. &_vq_auxt__44u7__p5_0,
  150553. NULL,
  150554. 0
  150555. };
  150556. static long _vq_quantlist__44u7__p6_0[] = {
  150557. 4,
  150558. 3,
  150559. 5,
  150560. 2,
  150561. 6,
  150562. 1,
  150563. 7,
  150564. 0,
  150565. 8,
  150566. };
  150567. static long _vq_lengthlist__44u7__p6_0[] = {
  150568. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150569. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150570. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150571. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150572. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150573. 12,
  150574. };
  150575. static float _vq_quantthresh__44u7__p6_0[] = {
  150576. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150577. };
  150578. static long _vq_quantmap__44u7__p6_0[] = {
  150579. 7, 5, 3, 1, 0, 2, 4, 6,
  150580. 8,
  150581. };
  150582. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150583. _vq_quantthresh__44u7__p6_0,
  150584. _vq_quantmap__44u7__p6_0,
  150585. 9,
  150586. 9
  150587. };
  150588. static static_codebook _44u7__p6_0 = {
  150589. 2, 81,
  150590. _vq_lengthlist__44u7__p6_0,
  150591. 1, -531628032, 1611661312, 4, 0,
  150592. _vq_quantlist__44u7__p6_0,
  150593. NULL,
  150594. &_vq_auxt__44u7__p6_0,
  150595. NULL,
  150596. 0
  150597. };
  150598. static long _vq_quantlist__44u7__p7_0[] = {
  150599. 1,
  150600. 0,
  150601. 2,
  150602. };
  150603. static long _vq_lengthlist__44u7__p7_0[] = {
  150604. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150605. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150606. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150607. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150608. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150609. 10,
  150610. };
  150611. static float _vq_quantthresh__44u7__p7_0[] = {
  150612. -5.5, 5.5,
  150613. };
  150614. static long _vq_quantmap__44u7__p7_0[] = {
  150615. 1, 0, 2,
  150616. };
  150617. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150618. _vq_quantthresh__44u7__p7_0,
  150619. _vq_quantmap__44u7__p7_0,
  150620. 3,
  150621. 3
  150622. };
  150623. static static_codebook _44u7__p7_0 = {
  150624. 4, 81,
  150625. _vq_lengthlist__44u7__p7_0,
  150626. 1, -529137664, 1618345984, 2, 0,
  150627. _vq_quantlist__44u7__p7_0,
  150628. NULL,
  150629. &_vq_auxt__44u7__p7_0,
  150630. NULL,
  150631. 0
  150632. };
  150633. static long _vq_quantlist__44u7__p7_1[] = {
  150634. 5,
  150635. 4,
  150636. 6,
  150637. 3,
  150638. 7,
  150639. 2,
  150640. 8,
  150641. 1,
  150642. 9,
  150643. 0,
  150644. 10,
  150645. };
  150646. static long _vq_lengthlist__44u7__p7_1[] = {
  150647. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150648. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150649. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150650. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150651. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150652. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150653. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150654. 8, 9, 9, 9, 9, 9,10,10,10,
  150655. };
  150656. static float _vq_quantthresh__44u7__p7_1[] = {
  150657. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150658. 3.5, 4.5,
  150659. };
  150660. static long _vq_quantmap__44u7__p7_1[] = {
  150661. 9, 7, 5, 3, 1, 0, 2, 4,
  150662. 6, 8, 10,
  150663. };
  150664. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150665. _vq_quantthresh__44u7__p7_1,
  150666. _vq_quantmap__44u7__p7_1,
  150667. 11,
  150668. 11
  150669. };
  150670. static static_codebook _44u7__p7_1 = {
  150671. 2, 121,
  150672. _vq_lengthlist__44u7__p7_1,
  150673. 1, -531365888, 1611661312, 4, 0,
  150674. _vq_quantlist__44u7__p7_1,
  150675. NULL,
  150676. &_vq_auxt__44u7__p7_1,
  150677. NULL,
  150678. 0
  150679. };
  150680. static long _vq_quantlist__44u7__p8_0[] = {
  150681. 5,
  150682. 4,
  150683. 6,
  150684. 3,
  150685. 7,
  150686. 2,
  150687. 8,
  150688. 1,
  150689. 9,
  150690. 0,
  150691. 10,
  150692. };
  150693. static long _vq_lengthlist__44u7__p8_0[] = {
  150694. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150695. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150696. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150697. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150698. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150699. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150700. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150701. 12,13,13,14,14,15,15,15,16,
  150702. };
  150703. static float _vq_quantthresh__44u7__p8_0[] = {
  150704. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150705. 38.5, 49.5,
  150706. };
  150707. static long _vq_quantmap__44u7__p8_0[] = {
  150708. 9, 7, 5, 3, 1, 0, 2, 4,
  150709. 6, 8, 10,
  150710. };
  150711. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150712. _vq_quantthresh__44u7__p8_0,
  150713. _vq_quantmap__44u7__p8_0,
  150714. 11,
  150715. 11
  150716. };
  150717. static static_codebook _44u7__p8_0 = {
  150718. 2, 121,
  150719. _vq_lengthlist__44u7__p8_0,
  150720. 1, -524582912, 1618345984, 4, 0,
  150721. _vq_quantlist__44u7__p8_0,
  150722. NULL,
  150723. &_vq_auxt__44u7__p8_0,
  150724. NULL,
  150725. 0
  150726. };
  150727. static long _vq_quantlist__44u7__p8_1[] = {
  150728. 5,
  150729. 4,
  150730. 6,
  150731. 3,
  150732. 7,
  150733. 2,
  150734. 8,
  150735. 1,
  150736. 9,
  150737. 0,
  150738. 10,
  150739. };
  150740. static long _vq_lengthlist__44u7__p8_1[] = {
  150741. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150742. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150743. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150744. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150745. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150746. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150747. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150748. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150749. };
  150750. static float _vq_quantthresh__44u7__p8_1[] = {
  150751. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150752. 3.5, 4.5,
  150753. };
  150754. static long _vq_quantmap__44u7__p8_1[] = {
  150755. 9, 7, 5, 3, 1, 0, 2, 4,
  150756. 6, 8, 10,
  150757. };
  150758. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150759. _vq_quantthresh__44u7__p8_1,
  150760. _vq_quantmap__44u7__p8_1,
  150761. 11,
  150762. 11
  150763. };
  150764. static static_codebook _44u7__p8_1 = {
  150765. 2, 121,
  150766. _vq_lengthlist__44u7__p8_1,
  150767. 1, -531365888, 1611661312, 4, 0,
  150768. _vq_quantlist__44u7__p8_1,
  150769. NULL,
  150770. &_vq_auxt__44u7__p8_1,
  150771. NULL,
  150772. 0
  150773. };
  150774. static long _vq_quantlist__44u7__p9_0[] = {
  150775. 5,
  150776. 4,
  150777. 6,
  150778. 3,
  150779. 7,
  150780. 2,
  150781. 8,
  150782. 1,
  150783. 9,
  150784. 0,
  150785. 10,
  150786. };
  150787. static long _vq_lengthlist__44u7__p9_0[] = {
  150788. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150789. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150790. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150791. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150792. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150793. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150794. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150795. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150796. };
  150797. static float _vq_quantthresh__44u7__p9_0[] = {
  150798. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150799. 2229.5, 2866.5,
  150800. };
  150801. static long _vq_quantmap__44u7__p9_0[] = {
  150802. 9, 7, 5, 3, 1, 0, 2, 4,
  150803. 6, 8, 10,
  150804. };
  150805. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150806. _vq_quantthresh__44u7__p9_0,
  150807. _vq_quantmap__44u7__p9_0,
  150808. 11,
  150809. 11
  150810. };
  150811. static static_codebook _44u7__p9_0 = {
  150812. 2, 121,
  150813. _vq_lengthlist__44u7__p9_0,
  150814. 1, -512171520, 1630791680, 4, 0,
  150815. _vq_quantlist__44u7__p9_0,
  150816. NULL,
  150817. &_vq_auxt__44u7__p9_0,
  150818. NULL,
  150819. 0
  150820. };
  150821. static long _vq_quantlist__44u7__p9_1[] = {
  150822. 6,
  150823. 5,
  150824. 7,
  150825. 4,
  150826. 8,
  150827. 3,
  150828. 9,
  150829. 2,
  150830. 10,
  150831. 1,
  150832. 11,
  150833. 0,
  150834. 12,
  150835. };
  150836. static long _vq_lengthlist__44u7__p9_1[] = {
  150837. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150838. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150839. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150840. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150841. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150842. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150843. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150844. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150845. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150846. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150847. 15,15,15,15,17,17,16,17,16,
  150848. };
  150849. static float _vq_quantthresh__44u7__p9_1[] = {
  150850. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150851. 122.5, 171.5, 220.5, 269.5,
  150852. };
  150853. static long _vq_quantmap__44u7__p9_1[] = {
  150854. 11, 9, 7, 5, 3, 1, 0, 2,
  150855. 4, 6, 8, 10, 12,
  150856. };
  150857. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150858. _vq_quantthresh__44u7__p9_1,
  150859. _vq_quantmap__44u7__p9_1,
  150860. 13,
  150861. 13
  150862. };
  150863. static static_codebook _44u7__p9_1 = {
  150864. 2, 169,
  150865. _vq_lengthlist__44u7__p9_1,
  150866. 1, -518889472, 1622704128, 4, 0,
  150867. _vq_quantlist__44u7__p9_1,
  150868. NULL,
  150869. &_vq_auxt__44u7__p9_1,
  150870. NULL,
  150871. 0
  150872. };
  150873. static long _vq_quantlist__44u7__p9_2[] = {
  150874. 24,
  150875. 23,
  150876. 25,
  150877. 22,
  150878. 26,
  150879. 21,
  150880. 27,
  150881. 20,
  150882. 28,
  150883. 19,
  150884. 29,
  150885. 18,
  150886. 30,
  150887. 17,
  150888. 31,
  150889. 16,
  150890. 32,
  150891. 15,
  150892. 33,
  150893. 14,
  150894. 34,
  150895. 13,
  150896. 35,
  150897. 12,
  150898. 36,
  150899. 11,
  150900. 37,
  150901. 10,
  150902. 38,
  150903. 9,
  150904. 39,
  150905. 8,
  150906. 40,
  150907. 7,
  150908. 41,
  150909. 6,
  150910. 42,
  150911. 5,
  150912. 43,
  150913. 4,
  150914. 44,
  150915. 3,
  150916. 45,
  150917. 2,
  150918. 46,
  150919. 1,
  150920. 47,
  150921. 0,
  150922. 48,
  150923. };
  150924. static long _vq_lengthlist__44u7__p9_2[] = {
  150925. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150926. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150927. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150928. 8,
  150929. };
  150930. static float _vq_quantthresh__44u7__p9_2[] = {
  150931. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150932. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150933. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150934. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150935. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150936. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150937. };
  150938. static long _vq_quantmap__44u7__p9_2[] = {
  150939. 47, 45, 43, 41, 39, 37, 35, 33,
  150940. 31, 29, 27, 25, 23, 21, 19, 17,
  150941. 15, 13, 11, 9, 7, 5, 3, 1,
  150942. 0, 2, 4, 6, 8, 10, 12, 14,
  150943. 16, 18, 20, 22, 24, 26, 28, 30,
  150944. 32, 34, 36, 38, 40, 42, 44, 46,
  150945. 48,
  150946. };
  150947. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150948. _vq_quantthresh__44u7__p9_2,
  150949. _vq_quantmap__44u7__p9_2,
  150950. 49,
  150951. 49
  150952. };
  150953. static static_codebook _44u7__p9_2 = {
  150954. 1, 49,
  150955. _vq_lengthlist__44u7__p9_2,
  150956. 1, -526909440, 1611661312, 6, 0,
  150957. _vq_quantlist__44u7__p9_2,
  150958. NULL,
  150959. &_vq_auxt__44u7__p9_2,
  150960. NULL,
  150961. 0
  150962. };
  150963. static long _huff_lengthlist__44u7__short[] = {
  150964. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150965. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150966. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150967. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150968. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150969. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150970. 6, 8, 5, 9,
  150971. };
  150972. static static_codebook _huff_book__44u7__short = {
  150973. 2, 100,
  150974. _huff_lengthlist__44u7__short,
  150975. 0, 0, 0, 0, 0,
  150976. NULL,
  150977. NULL,
  150978. NULL,
  150979. NULL,
  150980. 0
  150981. };
  150982. static long _huff_lengthlist__44u8__long[] = {
  150983. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150984. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150985. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150986. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150987. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150988. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150989. 10, 8, 8, 9,
  150990. };
  150991. static static_codebook _huff_book__44u8__long = {
  150992. 2, 100,
  150993. _huff_lengthlist__44u8__long,
  150994. 0, 0, 0, 0, 0,
  150995. NULL,
  150996. NULL,
  150997. NULL,
  150998. NULL,
  150999. 0
  151000. };
  151001. static long _huff_lengthlist__44u8__short[] = {
  151002. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151003. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151004. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151005. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151006. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151007. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151008. 10,10,15,17,
  151009. };
  151010. static static_codebook _huff_book__44u8__short = {
  151011. 2, 100,
  151012. _huff_lengthlist__44u8__short,
  151013. 0, 0, 0, 0, 0,
  151014. NULL,
  151015. NULL,
  151016. NULL,
  151017. NULL,
  151018. 0
  151019. };
  151020. static long _vq_quantlist__44u8_p1_0[] = {
  151021. 1,
  151022. 0,
  151023. 2,
  151024. };
  151025. static long _vq_lengthlist__44u8_p1_0[] = {
  151026. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151027. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151028. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151029. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151030. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151031. 10,
  151032. };
  151033. static float _vq_quantthresh__44u8_p1_0[] = {
  151034. -0.5, 0.5,
  151035. };
  151036. static long _vq_quantmap__44u8_p1_0[] = {
  151037. 1, 0, 2,
  151038. };
  151039. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151040. _vq_quantthresh__44u8_p1_0,
  151041. _vq_quantmap__44u8_p1_0,
  151042. 3,
  151043. 3
  151044. };
  151045. static static_codebook _44u8_p1_0 = {
  151046. 4, 81,
  151047. _vq_lengthlist__44u8_p1_0,
  151048. 1, -535822336, 1611661312, 2, 0,
  151049. _vq_quantlist__44u8_p1_0,
  151050. NULL,
  151051. &_vq_auxt__44u8_p1_0,
  151052. NULL,
  151053. 0
  151054. };
  151055. static long _vq_quantlist__44u8_p2_0[] = {
  151056. 2,
  151057. 1,
  151058. 3,
  151059. 0,
  151060. 4,
  151061. };
  151062. static long _vq_lengthlist__44u8_p2_0[] = {
  151063. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151064. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151065. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151066. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151067. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151068. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151069. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151070. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151071. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151072. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151073. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151074. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151075. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151076. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151077. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151078. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151079. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151080. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151081. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151082. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151083. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151084. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151085. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151086. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151087. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151088. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151089. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151090. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151091. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151092. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151093. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151094. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151095. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151096. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151097. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151098. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151099. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151100. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151101. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151102. 14,
  151103. };
  151104. static float _vq_quantthresh__44u8_p2_0[] = {
  151105. -1.5, -0.5, 0.5, 1.5,
  151106. };
  151107. static long _vq_quantmap__44u8_p2_0[] = {
  151108. 3, 1, 0, 2, 4,
  151109. };
  151110. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151111. _vq_quantthresh__44u8_p2_0,
  151112. _vq_quantmap__44u8_p2_0,
  151113. 5,
  151114. 5
  151115. };
  151116. static static_codebook _44u8_p2_0 = {
  151117. 4, 625,
  151118. _vq_lengthlist__44u8_p2_0,
  151119. 1, -533725184, 1611661312, 3, 0,
  151120. _vq_quantlist__44u8_p2_0,
  151121. NULL,
  151122. &_vq_auxt__44u8_p2_0,
  151123. NULL,
  151124. 0
  151125. };
  151126. static long _vq_quantlist__44u8_p3_0[] = {
  151127. 4,
  151128. 3,
  151129. 5,
  151130. 2,
  151131. 6,
  151132. 1,
  151133. 7,
  151134. 0,
  151135. 8,
  151136. };
  151137. static long _vq_lengthlist__44u8_p3_0[] = {
  151138. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151139. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151140. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151141. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151142. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151143. 12,
  151144. };
  151145. static float _vq_quantthresh__44u8_p3_0[] = {
  151146. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151147. };
  151148. static long _vq_quantmap__44u8_p3_0[] = {
  151149. 7, 5, 3, 1, 0, 2, 4, 6,
  151150. 8,
  151151. };
  151152. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151153. _vq_quantthresh__44u8_p3_0,
  151154. _vq_quantmap__44u8_p3_0,
  151155. 9,
  151156. 9
  151157. };
  151158. static static_codebook _44u8_p3_0 = {
  151159. 2, 81,
  151160. _vq_lengthlist__44u8_p3_0,
  151161. 1, -531628032, 1611661312, 4, 0,
  151162. _vq_quantlist__44u8_p3_0,
  151163. NULL,
  151164. &_vq_auxt__44u8_p3_0,
  151165. NULL,
  151166. 0
  151167. };
  151168. static long _vq_quantlist__44u8_p4_0[] = {
  151169. 8,
  151170. 7,
  151171. 9,
  151172. 6,
  151173. 10,
  151174. 5,
  151175. 11,
  151176. 4,
  151177. 12,
  151178. 3,
  151179. 13,
  151180. 2,
  151181. 14,
  151182. 1,
  151183. 15,
  151184. 0,
  151185. 16,
  151186. };
  151187. static long _vq_lengthlist__44u8_p4_0[] = {
  151188. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151189. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151190. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151191. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151192. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151193. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151194. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151195. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151196. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151197. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151198. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151199. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151200. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151201. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151202. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151203. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151204. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151205. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151206. 14,
  151207. };
  151208. static float _vq_quantthresh__44u8_p4_0[] = {
  151209. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151210. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151211. };
  151212. static long _vq_quantmap__44u8_p4_0[] = {
  151213. 15, 13, 11, 9, 7, 5, 3, 1,
  151214. 0, 2, 4, 6, 8, 10, 12, 14,
  151215. 16,
  151216. };
  151217. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151218. _vq_quantthresh__44u8_p4_0,
  151219. _vq_quantmap__44u8_p4_0,
  151220. 17,
  151221. 17
  151222. };
  151223. static static_codebook _44u8_p4_0 = {
  151224. 2, 289,
  151225. _vq_lengthlist__44u8_p4_0,
  151226. 1, -529530880, 1611661312, 5, 0,
  151227. _vq_quantlist__44u8_p4_0,
  151228. NULL,
  151229. &_vq_auxt__44u8_p4_0,
  151230. NULL,
  151231. 0
  151232. };
  151233. static long _vq_quantlist__44u8_p5_0[] = {
  151234. 1,
  151235. 0,
  151236. 2,
  151237. };
  151238. static long _vq_lengthlist__44u8_p5_0[] = {
  151239. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151240. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151241. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151242. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151243. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151244. 10,
  151245. };
  151246. static float _vq_quantthresh__44u8_p5_0[] = {
  151247. -5.5, 5.5,
  151248. };
  151249. static long _vq_quantmap__44u8_p5_0[] = {
  151250. 1, 0, 2,
  151251. };
  151252. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151253. _vq_quantthresh__44u8_p5_0,
  151254. _vq_quantmap__44u8_p5_0,
  151255. 3,
  151256. 3
  151257. };
  151258. static static_codebook _44u8_p5_0 = {
  151259. 4, 81,
  151260. _vq_lengthlist__44u8_p5_0,
  151261. 1, -529137664, 1618345984, 2, 0,
  151262. _vq_quantlist__44u8_p5_0,
  151263. NULL,
  151264. &_vq_auxt__44u8_p5_0,
  151265. NULL,
  151266. 0
  151267. };
  151268. static long _vq_quantlist__44u8_p5_1[] = {
  151269. 5,
  151270. 4,
  151271. 6,
  151272. 3,
  151273. 7,
  151274. 2,
  151275. 8,
  151276. 1,
  151277. 9,
  151278. 0,
  151279. 10,
  151280. };
  151281. static long _vq_lengthlist__44u8_p5_1[] = {
  151282. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151283. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151284. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151285. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151286. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151287. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151288. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151289. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151290. };
  151291. static float _vq_quantthresh__44u8_p5_1[] = {
  151292. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151293. 3.5, 4.5,
  151294. };
  151295. static long _vq_quantmap__44u8_p5_1[] = {
  151296. 9, 7, 5, 3, 1, 0, 2, 4,
  151297. 6, 8, 10,
  151298. };
  151299. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151300. _vq_quantthresh__44u8_p5_1,
  151301. _vq_quantmap__44u8_p5_1,
  151302. 11,
  151303. 11
  151304. };
  151305. static static_codebook _44u8_p5_1 = {
  151306. 2, 121,
  151307. _vq_lengthlist__44u8_p5_1,
  151308. 1, -531365888, 1611661312, 4, 0,
  151309. _vq_quantlist__44u8_p5_1,
  151310. NULL,
  151311. &_vq_auxt__44u8_p5_1,
  151312. NULL,
  151313. 0
  151314. };
  151315. static long _vq_quantlist__44u8_p6_0[] = {
  151316. 6,
  151317. 5,
  151318. 7,
  151319. 4,
  151320. 8,
  151321. 3,
  151322. 9,
  151323. 2,
  151324. 10,
  151325. 1,
  151326. 11,
  151327. 0,
  151328. 12,
  151329. };
  151330. static long _vq_lengthlist__44u8_p6_0[] = {
  151331. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151332. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151333. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151334. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151335. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151336. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151337. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151338. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151339. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151340. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151341. 11,11,11,11,11,12,11,12,12,
  151342. };
  151343. static float _vq_quantthresh__44u8_p6_0[] = {
  151344. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151345. 12.5, 17.5, 22.5, 27.5,
  151346. };
  151347. static long _vq_quantmap__44u8_p6_0[] = {
  151348. 11, 9, 7, 5, 3, 1, 0, 2,
  151349. 4, 6, 8, 10, 12,
  151350. };
  151351. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151352. _vq_quantthresh__44u8_p6_0,
  151353. _vq_quantmap__44u8_p6_0,
  151354. 13,
  151355. 13
  151356. };
  151357. static static_codebook _44u8_p6_0 = {
  151358. 2, 169,
  151359. _vq_lengthlist__44u8_p6_0,
  151360. 1, -526516224, 1616117760, 4, 0,
  151361. _vq_quantlist__44u8_p6_0,
  151362. NULL,
  151363. &_vq_auxt__44u8_p6_0,
  151364. NULL,
  151365. 0
  151366. };
  151367. static long _vq_quantlist__44u8_p6_1[] = {
  151368. 2,
  151369. 1,
  151370. 3,
  151371. 0,
  151372. 4,
  151373. };
  151374. static long _vq_lengthlist__44u8_p6_1[] = {
  151375. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151376. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151377. };
  151378. static float _vq_quantthresh__44u8_p6_1[] = {
  151379. -1.5, -0.5, 0.5, 1.5,
  151380. };
  151381. static long _vq_quantmap__44u8_p6_1[] = {
  151382. 3, 1, 0, 2, 4,
  151383. };
  151384. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151385. _vq_quantthresh__44u8_p6_1,
  151386. _vq_quantmap__44u8_p6_1,
  151387. 5,
  151388. 5
  151389. };
  151390. static static_codebook _44u8_p6_1 = {
  151391. 2, 25,
  151392. _vq_lengthlist__44u8_p6_1,
  151393. 1, -533725184, 1611661312, 3, 0,
  151394. _vq_quantlist__44u8_p6_1,
  151395. NULL,
  151396. &_vq_auxt__44u8_p6_1,
  151397. NULL,
  151398. 0
  151399. };
  151400. static long _vq_quantlist__44u8_p7_0[] = {
  151401. 6,
  151402. 5,
  151403. 7,
  151404. 4,
  151405. 8,
  151406. 3,
  151407. 9,
  151408. 2,
  151409. 10,
  151410. 1,
  151411. 11,
  151412. 0,
  151413. 12,
  151414. };
  151415. static long _vq_lengthlist__44u8_p7_0[] = {
  151416. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151417. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151418. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151419. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151420. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151421. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151422. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151423. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151424. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151425. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151426. 13,13,14,14,14,15,15,15,16,
  151427. };
  151428. static float _vq_quantthresh__44u8_p7_0[] = {
  151429. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151430. 27.5, 38.5, 49.5, 60.5,
  151431. };
  151432. static long _vq_quantmap__44u8_p7_0[] = {
  151433. 11, 9, 7, 5, 3, 1, 0, 2,
  151434. 4, 6, 8, 10, 12,
  151435. };
  151436. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151437. _vq_quantthresh__44u8_p7_0,
  151438. _vq_quantmap__44u8_p7_0,
  151439. 13,
  151440. 13
  151441. };
  151442. static static_codebook _44u8_p7_0 = {
  151443. 2, 169,
  151444. _vq_lengthlist__44u8_p7_0,
  151445. 1, -523206656, 1618345984, 4, 0,
  151446. _vq_quantlist__44u8_p7_0,
  151447. NULL,
  151448. &_vq_auxt__44u8_p7_0,
  151449. NULL,
  151450. 0
  151451. };
  151452. static long _vq_quantlist__44u8_p7_1[] = {
  151453. 5,
  151454. 4,
  151455. 6,
  151456. 3,
  151457. 7,
  151458. 2,
  151459. 8,
  151460. 1,
  151461. 9,
  151462. 0,
  151463. 10,
  151464. };
  151465. static long _vq_lengthlist__44u8_p7_1[] = {
  151466. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151467. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151468. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151469. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151470. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151471. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151472. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151473. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151474. };
  151475. static float _vq_quantthresh__44u8_p7_1[] = {
  151476. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151477. 3.5, 4.5,
  151478. };
  151479. static long _vq_quantmap__44u8_p7_1[] = {
  151480. 9, 7, 5, 3, 1, 0, 2, 4,
  151481. 6, 8, 10,
  151482. };
  151483. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151484. _vq_quantthresh__44u8_p7_1,
  151485. _vq_quantmap__44u8_p7_1,
  151486. 11,
  151487. 11
  151488. };
  151489. static static_codebook _44u8_p7_1 = {
  151490. 2, 121,
  151491. _vq_lengthlist__44u8_p7_1,
  151492. 1, -531365888, 1611661312, 4, 0,
  151493. _vq_quantlist__44u8_p7_1,
  151494. NULL,
  151495. &_vq_auxt__44u8_p7_1,
  151496. NULL,
  151497. 0
  151498. };
  151499. static long _vq_quantlist__44u8_p8_0[] = {
  151500. 7,
  151501. 6,
  151502. 8,
  151503. 5,
  151504. 9,
  151505. 4,
  151506. 10,
  151507. 3,
  151508. 11,
  151509. 2,
  151510. 12,
  151511. 1,
  151512. 13,
  151513. 0,
  151514. 14,
  151515. };
  151516. static long _vq_lengthlist__44u8_p8_0[] = {
  151517. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151518. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151519. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151520. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151521. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151522. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151523. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151524. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151525. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151526. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151527. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151528. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151529. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151530. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151531. 17,
  151532. };
  151533. static float _vq_quantthresh__44u8_p8_0[] = {
  151534. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151535. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151536. };
  151537. static long _vq_quantmap__44u8_p8_0[] = {
  151538. 13, 11, 9, 7, 5, 3, 1, 0,
  151539. 2, 4, 6, 8, 10, 12, 14,
  151540. };
  151541. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151542. _vq_quantthresh__44u8_p8_0,
  151543. _vq_quantmap__44u8_p8_0,
  151544. 15,
  151545. 15
  151546. };
  151547. static static_codebook _44u8_p8_0 = {
  151548. 2, 225,
  151549. _vq_lengthlist__44u8_p8_0,
  151550. 1, -520986624, 1620377600, 4, 0,
  151551. _vq_quantlist__44u8_p8_0,
  151552. NULL,
  151553. &_vq_auxt__44u8_p8_0,
  151554. NULL,
  151555. 0
  151556. };
  151557. static long _vq_quantlist__44u8_p8_1[] = {
  151558. 10,
  151559. 9,
  151560. 11,
  151561. 8,
  151562. 12,
  151563. 7,
  151564. 13,
  151565. 6,
  151566. 14,
  151567. 5,
  151568. 15,
  151569. 4,
  151570. 16,
  151571. 3,
  151572. 17,
  151573. 2,
  151574. 18,
  151575. 1,
  151576. 19,
  151577. 0,
  151578. 20,
  151579. };
  151580. static long _vq_lengthlist__44u8_p8_1[] = {
  151581. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151582. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151583. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151584. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151585. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151586. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151587. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151588. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151589. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151590. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151591. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151592. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151593. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151594. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151595. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151596. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151597. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151598. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151599. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151600. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151601. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151602. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151603. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151604. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151605. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151606. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151607. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151608. 10,10,10,10,10,10,10,10,10,
  151609. };
  151610. static float _vq_quantthresh__44u8_p8_1[] = {
  151611. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151612. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151613. 6.5, 7.5, 8.5, 9.5,
  151614. };
  151615. static long _vq_quantmap__44u8_p8_1[] = {
  151616. 19, 17, 15, 13, 11, 9, 7, 5,
  151617. 3, 1, 0, 2, 4, 6, 8, 10,
  151618. 12, 14, 16, 18, 20,
  151619. };
  151620. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151621. _vq_quantthresh__44u8_p8_1,
  151622. _vq_quantmap__44u8_p8_1,
  151623. 21,
  151624. 21
  151625. };
  151626. static static_codebook _44u8_p8_1 = {
  151627. 2, 441,
  151628. _vq_lengthlist__44u8_p8_1,
  151629. 1, -529268736, 1611661312, 5, 0,
  151630. _vq_quantlist__44u8_p8_1,
  151631. NULL,
  151632. &_vq_auxt__44u8_p8_1,
  151633. NULL,
  151634. 0
  151635. };
  151636. static long _vq_quantlist__44u8_p9_0[] = {
  151637. 4,
  151638. 3,
  151639. 5,
  151640. 2,
  151641. 6,
  151642. 1,
  151643. 7,
  151644. 0,
  151645. 8,
  151646. };
  151647. static long _vq_lengthlist__44u8_p9_0[] = {
  151648. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151649. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151650. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151651. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151652. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151653. 8,
  151654. };
  151655. static float _vq_quantthresh__44u8_p9_0[] = {
  151656. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151657. };
  151658. static long _vq_quantmap__44u8_p9_0[] = {
  151659. 7, 5, 3, 1, 0, 2, 4, 6,
  151660. 8,
  151661. };
  151662. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151663. _vq_quantthresh__44u8_p9_0,
  151664. _vq_quantmap__44u8_p9_0,
  151665. 9,
  151666. 9
  151667. };
  151668. static static_codebook _44u8_p9_0 = {
  151669. 2, 81,
  151670. _vq_lengthlist__44u8_p9_0,
  151671. 1, -511895552, 1631393792, 4, 0,
  151672. _vq_quantlist__44u8_p9_0,
  151673. NULL,
  151674. &_vq_auxt__44u8_p9_0,
  151675. NULL,
  151676. 0
  151677. };
  151678. static long _vq_quantlist__44u8_p9_1[] = {
  151679. 9,
  151680. 8,
  151681. 10,
  151682. 7,
  151683. 11,
  151684. 6,
  151685. 12,
  151686. 5,
  151687. 13,
  151688. 4,
  151689. 14,
  151690. 3,
  151691. 15,
  151692. 2,
  151693. 16,
  151694. 1,
  151695. 17,
  151696. 0,
  151697. 18,
  151698. };
  151699. static long _vq_lengthlist__44u8_p9_1[] = {
  151700. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151701. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151702. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151703. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151704. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151705. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151706. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151707. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151708. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151709. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151710. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151711. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151712. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151713. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151714. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151715. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151716. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151717. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151718. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151719. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151720. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151721. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151722. 16,15,16,16,16,16,16,16,16,
  151723. };
  151724. static float _vq_quantthresh__44u8_p9_1[] = {
  151725. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151726. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151727. 367.5, 416.5,
  151728. };
  151729. static long _vq_quantmap__44u8_p9_1[] = {
  151730. 17, 15, 13, 11, 9, 7, 5, 3,
  151731. 1, 0, 2, 4, 6, 8, 10, 12,
  151732. 14, 16, 18,
  151733. };
  151734. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151735. _vq_quantthresh__44u8_p9_1,
  151736. _vq_quantmap__44u8_p9_1,
  151737. 19,
  151738. 19
  151739. };
  151740. static static_codebook _44u8_p9_1 = {
  151741. 2, 361,
  151742. _vq_lengthlist__44u8_p9_1,
  151743. 1, -518287360, 1622704128, 5, 0,
  151744. _vq_quantlist__44u8_p9_1,
  151745. NULL,
  151746. &_vq_auxt__44u8_p9_1,
  151747. NULL,
  151748. 0
  151749. };
  151750. static long _vq_quantlist__44u8_p9_2[] = {
  151751. 24,
  151752. 23,
  151753. 25,
  151754. 22,
  151755. 26,
  151756. 21,
  151757. 27,
  151758. 20,
  151759. 28,
  151760. 19,
  151761. 29,
  151762. 18,
  151763. 30,
  151764. 17,
  151765. 31,
  151766. 16,
  151767. 32,
  151768. 15,
  151769. 33,
  151770. 14,
  151771. 34,
  151772. 13,
  151773. 35,
  151774. 12,
  151775. 36,
  151776. 11,
  151777. 37,
  151778. 10,
  151779. 38,
  151780. 9,
  151781. 39,
  151782. 8,
  151783. 40,
  151784. 7,
  151785. 41,
  151786. 6,
  151787. 42,
  151788. 5,
  151789. 43,
  151790. 4,
  151791. 44,
  151792. 3,
  151793. 45,
  151794. 2,
  151795. 46,
  151796. 1,
  151797. 47,
  151798. 0,
  151799. 48,
  151800. };
  151801. static long _vq_lengthlist__44u8_p9_2[] = {
  151802. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151803. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151804. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151805. 7,
  151806. };
  151807. static float _vq_quantthresh__44u8_p9_2[] = {
  151808. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151809. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151810. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151811. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151812. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151813. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151814. };
  151815. static long _vq_quantmap__44u8_p9_2[] = {
  151816. 47, 45, 43, 41, 39, 37, 35, 33,
  151817. 31, 29, 27, 25, 23, 21, 19, 17,
  151818. 15, 13, 11, 9, 7, 5, 3, 1,
  151819. 0, 2, 4, 6, 8, 10, 12, 14,
  151820. 16, 18, 20, 22, 24, 26, 28, 30,
  151821. 32, 34, 36, 38, 40, 42, 44, 46,
  151822. 48,
  151823. };
  151824. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151825. _vq_quantthresh__44u8_p9_2,
  151826. _vq_quantmap__44u8_p9_2,
  151827. 49,
  151828. 49
  151829. };
  151830. static static_codebook _44u8_p9_2 = {
  151831. 1, 49,
  151832. _vq_lengthlist__44u8_p9_2,
  151833. 1, -526909440, 1611661312, 6, 0,
  151834. _vq_quantlist__44u8_p9_2,
  151835. NULL,
  151836. &_vq_auxt__44u8_p9_2,
  151837. NULL,
  151838. 0
  151839. };
  151840. static long _huff_lengthlist__44u9__long[] = {
  151841. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151842. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151843. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151844. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151845. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151846. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151847. 10, 8, 8, 9,
  151848. };
  151849. static static_codebook _huff_book__44u9__long = {
  151850. 2, 100,
  151851. _huff_lengthlist__44u9__long,
  151852. 0, 0, 0, 0, 0,
  151853. NULL,
  151854. NULL,
  151855. NULL,
  151856. NULL,
  151857. 0
  151858. };
  151859. static long _huff_lengthlist__44u9__short[] = {
  151860. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151861. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151862. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151863. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151864. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151865. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151866. 9, 9,12,15,
  151867. };
  151868. static static_codebook _huff_book__44u9__short = {
  151869. 2, 100,
  151870. _huff_lengthlist__44u9__short,
  151871. 0, 0, 0, 0, 0,
  151872. NULL,
  151873. NULL,
  151874. NULL,
  151875. NULL,
  151876. 0
  151877. };
  151878. static long _vq_quantlist__44u9_p1_0[] = {
  151879. 1,
  151880. 0,
  151881. 2,
  151882. };
  151883. static long _vq_lengthlist__44u9_p1_0[] = {
  151884. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151885. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151886. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151887. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151888. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151889. 10,
  151890. };
  151891. static float _vq_quantthresh__44u9_p1_0[] = {
  151892. -0.5, 0.5,
  151893. };
  151894. static long _vq_quantmap__44u9_p1_0[] = {
  151895. 1, 0, 2,
  151896. };
  151897. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151898. _vq_quantthresh__44u9_p1_0,
  151899. _vq_quantmap__44u9_p1_0,
  151900. 3,
  151901. 3
  151902. };
  151903. static static_codebook _44u9_p1_0 = {
  151904. 4, 81,
  151905. _vq_lengthlist__44u9_p1_0,
  151906. 1, -535822336, 1611661312, 2, 0,
  151907. _vq_quantlist__44u9_p1_0,
  151908. NULL,
  151909. &_vq_auxt__44u9_p1_0,
  151910. NULL,
  151911. 0
  151912. };
  151913. static long _vq_quantlist__44u9_p2_0[] = {
  151914. 2,
  151915. 1,
  151916. 3,
  151917. 0,
  151918. 4,
  151919. };
  151920. static long _vq_lengthlist__44u9_p2_0[] = {
  151921. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151922. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151923. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151924. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151925. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151926. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151927. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151928. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151929. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151930. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151931. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151932. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151933. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151934. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151935. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151936. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151937. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151938. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151939. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151940. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151941. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151942. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151943. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151944. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151945. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151946. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151947. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151948. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151949. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151950. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151951. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151952. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151953. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151954. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151955. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151956. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151957. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151958. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151959. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151960. 14,
  151961. };
  151962. static float _vq_quantthresh__44u9_p2_0[] = {
  151963. -1.5, -0.5, 0.5, 1.5,
  151964. };
  151965. static long _vq_quantmap__44u9_p2_0[] = {
  151966. 3, 1, 0, 2, 4,
  151967. };
  151968. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151969. _vq_quantthresh__44u9_p2_0,
  151970. _vq_quantmap__44u9_p2_0,
  151971. 5,
  151972. 5
  151973. };
  151974. static static_codebook _44u9_p2_0 = {
  151975. 4, 625,
  151976. _vq_lengthlist__44u9_p2_0,
  151977. 1, -533725184, 1611661312, 3, 0,
  151978. _vq_quantlist__44u9_p2_0,
  151979. NULL,
  151980. &_vq_auxt__44u9_p2_0,
  151981. NULL,
  151982. 0
  151983. };
  151984. static long _vq_quantlist__44u9_p3_0[] = {
  151985. 4,
  151986. 3,
  151987. 5,
  151988. 2,
  151989. 6,
  151990. 1,
  151991. 7,
  151992. 0,
  151993. 8,
  151994. };
  151995. static long _vq_lengthlist__44u9_p3_0[] = {
  151996. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151997. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151998. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151999. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152000. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152001. 11,
  152002. };
  152003. static float _vq_quantthresh__44u9_p3_0[] = {
  152004. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152005. };
  152006. static long _vq_quantmap__44u9_p3_0[] = {
  152007. 7, 5, 3, 1, 0, 2, 4, 6,
  152008. 8,
  152009. };
  152010. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152011. _vq_quantthresh__44u9_p3_0,
  152012. _vq_quantmap__44u9_p3_0,
  152013. 9,
  152014. 9
  152015. };
  152016. static static_codebook _44u9_p3_0 = {
  152017. 2, 81,
  152018. _vq_lengthlist__44u9_p3_0,
  152019. 1, -531628032, 1611661312, 4, 0,
  152020. _vq_quantlist__44u9_p3_0,
  152021. NULL,
  152022. &_vq_auxt__44u9_p3_0,
  152023. NULL,
  152024. 0
  152025. };
  152026. static long _vq_quantlist__44u9_p4_0[] = {
  152027. 8,
  152028. 7,
  152029. 9,
  152030. 6,
  152031. 10,
  152032. 5,
  152033. 11,
  152034. 4,
  152035. 12,
  152036. 3,
  152037. 13,
  152038. 2,
  152039. 14,
  152040. 1,
  152041. 15,
  152042. 0,
  152043. 16,
  152044. };
  152045. static long _vq_lengthlist__44u9_p4_0[] = {
  152046. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152047. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152048. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152049. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152050. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152051. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152052. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152053. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152054. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152055. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152056. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152057. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152058. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152059. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152060. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152061. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152062. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152063. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152064. 14,
  152065. };
  152066. static float _vq_quantthresh__44u9_p4_0[] = {
  152067. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152068. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152069. };
  152070. static long _vq_quantmap__44u9_p4_0[] = {
  152071. 15, 13, 11, 9, 7, 5, 3, 1,
  152072. 0, 2, 4, 6, 8, 10, 12, 14,
  152073. 16,
  152074. };
  152075. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152076. _vq_quantthresh__44u9_p4_0,
  152077. _vq_quantmap__44u9_p4_0,
  152078. 17,
  152079. 17
  152080. };
  152081. static static_codebook _44u9_p4_0 = {
  152082. 2, 289,
  152083. _vq_lengthlist__44u9_p4_0,
  152084. 1, -529530880, 1611661312, 5, 0,
  152085. _vq_quantlist__44u9_p4_0,
  152086. NULL,
  152087. &_vq_auxt__44u9_p4_0,
  152088. NULL,
  152089. 0
  152090. };
  152091. static long _vq_quantlist__44u9_p5_0[] = {
  152092. 1,
  152093. 0,
  152094. 2,
  152095. };
  152096. static long _vq_lengthlist__44u9_p5_0[] = {
  152097. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152098. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152099. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152100. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152101. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152102. 10,
  152103. };
  152104. static float _vq_quantthresh__44u9_p5_0[] = {
  152105. -5.5, 5.5,
  152106. };
  152107. static long _vq_quantmap__44u9_p5_0[] = {
  152108. 1, 0, 2,
  152109. };
  152110. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152111. _vq_quantthresh__44u9_p5_0,
  152112. _vq_quantmap__44u9_p5_0,
  152113. 3,
  152114. 3
  152115. };
  152116. static static_codebook _44u9_p5_0 = {
  152117. 4, 81,
  152118. _vq_lengthlist__44u9_p5_0,
  152119. 1, -529137664, 1618345984, 2, 0,
  152120. _vq_quantlist__44u9_p5_0,
  152121. NULL,
  152122. &_vq_auxt__44u9_p5_0,
  152123. NULL,
  152124. 0
  152125. };
  152126. static long _vq_quantlist__44u9_p5_1[] = {
  152127. 5,
  152128. 4,
  152129. 6,
  152130. 3,
  152131. 7,
  152132. 2,
  152133. 8,
  152134. 1,
  152135. 9,
  152136. 0,
  152137. 10,
  152138. };
  152139. static long _vq_lengthlist__44u9_p5_1[] = {
  152140. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152141. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152142. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152143. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152144. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152145. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152146. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152147. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152148. };
  152149. static float _vq_quantthresh__44u9_p5_1[] = {
  152150. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152151. 3.5, 4.5,
  152152. };
  152153. static long _vq_quantmap__44u9_p5_1[] = {
  152154. 9, 7, 5, 3, 1, 0, 2, 4,
  152155. 6, 8, 10,
  152156. };
  152157. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152158. _vq_quantthresh__44u9_p5_1,
  152159. _vq_quantmap__44u9_p5_1,
  152160. 11,
  152161. 11
  152162. };
  152163. static static_codebook _44u9_p5_1 = {
  152164. 2, 121,
  152165. _vq_lengthlist__44u9_p5_1,
  152166. 1, -531365888, 1611661312, 4, 0,
  152167. _vq_quantlist__44u9_p5_1,
  152168. NULL,
  152169. &_vq_auxt__44u9_p5_1,
  152170. NULL,
  152171. 0
  152172. };
  152173. static long _vq_quantlist__44u9_p6_0[] = {
  152174. 6,
  152175. 5,
  152176. 7,
  152177. 4,
  152178. 8,
  152179. 3,
  152180. 9,
  152181. 2,
  152182. 10,
  152183. 1,
  152184. 11,
  152185. 0,
  152186. 12,
  152187. };
  152188. static long _vq_lengthlist__44u9_p6_0[] = {
  152189. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152190. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152191. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152192. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152193. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152194. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152195. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152196. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152197. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152198. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152199. 10,11,11,11,11,12,11,12,12,
  152200. };
  152201. static float _vq_quantthresh__44u9_p6_0[] = {
  152202. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152203. 12.5, 17.5, 22.5, 27.5,
  152204. };
  152205. static long _vq_quantmap__44u9_p6_0[] = {
  152206. 11, 9, 7, 5, 3, 1, 0, 2,
  152207. 4, 6, 8, 10, 12,
  152208. };
  152209. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152210. _vq_quantthresh__44u9_p6_0,
  152211. _vq_quantmap__44u9_p6_0,
  152212. 13,
  152213. 13
  152214. };
  152215. static static_codebook _44u9_p6_0 = {
  152216. 2, 169,
  152217. _vq_lengthlist__44u9_p6_0,
  152218. 1, -526516224, 1616117760, 4, 0,
  152219. _vq_quantlist__44u9_p6_0,
  152220. NULL,
  152221. &_vq_auxt__44u9_p6_0,
  152222. NULL,
  152223. 0
  152224. };
  152225. static long _vq_quantlist__44u9_p6_1[] = {
  152226. 2,
  152227. 1,
  152228. 3,
  152229. 0,
  152230. 4,
  152231. };
  152232. static long _vq_lengthlist__44u9_p6_1[] = {
  152233. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152234. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152235. };
  152236. static float _vq_quantthresh__44u9_p6_1[] = {
  152237. -1.5, -0.5, 0.5, 1.5,
  152238. };
  152239. static long _vq_quantmap__44u9_p6_1[] = {
  152240. 3, 1, 0, 2, 4,
  152241. };
  152242. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152243. _vq_quantthresh__44u9_p6_1,
  152244. _vq_quantmap__44u9_p6_1,
  152245. 5,
  152246. 5
  152247. };
  152248. static static_codebook _44u9_p6_1 = {
  152249. 2, 25,
  152250. _vq_lengthlist__44u9_p6_1,
  152251. 1, -533725184, 1611661312, 3, 0,
  152252. _vq_quantlist__44u9_p6_1,
  152253. NULL,
  152254. &_vq_auxt__44u9_p6_1,
  152255. NULL,
  152256. 0
  152257. };
  152258. static long _vq_quantlist__44u9_p7_0[] = {
  152259. 6,
  152260. 5,
  152261. 7,
  152262. 4,
  152263. 8,
  152264. 3,
  152265. 9,
  152266. 2,
  152267. 10,
  152268. 1,
  152269. 11,
  152270. 0,
  152271. 12,
  152272. };
  152273. static long _vq_lengthlist__44u9_p7_0[] = {
  152274. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152275. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152276. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152277. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152278. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152279. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152280. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152281. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152282. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152283. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152284. 12,13,13,14,14,14,15,15,15,
  152285. };
  152286. static float _vq_quantthresh__44u9_p7_0[] = {
  152287. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152288. 27.5, 38.5, 49.5, 60.5,
  152289. };
  152290. static long _vq_quantmap__44u9_p7_0[] = {
  152291. 11, 9, 7, 5, 3, 1, 0, 2,
  152292. 4, 6, 8, 10, 12,
  152293. };
  152294. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152295. _vq_quantthresh__44u9_p7_0,
  152296. _vq_quantmap__44u9_p7_0,
  152297. 13,
  152298. 13
  152299. };
  152300. static static_codebook _44u9_p7_0 = {
  152301. 2, 169,
  152302. _vq_lengthlist__44u9_p7_0,
  152303. 1, -523206656, 1618345984, 4, 0,
  152304. _vq_quantlist__44u9_p7_0,
  152305. NULL,
  152306. &_vq_auxt__44u9_p7_0,
  152307. NULL,
  152308. 0
  152309. };
  152310. static long _vq_quantlist__44u9_p7_1[] = {
  152311. 5,
  152312. 4,
  152313. 6,
  152314. 3,
  152315. 7,
  152316. 2,
  152317. 8,
  152318. 1,
  152319. 9,
  152320. 0,
  152321. 10,
  152322. };
  152323. static long _vq_lengthlist__44u9_p7_1[] = {
  152324. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152325. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152326. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152327. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152328. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152329. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152330. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152331. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152332. };
  152333. static float _vq_quantthresh__44u9_p7_1[] = {
  152334. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152335. 3.5, 4.5,
  152336. };
  152337. static long _vq_quantmap__44u9_p7_1[] = {
  152338. 9, 7, 5, 3, 1, 0, 2, 4,
  152339. 6, 8, 10,
  152340. };
  152341. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152342. _vq_quantthresh__44u9_p7_1,
  152343. _vq_quantmap__44u9_p7_1,
  152344. 11,
  152345. 11
  152346. };
  152347. static static_codebook _44u9_p7_1 = {
  152348. 2, 121,
  152349. _vq_lengthlist__44u9_p7_1,
  152350. 1, -531365888, 1611661312, 4, 0,
  152351. _vq_quantlist__44u9_p7_1,
  152352. NULL,
  152353. &_vq_auxt__44u9_p7_1,
  152354. NULL,
  152355. 0
  152356. };
  152357. static long _vq_quantlist__44u9_p8_0[] = {
  152358. 7,
  152359. 6,
  152360. 8,
  152361. 5,
  152362. 9,
  152363. 4,
  152364. 10,
  152365. 3,
  152366. 11,
  152367. 2,
  152368. 12,
  152369. 1,
  152370. 13,
  152371. 0,
  152372. 14,
  152373. };
  152374. static long _vq_lengthlist__44u9_p8_0[] = {
  152375. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152376. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152377. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152378. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152379. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152380. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152381. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152382. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152383. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152384. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152385. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152386. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152387. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152388. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152389. 15,
  152390. };
  152391. static float _vq_quantthresh__44u9_p8_0[] = {
  152392. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152393. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152394. };
  152395. static long _vq_quantmap__44u9_p8_0[] = {
  152396. 13, 11, 9, 7, 5, 3, 1, 0,
  152397. 2, 4, 6, 8, 10, 12, 14,
  152398. };
  152399. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152400. _vq_quantthresh__44u9_p8_0,
  152401. _vq_quantmap__44u9_p8_0,
  152402. 15,
  152403. 15
  152404. };
  152405. static static_codebook _44u9_p8_0 = {
  152406. 2, 225,
  152407. _vq_lengthlist__44u9_p8_0,
  152408. 1, -520986624, 1620377600, 4, 0,
  152409. _vq_quantlist__44u9_p8_0,
  152410. NULL,
  152411. &_vq_auxt__44u9_p8_0,
  152412. NULL,
  152413. 0
  152414. };
  152415. static long _vq_quantlist__44u9_p8_1[] = {
  152416. 10,
  152417. 9,
  152418. 11,
  152419. 8,
  152420. 12,
  152421. 7,
  152422. 13,
  152423. 6,
  152424. 14,
  152425. 5,
  152426. 15,
  152427. 4,
  152428. 16,
  152429. 3,
  152430. 17,
  152431. 2,
  152432. 18,
  152433. 1,
  152434. 19,
  152435. 0,
  152436. 20,
  152437. };
  152438. static long _vq_lengthlist__44u9_p8_1[] = {
  152439. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152440. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152441. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152442. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152443. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152444. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152445. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152446. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152447. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152448. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152449. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152450. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152451. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152452. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152453. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152454. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152455. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152456. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152457. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152458. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152459. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152460. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152461. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152462. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152463. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152464. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152465. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152466. 10,10,10,10,10,10,10,10,10,
  152467. };
  152468. static float _vq_quantthresh__44u9_p8_1[] = {
  152469. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152470. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152471. 6.5, 7.5, 8.5, 9.5,
  152472. };
  152473. static long _vq_quantmap__44u9_p8_1[] = {
  152474. 19, 17, 15, 13, 11, 9, 7, 5,
  152475. 3, 1, 0, 2, 4, 6, 8, 10,
  152476. 12, 14, 16, 18, 20,
  152477. };
  152478. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152479. _vq_quantthresh__44u9_p8_1,
  152480. _vq_quantmap__44u9_p8_1,
  152481. 21,
  152482. 21
  152483. };
  152484. static static_codebook _44u9_p8_1 = {
  152485. 2, 441,
  152486. _vq_lengthlist__44u9_p8_1,
  152487. 1, -529268736, 1611661312, 5, 0,
  152488. _vq_quantlist__44u9_p8_1,
  152489. NULL,
  152490. &_vq_auxt__44u9_p8_1,
  152491. NULL,
  152492. 0
  152493. };
  152494. static long _vq_quantlist__44u9_p9_0[] = {
  152495. 7,
  152496. 6,
  152497. 8,
  152498. 5,
  152499. 9,
  152500. 4,
  152501. 10,
  152502. 3,
  152503. 11,
  152504. 2,
  152505. 12,
  152506. 1,
  152507. 13,
  152508. 0,
  152509. 14,
  152510. };
  152511. static long _vq_lengthlist__44u9_p9_0[] = {
  152512. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152513. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152514. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152515. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152516. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152517. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152518. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152519. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152520. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152521. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152522. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152523. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152524. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152526. 10,
  152527. };
  152528. static float _vq_quantthresh__44u9_p9_0[] = {
  152529. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152530. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152531. };
  152532. static long _vq_quantmap__44u9_p9_0[] = {
  152533. 13, 11, 9, 7, 5, 3, 1, 0,
  152534. 2, 4, 6, 8, 10, 12, 14,
  152535. };
  152536. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152537. _vq_quantthresh__44u9_p9_0,
  152538. _vq_quantmap__44u9_p9_0,
  152539. 15,
  152540. 15
  152541. };
  152542. static static_codebook _44u9_p9_0 = {
  152543. 2, 225,
  152544. _vq_lengthlist__44u9_p9_0,
  152545. 1, -510036736, 1631393792, 4, 0,
  152546. _vq_quantlist__44u9_p9_0,
  152547. NULL,
  152548. &_vq_auxt__44u9_p9_0,
  152549. NULL,
  152550. 0
  152551. };
  152552. static long _vq_quantlist__44u9_p9_1[] = {
  152553. 9,
  152554. 8,
  152555. 10,
  152556. 7,
  152557. 11,
  152558. 6,
  152559. 12,
  152560. 5,
  152561. 13,
  152562. 4,
  152563. 14,
  152564. 3,
  152565. 15,
  152566. 2,
  152567. 16,
  152568. 1,
  152569. 17,
  152570. 0,
  152571. 18,
  152572. };
  152573. static long _vq_lengthlist__44u9_p9_1[] = {
  152574. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152575. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152576. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152577. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152578. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152579. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152580. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152581. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152582. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152583. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152584. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152585. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152586. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152587. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152588. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152589. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152590. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152591. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152592. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152593. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152594. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152595. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152596. 17,17,15,17,15,17,16,16,17,
  152597. };
  152598. static float _vq_quantthresh__44u9_p9_1[] = {
  152599. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152600. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152601. 367.5, 416.5,
  152602. };
  152603. static long _vq_quantmap__44u9_p9_1[] = {
  152604. 17, 15, 13, 11, 9, 7, 5, 3,
  152605. 1, 0, 2, 4, 6, 8, 10, 12,
  152606. 14, 16, 18,
  152607. };
  152608. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152609. _vq_quantthresh__44u9_p9_1,
  152610. _vq_quantmap__44u9_p9_1,
  152611. 19,
  152612. 19
  152613. };
  152614. static static_codebook _44u9_p9_1 = {
  152615. 2, 361,
  152616. _vq_lengthlist__44u9_p9_1,
  152617. 1, -518287360, 1622704128, 5, 0,
  152618. _vq_quantlist__44u9_p9_1,
  152619. NULL,
  152620. &_vq_auxt__44u9_p9_1,
  152621. NULL,
  152622. 0
  152623. };
  152624. static long _vq_quantlist__44u9_p9_2[] = {
  152625. 24,
  152626. 23,
  152627. 25,
  152628. 22,
  152629. 26,
  152630. 21,
  152631. 27,
  152632. 20,
  152633. 28,
  152634. 19,
  152635. 29,
  152636. 18,
  152637. 30,
  152638. 17,
  152639. 31,
  152640. 16,
  152641. 32,
  152642. 15,
  152643. 33,
  152644. 14,
  152645. 34,
  152646. 13,
  152647. 35,
  152648. 12,
  152649. 36,
  152650. 11,
  152651. 37,
  152652. 10,
  152653. 38,
  152654. 9,
  152655. 39,
  152656. 8,
  152657. 40,
  152658. 7,
  152659. 41,
  152660. 6,
  152661. 42,
  152662. 5,
  152663. 43,
  152664. 4,
  152665. 44,
  152666. 3,
  152667. 45,
  152668. 2,
  152669. 46,
  152670. 1,
  152671. 47,
  152672. 0,
  152673. 48,
  152674. };
  152675. static long _vq_lengthlist__44u9_p9_2[] = {
  152676. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152677. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152678. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152679. 7,
  152680. };
  152681. static float _vq_quantthresh__44u9_p9_2[] = {
  152682. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152683. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152684. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152685. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152686. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152687. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152688. };
  152689. static long _vq_quantmap__44u9_p9_2[] = {
  152690. 47, 45, 43, 41, 39, 37, 35, 33,
  152691. 31, 29, 27, 25, 23, 21, 19, 17,
  152692. 15, 13, 11, 9, 7, 5, 3, 1,
  152693. 0, 2, 4, 6, 8, 10, 12, 14,
  152694. 16, 18, 20, 22, 24, 26, 28, 30,
  152695. 32, 34, 36, 38, 40, 42, 44, 46,
  152696. 48,
  152697. };
  152698. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152699. _vq_quantthresh__44u9_p9_2,
  152700. _vq_quantmap__44u9_p9_2,
  152701. 49,
  152702. 49
  152703. };
  152704. static static_codebook _44u9_p9_2 = {
  152705. 1, 49,
  152706. _vq_lengthlist__44u9_p9_2,
  152707. 1, -526909440, 1611661312, 6, 0,
  152708. _vq_quantlist__44u9_p9_2,
  152709. NULL,
  152710. &_vq_auxt__44u9_p9_2,
  152711. NULL,
  152712. 0
  152713. };
  152714. static long _huff_lengthlist__44un1__long[] = {
  152715. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152716. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152717. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152718. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152719. };
  152720. static static_codebook _huff_book__44un1__long = {
  152721. 2, 64,
  152722. _huff_lengthlist__44un1__long,
  152723. 0, 0, 0, 0, 0,
  152724. NULL,
  152725. NULL,
  152726. NULL,
  152727. NULL,
  152728. 0
  152729. };
  152730. static long _vq_quantlist__44un1__p1_0[] = {
  152731. 1,
  152732. 0,
  152733. 2,
  152734. };
  152735. static long _vq_lengthlist__44un1__p1_0[] = {
  152736. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152737. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152738. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152739. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152740. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152741. 12,
  152742. };
  152743. static float _vq_quantthresh__44un1__p1_0[] = {
  152744. -0.5, 0.5,
  152745. };
  152746. static long _vq_quantmap__44un1__p1_0[] = {
  152747. 1, 0, 2,
  152748. };
  152749. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152750. _vq_quantthresh__44un1__p1_0,
  152751. _vq_quantmap__44un1__p1_0,
  152752. 3,
  152753. 3
  152754. };
  152755. static static_codebook _44un1__p1_0 = {
  152756. 4, 81,
  152757. _vq_lengthlist__44un1__p1_0,
  152758. 1, -535822336, 1611661312, 2, 0,
  152759. _vq_quantlist__44un1__p1_0,
  152760. NULL,
  152761. &_vq_auxt__44un1__p1_0,
  152762. NULL,
  152763. 0
  152764. };
  152765. static long _vq_quantlist__44un1__p2_0[] = {
  152766. 1,
  152767. 0,
  152768. 2,
  152769. };
  152770. static long _vq_lengthlist__44un1__p2_0[] = {
  152771. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152772. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152773. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152774. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152775. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152776. 8,
  152777. };
  152778. static float _vq_quantthresh__44un1__p2_0[] = {
  152779. -0.5, 0.5,
  152780. };
  152781. static long _vq_quantmap__44un1__p2_0[] = {
  152782. 1, 0, 2,
  152783. };
  152784. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152785. _vq_quantthresh__44un1__p2_0,
  152786. _vq_quantmap__44un1__p2_0,
  152787. 3,
  152788. 3
  152789. };
  152790. static static_codebook _44un1__p2_0 = {
  152791. 4, 81,
  152792. _vq_lengthlist__44un1__p2_0,
  152793. 1, -535822336, 1611661312, 2, 0,
  152794. _vq_quantlist__44un1__p2_0,
  152795. NULL,
  152796. &_vq_auxt__44un1__p2_0,
  152797. NULL,
  152798. 0
  152799. };
  152800. static long _vq_quantlist__44un1__p3_0[] = {
  152801. 2,
  152802. 1,
  152803. 3,
  152804. 0,
  152805. 4,
  152806. };
  152807. static long _vq_lengthlist__44un1__p3_0[] = {
  152808. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152809. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152810. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152811. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152812. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152813. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152814. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152815. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152816. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152817. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152818. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152819. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152820. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152821. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152822. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152823. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152824. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152825. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152826. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152827. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152828. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152829. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152830. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152831. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152832. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152833. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152834. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152835. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152836. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152837. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152838. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152839. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152840. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152841. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152842. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152843. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152844. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152845. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152846. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152847. 17,
  152848. };
  152849. static float _vq_quantthresh__44un1__p3_0[] = {
  152850. -1.5, -0.5, 0.5, 1.5,
  152851. };
  152852. static long _vq_quantmap__44un1__p3_0[] = {
  152853. 3, 1, 0, 2, 4,
  152854. };
  152855. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152856. _vq_quantthresh__44un1__p3_0,
  152857. _vq_quantmap__44un1__p3_0,
  152858. 5,
  152859. 5
  152860. };
  152861. static static_codebook _44un1__p3_0 = {
  152862. 4, 625,
  152863. _vq_lengthlist__44un1__p3_0,
  152864. 1, -533725184, 1611661312, 3, 0,
  152865. _vq_quantlist__44un1__p3_0,
  152866. NULL,
  152867. &_vq_auxt__44un1__p3_0,
  152868. NULL,
  152869. 0
  152870. };
  152871. static long _vq_quantlist__44un1__p4_0[] = {
  152872. 2,
  152873. 1,
  152874. 3,
  152875. 0,
  152876. 4,
  152877. };
  152878. static long _vq_lengthlist__44un1__p4_0[] = {
  152879. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152880. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152881. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152882. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152883. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152884. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152885. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152886. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152887. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152888. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152889. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152890. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152891. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152892. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152893. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152894. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152895. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152896. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152897. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152898. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152899. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152900. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152901. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152902. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152903. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152904. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152905. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152906. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152907. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152908. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152909. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152910. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152911. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152912. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152913. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152914. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152915. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152916. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152917. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152918. 12,
  152919. };
  152920. static float _vq_quantthresh__44un1__p4_0[] = {
  152921. -1.5, -0.5, 0.5, 1.5,
  152922. };
  152923. static long _vq_quantmap__44un1__p4_0[] = {
  152924. 3, 1, 0, 2, 4,
  152925. };
  152926. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152927. _vq_quantthresh__44un1__p4_0,
  152928. _vq_quantmap__44un1__p4_0,
  152929. 5,
  152930. 5
  152931. };
  152932. static static_codebook _44un1__p4_0 = {
  152933. 4, 625,
  152934. _vq_lengthlist__44un1__p4_0,
  152935. 1, -533725184, 1611661312, 3, 0,
  152936. _vq_quantlist__44un1__p4_0,
  152937. NULL,
  152938. &_vq_auxt__44un1__p4_0,
  152939. NULL,
  152940. 0
  152941. };
  152942. static long _vq_quantlist__44un1__p5_0[] = {
  152943. 4,
  152944. 3,
  152945. 5,
  152946. 2,
  152947. 6,
  152948. 1,
  152949. 7,
  152950. 0,
  152951. 8,
  152952. };
  152953. static long _vq_lengthlist__44un1__p5_0[] = {
  152954. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152955. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152956. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152957. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152958. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152959. 12,
  152960. };
  152961. static float _vq_quantthresh__44un1__p5_0[] = {
  152962. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152963. };
  152964. static long _vq_quantmap__44un1__p5_0[] = {
  152965. 7, 5, 3, 1, 0, 2, 4, 6,
  152966. 8,
  152967. };
  152968. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152969. _vq_quantthresh__44un1__p5_0,
  152970. _vq_quantmap__44un1__p5_0,
  152971. 9,
  152972. 9
  152973. };
  152974. static static_codebook _44un1__p5_0 = {
  152975. 2, 81,
  152976. _vq_lengthlist__44un1__p5_0,
  152977. 1, -531628032, 1611661312, 4, 0,
  152978. _vq_quantlist__44un1__p5_0,
  152979. NULL,
  152980. &_vq_auxt__44un1__p5_0,
  152981. NULL,
  152982. 0
  152983. };
  152984. static long _vq_quantlist__44un1__p6_0[] = {
  152985. 6,
  152986. 5,
  152987. 7,
  152988. 4,
  152989. 8,
  152990. 3,
  152991. 9,
  152992. 2,
  152993. 10,
  152994. 1,
  152995. 11,
  152996. 0,
  152997. 12,
  152998. };
  152999. static long _vq_lengthlist__44un1__p6_0[] = {
  153000. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153001. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153002. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153003. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153004. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153005. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153006. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153007. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153008. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153009. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153010. 16, 0,15,18,18, 0,16, 0, 0,
  153011. };
  153012. static float _vq_quantthresh__44un1__p6_0[] = {
  153013. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153014. 12.5, 17.5, 22.5, 27.5,
  153015. };
  153016. static long _vq_quantmap__44un1__p6_0[] = {
  153017. 11, 9, 7, 5, 3, 1, 0, 2,
  153018. 4, 6, 8, 10, 12,
  153019. };
  153020. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153021. _vq_quantthresh__44un1__p6_0,
  153022. _vq_quantmap__44un1__p6_0,
  153023. 13,
  153024. 13
  153025. };
  153026. static static_codebook _44un1__p6_0 = {
  153027. 2, 169,
  153028. _vq_lengthlist__44un1__p6_0,
  153029. 1, -526516224, 1616117760, 4, 0,
  153030. _vq_quantlist__44un1__p6_0,
  153031. NULL,
  153032. &_vq_auxt__44un1__p6_0,
  153033. NULL,
  153034. 0
  153035. };
  153036. static long _vq_quantlist__44un1__p6_1[] = {
  153037. 2,
  153038. 1,
  153039. 3,
  153040. 0,
  153041. 4,
  153042. };
  153043. static long _vq_lengthlist__44un1__p6_1[] = {
  153044. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153045. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153046. };
  153047. static float _vq_quantthresh__44un1__p6_1[] = {
  153048. -1.5, -0.5, 0.5, 1.5,
  153049. };
  153050. static long _vq_quantmap__44un1__p6_1[] = {
  153051. 3, 1, 0, 2, 4,
  153052. };
  153053. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153054. _vq_quantthresh__44un1__p6_1,
  153055. _vq_quantmap__44un1__p6_1,
  153056. 5,
  153057. 5
  153058. };
  153059. static static_codebook _44un1__p6_1 = {
  153060. 2, 25,
  153061. _vq_lengthlist__44un1__p6_1,
  153062. 1, -533725184, 1611661312, 3, 0,
  153063. _vq_quantlist__44un1__p6_1,
  153064. NULL,
  153065. &_vq_auxt__44un1__p6_1,
  153066. NULL,
  153067. 0
  153068. };
  153069. static long _vq_quantlist__44un1__p7_0[] = {
  153070. 2,
  153071. 1,
  153072. 3,
  153073. 0,
  153074. 4,
  153075. };
  153076. static long _vq_lengthlist__44un1__p7_0[] = {
  153077. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153078. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153079. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153080. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153081. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153082. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153083. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153084. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153085. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153086. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153087. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153088. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153089. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153090. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153091. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153092. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153094. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153098. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153099. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153100. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153101. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153102. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153103. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153104. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153105. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153106. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153107. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153108. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153109. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153110. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153111. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153112. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153113. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153114. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153115. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153116. 10,
  153117. };
  153118. static float _vq_quantthresh__44un1__p7_0[] = {
  153119. -253.5, -84.5, 84.5, 253.5,
  153120. };
  153121. static long _vq_quantmap__44un1__p7_0[] = {
  153122. 3, 1, 0, 2, 4,
  153123. };
  153124. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153125. _vq_quantthresh__44un1__p7_0,
  153126. _vq_quantmap__44un1__p7_0,
  153127. 5,
  153128. 5
  153129. };
  153130. static static_codebook _44un1__p7_0 = {
  153131. 4, 625,
  153132. _vq_lengthlist__44un1__p7_0,
  153133. 1, -518709248, 1626677248, 3, 0,
  153134. _vq_quantlist__44un1__p7_0,
  153135. NULL,
  153136. &_vq_auxt__44un1__p7_0,
  153137. NULL,
  153138. 0
  153139. };
  153140. static long _vq_quantlist__44un1__p7_1[] = {
  153141. 6,
  153142. 5,
  153143. 7,
  153144. 4,
  153145. 8,
  153146. 3,
  153147. 9,
  153148. 2,
  153149. 10,
  153150. 1,
  153151. 11,
  153152. 0,
  153153. 12,
  153154. };
  153155. static long _vq_lengthlist__44un1__p7_1[] = {
  153156. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153157. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153158. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153159. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153160. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153161. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153162. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153163. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153164. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153165. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153166. 12,13,13,12,13,13,14,14,14,
  153167. };
  153168. static float _vq_quantthresh__44un1__p7_1[] = {
  153169. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153170. 32.5, 45.5, 58.5, 71.5,
  153171. };
  153172. static long _vq_quantmap__44un1__p7_1[] = {
  153173. 11, 9, 7, 5, 3, 1, 0, 2,
  153174. 4, 6, 8, 10, 12,
  153175. };
  153176. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153177. _vq_quantthresh__44un1__p7_1,
  153178. _vq_quantmap__44un1__p7_1,
  153179. 13,
  153180. 13
  153181. };
  153182. static static_codebook _44un1__p7_1 = {
  153183. 2, 169,
  153184. _vq_lengthlist__44un1__p7_1,
  153185. 1, -523010048, 1618608128, 4, 0,
  153186. _vq_quantlist__44un1__p7_1,
  153187. NULL,
  153188. &_vq_auxt__44un1__p7_1,
  153189. NULL,
  153190. 0
  153191. };
  153192. static long _vq_quantlist__44un1__p7_2[] = {
  153193. 6,
  153194. 5,
  153195. 7,
  153196. 4,
  153197. 8,
  153198. 3,
  153199. 9,
  153200. 2,
  153201. 10,
  153202. 1,
  153203. 11,
  153204. 0,
  153205. 12,
  153206. };
  153207. static long _vq_lengthlist__44un1__p7_2[] = {
  153208. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153209. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153210. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153211. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153212. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153213. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153214. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153215. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153216. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153217. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153218. 9, 9, 9,10,10,10,10,10,10,
  153219. };
  153220. static float _vq_quantthresh__44un1__p7_2[] = {
  153221. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153222. 2.5, 3.5, 4.5, 5.5,
  153223. };
  153224. static long _vq_quantmap__44un1__p7_2[] = {
  153225. 11, 9, 7, 5, 3, 1, 0, 2,
  153226. 4, 6, 8, 10, 12,
  153227. };
  153228. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153229. _vq_quantthresh__44un1__p7_2,
  153230. _vq_quantmap__44un1__p7_2,
  153231. 13,
  153232. 13
  153233. };
  153234. static static_codebook _44un1__p7_2 = {
  153235. 2, 169,
  153236. _vq_lengthlist__44un1__p7_2,
  153237. 1, -531103744, 1611661312, 4, 0,
  153238. _vq_quantlist__44un1__p7_2,
  153239. NULL,
  153240. &_vq_auxt__44un1__p7_2,
  153241. NULL,
  153242. 0
  153243. };
  153244. static long _huff_lengthlist__44un1__short[] = {
  153245. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153246. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153247. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153248. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153249. };
  153250. static static_codebook _huff_book__44un1__short = {
  153251. 2, 64,
  153252. _huff_lengthlist__44un1__short,
  153253. 0, 0, 0, 0, 0,
  153254. NULL,
  153255. NULL,
  153256. NULL,
  153257. NULL,
  153258. 0
  153259. };
  153260. /*** End of inlined file: res_books_uncoupled.h ***/
  153261. /***** residue backends *********************************************/
  153262. static vorbis_info_residue0 _residue_44_low_un={
  153263. 0,-1, -1, 8,-1,
  153264. {0},
  153265. {-1},
  153266. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153267. { -1, 25, -1, 45, -1, -1, -1}
  153268. };
  153269. static vorbis_info_residue0 _residue_44_mid_un={
  153270. 0,-1, -1, 10,-1,
  153271. /* 0 1 2 3 4 5 6 7 8 9 */
  153272. {0},
  153273. {-1},
  153274. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153275. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153276. };
  153277. static vorbis_info_residue0 _residue_44_hi_un={
  153278. 0,-1, -1, 10,-1,
  153279. /* 0 1 2 3 4 5 6 7 8 9 */
  153280. {0},
  153281. {-1},
  153282. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153283. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153284. };
  153285. /* mapping conventions:
  153286. only one submap (this would change for efficient 5.1 support for example)*/
  153287. /* Four psychoacoustic profiles are used, one for each blocktype */
  153288. static vorbis_info_mapping0 _map_nominal_u[2]={
  153289. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153290. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153291. };
  153292. static static_bookblock _resbook_44u_n1={
  153293. {
  153294. {0},
  153295. {0,0,&_44un1__p1_0},
  153296. {0,0,&_44un1__p2_0},
  153297. {0,0,&_44un1__p3_0},
  153298. {0,0,&_44un1__p4_0},
  153299. {0,0,&_44un1__p5_0},
  153300. {&_44un1__p6_0,&_44un1__p6_1},
  153301. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153302. }
  153303. };
  153304. static static_bookblock _resbook_44u_0={
  153305. {
  153306. {0},
  153307. {0,0,&_44u0__p1_0},
  153308. {0,0,&_44u0__p2_0},
  153309. {0,0,&_44u0__p3_0},
  153310. {0,0,&_44u0__p4_0},
  153311. {0,0,&_44u0__p5_0},
  153312. {&_44u0__p6_0,&_44u0__p6_1},
  153313. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153314. }
  153315. };
  153316. static static_bookblock _resbook_44u_1={
  153317. {
  153318. {0},
  153319. {0,0,&_44u1__p1_0},
  153320. {0,0,&_44u1__p2_0},
  153321. {0,0,&_44u1__p3_0},
  153322. {0,0,&_44u1__p4_0},
  153323. {0,0,&_44u1__p5_0},
  153324. {&_44u1__p6_0,&_44u1__p6_1},
  153325. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153326. }
  153327. };
  153328. static static_bookblock _resbook_44u_2={
  153329. {
  153330. {0},
  153331. {0,0,&_44u2__p1_0},
  153332. {0,0,&_44u2__p2_0},
  153333. {0,0,&_44u2__p3_0},
  153334. {0,0,&_44u2__p4_0},
  153335. {0,0,&_44u2__p5_0},
  153336. {&_44u2__p6_0,&_44u2__p6_1},
  153337. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153338. }
  153339. };
  153340. static static_bookblock _resbook_44u_3={
  153341. {
  153342. {0},
  153343. {0,0,&_44u3__p1_0},
  153344. {0,0,&_44u3__p2_0},
  153345. {0,0,&_44u3__p3_0},
  153346. {0,0,&_44u3__p4_0},
  153347. {0,0,&_44u3__p5_0},
  153348. {&_44u3__p6_0,&_44u3__p6_1},
  153349. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153350. }
  153351. };
  153352. static static_bookblock _resbook_44u_4={
  153353. {
  153354. {0},
  153355. {0,0,&_44u4__p1_0},
  153356. {0,0,&_44u4__p2_0},
  153357. {0,0,&_44u4__p3_0},
  153358. {0,0,&_44u4__p4_0},
  153359. {0,0,&_44u4__p5_0},
  153360. {&_44u4__p6_0,&_44u4__p6_1},
  153361. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153362. }
  153363. };
  153364. static static_bookblock _resbook_44u_5={
  153365. {
  153366. {0},
  153367. {0,0,&_44u5__p1_0},
  153368. {0,0,&_44u5__p2_0},
  153369. {0,0,&_44u5__p3_0},
  153370. {0,0,&_44u5__p4_0},
  153371. {0,0,&_44u5__p5_0},
  153372. {0,0,&_44u5__p6_0},
  153373. {&_44u5__p7_0,&_44u5__p7_1},
  153374. {&_44u5__p8_0,&_44u5__p8_1},
  153375. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153376. }
  153377. };
  153378. static static_bookblock _resbook_44u_6={
  153379. {
  153380. {0},
  153381. {0,0,&_44u6__p1_0},
  153382. {0,0,&_44u6__p2_0},
  153383. {0,0,&_44u6__p3_0},
  153384. {0,0,&_44u6__p4_0},
  153385. {0,0,&_44u6__p5_0},
  153386. {0,0,&_44u6__p6_0},
  153387. {&_44u6__p7_0,&_44u6__p7_1},
  153388. {&_44u6__p8_0,&_44u6__p8_1},
  153389. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153390. }
  153391. };
  153392. static static_bookblock _resbook_44u_7={
  153393. {
  153394. {0},
  153395. {0,0,&_44u7__p1_0},
  153396. {0,0,&_44u7__p2_0},
  153397. {0,0,&_44u7__p3_0},
  153398. {0,0,&_44u7__p4_0},
  153399. {0,0,&_44u7__p5_0},
  153400. {0,0,&_44u7__p6_0},
  153401. {&_44u7__p7_0,&_44u7__p7_1},
  153402. {&_44u7__p8_0,&_44u7__p8_1},
  153403. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153404. }
  153405. };
  153406. static static_bookblock _resbook_44u_8={
  153407. {
  153408. {0},
  153409. {0,0,&_44u8_p1_0},
  153410. {0,0,&_44u8_p2_0},
  153411. {0,0,&_44u8_p3_0},
  153412. {0,0,&_44u8_p4_0},
  153413. {&_44u8_p5_0,&_44u8_p5_1},
  153414. {&_44u8_p6_0,&_44u8_p6_1},
  153415. {&_44u8_p7_0,&_44u8_p7_1},
  153416. {&_44u8_p8_0,&_44u8_p8_1},
  153417. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153418. }
  153419. };
  153420. static static_bookblock _resbook_44u_9={
  153421. {
  153422. {0},
  153423. {0,0,&_44u9_p1_0},
  153424. {0,0,&_44u9_p2_0},
  153425. {0,0,&_44u9_p3_0},
  153426. {0,0,&_44u9_p4_0},
  153427. {&_44u9_p5_0,&_44u9_p5_1},
  153428. {&_44u9_p6_0,&_44u9_p6_1},
  153429. {&_44u9_p7_0,&_44u9_p7_1},
  153430. {&_44u9_p8_0,&_44u9_p8_1},
  153431. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153432. }
  153433. };
  153434. static vorbis_residue_template _res_44u_n1[]={
  153435. {1,0, &_residue_44_low_un,
  153436. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153437. &_resbook_44u_n1,&_resbook_44u_n1},
  153438. {1,0, &_residue_44_low_un,
  153439. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153440. &_resbook_44u_n1,&_resbook_44u_n1}
  153441. };
  153442. static vorbis_residue_template _res_44u_0[]={
  153443. {1,0, &_residue_44_low_un,
  153444. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153445. &_resbook_44u_0,&_resbook_44u_0},
  153446. {1,0, &_residue_44_low_un,
  153447. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153448. &_resbook_44u_0,&_resbook_44u_0}
  153449. };
  153450. static vorbis_residue_template _res_44u_1[]={
  153451. {1,0, &_residue_44_low_un,
  153452. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153453. &_resbook_44u_1,&_resbook_44u_1},
  153454. {1,0, &_residue_44_low_un,
  153455. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153456. &_resbook_44u_1,&_resbook_44u_1}
  153457. };
  153458. static vorbis_residue_template _res_44u_2[]={
  153459. {1,0, &_residue_44_low_un,
  153460. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153461. &_resbook_44u_2,&_resbook_44u_2},
  153462. {1,0, &_residue_44_low_un,
  153463. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153464. &_resbook_44u_2,&_resbook_44u_2}
  153465. };
  153466. static vorbis_residue_template _res_44u_3[]={
  153467. {1,0, &_residue_44_low_un,
  153468. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153469. &_resbook_44u_3,&_resbook_44u_3},
  153470. {1,0, &_residue_44_low_un,
  153471. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153472. &_resbook_44u_3,&_resbook_44u_3}
  153473. };
  153474. static vorbis_residue_template _res_44u_4[]={
  153475. {1,0, &_residue_44_low_un,
  153476. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153477. &_resbook_44u_4,&_resbook_44u_4},
  153478. {1,0, &_residue_44_low_un,
  153479. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153480. &_resbook_44u_4,&_resbook_44u_4}
  153481. };
  153482. static vorbis_residue_template _res_44u_5[]={
  153483. {1,0, &_residue_44_mid_un,
  153484. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153485. &_resbook_44u_5,&_resbook_44u_5},
  153486. {1,0, &_residue_44_mid_un,
  153487. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153488. &_resbook_44u_5,&_resbook_44u_5}
  153489. };
  153490. static vorbis_residue_template _res_44u_6[]={
  153491. {1,0, &_residue_44_mid_un,
  153492. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153493. &_resbook_44u_6,&_resbook_44u_6},
  153494. {1,0, &_residue_44_mid_un,
  153495. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153496. &_resbook_44u_6,&_resbook_44u_6}
  153497. };
  153498. static vorbis_residue_template _res_44u_7[]={
  153499. {1,0, &_residue_44_mid_un,
  153500. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153501. &_resbook_44u_7,&_resbook_44u_7},
  153502. {1,0, &_residue_44_mid_un,
  153503. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153504. &_resbook_44u_7,&_resbook_44u_7}
  153505. };
  153506. static vorbis_residue_template _res_44u_8[]={
  153507. {1,0, &_residue_44_hi_un,
  153508. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153509. &_resbook_44u_8,&_resbook_44u_8},
  153510. {1,0, &_residue_44_hi_un,
  153511. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153512. &_resbook_44u_8,&_resbook_44u_8}
  153513. };
  153514. static vorbis_residue_template _res_44u_9[]={
  153515. {1,0, &_residue_44_hi_un,
  153516. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153517. &_resbook_44u_9,&_resbook_44u_9},
  153518. {1,0, &_residue_44_hi_un,
  153519. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153520. &_resbook_44u_9,&_resbook_44u_9}
  153521. };
  153522. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153523. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153524. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153525. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153526. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153527. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153528. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153529. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153530. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153531. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153532. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153533. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153534. };
  153535. /*** End of inlined file: residue_44u.h ***/
  153536. static double rate_mapping_44_un[12]={
  153537. 32000.,48000.,60000.,70000.,80000.,86000.,
  153538. 96000.,110000.,120000.,140000.,160000.,240001.
  153539. };
  153540. ve_setup_data_template ve_setup_44_uncoupled={
  153541. 11,
  153542. rate_mapping_44_un,
  153543. quality_mapping_44,
  153544. -1,
  153545. 40000,
  153546. 50000,
  153547. blocksize_short_44,
  153548. blocksize_long_44,
  153549. _psy_tone_masteratt_44,
  153550. _psy_tone_0dB,
  153551. _psy_tone_suppress,
  153552. _vp_tonemask_adj_otherblock,
  153553. _vp_tonemask_adj_longblock,
  153554. _vp_tonemask_adj_otherblock,
  153555. _psy_noiseguards_44,
  153556. _psy_noisebias_impulse,
  153557. _psy_noisebias_padding,
  153558. _psy_noisebias_trans,
  153559. _psy_noisebias_long,
  153560. _psy_noise_suppress,
  153561. _psy_compand_44,
  153562. _psy_compand_short_mapping,
  153563. _psy_compand_long_mapping,
  153564. {_noise_start_short_44,_noise_start_long_44},
  153565. {_noise_part_short_44,_noise_part_long_44},
  153566. _noise_thresh_44,
  153567. _psy_ath_floater,
  153568. _psy_ath_abs,
  153569. _psy_lowpass_44,
  153570. _psy_global_44,
  153571. _global_mapping_44,
  153572. NULL,
  153573. _floor_books,
  153574. _floor,
  153575. _floor_short_mapping_44,
  153576. _floor_long_mapping_44,
  153577. _mapres_template_44_uncoupled
  153578. };
  153579. /*** End of inlined file: setup_44u.h ***/
  153580. /*** Start of inlined file: setup_32.h ***/
  153581. static double rate_mapping_32[12]={
  153582. 18000.,28000.,35000.,45000.,56000.,60000.,
  153583. 75000.,90000.,100000.,115000.,150000.,190000.,
  153584. };
  153585. static double rate_mapping_32_un[12]={
  153586. 30000.,42000.,52000.,64000.,72000.,78000.,
  153587. 86000.,92000.,110000.,120000.,140000.,190000.,
  153588. };
  153589. static double _psy_lowpass_32[12]={
  153590. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153591. };
  153592. ve_setup_data_template ve_setup_32_stereo={
  153593. 11,
  153594. rate_mapping_32,
  153595. quality_mapping_44,
  153596. 2,
  153597. 26000,
  153598. 40000,
  153599. blocksize_short_44,
  153600. blocksize_long_44,
  153601. _psy_tone_masteratt_44,
  153602. _psy_tone_0dB,
  153603. _psy_tone_suppress,
  153604. _vp_tonemask_adj_otherblock,
  153605. _vp_tonemask_adj_longblock,
  153606. _vp_tonemask_adj_otherblock,
  153607. _psy_noiseguards_44,
  153608. _psy_noisebias_impulse,
  153609. _psy_noisebias_padding,
  153610. _psy_noisebias_trans,
  153611. _psy_noisebias_long,
  153612. _psy_noise_suppress,
  153613. _psy_compand_44,
  153614. _psy_compand_short_mapping,
  153615. _psy_compand_long_mapping,
  153616. {_noise_start_short_44,_noise_start_long_44},
  153617. {_noise_part_short_44,_noise_part_long_44},
  153618. _noise_thresh_44,
  153619. _psy_ath_floater,
  153620. _psy_ath_abs,
  153621. _psy_lowpass_32,
  153622. _psy_global_44,
  153623. _global_mapping_44,
  153624. _psy_stereo_modes_44,
  153625. _floor_books,
  153626. _floor,
  153627. _floor_short_mapping_44,
  153628. _floor_long_mapping_44,
  153629. _mapres_template_44_stereo
  153630. };
  153631. ve_setup_data_template ve_setup_32_uncoupled={
  153632. 11,
  153633. rate_mapping_32_un,
  153634. quality_mapping_44,
  153635. -1,
  153636. 26000,
  153637. 40000,
  153638. blocksize_short_44,
  153639. blocksize_long_44,
  153640. _psy_tone_masteratt_44,
  153641. _psy_tone_0dB,
  153642. _psy_tone_suppress,
  153643. _vp_tonemask_adj_otherblock,
  153644. _vp_tonemask_adj_longblock,
  153645. _vp_tonemask_adj_otherblock,
  153646. _psy_noiseguards_44,
  153647. _psy_noisebias_impulse,
  153648. _psy_noisebias_padding,
  153649. _psy_noisebias_trans,
  153650. _psy_noisebias_long,
  153651. _psy_noise_suppress,
  153652. _psy_compand_44,
  153653. _psy_compand_short_mapping,
  153654. _psy_compand_long_mapping,
  153655. {_noise_start_short_44,_noise_start_long_44},
  153656. {_noise_part_short_44,_noise_part_long_44},
  153657. _noise_thresh_44,
  153658. _psy_ath_floater,
  153659. _psy_ath_abs,
  153660. _psy_lowpass_32,
  153661. _psy_global_44,
  153662. _global_mapping_44,
  153663. NULL,
  153664. _floor_books,
  153665. _floor,
  153666. _floor_short_mapping_44,
  153667. _floor_long_mapping_44,
  153668. _mapres_template_44_uncoupled
  153669. };
  153670. /*** End of inlined file: setup_32.h ***/
  153671. /*** Start of inlined file: setup_8.h ***/
  153672. /*** Start of inlined file: psych_8.h ***/
  153673. static att3 _psy_tone_masteratt_8[3]={
  153674. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153675. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153676. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153677. };
  153678. static vp_adjblock _vp_tonemask_adj_8[3]={
  153679. /* adjust for mode zero */
  153680. /* 63 125 250 500 1 2 4 8 16 */
  153681. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153682. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153683. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153684. };
  153685. static noise3 _psy_noisebias_8[3]={
  153686. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153687. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153688. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153689. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153690. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153691. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153692. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153693. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153694. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153695. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153696. };
  153697. /* stereo mode by base quality level */
  153698. static adj_stereo _psy_stereo_modes_8[3]={
  153699. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153700. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153701. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153702. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153703. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153704. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153705. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153706. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153707. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153708. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153709. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153710. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153711. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153712. };
  153713. static noiseguard _psy_noiseguards_8[2]={
  153714. {10,10,-1},
  153715. {10,10,-1},
  153716. };
  153717. static compandblock _psy_compand_8[2]={
  153718. {{
  153719. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153720. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153721. 12,12,13,13,14,14,15, 15, /* 23dB */
  153722. 16,16,17,17,17,18,18, 19, /* 31dB */
  153723. 19,19,20,21,22,23,24, 25, /* 39dB */
  153724. }},
  153725. {{
  153726. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153727. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153728. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153729. 9,10,11,12,13,14,15, 16, /* 31dB */
  153730. 17,18,19,20,21,22,23, 24, /* 39dB */
  153731. }},
  153732. };
  153733. static double _psy_lowpass_8[3]={3.,4.,4.};
  153734. static int _noise_start_8[2]={
  153735. 64,64,
  153736. };
  153737. static int _noise_part_8[2]={
  153738. 8,8,
  153739. };
  153740. static int _psy_ath_floater_8[3]={
  153741. -100,-100,-105,
  153742. };
  153743. static int _psy_ath_abs_8[3]={
  153744. -130,-130,-140,
  153745. };
  153746. /*** End of inlined file: psych_8.h ***/
  153747. /*** Start of inlined file: residue_8.h ***/
  153748. /***** residue backends *********************************************/
  153749. static static_bookblock _resbook_8s_0={
  153750. {
  153751. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153752. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153753. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153754. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153755. }
  153756. };
  153757. static static_bookblock _resbook_8s_1={
  153758. {
  153759. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153760. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153761. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153762. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153763. }
  153764. };
  153765. static vorbis_residue_template _res_8s_0[]={
  153766. {2,0, &_residue_44_mid,
  153767. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153768. &_resbook_8s_0,&_resbook_8s_0},
  153769. };
  153770. static vorbis_residue_template _res_8s_1[]={
  153771. {2,0, &_residue_44_mid,
  153772. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153773. &_resbook_8s_1,&_resbook_8s_1},
  153774. };
  153775. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153776. { _map_nominal, _res_8s_0 }, /* 0 */
  153777. { _map_nominal, _res_8s_1 }, /* 1 */
  153778. };
  153779. static static_bookblock _resbook_8u_0={
  153780. {
  153781. {0},
  153782. {0,0,&_8u0__p1_0},
  153783. {0,0,&_8u0__p2_0},
  153784. {0,0,&_8u0__p3_0},
  153785. {0,0,&_8u0__p4_0},
  153786. {0,0,&_8u0__p5_0},
  153787. {&_8u0__p6_0,&_8u0__p6_1},
  153788. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153789. }
  153790. };
  153791. static static_bookblock _resbook_8u_1={
  153792. {
  153793. {0},
  153794. {0,0,&_8u1__p1_0},
  153795. {0,0,&_8u1__p2_0},
  153796. {0,0,&_8u1__p3_0},
  153797. {0,0,&_8u1__p4_0},
  153798. {0,0,&_8u1__p5_0},
  153799. {0,0,&_8u1__p6_0},
  153800. {&_8u1__p7_0,&_8u1__p7_1},
  153801. {&_8u1__p8_0,&_8u1__p8_1},
  153802. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153803. }
  153804. };
  153805. static vorbis_residue_template _res_8u_0[]={
  153806. {1,0, &_residue_44_low_un,
  153807. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153808. &_resbook_8u_0,&_resbook_8u_0},
  153809. };
  153810. static vorbis_residue_template _res_8u_1[]={
  153811. {1,0, &_residue_44_mid_un,
  153812. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153813. &_resbook_8u_1,&_resbook_8u_1},
  153814. };
  153815. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153816. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153817. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153818. };
  153819. /*** End of inlined file: residue_8.h ***/
  153820. static int blocksize_8[2]={
  153821. 512,512
  153822. };
  153823. static int _floor_mapping_8[2]={
  153824. 6,6,
  153825. };
  153826. static double rate_mapping_8[3]={
  153827. 6000.,9000.,32000.,
  153828. };
  153829. static double rate_mapping_8_uncoupled[3]={
  153830. 8000.,14000.,42000.,
  153831. };
  153832. static double quality_mapping_8[3]={
  153833. -.1,.0,1.
  153834. };
  153835. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153836. static double _global_mapping_8[3]={ 1., 2., 3. };
  153837. ve_setup_data_template ve_setup_8_stereo={
  153838. 2,
  153839. rate_mapping_8,
  153840. quality_mapping_8,
  153841. 2,
  153842. 8000,
  153843. 9000,
  153844. blocksize_8,
  153845. blocksize_8,
  153846. _psy_tone_masteratt_8,
  153847. _psy_tone_0dB,
  153848. _psy_tone_suppress,
  153849. _vp_tonemask_adj_8,
  153850. NULL,
  153851. _vp_tonemask_adj_8,
  153852. _psy_noiseguards_8,
  153853. _psy_noisebias_8,
  153854. _psy_noisebias_8,
  153855. NULL,
  153856. NULL,
  153857. _psy_noise_suppress,
  153858. _psy_compand_8,
  153859. _psy_compand_8_mapping,
  153860. NULL,
  153861. {_noise_start_8,_noise_start_8},
  153862. {_noise_part_8,_noise_part_8},
  153863. _noise_thresh_5only,
  153864. _psy_ath_floater_8,
  153865. _psy_ath_abs_8,
  153866. _psy_lowpass_8,
  153867. _psy_global_44,
  153868. _global_mapping_8,
  153869. _psy_stereo_modes_8,
  153870. _floor_books,
  153871. _floor,
  153872. _floor_mapping_8,
  153873. NULL,
  153874. _mapres_template_8_stereo
  153875. };
  153876. ve_setup_data_template ve_setup_8_uncoupled={
  153877. 2,
  153878. rate_mapping_8_uncoupled,
  153879. quality_mapping_8,
  153880. -1,
  153881. 8000,
  153882. 9000,
  153883. blocksize_8,
  153884. blocksize_8,
  153885. _psy_tone_masteratt_8,
  153886. _psy_tone_0dB,
  153887. _psy_tone_suppress,
  153888. _vp_tonemask_adj_8,
  153889. NULL,
  153890. _vp_tonemask_adj_8,
  153891. _psy_noiseguards_8,
  153892. _psy_noisebias_8,
  153893. _psy_noisebias_8,
  153894. NULL,
  153895. NULL,
  153896. _psy_noise_suppress,
  153897. _psy_compand_8,
  153898. _psy_compand_8_mapping,
  153899. NULL,
  153900. {_noise_start_8,_noise_start_8},
  153901. {_noise_part_8,_noise_part_8},
  153902. _noise_thresh_5only,
  153903. _psy_ath_floater_8,
  153904. _psy_ath_abs_8,
  153905. _psy_lowpass_8,
  153906. _psy_global_44,
  153907. _global_mapping_8,
  153908. _psy_stereo_modes_8,
  153909. _floor_books,
  153910. _floor,
  153911. _floor_mapping_8,
  153912. NULL,
  153913. _mapres_template_8_uncoupled
  153914. };
  153915. /*** End of inlined file: setup_8.h ***/
  153916. /*** Start of inlined file: setup_11.h ***/
  153917. /*** Start of inlined file: psych_11.h ***/
  153918. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153919. static att3 _psy_tone_masteratt_11[3]={
  153920. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153921. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153922. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153923. };
  153924. static vp_adjblock _vp_tonemask_adj_11[3]={
  153925. /* adjust for mode zero */
  153926. /* 63 125 250 500 1 2 4 8 16 */
  153927. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153928. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153929. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153930. };
  153931. static noise3 _psy_noisebias_11[3]={
  153932. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153933. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153934. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153935. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153936. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153937. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153938. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153939. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153940. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153941. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153942. };
  153943. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153944. /*** End of inlined file: psych_11.h ***/
  153945. static int blocksize_11[2]={
  153946. 512,512
  153947. };
  153948. static int _floor_mapping_11[2]={
  153949. 6,6,
  153950. };
  153951. static double rate_mapping_11[3]={
  153952. 8000.,13000.,44000.,
  153953. };
  153954. static double rate_mapping_11_uncoupled[3]={
  153955. 12000.,20000.,50000.,
  153956. };
  153957. static double quality_mapping_11[3]={
  153958. -.1,.0,1.
  153959. };
  153960. ve_setup_data_template ve_setup_11_stereo={
  153961. 2,
  153962. rate_mapping_11,
  153963. quality_mapping_11,
  153964. 2,
  153965. 9000,
  153966. 15000,
  153967. blocksize_11,
  153968. blocksize_11,
  153969. _psy_tone_masteratt_11,
  153970. _psy_tone_0dB,
  153971. _psy_tone_suppress,
  153972. _vp_tonemask_adj_11,
  153973. NULL,
  153974. _vp_tonemask_adj_11,
  153975. _psy_noiseguards_8,
  153976. _psy_noisebias_11,
  153977. _psy_noisebias_11,
  153978. NULL,
  153979. NULL,
  153980. _psy_noise_suppress,
  153981. _psy_compand_8,
  153982. _psy_compand_8_mapping,
  153983. NULL,
  153984. {_noise_start_8,_noise_start_8},
  153985. {_noise_part_8,_noise_part_8},
  153986. _noise_thresh_11,
  153987. _psy_ath_floater_8,
  153988. _psy_ath_abs_8,
  153989. _psy_lowpass_11,
  153990. _psy_global_44,
  153991. _global_mapping_8,
  153992. _psy_stereo_modes_8,
  153993. _floor_books,
  153994. _floor,
  153995. _floor_mapping_11,
  153996. NULL,
  153997. _mapres_template_8_stereo
  153998. };
  153999. ve_setup_data_template ve_setup_11_uncoupled={
  154000. 2,
  154001. rate_mapping_11_uncoupled,
  154002. quality_mapping_11,
  154003. -1,
  154004. 9000,
  154005. 15000,
  154006. blocksize_11,
  154007. blocksize_11,
  154008. _psy_tone_masteratt_11,
  154009. _psy_tone_0dB,
  154010. _psy_tone_suppress,
  154011. _vp_tonemask_adj_11,
  154012. NULL,
  154013. _vp_tonemask_adj_11,
  154014. _psy_noiseguards_8,
  154015. _psy_noisebias_11,
  154016. _psy_noisebias_11,
  154017. NULL,
  154018. NULL,
  154019. _psy_noise_suppress,
  154020. _psy_compand_8,
  154021. _psy_compand_8_mapping,
  154022. NULL,
  154023. {_noise_start_8,_noise_start_8},
  154024. {_noise_part_8,_noise_part_8},
  154025. _noise_thresh_11,
  154026. _psy_ath_floater_8,
  154027. _psy_ath_abs_8,
  154028. _psy_lowpass_11,
  154029. _psy_global_44,
  154030. _global_mapping_8,
  154031. _psy_stereo_modes_8,
  154032. _floor_books,
  154033. _floor,
  154034. _floor_mapping_11,
  154035. NULL,
  154036. _mapres_template_8_uncoupled
  154037. };
  154038. /*** End of inlined file: setup_11.h ***/
  154039. /*** Start of inlined file: setup_16.h ***/
  154040. /*** Start of inlined file: psych_16.h ***/
  154041. /* stereo mode by base quality level */
  154042. static adj_stereo _psy_stereo_modes_16[4]={
  154043. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154044. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154045. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154046. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154047. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154048. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154049. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154050. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154051. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154052. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154053. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154054. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154055. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154056. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154057. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154058. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154059. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154060. };
  154061. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154062. static att3 _psy_tone_masteratt_16[4]={
  154063. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154064. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154065. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154066. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154067. };
  154068. static vp_adjblock _vp_tonemask_adj_16[4]={
  154069. /* adjust for mode zero */
  154070. /* 63 125 250 500 1 2 4 8 16 */
  154071. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154072. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154073. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154074. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154075. };
  154076. static noise3 _psy_noisebias_16_short[4]={
  154077. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154078. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154079. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154080. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154081. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154082. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154083. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154084. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154085. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154086. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154087. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154088. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154089. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154090. };
  154091. static noise3 _psy_noisebias_16_impulse[4]={
  154092. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154093. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154094. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154095. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154096. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154097. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154098. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154099. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154100. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154101. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154102. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154103. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154104. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154105. };
  154106. static noise3 _psy_noisebias_16[4]={
  154107. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154108. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154109. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154110. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154111. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154112. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154113. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154114. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154115. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154116. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154117. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154118. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154119. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154120. };
  154121. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154122. static int _noise_start_16[3]={ 256,256,9999 };
  154123. static int _noise_part_16[4]={ 8,8,8,8 };
  154124. static int _psy_ath_floater_16[4]={
  154125. -100,-100,-100,-105,
  154126. };
  154127. static int _psy_ath_abs_16[4]={
  154128. -130,-130,-130,-140,
  154129. };
  154130. /*** End of inlined file: psych_16.h ***/
  154131. /*** Start of inlined file: residue_16.h ***/
  154132. /***** residue backends *********************************************/
  154133. static static_bookblock _resbook_16s_0={
  154134. {
  154135. {0},
  154136. {0,0,&_16c0_s_p1_0},
  154137. {0,0,&_16c0_s_p2_0},
  154138. {0,0,&_16c0_s_p3_0},
  154139. {0,0,&_16c0_s_p4_0},
  154140. {0,0,&_16c0_s_p5_0},
  154141. {0,0,&_16c0_s_p6_0},
  154142. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154143. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154144. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154145. }
  154146. };
  154147. static static_bookblock _resbook_16s_1={
  154148. {
  154149. {0},
  154150. {0,0,&_16c1_s_p1_0},
  154151. {0,0,&_16c1_s_p2_0},
  154152. {0,0,&_16c1_s_p3_0},
  154153. {0,0,&_16c1_s_p4_0},
  154154. {0,0,&_16c1_s_p5_0},
  154155. {0,0,&_16c1_s_p6_0},
  154156. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154157. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154158. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154159. }
  154160. };
  154161. static static_bookblock _resbook_16s_2={
  154162. {
  154163. {0},
  154164. {0,0,&_16c2_s_p1_0},
  154165. {0,0,&_16c2_s_p2_0},
  154166. {0,0,&_16c2_s_p3_0},
  154167. {0,0,&_16c2_s_p4_0},
  154168. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154169. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154170. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154171. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154172. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154173. }
  154174. };
  154175. static vorbis_residue_template _res_16s_0[]={
  154176. {2,0, &_residue_44_mid,
  154177. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154178. &_resbook_16s_0,&_resbook_16s_0},
  154179. };
  154180. static vorbis_residue_template _res_16s_1[]={
  154181. {2,0, &_residue_44_mid,
  154182. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154183. &_resbook_16s_1,&_resbook_16s_1},
  154184. {2,0, &_residue_44_mid,
  154185. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154186. &_resbook_16s_1,&_resbook_16s_1}
  154187. };
  154188. static vorbis_residue_template _res_16s_2[]={
  154189. {2,0, &_residue_44_high,
  154190. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154191. &_resbook_16s_2,&_resbook_16s_2},
  154192. {2,0, &_residue_44_high,
  154193. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154194. &_resbook_16s_2,&_resbook_16s_2}
  154195. };
  154196. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154197. { _map_nominal, _res_16s_0 }, /* 0 */
  154198. { _map_nominal, _res_16s_1 }, /* 1 */
  154199. { _map_nominal, _res_16s_2 }, /* 2 */
  154200. };
  154201. static static_bookblock _resbook_16u_0={
  154202. {
  154203. {0},
  154204. {0,0,&_16u0__p1_0},
  154205. {0,0,&_16u0__p2_0},
  154206. {0,0,&_16u0__p3_0},
  154207. {0,0,&_16u0__p4_0},
  154208. {0,0,&_16u0__p5_0},
  154209. {&_16u0__p6_0,&_16u0__p6_1},
  154210. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154211. }
  154212. };
  154213. static static_bookblock _resbook_16u_1={
  154214. {
  154215. {0},
  154216. {0,0,&_16u1__p1_0},
  154217. {0,0,&_16u1__p2_0},
  154218. {0,0,&_16u1__p3_0},
  154219. {0,0,&_16u1__p4_0},
  154220. {0,0,&_16u1__p5_0},
  154221. {0,0,&_16u1__p6_0},
  154222. {&_16u1__p7_0,&_16u1__p7_1},
  154223. {&_16u1__p8_0,&_16u1__p8_1},
  154224. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154225. }
  154226. };
  154227. static static_bookblock _resbook_16u_2={
  154228. {
  154229. {0},
  154230. {0,0,&_16u2_p1_0},
  154231. {0,0,&_16u2_p2_0},
  154232. {0,0,&_16u2_p3_0},
  154233. {0,0,&_16u2_p4_0},
  154234. {&_16u2_p5_0,&_16u2_p5_1},
  154235. {&_16u2_p6_0,&_16u2_p6_1},
  154236. {&_16u2_p7_0,&_16u2_p7_1},
  154237. {&_16u2_p8_0,&_16u2_p8_1},
  154238. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154239. }
  154240. };
  154241. static vorbis_residue_template _res_16u_0[]={
  154242. {1,0, &_residue_44_low_un,
  154243. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154244. &_resbook_16u_0,&_resbook_16u_0},
  154245. };
  154246. static vorbis_residue_template _res_16u_1[]={
  154247. {1,0, &_residue_44_mid_un,
  154248. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154249. &_resbook_16u_1,&_resbook_16u_1},
  154250. {1,0, &_residue_44_mid_un,
  154251. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154252. &_resbook_16u_1,&_resbook_16u_1}
  154253. };
  154254. static vorbis_residue_template _res_16u_2[]={
  154255. {1,0, &_residue_44_hi_un,
  154256. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154257. &_resbook_16u_2,&_resbook_16u_2},
  154258. {1,0, &_residue_44_hi_un,
  154259. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154260. &_resbook_16u_2,&_resbook_16u_2}
  154261. };
  154262. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154263. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154264. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154265. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154266. };
  154267. /*** End of inlined file: residue_16.h ***/
  154268. static int blocksize_16_short[3]={
  154269. 1024,512,512
  154270. };
  154271. static int blocksize_16_long[3]={
  154272. 1024,1024,1024
  154273. };
  154274. static int _floor_mapping_16_short[3]={
  154275. 9,3,3
  154276. };
  154277. static int _floor_mapping_16[3]={
  154278. 9,9,9
  154279. };
  154280. static double rate_mapping_16[4]={
  154281. 12000.,20000.,44000.,86000.
  154282. };
  154283. static double rate_mapping_16_uncoupled[4]={
  154284. 16000.,28000.,64000.,100000.
  154285. };
  154286. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154287. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154288. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154289. ve_setup_data_template ve_setup_16_stereo={
  154290. 3,
  154291. rate_mapping_16,
  154292. quality_mapping_16,
  154293. 2,
  154294. 15000,
  154295. 19000,
  154296. blocksize_16_short,
  154297. blocksize_16_long,
  154298. _psy_tone_masteratt_16,
  154299. _psy_tone_0dB,
  154300. _psy_tone_suppress,
  154301. _vp_tonemask_adj_16,
  154302. _vp_tonemask_adj_16,
  154303. _vp_tonemask_adj_16,
  154304. _psy_noiseguards_8,
  154305. _psy_noisebias_16_impulse,
  154306. _psy_noisebias_16_short,
  154307. _psy_noisebias_16_short,
  154308. _psy_noisebias_16,
  154309. _psy_noise_suppress,
  154310. _psy_compand_8,
  154311. _psy_compand_16_mapping,
  154312. _psy_compand_16_mapping,
  154313. {_noise_start_16,_noise_start_16},
  154314. { _noise_part_16, _noise_part_16},
  154315. _noise_thresh_16,
  154316. _psy_ath_floater_16,
  154317. _psy_ath_abs_16,
  154318. _psy_lowpass_16,
  154319. _psy_global_44,
  154320. _global_mapping_16,
  154321. _psy_stereo_modes_16,
  154322. _floor_books,
  154323. _floor,
  154324. _floor_mapping_16_short,
  154325. _floor_mapping_16,
  154326. _mapres_template_16_stereo
  154327. };
  154328. ve_setup_data_template ve_setup_16_uncoupled={
  154329. 3,
  154330. rate_mapping_16_uncoupled,
  154331. quality_mapping_16,
  154332. -1,
  154333. 15000,
  154334. 19000,
  154335. blocksize_16_short,
  154336. blocksize_16_long,
  154337. _psy_tone_masteratt_16,
  154338. _psy_tone_0dB,
  154339. _psy_tone_suppress,
  154340. _vp_tonemask_adj_16,
  154341. _vp_tonemask_adj_16,
  154342. _vp_tonemask_adj_16,
  154343. _psy_noiseguards_8,
  154344. _psy_noisebias_16_impulse,
  154345. _psy_noisebias_16_short,
  154346. _psy_noisebias_16_short,
  154347. _psy_noisebias_16,
  154348. _psy_noise_suppress,
  154349. _psy_compand_8,
  154350. _psy_compand_16_mapping,
  154351. _psy_compand_16_mapping,
  154352. {_noise_start_16,_noise_start_16},
  154353. { _noise_part_16, _noise_part_16},
  154354. _noise_thresh_16,
  154355. _psy_ath_floater_16,
  154356. _psy_ath_abs_16,
  154357. _psy_lowpass_16,
  154358. _psy_global_44,
  154359. _global_mapping_16,
  154360. _psy_stereo_modes_16,
  154361. _floor_books,
  154362. _floor,
  154363. _floor_mapping_16_short,
  154364. _floor_mapping_16,
  154365. _mapres_template_16_uncoupled
  154366. };
  154367. /*** End of inlined file: setup_16.h ***/
  154368. /*** Start of inlined file: setup_22.h ***/
  154369. static double rate_mapping_22[4]={
  154370. 15000.,20000.,44000.,86000.
  154371. };
  154372. static double rate_mapping_22_uncoupled[4]={
  154373. 16000.,28000.,50000.,90000.
  154374. };
  154375. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154376. ve_setup_data_template ve_setup_22_stereo={
  154377. 3,
  154378. rate_mapping_22,
  154379. quality_mapping_16,
  154380. 2,
  154381. 19000,
  154382. 26000,
  154383. blocksize_16_short,
  154384. blocksize_16_long,
  154385. _psy_tone_masteratt_16,
  154386. _psy_tone_0dB,
  154387. _psy_tone_suppress,
  154388. _vp_tonemask_adj_16,
  154389. _vp_tonemask_adj_16,
  154390. _vp_tonemask_adj_16,
  154391. _psy_noiseguards_8,
  154392. _psy_noisebias_16_impulse,
  154393. _psy_noisebias_16_short,
  154394. _psy_noisebias_16_short,
  154395. _psy_noisebias_16,
  154396. _psy_noise_suppress,
  154397. _psy_compand_8,
  154398. _psy_compand_8_mapping,
  154399. _psy_compand_8_mapping,
  154400. {_noise_start_16,_noise_start_16},
  154401. { _noise_part_16, _noise_part_16},
  154402. _noise_thresh_16,
  154403. _psy_ath_floater_16,
  154404. _psy_ath_abs_16,
  154405. _psy_lowpass_22,
  154406. _psy_global_44,
  154407. _global_mapping_16,
  154408. _psy_stereo_modes_16,
  154409. _floor_books,
  154410. _floor,
  154411. _floor_mapping_16_short,
  154412. _floor_mapping_16,
  154413. _mapres_template_16_stereo
  154414. };
  154415. ve_setup_data_template ve_setup_22_uncoupled={
  154416. 3,
  154417. rate_mapping_22_uncoupled,
  154418. quality_mapping_16,
  154419. -1,
  154420. 19000,
  154421. 26000,
  154422. blocksize_16_short,
  154423. blocksize_16_long,
  154424. _psy_tone_masteratt_16,
  154425. _psy_tone_0dB,
  154426. _psy_tone_suppress,
  154427. _vp_tonemask_adj_16,
  154428. _vp_tonemask_adj_16,
  154429. _vp_tonemask_adj_16,
  154430. _psy_noiseguards_8,
  154431. _psy_noisebias_16_impulse,
  154432. _psy_noisebias_16_short,
  154433. _psy_noisebias_16_short,
  154434. _psy_noisebias_16,
  154435. _psy_noise_suppress,
  154436. _psy_compand_8,
  154437. _psy_compand_8_mapping,
  154438. _psy_compand_8_mapping,
  154439. {_noise_start_16,_noise_start_16},
  154440. { _noise_part_16, _noise_part_16},
  154441. _noise_thresh_16,
  154442. _psy_ath_floater_16,
  154443. _psy_ath_abs_16,
  154444. _psy_lowpass_22,
  154445. _psy_global_44,
  154446. _global_mapping_16,
  154447. _psy_stereo_modes_16,
  154448. _floor_books,
  154449. _floor,
  154450. _floor_mapping_16_short,
  154451. _floor_mapping_16,
  154452. _mapres_template_16_uncoupled
  154453. };
  154454. /*** End of inlined file: setup_22.h ***/
  154455. /*** Start of inlined file: setup_X.h ***/
  154456. static double rate_mapping_X[12]={
  154457. -1.,-1.,-1.,-1.,-1.,-1.,
  154458. -1.,-1.,-1.,-1.,-1.,-1.
  154459. };
  154460. ve_setup_data_template ve_setup_X_stereo={
  154461. 11,
  154462. rate_mapping_X,
  154463. quality_mapping_44,
  154464. 2,
  154465. 50000,
  154466. 200000,
  154467. blocksize_short_44,
  154468. blocksize_long_44,
  154469. _psy_tone_masteratt_44,
  154470. _psy_tone_0dB,
  154471. _psy_tone_suppress,
  154472. _vp_tonemask_adj_otherblock,
  154473. _vp_tonemask_adj_longblock,
  154474. _vp_tonemask_adj_otherblock,
  154475. _psy_noiseguards_44,
  154476. _psy_noisebias_impulse,
  154477. _psy_noisebias_padding,
  154478. _psy_noisebias_trans,
  154479. _psy_noisebias_long,
  154480. _psy_noise_suppress,
  154481. _psy_compand_44,
  154482. _psy_compand_short_mapping,
  154483. _psy_compand_long_mapping,
  154484. {_noise_start_short_44,_noise_start_long_44},
  154485. {_noise_part_short_44,_noise_part_long_44},
  154486. _noise_thresh_44,
  154487. _psy_ath_floater,
  154488. _psy_ath_abs,
  154489. _psy_lowpass_44,
  154490. _psy_global_44,
  154491. _global_mapping_44,
  154492. _psy_stereo_modes_44,
  154493. _floor_books,
  154494. _floor,
  154495. _floor_short_mapping_44,
  154496. _floor_long_mapping_44,
  154497. _mapres_template_44_stereo
  154498. };
  154499. ve_setup_data_template ve_setup_X_uncoupled={
  154500. 11,
  154501. rate_mapping_X,
  154502. quality_mapping_44,
  154503. -1,
  154504. 50000,
  154505. 200000,
  154506. blocksize_short_44,
  154507. blocksize_long_44,
  154508. _psy_tone_masteratt_44,
  154509. _psy_tone_0dB,
  154510. _psy_tone_suppress,
  154511. _vp_tonemask_adj_otherblock,
  154512. _vp_tonemask_adj_longblock,
  154513. _vp_tonemask_adj_otherblock,
  154514. _psy_noiseguards_44,
  154515. _psy_noisebias_impulse,
  154516. _psy_noisebias_padding,
  154517. _psy_noisebias_trans,
  154518. _psy_noisebias_long,
  154519. _psy_noise_suppress,
  154520. _psy_compand_44,
  154521. _psy_compand_short_mapping,
  154522. _psy_compand_long_mapping,
  154523. {_noise_start_short_44,_noise_start_long_44},
  154524. {_noise_part_short_44,_noise_part_long_44},
  154525. _noise_thresh_44,
  154526. _psy_ath_floater,
  154527. _psy_ath_abs,
  154528. _psy_lowpass_44,
  154529. _psy_global_44,
  154530. _global_mapping_44,
  154531. NULL,
  154532. _floor_books,
  154533. _floor,
  154534. _floor_short_mapping_44,
  154535. _floor_long_mapping_44,
  154536. _mapres_template_44_uncoupled
  154537. };
  154538. ve_setup_data_template ve_setup_XX_stereo={
  154539. 2,
  154540. rate_mapping_X,
  154541. quality_mapping_8,
  154542. 2,
  154543. 0,
  154544. 8000,
  154545. blocksize_8,
  154546. blocksize_8,
  154547. _psy_tone_masteratt_8,
  154548. _psy_tone_0dB,
  154549. _psy_tone_suppress,
  154550. _vp_tonemask_adj_8,
  154551. NULL,
  154552. _vp_tonemask_adj_8,
  154553. _psy_noiseguards_8,
  154554. _psy_noisebias_8,
  154555. _psy_noisebias_8,
  154556. NULL,
  154557. NULL,
  154558. _psy_noise_suppress,
  154559. _psy_compand_8,
  154560. _psy_compand_8_mapping,
  154561. NULL,
  154562. {_noise_start_8,_noise_start_8},
  154563. {_noise_part_8,_noise_part_8},
  154564. _noise_thresh_5only,
  154565. _psy_ath_floater_8,
  154566. _psy_ath_abs_8,
  154567. _psy_lowpass_8,
  154568. _psy_global_44,
  154569. _global_mapping_8,
  154570. _psy_stereo_modes_8,
  154571. _floor_books,
  154572. _floor,
  154573. _floor_mapping_8,
  154574. NULL,
  154575. _mapres_template_8_stereo
  154576. };
  154577. ve_setup_data_template ve_setup_XX_uncoupled={
  154578. 2,
  154579. rate_mapping_X,
  154580. quality_mapping_8,
  154581. -1,
  154582. 0,
  154583. 8000,
  154584. blocksize_8,
  154585. blocksize_8,
  154586. _psy_tone_masteratt_8,
  154587. _psy_tone_0dB,
  154588. _psy_tone_suppress,
  154589. _vp_tonemask_adj_8,
  154590. NULL,
  154591. _vp_tonemask_adj_8,
  154592. _psy_noiseguards_8,
  154593. _psy_noisebias_8,
  154594. _psy_noisebias_8,
  154595. NULL,
  154596. NULL,
  154597. _psy_noise_suppress,
  154598. _psy_compand_8,
  154599. _psy_compand_8_mapping,
  154600. NULL,
  154601. {_noise_start_8,_noise_start_8},
  154602. {_noise_part_8,_noise_part_8},
  154603. _noise_thresh_5only,
  154604. _psy_ath_floater_8,
  154605. _psy_ath_abs_8,
  154606. _psy_lowpass_8,
  154607. _psy_global_44,
  154608. _global_mapping_8,
  154609. _psy_stereo_modes_8,
  154610. _floor_books,
  154611. _floor,
  154612. _floor_mapping_8,
  154613. NULL,
  154614. _mapres_template_8_uncoupled
  154615. };
  154616. /*** End of inlined file: setup_X.h ***/
  154617. static ve_setup_data_template *setup_list[]={
  154618. &ve_setup_44_stereo,
  154619. &ve_setup_44_uncoupled,
  154620. &ve_setup_32_stereo,
  154621. &ve_setup_32_uncoupled,
  154622. &ve_setup_22_stereo,
  154623. &ve_setup_22_uncoupled,
  154624. &ve_setup_16_stereo,
  154625. &ve_setup_16_uncoupled,
  154626. &ve_setup_11_stereo,
  154627. &ve_setup_11_uncoupled,
  154628. &ve_setup_8_stereo,
  154629. &ve_setup_8_uncoupled,
  154630. &ve_setup_X_stereo,
  154631. &ve_setup_X_uncoupled,
  154632. &ve_setup_XX_stereo,
  154633. &ve_setup_XX_uncoupled,
  154634. 0
  154635. };
  154636. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154637. if(vi && vi->codec_setup){
  154638. vi->version=0;
  154639. vi->channels=ch;
  154640. vi->rate=rate;
  154641. return(0);
  154642. }
  154643. return(OV_EINVAL);
  154644. }
  154645. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154646. static_codebook ***books,
  154647. vorbis_info_floor1 *in,
  154648. int *x){
  154649. int i,k,is=s;
  154650. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154651. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154652. memcpy(f,in+x[is],sizeof(*f));
  154653. /* fill in the lowpass field, even if it's temporary */
  154654. f->n=ci->blocksizes[block]>>1;
  154655. /* books */
  154656. {
  154657. int partitions=f->partitions;
  154658. int maxclass=-1;
  154659. int maxbook=-1;
  154660. for(i=0;i<partitions;i++)
  154661. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154662. for(i=0;i<=maxclass;i++){
  154663. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154664. f->class_book[i]+=ci->books;
  154665. for(k=0;k<(1<<f->class_subs[i]);k++){
  154666. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154667. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154668. }
  154669. }
  154670. for(i=0;i<=maxbook;i++)
  154671. ci->book_param[ci->books++]=books[x[is]][i];
  154672. }
  154673. /* for now, we're only using floor 1 */
  154674. ci->floor_type[ci->floors]=1;
  154675. ci->floor_param[ci->floors]=f;
  154676. ci->floors++;
  154677. return;
  154678. }
  154679. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154680. vorbis_info_psy_global *in,
  154681. double *x){
  154682. int i,is=s;
  154683. double ds=s-is;
  154684. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154685. vorbis_info_psy_global *g=&ci->psy_g_param;
  154686. memcpy(g,in+(int)x[is],sizeof(*g));
  154687. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154688. is=(int)ds;
  154689. ds-=is;
  154690. if(ds==0 && is>0){
  154691. is--;
  154692. ds=1.;
  154693. }
  154694. /* interpolate the trigger threshholds */
  154695. for(i=0;i<4;i++){
  154696. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154697. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154698. }
  154699. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154700. return;
  154701. }
  154702. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154703. highlevel_encode_setup *hi,
  154704. adj_stereo *p){
  154705. float s=hi->stereo_point_setting;
  154706. int i,is=s;
  154707. double ds=s-is;
  154708. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154709. vorbis_info_psy_global *g=&ci->psy_g_param;
  154710. if(p){
  154711. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154712. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154713. if(hi->managed){
  154714. /* interpolate the kHz threshholds */
  154715. for(i=0;i<PACKETBLOBS;i++){
  154716. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154717. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154718. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154719. g->coupling_pkHz[i]=kHz;
  154720. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154721. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154722. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154723. }
  154724. }else{
  154725. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154726. for(i=0;i<PACKETBLOBS;i++){
  154727. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154728. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154729. g->coupling_pkHz[i]=kHz;
  154730. }
  154731. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154732. for(i=0;i<PACKETBLOBS;i++){
  154733. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154734. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154735. }
  154736. }
  154737. }else{
  154738. for(i=0;i<PACKETBLOBS;i++){
  154739. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154740. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154741. }
  154742. }
  154743. return;
  154744. }
  154745. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154746. int *nn_start,
  154747. int *nn_partition,
  154748. double *nn_thresh,
  154749. int block){
  154750. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154751. vorbis_info_psy *p=ci->psy_param[block];
  154752. highlevel_encode_setup *hi=&ci->hi;
  154753. int is=s;
  154754. if(block>=ci->psys)
  154755. ci->psys=block+1;
  154756. if(!p){
  154757. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154758. ci->psy_param[block]=p;
  154759. }
  154760. memcpy(p,&_psy_info_template,sizeof(*p));
  154761. p->blockflag=block>>1;
  154762. if(hi->noise_normalize_p){
  154763. p->normal_channel_p=1;
  154764. p->normal_point_p=1;
  154765. p->normal_start=nn_start[is];
  154766. p->normal_partition=nn_partition[is];
  154767. p->normal_thresh=nn_thresh[is];
  154768. }
  154769. return;
  154770. }
  154771. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154772. att3 *att,
  154773. int *max,
  154774. vp_adjblock *in){
  154775. int i,is=s;
  154776. double ds=s-is;
  154777. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154778. vorbis_info_psy *p=ci->psy_param[block];
  154779. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154780. filling the values in here */
  154781. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154782. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154783. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154784. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154785. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154786. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154787. for(i=0;i<P_BANDS;i++)
  154788. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154789. return;
  154790. }
  154791. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154792. compandblock *in, double *x){
  154793. int i,is=s;
  154794. double ds=s-is;
  154795. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154796. vorbis_info_psy *p=ci->psy_param[block];
  154797. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154798. is=(int)ds;
  154799. ds-=is;
  154800. if(ds==0 && is>0){
  154801. is--;
  154802. ds=1.;
  154803. }
  154804. /* interpolate the compander settings */
  154805. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154806. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154807. return;
  154808. }
  154809. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154810. int *suppress){
  154811. int is=s;
  154812. double ds=s-is;
  154813. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154814. vorbis_info_psy *p=ci->psy_param[block];
  154815. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154816. return;
  154817. }
  154818. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154819. int *suppress,
  154820. noise3 *in,
  154821. noiseguard *guard,
  154822. double userbias){
  154823. int i,is=s,j;
  154824. double ds=s-is;
  154825. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154826. vorbis_info_psy *p=ci->psy_param[block];
  154827. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154828. p->noisewindowlomin=guard[block].lo;
  154829. p->noisewindowhimin=guard[block].hi;
  154830. p->noisewindowfixed=guard[block].fixed;
  154831. for(j=0;j<P_NOISECURVES;j++)
  154832. for(i=0;i<P_BANDS;i++)
  154833. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154834. /* impulse blocks may take a user specified bias to boost the
  154835. nominal/high noise encoding depth */
  154836. for(j=0;j<P_NOISECURVES;j++){
  154837. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154838. for(i=0;i<P_BANDS;i++){
  154839. p->noiseoff[j][i]+=userbias;
  154840. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154841. }
  154842. }
  154843. return;
  154844. }
  154845. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154846. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154847. vorbis_info_psy *p=ci->psy_param[block];
  154848. p->ath_adjatt=ci->hi.ath_floating_dB;
  154849. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154850. return;
  154851. }
  154852. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154853. int i;
  154854. for(i=0;i<ci->books;i++)
  154855. if(ci->book_param[i]==book)return(i);
  154856. return(ci->books++);
  154857. }
  154858. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154859. int *shortb,int *longb){
  154860. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154861. int is=s;
  154862. int blockshort=shortb[is];
  154863. int blocklong=longb[is];
  154864. ci->blocksizes[0]=blockshort;
  154865. ci->blocksizes[1]=blocklong;
  154866. }
  154867. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154868. int number, int block,
  154869. vorbis_residue_template *res){
  154870. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154871. int i,n;
  154872. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154873. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154874. memcpy(r,res->res,sizeof(*r));
  154875. if(ci->residues<=number)ci->residues=number+1;
  154876. switch(ci->blocksizes[block]){
  154877. case 64:case 128:case 256:
  154878. r->grouping=16;
  154879. break;
  154880. default:
  154881. r->grouping=32;
  154882. break;
  154883. }
  154884. ci->residue_type[number]=res->res_type;
  154885. /* to be adjusted by lowpass/pointlimit later */
  154886. n=r->end=ci->blocksizes[block]>>1;
  154887. if(res->res_type==2)
  154888. n=r->end*=vi->channels;
  154889. /* fill in all the books */
  154890. {
  154891. int booklist=0,k;
  154892. if(ci->hi.managed){
  154893. for(i=0;i<r->partitions;i++)
  154894. for(k=0;k<3;k++)
  154895. if(res->books_base_managed->books[i][k])
  154896. r->secondstages[i]|=(1<<k);
  154897. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154898. ci->book_param[r->groupbook]=res->book_aux_managed;
  154899. for(i=0;i<r->partitions;i++){
  154900. for(k=0;k<3;k++){
  154901. if(res->books_base_managed->books[i][k]){
  154902. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154903. r->booklist[booklist++]=bookid;
  154904. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154905. }
  154906. }
  154907. }
  154908. }else{
  154909. for(i=0;i<r->partitions;i++)
  154910. for(k=0;k<3;k++)
  154911. if(res->books_base->books[i][k])
  154912. r->secondstages[i]|=(1<<k);
  154913. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154914. ci->book_param[r->groupbook]=res->book_aux;
  154915. for(i=0;i<r->partitions;i++){
  154916. for(k=0;k<3;k++){
  154917. if(res->books_base->books[i][k]){
  154918. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154919. r->booklist[booklist++]=bookid;
  154920. ci->book_param[bookid]=res->books_base->books[i][k];
  154921. }
  154922. }
  154923. }
  154924. }
  154925. }
  154926. /* lowpass setup/pointlimit */
  154927. {
  154928. double freq=ci->hi.lowpass_kHz*1000.;
  154929. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154930. double nyq=vi->rate/2.;
  154931. long blocksize=ci->blocksizes[block]>>1;
  154932. /* lowpass needs to be set in the floor and the residue. */
  154933. if(freq>nyq)freq=nyq;
  154934. /* in the floor, the granularity can be very fine; it doesn't alter
  154935. the encoding structure, only the samples used to fit the floor
  154936. approximation */
  154937. f->n=freq/nyq*blocksize;
  154938. /* this res may by limited by the maximum pointlimit of the mode,
  154939. not the lowpass. the floor is always lowpass limited. */
  154940. if(res->limit_type){
  154941. if(ci->hi.managed)
  154942. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154943. else
  154944. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154945. if(freq>nyq)freq=nyq;
  154946. }
  154947. /* in the residue, we're constrained, physically, by partition
  154948. boundaries. We still lowpass 'wherever', but we have to round up
  154949. here to next boundary, or the vorbis spec will round it *down* to
  154950. previous boundary in encode/decode */
  154951. if(ci->residue_type[block]==2)
  154952. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154953. r->grouping;
  154954. else
  154955. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154956. r->grouping;
  154957. }
  154958. }
  154959. /* we assume two maps in this encoder */
  154960. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154961. vorbis_mapping_template *maps){
  154962. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154963. int i,j,is=s,modes=2;
  154964. vorbis_info_mapping0 *map=maps[is].map;
  154965. vorbis_info_mode *mode=_mode_template;
  154966. vorbis_residue_template *res=maps[is].res;
  154967. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154968. for(i=0;i<modes;i++){
  154969. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154970. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154971. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154972. if(i>=ci->modes)ci->modes=i+1;
  154973. ci->map_type[i]=0;
  154974. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154975. if(i>=ci->maps)ci->maps=i+1;
  154976. for(j=0;j<map[i].submaps;j++)
  154977. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154978. ,res+map[i].residuesubmap[j]);
  154979. }
  154980. }
  154981. static double setting_to_approx_bitrate(vorbis_info *vi){
  154982. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154983. highlevel_encode_setup *hi=&ci->hi;
  154984. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154985. int is=hi->base_setting;
  154986. double ds=hi->base_setting-is;
  154987. int ch=vi->channels;
  154988. double *r=setup->rate_mapping;
  154989. if(r==NULL)
  154990. return(-1);
  154991. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154992. }
  154993. static void get_setup_template(vorbis_info *vi,
  154994. long ch,long srate,
  154995. double req,int q_or_bitrate){
  154996. int i=0,j;
  154997. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154998. highlevel_encode_setup *hi=&ci->hi;
  154999. if(q_or_bitrate)req/=ch;
  155000. while(setup_list[i]){
  155001. if(setup_list[i]->coupling_restriction==-1 ||
  155002. setup_list[i]->coupling_restriction==ch){
  155003. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155004. srate<=setup_list[i]->samplerate_max_restriction){
  155005. int mappings=setup_list[i]->mappings;
  155006. double *map=(q_or_bitrate?
  155007. setup_list[i]->rate_mapping:
  155008. setup_list[i]->quality_mapping);
  155009. /* the template matches. Does the requested quality mode
  155010. fall within this template's modes? */
  155011. if(req<map[0]){++i;continue;}
  155012. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155013. for(j=0;j<mappings;j++)
  155014. if(req>=map[j] && req<map[j+1])break;
  155015. /* an all-points match */
  155016. hi->setup=setup_list[i];
  155017. if(j==mappings)
  155018. hi->base_setting=j-.001;
  155019. else{
  155020. float low=map[j];
  155021. float high=map[j+1];
  155022. float del=(req-low)/(high-low);
  155023. hi->base_setting=j+del;
  155024. }
  155025. return;
  155026. }
  155027. }
  155028. i++;
  155029. }
  155030. hi->setup=NULL;
  155031. }
  155032. /* encoders will need to use vorbis_info_init beforehand and call
  155033. vorbis_info clear when all done */
  155034. /* two interfaces; this, more detailed one, and later a convenience
  155035. layer on top */
  155036. /* the final setup call */
  155037. int vorbis_encode_setup_init(vorbis_info *vi){
  155038. int i0=0,singleblock=0;
  155039. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155040. ve_setup_data_template *setup=NULL;
  155041. highlevel_encode_setup *hi=&ci->hi;
  155042. if(ci==NULL)return(OV_EINVAL);
  155043. if(!hi->impulse_block_p)i0=1;
  155044. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155045. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155046. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155047. /* again, bound this to avoid the app shooting itself int he foot
  155048. too badly */
  155049. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155050. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155051. /* get the appropriate setup template; matches the fetch in previous
  155052. stages */
  155053. setup=(ve_setup_data_template *)hi->setup;
  155054. if(setup==NULL)return(OV_EINVAL);
  155055. hi->set_in_stone=1;
  155056. /* choose block sizes from configured sizes as well as paying
  155057. attention to long_block_p and short_block_p. If the configured
  155058. short and long blocks are the same length, we set long_block_p
  155059. and unset short_block_p */
  155060. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155061. setup->blocksize_short,
  155062. setup->blocksize_long);
  155063. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155064. /* floor setup; choose proper floor params. Allocated on the floor
  155065. stack in order; if we alloc only long floor, it's 0 */
  155066. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155067. setup->floor_books,
  155068. setup->floor_params,
  155069. setup->floor_short_mapping);
  155070. if(!singleblock)
  155071. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155072. setup->floor_books,
  155073. setup->floor_params,
  155074. setup->floor_long_mapping);
  155075. /* setup of [mostly] short block detection and stereo*/
  155076. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155077. setup->global_params,
  155078. setup->global_mapping);
  155079. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155080. /* basic psych setup and noise normalization */
  155081. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155082. setup->psy_noise_normal_start[0],
  155083. setup->psy_noise_normal_partition[0],
  155084. setup->psy_noise_normal_thresh,
  155085. 0);
  155086. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155087. setup->psy_noise_normal_start[0],
  155088. setup->psy_noise_normal_partition[0],
  155089. setup->psy_noise_normal_thresh,
  155090. 1);
  155091. if(!singleblock){
  155092. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155093. setup->psy_noise_normal_start[1],
  155094. setup->psy_noise_normal_partition[1],
  155095. setup->psy_noise_normal_thresh,
  155096. 2);
  155097. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155098. setup->psy_noise_normal_start[1],
  155099. setup->psy_noise_normal_partition[1],
  155100. setup->psy_noise_normal_thresh,
  155101. 3);
  155102. }
  155103. /* tone masking setup */
  155104. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155105. setup->psy_tone_masteratt,
  155106. setup->psy_tone_0dB,
  155107. setup->psy_tone_adj_impulse);
  155108. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155109. setup->psy_tone_masteratt,
  155110. setup->psy_tone_0dB,
  155111. setup->psy_tone_adj_other);
  155112. if(!singleblock){
  155113. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155114. setup->psy_tone_masteratt,
  155115. setup->psy_tone_0dB,
  155116. setup->psy_tone_adj_other);
  155117. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155118. setup->psy_tone_masteratt,
  155119. setup->psy_tone_0dB,
  155120. setup->psy_tone_adj_long);
  155121. }
  155122. /* noise companding setup */
  155123. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155124. setup->psy_noise_compand,
  155125. setup->psy_noise_compand_short_mapping);
  155126. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155127. setup->psy_noise_compand,
  155128. setup->psy_noise_compand_short_mapping);
  155129. if(!singleblock){
  155130. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155131. setup->psy_noise_compand,
  155132. setup->psy_noise_compand_long_mapping);
  155133. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155134. setup->psy_noise_compand,
  155135. setup->psy_noise_compand_long_mapping);
  155136. }
  155137. /* peak guarding setup */
  155138. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155139. setup->psy_tone_dBsuppress);
  155140. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155141. setup->psy_tone_dBsuppress);
  155142. if(!singleblock){
  155143. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155144. setup->psy_tone_dBsuppress);
  155145. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155146. setup->psy_tone_dBsuppress);
  155147. }
  155148. /* noise bias setup */
  155149. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155150. setup->psy_noise_dBsuppress,
  155151. setup->psy_noise_bias_impulse,
  155152. setup->psy_noiseguards,
  155153. (i0==0?hi->impulse_noisetune:0.));
  155154. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155155. setup->psy_noise_dBsuppress,
  155156. setup->psy_noise_bias_padding,
  155157. setup->psy_noiseguards,0.);
  155158. if(!singleblock){
  155159. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155160. setup->psy_noise_dBsuppress,
  155161. setup->psy_noise_bias_trans,
  155162. setup->psy_noiseguards,0.);
  155163. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155164. setup->psy_noise_dBsuppress,
  155165. setup->psy_noise_bias_long,
  155166. setup->psy_noiseguards,0.);
  155167. }
  155168. vorbis_encode_ath_setup(vi,0);
  155169. vorbis_encode_ath_setup(vi,1);
  155170. if(!singleblock){
  155171. vorbis_encode_ath_setup(vi,2);
  155172. vorbis_encode_ath_setup(vi,3);
  155173. }
  155174. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155175. /* set bitrate readonlies and management */
  155176. if(hi->bitrate_av>0)
  155177. vi->bitrate_nominal=hi->bitrate_av;
  155178. else{
  155179. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155180. }
  155181. vi->bitrate_lower=hi->bitrate_min;
  155182. vi->bitrate_upper=hi->bitrate_max;
  155183. if(hi->bitrate_av)
  155184. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155185. else
  155186. vi->bitrate_window=0.;
  155187. if(hi->managed){
  155188. ci->bi.avg_rate=hi->bitrate_av;
  155189. ci->bi.min_rate=hi->bitrate_min;
  155190. ci->bi.max_rate=hi->bitrate_max;
  155191. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155192. ci->bi.reservoir_bias=
  155193. hi->bitrate_reservoir_bias;
  155194. ci->bi.slew_damp=hi->bitrate_av_damp;
  155195. }
  155196. return(0);
  155197. }
  155198. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155199. long channels,
  155200. long rate){
  155201. int ret=0,i,is;
  155202. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155203. highlevel_encode_setup *hi=&ci->hi;
  155204. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155205. double ds;
  155206. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155207. if(ret)return(ret);
  155208. is=hi->base_setting;
  155209. ds=hi->base_setting-is;
  155210. hi->short_setting=hi->base_setting;
  155211. hi->long_setting=hi->base_setting;
  155212. hi->managed=0;
  155213. hi->impulse_block_p=1;
  155214. hi->noise_normalize_p=1;
  155215. hi->stereo_point_setting=hi->base_setting;
  155216. hi->lowpass_kHz=
  155217. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155218. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155219. setup->psy_ath_float[is+1]*ds;
  155220. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155221. setup->psy_ath_abs[is+1]*ds;
  155222. hi->amplitude_track_dBpersec=-6.;
  155223. hi->trigger_setting=hi->base_setting;
  155224. for(i=0;i<4;i++){
  155225. hi->block[i].tone_mask_setting=hi->base_setting;
  155226. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155227. hi->block[i].noise_bias_setting=hi->base_setting;
  155228. hi->block[i].noise_compand_setting=hi->base_setting;
  155229. }
  155230. return(ret);
  155231. }
  155232. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155233. long channels,
  155234. long rate,
  155235. float quality){
  155236. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155237. highlevel_encode_setup *hi=&ci->hi;
  155238. quality+=.0000001;
  155239. if(quality>=1.)quality=.9999;
  155240. get_setup_template(vi,channels,rate,quality,0);
  155241. if(!hi->setup)return OV_EIMPL;
  155242. return vorbis_encode_setup_setting(vi,channels,rate);
  155243. }
  155244. int vorbis_encode_init_vbr(vorbis_info *vi,
  155245. long channels,
  155246. long rate,
  155247. float base_quality /* 0. to 1. */
  155248. ){
  155249. int ret=0;
  155250. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155251. if(ret){
  155252. vorbis_info_clear(vi);
  155253. return ret;
  155254. }
  155255. ret=vorbis_encode_setup_init(vi);
  155256. if(ret)
  155257. vorbis_info_clear(vi);
  155258. return(ret);
  155259. }
  155260. int vorbis_encode_setup_managed(vorbis_info *vi,
  155261. long channels,
  155262. long rate,
  155263. long max_bitrate,
  155264. long nominal_bitrate,
  155265. long min_bitrate){
  155266. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155267. highlevel_encode_setup *hi=&ci->hi;
  155268. double tnominal=nominal_bitrate;
  155269. int ret=0;
  155270. if(nominal_bitrate<=0.){
  155271. if(max_bitrate>0.){
  155272. if(min_bitrate>0.)
  155273. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155274. else
  155275. nominal_bitrate=max_bitrate*.875;
  155276. }else{
  155277. if(min_bitrate>0.){
  155278. nominal_bitrate=min_bitrate;
  155279. }else{
  155280. return(OV_EINVAL);
  155281. }
  155282. }
  155283. }
  155284. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155285. if(!hi->setup)return OV_EIMPL;
  155286. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155287. if(ret){
  155288. vorbis_info_clear(vi);
  155289. return ret;
  155290. }
  155291. /* initialize management with sane defaults */
  155292. hi->managed=1;
  155293. hi->bitrate_min=min_bitrate;
  155294. hi->bitrate_max=max_bitrate;
  155295. hi->bitrate_av=tnominal;
  155296. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155297. hi->bitrate_reservoir=nominal_bitrate*2;
  155298. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155299. return(ret);
  155300. }
  155301. int vorbis_encode_init(vorbis_info *vi,
  155302. long channels,
  155303. long rate,
  155304. long max_bitrate,
  155305. long nominal_bitrate,
  155306. long min_bitrate){
  155307. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155308. max_bitrate,
  155309. nominal_bitrate,
  155310. min_bitrate);
  155311. if(ret){
  155312. vorbis_info_clear(vi);
  155313. return(ret);
  155314. }
  155315. ret=vorbis_encode_setup_init(vi);
  155316. if(ret)
  155317. vorbis_info_clear(vi);
  155318. return(ret);
  155319. }
  155320. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155321. if(vi){
  155322. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155323. highlevel_encode_setup *hi=&ci->hi;
  155324. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155325. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155326. switch(number){
  155327. /* now deprecated *****************/
  155328. case OV_ECTL_RATEMANAGE_GET:
  155329. {
  155330. struct ovectl_ratemanage_arg *ai=
  155331. (struct ovectl_ratemanage_arg *)arg;
  155332. ai->management_active=hi->managed;
  155333. ai->bitrate_hard_window=ai->bitrate_av_window=
  155334. (double)hi->bitrate_reservoir/vi->rate;
  155335. ai->bitrate_av_window_center=1.;
  155336. ai->bitrate_hard_min=hi->bitrate_min;
  155337. ai->bitrate_hard_max=hi->bitrate_max;
  155338. ai->bitrate_av_lo=hi->bitrate_av;
  155339. ai->bitrate_av_hi=hi->bitrate_av;
  155340. }
  155341. return(0);
  155342. /* now deprecated *****************/
  155343. case OV_ECTL_RATEMANAGE_SET:
  155344. {
  155345. struct ovectl_ratemanage_arg *ai=
  155346. (struct ovectl_ratemanage_arg *)arg;
  155347. if(ai==NULL){
  155348. hi->managed=0;
  155349. }else{
  155350. hi->managed=ai->management_active;
  155351. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155352. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155353. }
  155354. }
  155355. return 0;
  155356. /* now deprecated *****************/
  155357. case OV_ECTL_RATEMANAGE_AVG:
  155358. {
  155359. struct ovectl_ratemanage_arg *ai=
  155360. (struct ovectl_ratemanage_arg *)arg;
  155361. if(ai==NULL){
  155362. hi->bitrate_av=0;
  155363. }else{
  155364. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155365. }
  155366. }
  155367. return(0);
  155368. /* now deprecated *****************/
  155369. case OV_ECTL_RATEMANAGE_HARD:
  155370. {
  155371. struct ovectl_ratemanage_arg *ai=
  155372. (struct ovectl_ratemanage_arg *)arg;
  155373. if(ai==NULL){
  155374. hi->bitrate_min=0;
  155375. hi->bitrate_max=0;
  155376. }else{
  155377. hi->bitrate_min=ai->bitrate_hard_min;
  155378. hi->bitrate_max=ai->bitrate_hard_max;
  155379. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155380. (hi->bitrate_max+hi->bitrate_min)*.5;
  155381. }
  155382. if(hi->bitrate_reservoir<128.)
  155383. hi->bitrate_reservoir=128.;
  155384. }
  155385. return(0);
  155386. /* replacement ratemanage interface */
  155387. case OV_ECTL_RATEMANAGE2_GET:
  155388. {
  155389. struct ovectl_ratemanage2_arg *ai=
  155390. (struct ovectl_ratemanage2_arg *)arg;
  155391. if(ai==NULL)return OV_EINVAL;
  155392. ai->management_active=hi->managed;
  155393. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155394. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155395. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155396. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155397. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155398. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155399. }
  155400. return (0);
  155401. case OV_ECTL_RATEMANAGE2_SET:
  155402. {
  155403. struct ovectl_ratemanage2_arg *ai=
  155404. (struct ovectl_ratemanage2_arg *)arg;
  155405. if(ai==NULL){
  155406. hi->managed=0;
  155407. }else{
  155408. /* sanity check; only catch invariant violations */
  155409. if(ai->bitrate_limit_min_kbps>0 &&
  155410. ai->bitrate_average_kbps>0 &&
  155411. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155412. return OV_EINVAL;
  155413. if(ai->bitrate_limit_max_kbps>0 &&
  155414. ai->bitrate_average_kbps>0 &&
  155415. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155416. return OV_EINVAL;
  155417. if(ai->bitrate_limit_min_kbps>0 &&
  155418. ai->bitrate_limit_max_kbps>0 &&
  155419. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155420. return OV_EINVAL;
  155421. if(ai->bitrate_average_damping <= 0.)
  155422. return OV_EINVAL;
  155423. if(ai->bitrate_limit_reservoir_bits < 0)
  155424. return OV_EINVAL;
  155425. if(ai->bitrate_limit_reservoir_bias < 0.)
  155426. return OV_EINVAL;
  155427. if(ai->bitrate_limit_reservoir_bias > 1.)
  155428. return OV_EINVAL;
  155429. hi->managed=ai->management_active;
  155430. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155431. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155432. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155433. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155434. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155435. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155436. }
  155437. }
  155438. return 0;
  155439. case OV_ECTL_LOWPASS_GET:
  155440. {
  155441. double *farg=(double *)arg;
  155442. *farg=hi->lowpass_kHz;
  155443. }
  155444. return(0);
  155445. case OV_ECTL_LOWPASS_SET:
  155446. {
  155447. double *farg=(double *)arg;
  155448. hi->lowpass_kHz=*farg;
  155449. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155450. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155451. }
  155452. return(0);
  155453. case OV_ECTL_IBLOCK_GET:
  155454. {
  155455. double *farg=(double *)arg;
  155456. *farg=hi->impulse_noisetune;
  155457. }
  155458. return(0);
  155459. case OV_ECTL_IBLOCK_SET:
  155460. {
  155461. double *farg=(double *)arg;
  155462. hi->impulse_noisetune=*farg;
  155463. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155464. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155465. }
  155466. return(0);
  155467. }
  155468. return(OV_EIMPL);
  155469. }
  155470. return(OV_EINVAL);
  155471. }
  155472. #endif
  155473. /*** End of inlined file: vorbisenc.c ***/
  155474. /*** Start of inlined file: vorbisfile.c ***/
  155475. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155476. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155477. // tasks..
  155478. #if JUCE_MSVC
  155479. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155480. #endif
  155481. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155482. #if JUCE_USE_OGGVORBIS
  155483. #include <stdlib.h>
  155484. #include <stdio.h>
  155485. #include <errno.h>
  155486. #include <string.h>
  155487. #include <math.h>
  155488. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155489. one logical bitstream arranged end to end (the only form of Ogg
  155490. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155491. multiplexing] is not allowed in Vorbis) */
  155492. /* A Vorbis file can be played beginning to end (streamed) without
  155493. worrying ahead of time about chaining (see decoder_example.c). If
  155494. we have the whole file, however, and want random access
  155495. (seeking/scrubbing) or desire to know the total length/time of a
  155496. file, we need to account for the possibility of chaining. */
  155497. /* We can handle things a number of ways; we can determine the entire
  155498. bitstream structure right off the bat, or find pieces on demand.
  155499. This example determines and caches structure for the entire
  155500. bitstream, but builds a virtual decoder on the fly when moving
  155501. between links in the chain. */
  155502. /* There are also different ways to implement seeking. Enough
  155503. information exists in an Ogg bitstream to seek to
  155504. sample-granularity positions in the output. Or, one can seek by
  155505. picking some portion of the stream roughly in the desired area if
  155506. we only want coarse navigation through the stream. */
  155507. /*************************************************************************
  155508. * Many, many internal helpers. The intention is not to be confusing;
  155509. * rampant duplication and monolithic function implementation would be
  155510. * harder to understand anyway. The high level functions are last. Begin
  155511. * grokking near the end of the file */
  155512. /* read a little more data from the file/pipe into the ogg_sync framer
  155513. */
  155514. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155515. over 8k gets what they deserve */
  155516. static long _get_data(OggVorbis_File *vf){
  155517. errno=0;
  155518. if(vf->datasource){
  155519. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155520. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155521. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155522. if(bytes==0 && errno)return(-1);
  155523. return(bytes);
  155524. }else
  155525. return(0);
  155526. }
  155527. /* save a tiny smidge of verbosity to make the code more readable */
  155528. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155529. if(vf->datasource){
  155530. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155531. vf->offset=offset;
  155532. ogg_sync_reset(&vf->oy);
  155533. }else{
  155534. /* shouldn't happen unless someone writes a broken callback */
  155535. return;
  155536. }
  155537. }
  155538. /* The read/seek functions track absolute position within the stream */
  155539. /* from the head of the stream, get the next page. boundary specifies
  155540. if the function is allowed to fetch more data from the stream (and
  155541. how much) or only use internally buffered data.
  155542. boundary: -1) unbounded search
  155543. 0) read no additional data; use cached only
  155544. n) search for a new page beginning for n bytes
  155545. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155546. n) found a page at absolute offset n */
  155547. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155548. ogg_int64_t boundary){
  155549. if(boundary>0)boundary+=vf->offset;
  155550. while(1){
  155551. long more;
  155552. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155553. more=ogg_sync_pageseek(&vf->oy,og);
  155554. if(more<0){
  155555. /* skipped n bytes */
  155556. vf->offset-=more;
  155557. }else{
  155558. if(more==0){
  155559. /* send more paramedics */
  155560. if(!boundary)return(OV_FALSE);
  155561. {
  155562. long ret=_get_data(vf);
  155563. if(ret==0)return(OV_EOF);
  155564. if(ret<0)return(OV_EREAD);
  155565. }
  155566. }else{
  155567. /* got a page. Return the offset at the page beginning,
  155568. advance the internal offset past the page end */
  155569. ogg_int64_t ret=vf->offset;
  155570. vf->offset+=more;
  155571. return(ret);
  155572. }
  155573. }
  155574. }
  155575. }
  155576. /* find the latest page beginning before the current stream cursor
  155577. position. Much dirtier than the above as Ogg doesn't have any
  155578. backward search linkage. no 'readp' as it will certainly have to
  155579. read. */
  155580. /* returns offset or OV_EREAD, OV_FAULT */
  155581. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155582. ogg_int64_t begin=vf->offset;
  155583. ogg_int64_t end=begin;
  155584. ogg_int64_t ret;
  155585. ogg_int64_t offset=-1;
  155586. while(offset==-1){
  155587. begin-=CHUNKSIZE;
  155588. if(begin<0)
  155589. begin=0;
  155590. _seek_helper(vf,begin);
  155591. while(vf->offset<end){
  155592. ret=_get_next_page(vf,og,end-vf->offset);
  155593. if(ret==OV_EREAD)return(OV_EREAD);
  155594. if(ret<0){
  155595. break;
  155596. }else{
  155597. offset=ret;
  155598. }
  155599. }
  155600. }
  155601. /* we have the offset. Actually snork and hold the page now */
  155602. _seek_helper(vf,offset);
  155603. ret=_get_next_page(vf,og,CHUNKSIZE);
  155604. if(ret<0)
  155605. /* this shouldn't be possible */
  155606. return(OV_EFAULT);
  155607. return(offset);
  155608. }
  155609. /* finds each bitstream link one at a time using a bisection search
  155610. (has to begin by knowing the offset of the lb's initial page).
  155611. Recurses for each link so it can alloc the link storage after
  155612. finding them all, then unroll and fill the cache at the same time */
  155613. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155614. ogg_int64_t begin,
  155615. ogg_int64_t searched,
  155616. ogg_int64_t end,
  155617. long currentno,
  155618. long m){
  155619. ogg_int64_t endsearched=end;
  155620. ogg_int64_t next=end;
  155621. ogg_page og;
  155622. ogg_int64_t ret;
  155623. /* the below guards against garbage seperating the last and
  155624. first pages of two links. */
  155625. while(searched<endsearched){
  155626. ogg_int64_t bisect;
  155627. if(endsearched-searched<CHUNKSIZE){
  155628. bisect=searched;
  155629. }else{
  155630. bisect=(searched+endsearched)/2;
  155631. }
  155632. _seek_helper(vf,bisect);
  155633. ret=_get_next_page(vf,&og,-1);
  155634. if(ret==OV_EREAD)return(OV_EREAD);
  155635. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155636. endsearched=bisect;
  155637. if(ret>=0)next=ret;
  155638. }else{
  155639. searched=ret+og.header_len+og.body_len;
  155640. }
  155641. }
  155642. _seek_helper(vf,next);
  155643. ret=_get_next_page(vf,&og,-1);
  155644. if(ret==OV_EREAD)return(OV_EREAD);
  155645. if(searched>=end || ret<0){
  155646. vf->links=m+1;
  155647. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155648. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155649. vf->offsets[m+1]=searched;
  155650. }else{
  155651. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155652. end,ogg_page_serialno(&og),m+1);
  155653. if(ret==OV_EREAD)return(OV_EREAD);
  155654. }
  155655. vf->offsets[m]=begin;
  155656. vf->serialnos[m]=currentno;
  155657. return(0);
  155658. }
  155659. /* uses the local ogg_stream storage in vf; this is important for
  155660. non-streaming input sources */
  155661. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155662. long *serialno,ogg_page *og_ptr){
  155663. ogg_page og;
  155664. ogg_packet op;
  155665. int i,ret;
  155666. if(!og_ptr){
  155667. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155668. if(llret==OV_EREAD)return(OV_EREAD);
  155669. if(llret<0)return OV_ENOTVORBIS;
  155670. og_ptr=&og;
  155671. }
  155672. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155673. if(serialno)*serialno=vf->os.serialno;
  155674. vf->ready_state=STREAMSET;
  155675. /* extract the initial header from the first page and verify that the
  155676. Ogg bitstream is in fact Vorbis data */
  155677. vorbis_info_init(vi);
  155678. vorbis_comment_init(vc);
  155679. i=0;
  155680. while(i<3){
  155681. ogg_stream_pagein(&vf->os,og_ptr);
  155682. while(i<3){
  155683. int result=ogg_stream_packetout(&vf->os,&op);
  155684. if(result==0)break;
  155685. if(result==-1){
  155686. ret=OV_EBADHEADER;
  155687. goto bail_header;
  155688. }
  155689. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155690. goto bail_header;
  155691. }
  155692. i++;
  155693. }
  155694. if(i<3)
  155695. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155696. ret=OV_EBADHEADER;
  155697. goto bail_header;
  155698. }
  155699. }
  155700. return 0;
  155701. bail_header:
  155702. vorbis_info_clear(vi);
  155703. vorbis_comment_clear(vc);
  155704. vf->ready_state=OPENED;
  155705. return ret;
  155706. }
  155707. /* last step of the OggVorbis_File initialization; get all the
  155708. vorbis_info structs and PCM positions. Only called by the seekable
  155709. initialization (local stream storage is hacked slightly; pay
  155710. attention to how that's done) */
  155711. /* this is void and does not propogate errors up because we want to be
  155712. able to open and use damaged bitstreams as well as we can. Just
  155713. watch out for missing information for links in the OggVorbis_File
  155714. struct */
  155715. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155716. ogg_page og;
  155717. int i;
  155718. ogg_int64_t ret;
  155719. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155720. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155721. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155722. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155723. for(i=0;i<vf->links;i++){
  155724. if(i==0){
  155725. /* we already grabbed the initial header earlier. Just set the offset */
  155726. vf->dataoffsets[i]=dataoffset;
  155727. _seek_helper(vf,dataoffset);
  155728. }else{
  155729. /* seek to the location of the initial header */
  155730. _seek_helper(vf,vf->offsets[i]);
  155731. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155732. vf->dataoffsets[i]=-1;
  155733. }else{
  155734. vf->dataoffsets[i]=vf->offset;
  155735. }
  155736. }
  155737. /* fetch beginning PCM offset */
  155738. if(vf->dataoffsets[i]!=-1){
  155739. ogg_int64_t accumulated=0;
  155740. long lastblock=-1;
  155741. int result;
  155742. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155743. while(1){
  155744. ogg_packet op;
  155745. ret=_get_next_page(vf,&og,-1);
  155746. if(ret<0)
  155747. /* this should not be possible unless the file is
  155748. truncated/mangled */
  155749. break;
  155750. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155751. break;
  155752. /* count blocksizes of all frames in the page */
  155753. ogg_stream_pagein(&vf->os,&og);
  155754. while((result=ogg_stream_packetout(&vf->os,&op))){
  155755. if(result>0){ /* ignore holes */
  155756. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155757. if(lastblock!=-1)
  155758. accumulated+=(lastblock+thisblock)>>2;
  155759. lastblock=thisblock;
  155760. }
  155761. }
  155762. if(ogg_page_granulepos(&og)!=-1){
  155763. /* pcm offset of last packet on the first audio page */
  155764. accumulated= ogg_page_granulepos(&og)-accumulated;
  155765. break;
  155766. }
  155767. }
  155768. /* less than zero? This is a stream with samples trimmed off
  155769. the beginning, a normal occurrence; set the offset to zero */
  155770. if(accumulated<0)accumulated=0;
  155771. vf->pcmlengths[i*2]=accumulated;
  155772. }
  155773. /* get the PCM length of this link. To do this,
  155774. get the last page of the stream */
  155775. {
  155776. ogg_int64_t end=vf->offsets[i+1];
  155777. _seek_helper(vf,end);
  155778. while(1){
  155779. ret=_get_prev_page(vf,&og);
  155780. if(ret<0){
  155781. /* this should not be possible */
  155782. vorbis_info_clear(vf->vi+i);
  155783. vorbis_comment_clear(vf->vc+i);
  155784. break;
  155785. }
  155786. if(ogg_page_granulepos(&og)!=-1){
  155787. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155788. break;
  155789. }
  155790. vf->offset=ret;
  155791. }
  155792. }
  155793. }
  155794. }
  155795. static int _make_decode_ready(OggVorbis_File *vf){
  155796. if(vf->ready_state>STREAMSET)return 0;
  155797. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155798. if(vf->seekable){
  155799. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155800. return OV_EBADLINK;
  155801. }else{
  155802. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155803. return OV_EBADLINK;
  155804. }
  155805. vorbis_block_init(&vf->vd,&vf->vb);
  155806. vf->ready_state=INITSET;
  155807. vf->bittrack=0.f;
  155808. vf->samptrack=0.f;
  155809. return 0;
  155810. }
  155811. static int _open_seekable2(OggVorbis_File *vf){
  155812. long serialno=vf->current_serialno;
  155813. ogg_int64_t dataoffset=vf->offset, end;
  155814. ogg_page og;
  155815. /* we're partially open and have a first link header state in
  155816. storage in vf */
  155817. /* we can seek, so set out learning all about this file */
  155818. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155819. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155820. /* We get the offset for the last page of the physical bitstream.
  155821. Most OggVorbis files will contain a single logical bitstream */
  155822. end=_get_prev_page(vf,&og);
  155823. if(end<0)return(end);
  155824. /* more than one logical bitstream? */
  155825. if(ogg_page_serialno(&og)!=serialno){
  155826. /* Chained bitstream. Bisect-search each logical bitstream
  155827. section. Do so based on serial number only */
  155828. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155829. }else{
  155830. /* Only one logical bitstream */
  155831. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155832. }
  155833. /* the initial header memory is referenced by vf after; don't free it */
  155834. _prefetch_all_headers(vf,dataoffset);
  155835. return(ov_raw_seek(vf,0));
  155836. }
  155837. /* clear out the current logical bitstream decoder */
  155838. static void _decode_clear(OggVorbis_File *vf){
  155839. vorbis_dsp_clear(&vf->vd);
  155840. vorbis_block_clear(&vf->vb);
  155841. vf->ready_state=OPENED;
  155842. }
  155843. /* fetch and process a packet. Handles the case where we're at a
  155844. bitstream boundary and dumps the decoding machine. If the decoding
  155845. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155846. date (seek and read both use this. seek uses a special hack with
  155847. readp).
  155848. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155849. 0) need more data (only if readp==0)
  155850. 1) got a packet
  155851. */
  155852. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155853. ogg_packet *op_in,
  155854. int readp,
  155855. int spanp){
  155856. ogg_page og;
  155857. /* handle one packet. Try to fetch it from current stream state */
  155858. /* extract packets from page */
  155859. while(1){
  155860. /* process a packet if we can. If the machine isn't loaded,
  155861. neither is a page */
  155862. if(vf->ready_state==INITSET){
  155863. while(1) {
  155864. ogg_packet op;
  155865. ogg_packet *op_ptr=(op_in?op_in:&op);
  155866. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155867. ogg_int64_t granulepos;
  155868. op_in=NULL;
  155869. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155870. if(result>0){
  155871. /* got a packet. process it */
  155872. granulepos=op_ptr->granulepos;
  155873. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155874. header handling. The
  155875. header packets aren't
  155876. audio, so if/when we
  155877. submit them,
  155878. vorbis_synthesis will
  155879. reject them */
  155880. /* suck in the synthesis data and track bitrate */
  155881. {
  155882. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155883. /* for proper use of libvorbis within libvorbisfile,
  155884. oldsamples will always be zero. */
  155885. if(oldsamples)return(OV_EFAULT);
  155886. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155887. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155888. vf->bittrack+=op_ptr->bytes*8;
  155889. }
  155890. /* update the pcm offset. */
  155891. if(granulepos!=-1 && !op_ptr->e_o_s){
  155892. int link=(vf->seekable?vf->current_link:0);
  155893. int i,samples;
  155894. /* this packet has a pcm_offset on it (the last packet
  155895. completed on a page carries the offset) After processing
  155896. (above), we know the pcm position of the *last* sample
  155897. ready to be returned. Find the offset of the *first*
  155898. As an aside, this trick is inaccurate if we begin
  155899. reading anew right at the last page; the end-of-stream
  155900. granulepos declares the last frame in the stream, and the
  155901. last packet of the last page may be a partial frame.
  155902. So, we need a previous granulepos from an in-sequence page
  155903. to have a reference point. Thus the !op_ptr->e_o_s clause
  155904. above */
  155905. if(vf->seekable && link>0)
  155906. granulepos-=vf->pcmlengths[link*2];
  155907. if(granulepos<0)granulepos=0; /* actually, this
  155908. shouldn't be possible
  155909. here unless the stream
  155910. is very broken */
  155911. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155912. granulepos-=samples;
  155913. for(i=0;i<link;i++)
  155914. granulepos+=vf->pcmlengths[i*2+1];
  155915. vf->pcm_offset=granulepos;
  155916. }
  155917. return(1);
  155918. }
  155919. }
  155920. else
  155921. break;
  155922. }
  155923. }
  155924. if(vf->ready_state>=OPENED){
  155925. ogg_int64_t ret;
  155926. if(!readp)return(0);
  155927. if((ret=_get_next_page(vf,&og,-1))<0){
  155928. return(OV_EOF); /* eof.
  155929. leave unitialized */
  155930. }
  155931. /* bitrate tracking; add the header's bytes here, the body bytes
  155932. are done by packet above */
  155933. vf->bittrack+=og.header_len*8;
  155934. /* has our decoding just traversed a bitstream boundary? */
  155935. if(vf->ready_state==INITSET){
  155936. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155937. if(!spanp)
  155938. return(OV_EOF);
  155939. _decode_clear(vf);
  155940. if(!vf->seekable){
  155941. vorbis_info_clear(vf->vi);
  155942. vorbis_comment_clear(vf->vc);
  155943. }
  155944. }
  155945. }
  155946. }
  155947. /* Do we need to load a new machine before submitting the page? */
  155948. /* This is different in the seekable and non-seekable cases.
  155949. In the seekable case, we already have all the header
  155950. information loaded and cached; we just initialize the machine
  155951. with it and continue on our merry way.
  155952. In the non-seekable (streaming) case, we'll only be at a
  155953. boundary if we just left the previous logical bitstream and
  155954. we're now nominally at the header of the next bitstream
  155955. */
  155956. if(vf->ready_state!=INITSET){
  155957. int link;
  155958. if(vf->ready_state<STREAMSET){
  155959. if(vf->seekable){
  155960. vf->current_serialno=ogg_page_serialno(&og);
  155961. /* match the serialno to bitstream section. We use this rather than
  155962. offset positions to avoid problems near logical bitstream
  155963. boundaries */
  155964. for(link=0;link<vf->links;link++)
  155965. if(vf->serialnos[link]==vf->current_serialno)break;
  155966. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155967. stream. error out,
  155968. leave machine
  155969. uninitialized */
  155970. vf->current_link=link;
  155971. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155972. vf->ready_state=STREAMSET;
  155973. }else{
  155974. /* we're streaming */
  155975. /* fetch the three header packets, build the info struct */
  155976. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155977. if(ret)return(ret);
  155978. vf->current_link++;
  155979. link=0;
  155980. }
  155981. }
  155982. {
  155983. int ret=_make_decode_ready(vf);
  155984. if(ret<0)return ret;
  155985. }
  155986. }
  155987. ogg_stream_pagein(&vf->os,&og);
  155988. }
  155989. }
  155990. /* if, eg, 64 bit stdio is configured by default, this will build with
  155991. fseek64 */
  155992. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155993. if(f==NULL)return(-1);
  155994. return fseek(f,off,whence);
  155995. }
  155996. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155997. long ibytes, ov_callbacks callbacks){
  155998. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155999. int ret;
  156000. memset(vf,0,sizeof(*vf));
  156001. vf->datasource=f;
  156002. vf->callbacks = callbacks;
  156003. /* init the framing state */
  156004. ogg_sync_init(&vf->oy);
  156005. /* perhaps some data was previously read into a buffer for testing
  156006. against other stream types. Allow initialization from this
  156007. previously read data (as we may be reading from a non-seekable
  156008. stream) */
  156009. if(initial){
  156010. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156011. memcpy(buffer,initial,ibytes);
  156012. ogg_sync_wrote(&vf->oy,ibytes);
  156013. }
  156014. /* can we seek? Stevens suggests the seek test was portable */
  156015. if(offsettest!=-1)vf->seekable=1;
  156016. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156017. entry for partial open */
  156018. vf->links=1;
  156019. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156020. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156021. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156022. /* Try to fetch the headers, maintaining all the storage */
  156023. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156024. vf->datasource=NULL;
  156025. ov_clear(vf);
  156026. }else
  156027. vf->ready_state=PARTOPEN;
  156028. return(ret);
  156029. }
  156030. static int _ov_open2(OggVorbis_File *vf){
  156031. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156032. vf->ready_state=OPENED;
  156033. if(vf->seekable){
  156034. int ret=_open_seekable2(vf);
  156035. if(ret){
  156036. vf->datasource=NULL;
  156037. ov_clear(vf);
  156038. }
  156039. return(ret);
  156040. }else
  156041. vf->ready_state=STREAMSET;
  156042. return 0;
  156043. }
  156044. /* clear out the OggVorbis_File struct */
  156045. int ov_clear(OggVorbis_File *vf){
  156046. if(vf){
  156047. vorbis_block_clear(&vf->vb);
  156048. vorbis_dsp_clear(&vf->vd);
  156049. ogg_stream_clear(&vf->os);
  156050. if(vf->vi && vf->links){
  156051. int i;
  156052. for(i=0;i<vf->links;i++){
  156053. vorbis_info_clear(vf->vi+i);
  156054. vorbis_comment_clear(vf->vc+i);
  156055. }
  156056. _ogg_free(vf->vi);
  156057. _ogg_free(vf->vc);
  156058. }
  156059. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156060. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156061. if(vf->serialnos)_ogg_free(vf->serialnos);
  156062. if(vf->offsets)_ogg_free(vf->offsets);
  156063. ogg_sync_clear(&vf->oy);
  156064. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156065. memset(vf,0,sizeof(*vf));
  156066. }
  156067. #ifdef DEBUG_LEAKS
  156068. _VDBG_dump();
  156069. #endif
  156070. return(0);
  156071. }
  156072. /* inspects the OggVorbis file and finds/documents all the logical
  156073. bitstreams contained in it. Tries to be tolerant of logical
  156074. bitstream sections that are truncated/woogie.
  156075. return: -1) error
  156076. 0) OK
  156077. */
  156078. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156079. ov_callbacks callbacks){
  156080. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156081. if(ret)return ret;
  156082. return _ov_open2(vf);
  156083. }
  156084. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156085. ov_callbacks callbacks = {
  156086. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156087. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156088. (int (*)(void *)) fclose,
  156089. (long (*)(void *)) ftell
  156090. };
  156091. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156092. }
  156093. /* cheap hack for game usage where downsampling is desirable; there's
  156094. no need for SRC as we can just do it cheaply in libvorbis. */
  156095. int ov_halfrate(OggVorbis_File *vf,int flag){
  156096. int i;
  156097. if(vf->vi==NULL)return OV_EINVAL;
  156098. if(!vf->seekable)return OV_EINVAL;
  156099. if(vf->ready_state>=STREAMSET)
  156100. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156101. will be able to swap this on the fly, but
  156102. for now dumping the decode machine is needed
  156103. to reinit the MDCT lookups. 1.1 libvorbis
  156104. is planned to be able to switch on the fly */
  156105. for(i=0;i<vf->links;i++){
  156106. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156107. ov_halfrate(vf,0);
  156108. return OV_EINVAL;
  156109. }
  156110. }
  156111. return 0;
  156112. }
  156113. int ov_halfrate_p(OggVorbis_File *vf){
  156114. if(vf->vi==NULL)return OV_EINVAL;
  156115. return vorbis_synthesis_halfrate_p(vf->vi);
  156116. }
  156117. /* Only partially open the vorbis file; test for Vorbisness, and load
  156118. the headers for the first chain. Do not seek (although test for
  156119. seekability). Use ov_test_open to finish opening the file, else
  156120. ov_clear to close/free it. Same return codes as open. */
  156121. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156122. ov_callbacks callbacks)
  156123. {
  156124. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156125. }
  156126. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156127. ov_callbacks callbacks = {
  156128. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156129. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156130. (int (*)(void *)) fclose,
  156131. (long (*)(void *)) ftell
  156132. };
  156133. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156134. }
  156135. int ov_test_open(OggVorbis_File *vf){
  156136. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156137. return _ov_open2(vf);
  156138. }
  156139. /* How many logical bitstreams in this physical bitstream? */
  156140. long ov_streams(OggVorbis_File *vf){
  156141. return vf->links;
  156142. }
  156143. /* Is the FILE * associated with vf seekable? */
  156144. long ov_seekable(OggVorbis_File *vf){
  156145. return vf->seekable;
  156146. }
  156147. /* returns the bitrate for a given logical bitstream or the entire
  156148. physical bitstream. If the file is open for random access, it will
  156149. find the *actual* average bitrate. If the file is streaming, it
  156150. returns the nominal bitrate (if set) else the average of the
  156151. upper/lower bounds (if set) else -1 (unset).
  156152. If you want the actual bitrate field settings, get them from the
  156153. vorbis_info structs */
  156154. long ov_bitrate(OggVorbis_File *vf,int i){
  156155. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156156. if(i>=vf->links)return(OV_EINVAL);
  156157. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156158. if(i<0){
  156159. ogg_int64_t bits=0;
  156160. int i;
  156161. float br;
  156162. for(i=0;i<vf->links;i++)
  156163. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156164. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156165. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156166. * so this is slightly transformed to make it work.
  156167. */
  156168. br = bits/ov_time_total(vf,-1);
  156169. return(rint(br));
  156170. }else{
  156171. if(vf->seekable){
  156172. /* return the actual bitrate */
  156173. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156174. }else{
  156175. /* return nominal if set */
  156176. if(vf->vi[i].bitrate_nominal>0){
  156177. return vf->vi[i].bitrate_nominal;
  156178. }else{
  156179. if(vf->vi[i].bitrate_upper>0){
  156180. if(vf->vi[i].bitrate_lower>0){
  156181. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156182. }else{
  156183. return vf->vi[i].bitrate_upper;
  156184. }
  156185. }
  156186. return(OV_FALSE);
  156187. }
  156188. }
  156189. }
  156190. }
  156191. /* returns the actual bitrate since last call. returns -1 if no
  156192. additional data to offer since last call (or at beginning of stream),
  156193. EINVAL if stream is only partially open
  156194. */
  156195. long ov_bitrate_instant(OggVorbis_File *vf){
  156196. int link=(vf->seekable?vf->current_link:0);
  156197. long ret;
  156198. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156199. if(vf->samptrack==0)return(OV_FALSE);
  156200. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156201. vf->bittrack=0.f;
  156202. vf->samptrack=0.f;
  156203. return(ret);
  156204. }
  156205. /* Guess */
  156206. long ov_serialnumber(OggVorbis_File *vf,int i){
  156207. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156208. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156209. if(i<0){
  156210. return(vf->current_serialno);
  156211. }else{
  156212. return(vf->serialnos[i]);
  156213. }
  156214. }
  156215. /* returns: total raw (compressed) length of content if i==-1
  156216. raw (compressed) length of that logical bitstream for i==0 to n
  156217. OV_EINVAL if the stream is not seekable (we can't know the length)
  156218. or if stream is only partially open
  156219. */
  156220. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156221. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156222. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156223. if(i<0){
  156224. ogg_int64_t acc=0;
  156225. int i;
  156226. for(i=0;i<vf->links;i++)
  156227. acc+=ov_raw_total(vf,i);
  156228. return(acc);
  156229. }else{
  156230. return(vf->offsets[i+1]-vf->offsets[i]);
  156231. }
  156232. }
  156233. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156234. (samples) of that logical bitstream for i==0 to n
  156235. OV_EINVAL if the stream is not seekable (we can't know the
  156236. length) or only partially open
  156237. */
  156238. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156239. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156240. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156241. if(i<0){
  156242. ogg_int64_t acc=0;
  156243. int i;
  156244. for(i=0;i<vf->links;i++)
  156245. acc+=ov_pcm_total(vf,i);
  156246. return(acc);
  156247. }else{
  156248. return(vf->pcmlengths[i*2+1]);
  156249. }
  156250. }
  156251. /* returns: total seconds of content if i==-1
  156252. seconds in that logical bitstream for i==0 to n
  156253. OV_EINVAL if the stream is not seekable (we can't know the
  156254. length) or only partially open
  156255. */
  156256. double ov_time_total(OggVorbis_File *vf,int i){
  156257. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156258. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156259. if(i<0){
  156260. double acc=0;
  156261. int i;
  156262. for(i=0;i<vf->links;i++)
  156263. acc+=ov_time_total(vf,i);
  156264. return(acc);
  156265. }else{
  156266. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156267. }
  156268. }
  156269. /* seek to an offset relative to the *compressed* data. This also
  156270. scans packets to update the PCM cursor. It will cross a logical
  156271. bitstream boundary, but only if it can't get any packets out of the
  156272. tail of the bitstream we seek to (so no surprises).
  156273. returns zero on success, nonzero on failure */
  156274. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156275. ogg_stream_state work_os;
  156276. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156277. if(!vf->seekable)
  156278. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156279. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156280. /* don't yet clear out decoding machine (if it's initialized), in
  156281. the case we're in the same link. Restart the decode lapping, and
  156282. let _fetch_and_process_packet deal with a potential bitstream
  156283. boundary */
  156284. vf->pcm_offset=-1;
  156285. ogg_stream_reset_serialno(&vf->os,
  156286. vf->current_serialno); /* must set serialno */
  156287. vorbis_synthesis_restart(&vf->vd);
  156288. _seek_helper(vf,pos);
  156289. /* we need to make sure the pcm_offset is set, but we don't want to
  156290. advance the raw cursor past good packets just to get to the first
  156291. with a granulepos. That's not equivalent behavior to beginning
  156292. decoding as immediately after the seek position as possible.
  156293. So, a hack. We use two stream states; a local scratch state and
  156294. the shared vf->os stream state. We use the local state to
  156295. scan, and the shared state as a buffer for later decode.
  156296. Unfortuantely, on the last page we still advance to last packet
  156297. because the granulepos on the last page is not necessarily on a
  156298. packet boundary, and we need to make sure the granpos is
  156299. correct.
  156300. */
  156301. {
  156302. ogg_page og;
  156303. ogg_packet op;
  156304. int lastblock=0;
  156305. int accblock=0;
  156306. int thisblock;
  156307. int eosflag;
  156308. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156309. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156310. return from not necessarily
  156311. starting from the beginning */
  156312. while(1){
  156313. if(vf->ready_state>=STREAMSET){
  156314. /* snarf/scan a packet if we can */
  156315. int result=ogg_stream_packetout(&work_os,&op);
  156316. if(result>0){
  156317. if(vf->vi[vf->current_link].codec_setup){
  156318. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156319. if(thisblock<0){
  156320. ogg_stream_packetout(&vf->os,NULL);
  156321. thisblock=0;
  156322. }else{
  156323. if(eosflag)
  156324. ogg_stream_packetout(&vf->os,NULL);
  156325. else
  156326. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156327. }
  156328. if(op.granulepos!=-1){
  156329. int i,link=vf->current_link;
  156330. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156331. if(granulepos<0)granulepos=0;
  156332. for(i=0;i<link;i++)
  156333. granulepos+=vf->pcmlengths[i*2+1];
  156334. vf->pcm_offset=granulepos-accblock;
  156335. break;
  156336. }
  156337. lastblock=thisblock;
  156338. continue;
  156339. }else
  156340. ogg_stream_packetout(&vf->os,NULL);
  156341. }
  156342. }
  156343. if(!lastblock){
  156344. if(_get_next_page(vf,&og,-1)<0){
  156345. vf->pcm_offset=ov_pcm_total(vf,-1);
  156346. break;
  156347. }
  156348. }else{
  156349. /* huh? Bogus stream with packets but no granulepos */
  156350. vf->pcm_offset=-1;
  156351. break;
  156352. }
  156353. /* has our decoding just traversed a bitstream boundary? */
  156354. if(vf->ready_state>=STREAMSET)
  156355. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156356. _decode_clear(vf); /* clear out stream state */
  156357. ogg_stream_clear(&work_os);
  156358. }
  156359. if(vf->ready_state<STREAMSET){
  156360. int link;
  156361. vf->current_serialno=ogg_page_serialno(&og);
  156362. for(link=0;link<vf->links;link++)
  156363. if(vf->serialnos[link]==vf->current_serialno)break;
  156364. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156365. error out, leave
  156366. machine uninitialized */
  156367. vf->current_link=link;
  156368. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156369. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156370. vf->ready_state=STREAMSET;
  156371. }
  156372. ogg_stream_pagein(&vf->os,&og);
  156373. ogg_stream_pagein(&work_os,&og);
  156374. eosflag=ogg_page_eos(&og);
  156375. }
  156376. }
  156377. ogg_stream_clear(&work_os);
  156378. vf->bittrack=0.f;
  156379. vf->samptrack=0.f;
  156380. return(0);
  156381. seek_error:
  156382. /* dump the machine so we're in a known state */
  156383. vf->pcm_offset=-1;
  156384. ogg_stream_clear(&work_os);
  156385. _decode_clear(vf);
  156386. return OV_EBADLINK;
  156387. }
  156388. /* Page granularity seek (faster than sample granularity because we
  156389. don't do the last bit of decode to find a specific sample).
  156390. Seek to the last [granule marked] page preceeding the specified pos
  156391. location, such that decoding past the returned point will quickly
  156392. arrive at the requested position. */
  156393. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156394. int link=-1;
  156395. ogg_int64_t result=0;
  156396. ogg_int64_t total=ov_pcm_total(vf,-1);
  156397. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156398. if(!vf->seekable)return(OV_ENOSEEK);
  156399. if(pos<0 || pos>total)return(OV_EINVAL);
  156400. /* which bitstream section does this pcm offset occur in? */
  156401. for(link=vf->links-1;link>=0;link--){
  156402. total-=vf->pcmlengths[link*2+1];
  156403. if(pos>=total)break;
  156404. }
  156405. /* search within the logical bitstream for the page with the highest
  156406. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156407. missing pages or incorrect frame number information in the
  156408. bitstream could make our task impossible. Account for that (it
  156409. would be an error condition) */
  156410. /* new search algorithm by HB (Nicholas Vinen) */
  156411. {
  156412. ogg_int64_t end=vf->offsets[link+1];
  156413. ogg_int64_t begin=vf->offsets[link];
  156414. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156415. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156416. ogg_int64_t target=pos-total+begintime;
  156417. ogg_int64_t best=begin;
  156418. ogg_page og;
  156419. while(begin<end){
  156420. ogg_int64_t bisect;
  156421. if(end-begin<CHUNKSIZE){
  156422. bisect=begin;
  156423. }else{
  156424. /* take a (pretty decent) guess. */
  156425. bisect=begin +
  156426. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156427. if(bisect<=begin)
  156428. bisect=begin+1;
  156429. }
  156430. _seek_helper(vf,bisect);
  156431. while(begin<end){
  156432. result=_get_next_page(vf,&og,end-vf->offset);
  156433. if(result==OV_EREAD) goto seek_error;
  156434. if(result<0){
  156435. if(bisect<=begin+1)
  156436. end=begin; /* found it */
  156437. else{
  156438. if(bisect==0) goto seek_error;
  156439. bisect-=CHUNKSIZE;
  156440. if(bisect<=begin)bisect=begin+1;
  156441. _seek_helper(vf,bisect);
  156442. }
  156443. }else{
  156444. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156445. if(granulepos==-1)continue;
  156446. if(granulepos<target){
  156447. best=result; /* raw offset of packet with granulepos */
  156448. begin=vf->offset; /* raw offset of next page */
  156449. begintime=granulepos;
  156450. if(target-begintime>44100)break;
  156451. bisect=begin; /* *not* begin + 1 */
  156452. }else{
  156453. if(bisect<=begin+1)
  156454. end=begin; /* found it */
  156455. else{
  156456. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156457. end=result;
  156458. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156459. if(bisect<=begin)bisect=begin+1;
  156460. _seek_helper(vf,bisect);
  156461. }else{
  156462. end=result;
  156463. endtime=granulepos;
  156464. break;
  156465. }
  156466. }
  156467. }
  156468. }
  156469. }
  156470. }
  156471. /* found our page. seek to it, update pcm offset. Easier case than
  156472. raw_seek, don't keep packets preceeding granulepos. */
  156473. {
  156474. ogg_page og;
  156475. ogg_packet op;
  156476. /* seek */
  156477. _seek_helper(vf,best);
  156478. vf->pcm_offset=-1;
  156479. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156480. if(link!=vf->current_link){
  156481. /* Different link; dump entire decode machine */
  156482. _decode_clear(vf);
  156483. vf->current_link=link;
  156484. vf->current_serialno=ogg_page_serialno(&og);
  156485. vf->ready_state=STREAMSET;
  156486. }else{
  156487. vorbis_synthesis_restart(&vf->vd);
  156488. }
  156489. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156490. ogg_stream_pagein(&vf->os,&og);
  156491. /* pull out all but last packet; the one with granulepos */
  156492. while(1){
  156493. result=ogg_stream_packetpeek(&vf->os,&op);
  156494. if(result==0){
  156495. /* !!! the packet finishing this page originated on a
  156496. preceeding page. Keep fetching previous pages until we
  156497. get one with a granulepos or without the 'continued' flag
  156498. set. Then just use raw_seek for simplicity. */
  156499. _seek_helper(vf,best);
  156500. while(1){
  156501. result=_get_prev_page(vf,&og);
  156502. if(result<0) goto seek_error;
  156503. if(ogg_page_granulepos(&og)>-1 ||
  156504. !ogg_page_continued(&og)){
  156505. return ov_raw_seek(vf,result);
  156506. }
  156507. vf->offset=result;
  156508. }
  156509. }
  156510. if(result<0){
  156511. result = OV_EBADPACKET;
  156512. goto seek_error;
  156513. }
  156514. if(op.granulepos!=-1){
  156515. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156516. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156517. vf->pcm_offset+=total;
  156518. break;
  156519. }else
  156520. result=ogg_stream_packetout(&vf->os,NULL);
  156521. }
  156522. }
  156523. }
  156524. /* verify result */
  156525. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156526. result=OV_EFAULT;
  156527. goto seek_error;
  156528. }
  156529. vf->bittrack=0.f;
  156530. vf->samptrack=0.f;
  156531. return(0);
  156532. seek_error:
  156533. /* dump machine so we're in a known state */
  156534. vf->pcm_offset=-1;
  156535. _decode_clear(vf);
  156536. return (int)result;
  156537. }
  156538. /* seek to a sample offset relative to the decompressed pcm stream
  156539. returns zero on success, nonzero on failure */
  156540. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156541. int thisblock,lastblock=0;
  156542. int ret=ov_pcm_seek_page(vf,pos);
  156543. if(ret<0)return(ret);
  156544. if((ret=_make_decode_ready(vf)))return ret;
  156545. /* discard leading packets we don't need for the lapping of the
  156546. position we want; don't decode them */
  156547. while(1){
  156548. ogg_packet op;
  156549. ogg_page og;
  156550. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156551. if(ret>0){
  156552. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156553. if(thisblock<0){
  156554. ogg_stream_packetout(&vf->os,NULL);
  156555. continue; /* non audio packet */
  156556. }
  156557. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156558. if(vf->pcm_offset+((thisblock+
  156559. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156560. /* remove the packet from packet queue and track its granulepos */
  156561. ogg_stream_packetout(&vf->os,NULL);
  156562. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156563. only tracking, no
  156564. pcm_decode */
  156565. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156566. /* end of logical stream case is hard, especially with exact
  156567. length positioning. */
  156568. if(op.granulepos>-1){
  156569. int i;
  156570. /* always believe the stream markers */
  156571. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156572. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156573. for(i=0;i<vf->current_link;i++)
  156574. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156575. }
  156576. lastblock=thisblock;
  156577. }else{
  156578. if(ret<0 && ret!=OV_HOLE)break;
  156579. /* suck in a new page */
  156580. if(_get_next_page(vf,&og,-1)<0)break;
  156581. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156582. if(vf->ready_state<STREAMSET){
  156583. int link;
  156584. vf->current_serialno=ogg_page_serialno(&og);
  156585. for(link=0;link<vf->links;link++)
  156586. if(vf->serialnos[link]==vf->current_serialno)break;
  156587. if(link==vf->links)return(OV_EBADLINK);
  156588. vf->current_link=link;
  156589. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156590. vf->ready_state=STREAMSET;
  156591. ret=_make_decode_ready(vf);
  156592. if(ret)return ret;
  156593. lastblock=0;
  156594. }
  156595. ogg_stream_pagein(&vf->os,&og);
  156596. }
  156597. }
  156598. vf->bittrack=0.f;
  156599. vf->samptrack=0.f;
  156600. /* discard samples until we reach the desired position. Crossing a
  156601. logical bitstream boundary with abandon is OK. */
  156602. while(vf->pcm_offset<pos){
  156603. ogg_int64_t target=pos-vf->pcm_offset;
  156604. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156605. if(samples>target)samples=target;
  156606. vorbis_synthesis_read(&vf->vd,samples);
  156607. vf->pcm_offset+=samples;
  156608. if(samples<target)
  156609. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156610. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156611. }
  156612. return 0;
  156613. }
  156614. /* seek to a playback time relative to the decompressed pcm stream
  156615. returns zero on success, nonzero on failure */
  156616. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156617. /* translate time to PCM position and call ov_pcm_seek */
  156618. int link=-1;
  156619. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156620. double time_total=ov_time_total(vf,-1);
  156621. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156622. if(!vf->seekable)return(OV_ENOSEEK);
  156623. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156624. /* which bitstream section does this time offset occur in? */
  156625. for(link=vf->links-1;link>=0;link--){
  156626. pcm_total-=vf->pcmlengths[link*2+1];
  156627. time_total-=ov_time_total(vf,link);
  156628. if(seconds>=time_total)break;
  156629. }
  156630. /* enough information to convert time offset to pcm offset */
  156631. {
  156632. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156633. return(ov_pcm_seek(vf,target));
  156634. }
  156635. }
  156636. /* page-granularity version of ov_time_seek
  156637. returns zero on success, nonzero on failure */
  156638. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156639. /* translate time to PCM position and call ov_pcm_seek */
  156640. int link=-1;
  156641. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156642. double time_total=ov_time_total(vf,-1);
  156643. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156644. if(!vf->seekable)return(OV_ENOSEEK);
  156645. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156646. /* which bitstream section does this time offset occur in? */
  156647. for(link=vf->links-1;link>=0;link--){
  156648. pcm_total-=vf->pcmlengths[link*2+1];
  156649. time_total-=ov_time_total(vf,link);
  156650. if(seconds>=time_total)break;
  156651. }
  156652. /* enough information to convert time offset to pcm offset */
  156653. {
  156654. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156655. return(ov_pcm_seek_page(vf,target));
  156656. }
  156657. }
  156658. /* tell the current stream offset cursor. Note that seek followed by
  156659. tell will likely not give the set offset due to caching */
  156660. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156661. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156662. return(vf->offset);
  156663. }
  156664. /* return PCM offset (sample) of next PCM sample to be read */
  156665. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156666. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156667. return(vf->pcm_offset);
  156668. }
  156669. /* return time offset (seconds) of next PCM sample to be read */
  156670. double ov_time_tell(OggVorbis_File *vf){
  156671. int link=0;
  156672. ogg_int64_t pcm_total=0;
  156673. double time_total=0.f;
  156674. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156675. if(vf->seekable){
  156676. pcm_total=ov_pcm_total(vf,-1);
  156677. time_total=ov_time_total(vf,-1);
  156678. /* which bitstream section does this time offset occur in? */
  156679. for(link=vf->links-1;link>=0;link--){
  156680. pcm_total-=vf->pcmlengths[link*2+1];
  156681. time_total-=ov_time_total(vf,link);
  156682. if(vf->pcm_offset>=pcm_total)break;
  156683. }
  156684. }
  156685. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156686. }
  156687. /* link: -1) return the vorbis_info struct for the bitstream section
  156688. currently being decoded
  156689. 0-n) to request information for a specific bitstream section
  156690. In the case of a non-seekable bitstream, any call returns the
  156691. current bitstream. NULL in the case that the machine is not
  156692. initialized */
  156693. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156694. if(vf->seekable){
  156695. if(link<0)
  156696. if(vf->ready_state>=STREAMSET)
  156697. return vf->vi+vf->current_link;
  156698. else
  156699. return vf->vi;
  156700. else
  156701. if(link>=vf->links)
  156702. return NULL;
  156703. else
  156704. return vf->vi+link;
  156705. }else{
  156706. return vf->vi;
  156707. }
  156708. }
  156709. /* grr, strong typing, grr, no templates/inheritence, grr */
  156710. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156711. if(vf->seekable){
  156712. if(link<0)
  156713. if(vf->ready_state>=STREAMSET)
  156714. return vf->vc+vf->current_link;
  156715. else
  156716. return vf->vc;
  156717. else
  156718. if(link>=vf->links)
  156719. return NULL;
  156720. else
  156721. return vf->vc+link;
  156722. }else{
  156723. return vf->vc;
  156724. }
  156725. }
  156726. static int host_is_big_endian() {
  156727. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156728. unsigned char *bytewise = (unsigned char *)&pattern;
  156729. if (bytewise[0] == 0xfe) return 1;
  156730. return 0;
  156731. }
  156732. /* up to this point, everything could more or less hide the multiple
  156733. logical bitstream nature of chaining from the toplevel application
  156734. if the toplevel application didn't particularly care. However, at
  156735. the point that we actually read audio back, the multiple-section
  156736. nature must surface: Multiple bitstream sections do not necessarily
  156737. have to have the same number of channels or sampling rate.
  156738. ov_read returns the sequential logical bitstream number currently
  156739. being decoded along with the PCM data in order that the toplevel
  156740. application can take action on channel/sample rate changes. This
  156741. number will be incremented even for streamed (non-seekable) streams
  156742. (for seekable streams, it represents the actual logical bitstream
  156743. index within the physical bitstream. Note that the accessor
  156744. functions above are aware of this dichotomy).
  156745. input values: buffer) a buffer to hold packed PCM data for return
  156746. length) the byte length requested to be placed into buffer
  156747. bigendianp) should the data be packed LSB first (0) or
  156748. MSB first (1)
  156749. word) word size for output. currently 1 (byte) or
  156750. 2 (16 bit short)
  156751. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156752. 0) EOF
  156753. n) number of bytes of PCM actually returned. The
  156754. below works on a packet-by-packet basis, so the
  156755. return length is not related to the 'length' passed
  156756. in, just guaranteed to fit.
  156757. *section) set to the logical bitstream number */
  156758. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156759. int bigendianp,int word,int sgned,int *bitstream){
  156760. int i,j;
  156761. int host_endian = host_is_big_endian();
  156762. float **pcm;
  156763. long samples;
  156764. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156765. while(1){
  156766. if(vf->ready_state==INITSET){
  156767. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156768. if(samples)break;
  156769. }
  156770. /* suck in another packet */
  156771. {
  156772. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156773. if(ret==OV_EOF)
  156774. return(0);
  156775. if(ret<=0)
  156776. return(ret);
  156777. }
  156778. }
  156779. if(samples>0){
  156780. /* yay! proceed to pack data into the byte buffer */
  156781. long channels=ov_info(vf,-1)->channels;
  156782. long bytespersample=word * channels;
  156783. vorbis_fpu_control fpu;
  156784. (void) fpu; // (to avoid a warning about it being unused)
  156785. if(samples>length/bytespersample)samples=length/bytespersample;
  156786. if(samples <= 0)
  156787. return OV_EINVAL;
  156788. /* a tight loop to pack each size */
  156789. {
  156790. int val;
  156791. if(word==1){
  156792. int off=(sgned?0:128);
  156793. vorbis_fpu_setround(&fpu);
  156794. for(j=0;j<samples;j++)
  156795. for(i=0;i<channels;i++){
  156796. val=vorbis_ftoi(pcm[i][j]*128.f);
  156797. if(val>127)val=127;
  156798. else if(val<-128)val=-128;
  156799. *buffer++=val+off;
  156800. }
  156801. vorbis_fpu_restore(fpu);
  156802. }else{
  156803. int off=(sgned?0:32768);
  156804. if(host_endian==bigendianp){
  156805. if(sgned){
  156806. vorbis_fpu_setround(&fpu);
  156807. for(i=0;i<channels;i++) { /* It's faster in this order */
  156808. float *src=pcm[i];
  156809. short *dest=((short *)buffer)+i;
  156810. for(j=0;j<samples;j++) {
  156811. val=vorbis_ftoi(src[j]*32768.f);
  156812. if(val>32767)val=32767;
  156813. else if(val<-32768)val=-32768;
  156814. *dest=val;
  156815. dest+=channels;
  156816. }
  156817. }
  156818. vorbis_fpu_restore(fpu);
  156819. }else{
  156820. vorbis_fpu_setround(&fpu);
  156821. for(i=0;i<channels;i++) {
  156822. float *src=pcm[i];
  156823. short *dest=((short *)buffer)+i;
  156824. for(j=0;j<samples;j++) {
  156825. val=vorbis_ftoi(src[j]*32768.f);
  156826. if(val>32767)val=32767;
  156827. else if(val<-32768)val=-32768;
  156828. *dest=val+off;
  156829. dest+=channels;
  156830. }
  156831. }
  156832. vorbis_fpu_restore(fpu);
  156833. }
  156834. }else if(bigendianp){
  156835. vorbis_fpu_setround(&fpu);
  156836. for(j=0;j<samples;j++)
  156837. for(i=0;i<channels;i++){
  156838. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156839. if(val>32767)val=32767;
  156840. else if(val<-32768)val=-32768;
  156841. val+=off;
  156842. *buffer++=(val>>8);
  156843. *buffer++=(val&0xff);
  156844. }
  156845. vorbis_fpu_restore(fpu);
  156846. }else{
  156847. int val;
  156848. vorbis_fpu_setround(&fpu);
  156849. for(j=0;j<samples;j++)
  156850. for(i=0;i<channels;i++){
  156851. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156852. if(val>32767)val=32767;
  156853. else if(val<-32768)val=-32768;
  156854. val+=off;
  156855. *buffer++=(val&0xff);
  156856. *buffer++=(val>>8);
  156857. }
  156858. vorbis_fpu_restore(fpu);
  156859. }
  156860. }
  156861. }
  156862. vorbis_synthesis_read(&vf->vd,samples);
  156863. vf->pcm_offset+=samples;
  156864. if(bitstream)*bitstream=vf->current_link;
  156865. return(samples*bytespersample);
  156866. }else{
  156867. return(samples);
  156868. }
  156869. }
  156870. /* input values: pcm_channels) a float vector per channel of output
  156871. length) the sample length being read by the app
  156872. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156873. 0) EOF
  156874. n) number of samples of PCM actually returned. The
  156875. below works on a packet-by-packet basis, so the
  156876. return length is not related to the 'length' passed
  156877. in, just guaranteed to fit.
  156878. *section) set to the logical bitstream number */
  156879. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156880. int *bitstream){
  156881. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156882. while(1){
  156883. if(vf->ready_state==INITSET){
  156884. float **pcm;
  156885. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156886. if(samples){
  156887. if(pcm_channels)*pcm_channels=pcm;
  156888. if(samples>length)samples=length;
  156889. vorbis_synthesis_read(&vf->vd,samples);
  156890. vf->pcm_offset+=samples;
  156891. if(bitstream)*bitstream=vf->current_link;
  156892. return samples;
  156893. }
  156894. }
  156895. /* suck in another packet */
  156896. {
  156897. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156898. if(ret==OV_EOF)return(0);
  156899. if(ret<=0)return(ret);
  156900. }
  156901. }
  156902. }
  156903. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156904. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156905. ogg_int64_t off);
  156906. static void _ov_splice(float **pcm,float **lappcm,
  156907. int n1, int n2,
  156908. int ch1, int ch2,
  156909. float *w1, float *w2){
  156910. int i,j;
  156911. float *w=w1;
  156912. int n=n1;
  156913. if(n1>n2){
  156914. n=n2;
  156915. w=w2;
  156916. }
  156917. /* splice */
  156918. for(j=0;j<ch1 && j<ch2;j++){
  156919. float *s=lappcm[j];
  156920. float *d=pcm[j];
  156921. for(i=0;i<n;i++){
  156922. float wd=w[i]*w[i];
  156923. float ws=1.-wd;
  156924. d[i]=d[i]*wd + s[i]*ws;
  156925. }
  156926. }
  156927. /* window from zero */
  156928. for(;j<ch2;j++){
  156929. float *d=pcm[j];
  156930. for(i=0;i<n;i++){
  156931. float wd=w[i]*w[i];
  156932. d[i]=d[i]*wd;
  156933. }
  156934. }
  156935. }
  156936. /* make sure vf is INITSET */
  156937. static int _ov_initset(OggVorbis_File *vf){
  156938. while(1){
  156939. if(vf->ready_state==INITSET)break;
  156940. /* suck in another packet */
  156941. {
  156942. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156943. if(ret<0 && ret!=OV_HOLE)return(ret);
  156944. }
  156945. }
  156946. return 0;
  156947. }
  156948. /* make sure vf is INITSET and that we have a primed buffer; if
  156949. we're crosslapping at a stream section boundary, this also makes
  156950. sure we're sanity checking against the right stream information */
  156951. static int _ov_initprime(OggVorbis_File *vf){
  156952. vorbis_dsp_state *vd=&vf->vd;
  156953. while(1){
  156954. if(vf->ready_state==INITSET)
  156955. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156956. /* suck in another packet */
  156957. {
  156958. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156959. if(ret<0 && ret!=OV_HOLE)return(ret);
  156960. }
  156961. }
  156962. return 0;
  156963. }
  156964. /* grab enough data for lapping from vf; this may be in the form of
  156965. unreturned, already-decoded pcm, remaining PCM we will need to
  156966. decode, or synthetic postextrapolation from last packets. */
  156967. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156968. float **lappcm,int lapsize){
  156969. int lapcount=0,i;
  156970. float **pcm;
  156971. /* try first to decode the lapping data */
  156972. while(lapcount<lapsize){
  156973. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156974. if(samples){
  156975. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156976. for(i=0;i<vi->channels;i++)
  156977. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156978. lapcount+=samples;
  156979. vorbis_synthesis_read(vd,samples);
  156980. }else{
  156981. /* suck in another packet */
  156982. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156983. if(ret==OV_EOF)break;
  156984. }
  156985. }
  156986. if(lapcount<lapsize){
  156987. /* failed to get lapping data from normal decode; pry it from the
  156988. postextrapolation buffering, or the second half of the MDCT
  156989. from the last packet */
  156990. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156991. if(samples==0){
  156992. for(i=0;i<vi->channels;i++)
  156993. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156994. lapcount=lapsize;
  156995. }else{
  156996. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156997. for(i=0;i<vi->channels;i++)
  156998. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156999. lapcount+=samples;
  157000. }
  157001. }
  157002. }
  157003. /* this sets up crosslapping of a sample by using trailing data from
  157004. sample 1 and lapping it into the windowing buffer of sample 2 */
  157005. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157006. vorbis_info *vi1,*vi2;
  157007. float **lappcm;
  157008. float **pcm;
  157009. float *w1,*w2;
  157010. int n1,n2,i,ret,hs1,hs2;
  157011. if(vf1==vf2)return(0); /* degenerate case */
  157012. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157013. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157014. /* the relevant overlap buffers must be pre-checked and pre-primed
  157015. before looking at settings in the event that priming would cross
  157016. a bitstream boundary. So, do it now */
  157017. ret=_ov_initset(vf1);
  157018. if(ret)return(ret);
  157019. ret=_ov_initprime(vf2);
  157020. if(ret)return(ret);
  157021. vi1=ov_info(vf1,-1);
  157022. vi2=ov_info(vf2,-1);
  157023. hs1=ov_halfrate_p(vf1);
  157024. hs2=ov_halfrate_p(vf2);
  157025. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157026. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157027. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157028. w1=vorbis_window(&vf1->vd,0);
  157029. w2=vorbis_window(&vf2->vd,0);
  157030. for(i=0;i<vi1->channels;i++)
  157031. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157032. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157033. /* have a lapping buffer from vf1; now to splice it into the lapping
  157034. buffer of vf2 */
  157035. /* consolidate and expose the buffer. */
  157036. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157037. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157038. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157039. /* splice */
  157040. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157041. /* done */
  157042. return(0);
  157043. }
  157044. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157045. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157046. vorbis_info *vi;
  157047. float **lappcm;
  157048. float **pcm;
  157049. float *w1,*w2;
  157050. int n1,n2,ch1,ch2,hs;
  157051. int i,ret;
  157052. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157053. ret=_ov_initset(vf);
  157054. if(ret)return(ret);
  157055. vi=ov_info(vf,-1);
  157056. hs=ov_halfrate_p(vf);
  157057. ch1=vi->channels;
  157058. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157059. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157060. persistent; even if the decode state
  157061. from this link gets dumped, this
  157062. window array continues to exist */
  157063. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157064. for(i=0;i<ch1;i++)
  157065. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157066. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157067. /* have lapping data; seek and prime the buffer */
  157068. ret=localseek(vf,pos);
  157069. if(ret)return ret;
  157070. ret=_ov_initprime(vf);
  157071. if(ret)return(ret);
  157072. /* Guard against cross-link changes; they're perfectly legal */
  157073. vi=ov_info(vf,-1);
  157074. ch2=vi->channels;
  157075. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157076. w2=vorbis_window(&vf->vd,0);
  157077. /* consolidate and expose the buffer. */
  157078. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157079. /* splice */
  157080. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157081. /* done */
  157082. return(0);
  157083. }
  157084. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157085. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157086. }
  157087. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157088. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157089. }
  157090. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157091. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157092. }
  157093. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157094. int (*localseek)(OggVorbis_File *,double)){
  157095. vorbis_info *vi;
  157096. float **lappcm;
  157097. float **pcm;
  157098. float *w1,*w2;
  157099. int n1,n2,ch1,ch2,hs;
  157100. int i,ret;
  157101. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157102. ret=_ov_initset(vf);
  157103. if(ret)return(ret);
  157104. vi=ov_info(vf,-1);
  157105. hs=ov_halfrate_p(vf);
  157106. ch1=vi->channels;
  157107. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157108. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157109. persistent; even if the decode state
  157110. from this link gets dumped, this
  157111. window array continues to exist */
  157112. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157113. for(i=0;i<ch1;i++)
  157114. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157115. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157116. /* have lapping data; seek and prime the buffer */
  157117. ret=localseek(vf,pos);
  157118. if(ret)return ret;
  157119. ret=_ov_initprime(vf);
  157120. if(ret)return(ret);
  157121. /* Guard against cross-link changes; they're perfectly legal */
  157122. vi=ov_info(vf,-1);
  157123. ch2=vi->channels;
  157124. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157125. w2=vorbis_window(&vf->vd,0);
  157126. /* consolidate and expose the buffer. */
  157127. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157128. /* splice */
  157129. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157130. /* done */
  157131. return(0);
  157132. }
  157133. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157134. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157135. }
  157136. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157137. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157138. }
  157139. #endif
  157140. /*** End of inlined file: vorbisfile.c ***/
  157141. /*** Start of inlined file: window.c ***/
  157142. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157143. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157144. // tasks..
  157145. #if JUCE_MSVC
  157146. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157147. #endif
  157148. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157149. #if JUCE_USE_OGGVORBIS
  157150. #include <stdlib.h>
  157151. #include <math.h>
  157152. static float vwin64[32] = {
  157153. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157154. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157155. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157156. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157157. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157158. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157159. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157160. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157161. };
  157162. static float vwin128[64] = {
  157163. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157164. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157165. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157166. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157167. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157168. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157169. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157170. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157171. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157172. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157173. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157174. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157175. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157176. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157177. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157178. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157179. };
  157180. static float vwin256[128] = {
  157181. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157182. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157183. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157184. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157185. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157186. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157187. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157188. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157189. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157190. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157191. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157192. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157193. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157194. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157195. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157196. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157197. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157198. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157199. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157200. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157201. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157202. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157203. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157204. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157205. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157206. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157207. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157208. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157209. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157210. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157211. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157212. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157213. };
  157214. static float vwin512[256] = {
  157215. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157216. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157217. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157218. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157219. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157220. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157221. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157222. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157223. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157224. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157225. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157226. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157227. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157228. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157229. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157230. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157231. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157232. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157233. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157234. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157235. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157236. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157237. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157238. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157239. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157240. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157241. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157242. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157243. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157244. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157245. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157246. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157247. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157248. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157249. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157250. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157251. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157252. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157253. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157254. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157255. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157256. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157257. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157258. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157259. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157260. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157261. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157262. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157263. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157264. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157265. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157266. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157267. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157268. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157269. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157270. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157271. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157272. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157273. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157274. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157275. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157276. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157277. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157278. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157279. };
  157280. static float vwin1024[512] = {
  157281. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157282. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157283. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157284. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157285. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157286. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157287. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157288. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157289. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157290. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157291. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157292. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157293. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157294. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157295. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157296. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157297. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157298. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157299. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157300. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157301. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157302. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157303. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157304. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157305. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157306. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157307. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157308. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157309. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157310. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157311. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157312. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157313. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157314. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157315. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157316. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157317. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157318. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157319. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157320. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157321. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157322. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157323. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157324. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157325. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157326. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157327. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157328. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157329. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157330. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157331. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157332. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157333. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157334. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157335. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157336. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157337. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157338. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157339. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157340. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157341. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157342. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157343. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157344. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157345. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157346. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157347. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157348. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157349. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157350. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157351. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157352. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157353. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157354. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157355. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157356. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157357. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157358. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157359. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157360. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157361. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157362. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157363. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157364. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157365. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157366. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157367. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157368. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157369. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157370. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157371. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157372. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157373. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157374. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157375. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157376. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157377. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157378. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157379. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157380. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157381. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157382. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157383. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157384. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157385. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157386. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157387. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157388. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157389. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157390. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157391. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157392. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157393. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157394. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157395. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157396. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157397. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157398. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157399. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157400. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157401. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157402. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157403. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157404. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157405. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157406. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157407. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157408. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157409. };
  157410. static float vwin2048[1024] = {
  157411. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157412. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157413. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157414. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157415. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157416. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157417. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157418. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157419. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157420. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157421. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157422. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157423. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157424. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157425. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157426. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157427. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157428. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157429. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157430. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157431. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157432. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157433. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157434. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157435. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157436. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157437. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157438. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157439. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157440. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157441. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157442. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157443. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157444. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157445. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157446. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157447. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157448. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157449. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157450. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157451. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157452. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157453. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157454. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157455. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157456. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157457. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157458. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157459. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157460. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157461. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157462. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157463. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157464. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157465. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157466. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157467. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157468. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157469. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157470. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157471. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157472. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157473. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157474. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157475. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157476. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157477. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157478. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157479. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157480. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157481. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157482. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157483. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157484. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157485. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157486. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157487. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157488. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157489. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157490. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157491. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157492. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157493. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157494. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157495. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157496. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157497. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157498. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157499. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157500. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157501. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157502. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157503. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157504. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157505. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157506. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157507. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157508. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157509. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157510. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157511. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157512. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157513. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157514. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157515. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157516. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157517. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157518. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157519. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157520. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157521. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157522. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157523. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157524. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157525. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157526. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157527. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157528. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157529. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157530. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157531. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157532. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157533. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157534. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157535. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157536. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157537. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157538. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157539. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157540. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157541. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157542. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157543. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157544. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157545. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157546. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157547. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157548. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157549. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157550. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157551. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157552. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157553. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157554. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157555. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157556. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157557. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157558. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157559. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157560. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157561. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157562. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157563. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157564. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157565. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157566. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157567. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157568. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157569. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157570. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157571. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157572. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157573. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157574. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157575. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157576. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157577. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157578. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157579. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157580. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157581. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157582. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157583. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157584. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157585. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157586. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157587. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157588. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157589. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157590. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157591. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157592. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157593. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157594. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157595. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157596. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157597. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157598. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157599. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157600. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157601. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157602. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157603. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157604. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157605. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157606. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157607. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157608. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157609. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157610. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157611. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157612. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157613. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157614. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157615. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157616. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157617. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157618. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157619. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157620. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157621. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157622. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157623. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157624. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157625. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157626. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157627. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157628. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157629. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157630. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157631. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157632. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157633. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157634. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157635. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157636. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157637. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157638. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157639. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157640. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157641. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157642. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157643. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157644. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157645. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157646. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157647. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157648. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157649. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157650. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157651. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157652. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157653. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157654. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157655. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157656. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157657. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157658. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157659. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157660. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157661. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157662. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157663. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157664. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157665. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157666. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157667. };
  157668. static float vwin4096[2048] = {
  157669. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157670. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157671. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157672. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157673. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157674. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157675. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157676. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157677. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157678. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157679. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157680. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157681. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157682. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157683. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157684. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157685. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157686. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157687. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157688. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157689. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157690. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157691. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157692. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157693. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157694. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157695. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157696. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157697. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157698. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157699. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157700. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157701. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157702. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157703. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157704. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157705. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157706. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157707. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157708. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157709. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157710. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157711. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157712. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157713. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157714. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157715. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157716. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157717. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157718. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157719. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157720. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157721. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157722. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157723. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157724. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157725. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157726. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157727. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157728. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157729. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157730. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157731. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157732. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157733. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157734. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157735. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157736. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157737. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157738. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157739. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157740. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157741. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157742. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157743. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157744. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157745. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157746. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157747. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157748. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157749. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157750. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157751. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157752. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157753. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157754. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157755. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157756. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157757. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157758. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157759. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157760. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157761. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157762. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157763. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157764. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157765. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157766. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157767. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157768. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157769. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157770. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157771. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157772. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157773. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157774. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157775. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157776. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157777. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157778. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157779. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157780. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157781. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157782. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157783. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157784. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157785. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157786. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157787. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157788. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157789. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157790. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157791. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157792. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157793. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157794. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157795. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157796. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157797. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157798. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157799. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157800. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157801. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157802. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157803. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157804. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157805. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157806. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157807. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157808. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157809. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157810. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157811. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157812. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157813. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157814. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157815. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157816. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157817. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157818. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157819. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157820. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157821. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157822. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157823. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157824. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157825. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157826. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157827. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157828. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157829. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157830. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157831. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157832. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157833. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157834. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157835. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157836. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157837. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157838. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157839. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157840. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157841. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157842. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157843. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157844. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157845. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157846. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157847. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157848. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157849. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157850. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157851. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157852. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157853. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157854. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157855. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157856. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157857. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157858. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157859. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157860. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157861. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157862. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157863. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157864. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157865. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157866. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157867. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157868. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157869. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157870. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157871. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157872. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157873. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157874. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157875. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157876. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157877. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157878. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157879. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157880. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157881. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157882. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157883. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157884. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157885. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157886. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157887. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157888. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157889. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157890. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157891. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157892. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157893. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157894. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157895. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157896. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157897. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157898. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157899. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157900. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157901. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157902. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157903. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157904. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157905. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157906. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157907. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157908. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157909. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157910. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157911. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157912. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157913. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157914. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157915. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157916. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157917. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157918. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157919. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157920. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157921. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157922. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157923. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157924. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157925. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157926. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157927. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157928. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157929. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157930. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157931. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157932. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157933. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157934. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157935. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157936. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157937. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157938. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157939. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157940. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157941. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157942. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157943. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157944. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157945. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157946. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157947. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157948. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157949. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157950. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157951. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157952. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157953. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157954. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157955. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157956. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157957. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157958. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157959. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157960. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157961. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157962. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157963. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157964. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157965. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157966. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157967. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157968. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157969. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157970. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157971. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157972. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157973. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157974. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157975. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157976. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157977. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157978. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157979. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157980. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157981. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157982. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157983. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157984. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157985. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157986. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157987. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157988. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157989. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157990. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157991. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157992. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157993. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157994. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157995. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157996. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157997. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157998. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157999. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158000. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158001. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158002. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158003. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158004. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158005. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158006. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158007. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158008. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158009. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158010. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158011. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158012. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158013. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158014. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158015. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158016. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158017. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158018. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158019. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158020. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158021. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158022. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158023. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158024. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158025. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158026. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158027. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158028. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158029. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158030. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158031. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158032. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158033. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158034. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158035. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158036. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158037. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158038. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158039. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158040. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158041. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158042. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158043. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158044. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158045. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158046. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158047. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158048. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158049. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158050. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158051. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158052. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158053. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158054. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158055. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158056. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158057. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158058. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158059. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158060. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158061. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158062. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158063. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158064. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158065. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158066. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158067. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158068. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158069. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158070. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158071. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158072. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158073. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158074. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158075. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158076. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158077. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158078. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158079. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158080. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158081. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158082. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158083. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158084. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158085. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158086. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158087. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158088. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158089. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158090. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158091. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158092. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158093. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158094. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158095. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158096. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158097. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158098. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158099. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158100. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158101. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158102. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158103. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158104. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158105. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158106. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158107. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158108. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158109. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158110. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158111. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158112. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158113. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158114. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158115. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158116. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158117. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158118. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158119. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158120. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158121. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158122. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158123. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158124. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158125. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158126. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158127. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158128. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158129. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158130. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158131. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158132. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158133. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158134. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158135. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158136. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158137. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158138. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158139. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158140. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158141. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158142. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158143. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158144. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158145. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158146. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158147. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158148. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158149. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158150. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158151. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158152. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158153. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158154. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158155. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158156. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158157. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158158. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158159. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158160. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158161. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158162. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158163. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158164. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158165. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158166. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158167. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158168. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158169. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158170. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158171. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158172. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158173. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158174. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158175. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158176. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158177. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158178. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158179. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158180. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158181. };
  158182. static float vwin8192[4096] = {
  158183. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158184. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158185. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158186. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158187. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158188. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158189. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158190. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158191. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158192. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158193. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158194. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158195. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158196. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158197. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158198. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158199. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158200. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158201. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158202. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158203. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158204. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158205. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158206. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158207. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158208. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158209. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158210. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158211. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158212. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158213. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158214. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158215. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158216. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158217. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158218. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158219. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158220. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158221. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158222. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158223. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158224. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158225. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158226. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158227. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158228. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158229. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158230. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158231. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158232. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158233. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158234. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158235. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158236. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158237. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158238. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158239. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158240. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158241. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158242. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158243. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158244. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158245. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158246. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158247. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158248. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158249. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158250. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158251. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158252. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158253. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158254. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158255. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158256. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158257. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158258. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158259. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158260. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158261. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158262. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158263. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158264. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158265. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158266. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158267. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158268. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158269. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158270. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158271. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158272. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158273. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158274. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158275. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158276. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158277. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158278. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158279. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158280. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158281. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158282. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158283. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158284. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158285. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158286. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158287. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158288. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158289. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158290. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158291. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158292. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158293. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158294. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158295. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158296. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158297. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158298. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158299. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158300. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158301. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158302. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158303. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158304. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158305. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158306. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158307. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158308. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158309. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158310. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158311. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158312. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158313. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158314. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158315. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158316. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158317. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158318. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158319. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158320. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158321. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158322. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158323. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158324. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158325. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158326. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158327. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158328. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158329. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158330. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158331. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158332. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158333. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158334. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158335. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158336. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158337. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158338. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158339. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158340. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158341. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158342. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158343. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158344. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158345. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158346. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158347. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158348. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158349. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158350. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158351. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158352. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158353. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158354. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158355. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158356. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158357. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158358. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158359. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158360. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158361. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158362. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158363. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158364. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158365. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158366. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158367. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158368. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158369. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158370. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158371. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158372. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158373. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158374. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158375. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158376. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158377. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158378. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158379. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158380. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158381. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158382. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158383. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158384. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158385. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158386. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158387. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158388. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158389. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158390. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158391. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158392. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158393. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158394. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158395. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158396. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158397. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158398. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158399. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158400. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158401. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158402. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158403. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158404. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158405. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158406. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158407. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158408. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158409. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158410. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158411. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158412. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158413. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158414. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158415. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158416. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158417. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158418. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158419. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158420. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158421. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158422. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158423. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158424. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158425. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158426. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158427. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158428. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158429. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158430. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158431. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158432. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158433. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158434. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158435. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158436. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158437. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158438. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158439. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158440. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158441. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158442. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158443. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158444. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158445. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158446. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158447. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158448. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158449. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158450. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158451. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158452. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158453. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158454. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158455. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158456. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158457. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158458. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158459. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158460. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158461. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158462. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158463. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158464. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158465. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158466. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158467. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158468. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158469. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158470. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158471. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158472. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158473. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158474. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158475. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158476. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158477. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158478. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158479. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158480. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158481. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158482. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158483. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158484. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158485. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158486. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158487. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158488. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158489. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158490. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158491. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158492. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158493. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158494. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158495. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158496. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158497. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158498. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158499. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158500. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158501. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158502. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158503. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158504. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158505. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158506. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158507. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158508. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158509. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158510. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158511. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158512. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158513. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158514. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158515. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158516. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158517. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158518. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158519. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158520. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158521. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158522. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158523. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158524. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158525. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158526. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158527. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158528. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158529. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158530. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158531. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158532. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158533. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158534. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158535. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158536. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158537. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158538. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158539. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158540. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158541. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158542. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158543. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158544. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158545. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158546. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158547. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158548. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158549. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158550. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158551. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158552. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158553. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158554. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158555. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158556. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158557. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158558. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158559. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158560. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158561. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158562. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158563. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158564. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158565. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158566. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158567. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158568. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158569. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158570. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158571. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158572. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158573. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158574. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158575. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158576. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158577. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158578. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158579. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158580. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158581. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158582. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158583. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158584. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158585. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158586. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158587. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158588. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158589. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158590. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158591. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158592. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158593. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158594. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158595. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158596. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158597. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158598. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158599. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158600. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158601. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158602. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158603. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158604. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158605. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158606. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158607. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158608. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158609. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158610. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158611. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158612. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158613. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158614. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158615. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158616. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158617. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158618. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158619. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158620. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158621. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158622. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158623. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158624. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158625. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158626. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158627. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158628. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158629. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158630. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158631. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158632. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158633. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158634. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158635. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158636. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158637. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158638. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158639. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158640. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158641. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158642. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158643. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158644. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158645. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158646. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158647. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158648. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158649. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158650. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158651. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158652. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158653. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158654. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158655. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158656. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158657. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158658. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158659. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158660. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158661. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158662. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158663. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158664. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158665. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158666. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158667. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158668. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158669. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158670. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158671. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158672. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158673. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158674. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158675. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158676. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158677. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158678. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158679. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158680. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158681. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158682. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158683. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158684. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158685. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158686. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158687. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158688. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158689. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158690. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158691. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158692. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158693. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158694. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158695. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158696. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158697. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158698. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158699. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158700. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158701. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158702. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158703. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158704. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158705. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158706. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158707. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158708. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158709. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158710. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158711. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158712. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158713. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158714. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158715. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158716. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158717. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158718. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158719. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158720. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158721. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158722. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158723. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158724. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158725. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158726. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158727. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158728. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158729. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158730. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158731. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158732. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158733. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158734. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158735. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158736. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158737. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158738. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158739. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158740. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158741. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158742. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158743. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158744. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158745. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158746. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158747. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158748. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158749. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158750. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158751. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158752. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158753. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158754. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158755. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158756. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158757. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158758. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158759. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158760. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158761. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158762. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158763. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158764. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158765. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158766. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158767. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158768. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158769. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158770. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158771. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158772. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158773. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158774. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158775. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158776. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158777. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158778. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158779. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158780. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158781. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158782. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158783. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158784. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158785. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158786. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158787. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158788. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158789. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158790. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158791. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158792. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158793. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158794. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158795. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158796. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158797. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158798. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158799. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158800. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158801. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158802. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158803. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158804. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158805. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158806. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158807. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158808. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158809. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158810. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158811. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158812. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158813. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158814. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158815. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158816. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158817. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158818. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158819. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158820. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158821. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158822. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158823. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158824. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158825. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158826. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158827. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158828. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158829. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158830. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158831. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158832. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158833. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158834. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158835. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158836. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158837. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158838. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158839. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158840. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158841. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158842. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158843. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158844. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158845. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158846. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158847. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158848. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158849. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158850. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158851. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158852. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158853. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158854. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158855. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158856. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158857. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158858. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158859. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158860. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158861. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158862. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158863. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158864. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158865. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158866. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158867. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158868. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158869. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158870. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158871. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158872. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158873. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158874. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158875. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158876. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158877. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158878. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158879. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158880. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158881. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158882. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158883. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158884. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158885. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158886. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158887. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158888. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158889. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158890. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158891. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158892. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158893. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158894. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158895. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158896. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158897. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158898. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158899. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158900. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158901. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158902. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158903. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158904. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158905. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158906. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158907. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158908. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158909. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158910. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158911. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158912. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158913. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158914. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158915. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158916. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158917. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158918. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158919. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158920. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158921. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158922. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158923. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158924. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158925. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158926. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158927. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158928. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158929. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158930. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158931. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158932. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158933. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158934. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158935. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158936. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158937. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158938. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158939. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158940. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158941. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158942. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158943. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158944. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158945. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158946. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158947. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158948. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158949. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158950. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158951. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158952. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158953. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158954. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158955. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158956. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158957. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158958. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158959. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158960. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158961. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158962. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158963. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158964. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158965. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158966. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158967. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158968. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158969. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158970. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158971. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158972. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158973. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158974. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158975. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158976. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158977. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158978. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158979. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158980. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158981. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158982. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158983. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158984. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158985. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158986. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158987. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158988. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158989. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158990. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158991. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158992. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158993. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158994. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158995. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158996. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158997. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158998. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158999. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159000. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159001. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159002. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159003. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159004. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159005. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159006. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159007. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159008. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159009. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159010. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159011. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159012. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159013. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159014. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159015. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159016. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159017. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159018. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159019. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159020. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159021. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159022. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159023. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159024. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159025. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159026. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159027. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159028. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159029. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159030. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159031. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159032. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159033. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159034. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159035. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159036. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159037. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159038. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159039. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159040. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159041. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159042. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159043. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159044. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159045. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159046. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159047. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159048. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159049. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159050. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159051. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159052. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159053. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159054. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159055. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159056. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159057. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159058. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159059. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159060. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159061. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159062. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159063. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159064. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159065. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159066. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159067. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159068. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159069. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159070. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159071. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159072. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159073. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159074. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159075. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159076. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159077. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159078. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159079. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159080. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159081. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159082. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159083. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159084. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159085. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159086. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159087. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159088. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159089. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159090. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159091. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159092. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159093. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159094. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159095. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159096. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159097. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159098. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159099. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159100. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159101. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159102. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159103. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159104. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159105. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159106. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159107. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159108. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159109. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159110. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159111. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159112. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159113. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159114. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159115. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159116. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159117. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159118. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159119. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159120. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159121. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159122. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159123. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159124. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159125. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159126. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159127. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159128. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159129. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159130. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159131. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159132. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159133. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159134. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159135. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159136. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159137. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159138. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159139. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159140. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159141. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159142. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159143. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159144. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159145. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159146. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159147. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159148. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159149. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159150. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159151. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159152. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159153. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159154. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159155. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159156. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159157. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159158. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159159. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159160. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159161. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159162. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159163. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159164. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159165. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159166. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159167. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159168. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159169. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159170. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159171. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159172. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159173. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159174. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159175. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159176. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159177. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159178. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159179. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159180. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159181. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159182. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159183. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159184. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159185. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159186. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159187. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159188. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159189. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159190. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159191. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159192. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159193. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159194. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159195. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159196. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159197. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159198. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159199. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159200. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159201. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159202. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159203. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159204. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159205. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159206. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159207. };
  159208. static float *vwin[8] = {
  159209. vwin64,
  159210. vwin128,
  159211. vwin256,
  159212. vwin512,
  159213. vwin1024,
  159214. vwin2048,
  159215. vwin4096,
  159216. vwin8192,
  159217. };
  159218. float *_vorbis_window_get(int n){
  159219. return vwin[n];
  159220. }
  159221. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159222. int lW,int W,int nW){
  159223. lW=(W?lW:0);
  159224. nW=(W?nW:0);
  159225. {
  159226. float *windowLW=vwin[winno[lW]];
  159227. float *windowNW=vwin[winno[nW]];
  159228. long n=blocksizes[W];
  159229. long ln=blocksizes[lW];
  159230. long rn=blocksizes[nW];
  159231. long leftbegin=n/4-ln/4;
  159232. long leftend=leftbegin+ln/2;
  159233. long rightbegin=n/2+n/4-rn/4;
  159234. long rightend=rightbegin+rn/2;
  159235. int i,p;
  159236. for(i=0;i<leftbegin;i++)
  159237. d[i]=0.f;
  159238. for(p=0;i<leftend;i++,p++)
  159239. d[i]*=windowLW[p];
  159240. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159241. d[i]*=windowNW[p];
  159242. for(;i<n;i++)
  159243. d[i]=0.f;
  159244. }
  159245. }
  159246. #endif
  159247. /*** End of inlined file: window.c ***/
  159248. #else
  159249. #include <vorbis/vorbisenc.h>
  159250. #include <vorbis/codec.h>
  159251. #include <vorbis/vorbisfile.h>
  159252. #endif
  159253. }
  159254. #undef max
  159255. #undef min
  159256. BEGIN_JUCE_NAMESPACE
  159257. static const char* const oggFormatName = "Ogg-Vorbis file";
  159258. static const char* const oggExtensions[] = { ".ogg", 0 };
  159259. class OggReader : public AudioFormatReader
  159260. {
  159261. OggVorbisNamespace::OggVorbis_File ovFile;
  159262. OggVorbisNamespace::ov_callbacks callbacks;
  159263. AudioSampleBuffer reservoir;
  159264. int reservoirStart, samplesInReservoir;
  159265. public:
  159266. OggReader (InputStream* const inp)
  159267. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159268. reservoir (2, 4096),
  159269. reservoirStart (0),
  159270. samplesInReservoir (0)
  159271. {
  159272. using namespace OggVorbisNamespace;
  159273. sampleRate = 0;
  159274. usesFloatingPointData = true;
  159275. callbacks.read_func = &oggReadCallback;
  159276. callbacks.seek_func = &oggSeekCallback;
  159277. callbacks.close_func = &oggCloseCallback;
  159278. callbacks.tell_func = &oggTellCallback;
  159279. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159280. if (err == 0)
  159281. {
  159282. vorbis_info* info = ov_info (&ovFile, -1);
  159283. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159284. numChannels = info->channels;
  159285. bitsPerSample = 16;
  159286. sampleRate = info->rate;
  159287. reservoir.setSize (numChannels,
  159288. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159289. }
  159290. }
  159291. ~OggReader()
  159292. {
  159293. OggVorbisNamespace::ov_clear (&ovFile);
  159294. }
  159295. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159296. int64 startSampleInFile, int numSamples)
  159297. {
  159298. while (numSamples > 0)
  159299. {
  159300. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159301. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159302. {
  159303. // got a few samples overlapping, so use them before seeking..
  159304. const int numToUse = jmin (numSamples, numAvailable);
  159305. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159306. if (destSamples[i] != 0)
  159307. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159308. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159309. sizeof (float) * numToUse);
  159310. startSampleInFile += numToUse;
  159311. numSamples -= numToUse;
  159312. startOffsetInDestBuffer += numToUse;
  159313. if (numSamples == 0)
  159314. break;
  159315. }
  159316. if (startSampleInFile < reservoirStart
  159317. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159318. {
  159319. // buffer miss, so refill the reservoir
  159320. int bitStream = 0;
  159321. reservoirStart = jmax (0, (int) startSampleInFile);
  159322. samplesInReservoir = reservoir.getNumSamples();
  159323. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159324. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159325. int offset = 0;
  159326. int numToRead = samplesInReservoir;
  159327. while (numToRead > 0)
  159328. {
  159329. float** dataIn = 0;
  159330. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159331. if (samps <= 0)
  159332. break;
  159333. jassert (samps <= numToRead);
  159334. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159335. {
  159336. memcpy (reservoir.getSampleData (i, offset),
  159337. dataIn[i],
  159338. sizeof (float) * samps);
  159339. }
  159340. numToRead -= samps;
  159341. offset += samps;
  159342. }
  159343. if (numToRead > 0)
  159344. reservoir.clear (offset, numToRead);
  159345. }
  159346. }
  159347. if (numSamples > 0)
  159348. {
  159349. for (int i = numDestChannels; --i >= 0;)
  159350. if (destSamples[i] != 0)
  159351. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159352. sizeof (int) * numSamples);
  159353. }
  159354. return true;
  159355. }
  159356. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159357. {
  159358. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159359. }
  159360. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159361. {
  159362. InputStream* const in = static_cast <InputStream*> (datasource);
  159363. if (whence == SEEK_CUR)
  159364. offset += in->getPosition();
  159365. else if (whence == SEEK_END)
  159366. offset += in->getTotalLength();
  159367. in->setPosition (offset);
  159368. return 0;
  159369. }
  159370. static int oggCloseCallback (void*)
  159371. {
  159372. return 0;
  159373. }
  159374. static long oggTellCallback (void* datasource)
  159375. {
  159376. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159377. }
  159378. juce_UseDebuggingNewOperator
  159379. };
  159380. class OggWriter : public AudioFormatWriter
  159381. {
  159382. OggVorbisNamespace::ogg_stream_state os;
  159383. OggVorbisNamespace::ogg_page og;
  159384. OggVorbisNamespace::ogg_packet op;
  159385. OggVorbisNamespace::vorbis_info vi;
  159386. OggVorbisNamespace::vorbis_comment vc;
  159387. OggVorbisNamespace::vorbis_dsp_state vd;
  159388. OggVorbisNamespace::vorbis_block vb;
  159389. public:
  159390. bool ok;
  159391. OggWriter (OutputStream* const out,
  159392. const double sampleRate,
  159393. const int numChannels,
  159394. const int bitsPerSample,
  159395. const int qualityIndex)
  159396. : AudioFormatWriter (out, TRANS (oggFormatName),
  159397. sampleRate,
  159398. numChannels,
  159399. bitsPerSample)
  159400. {
  159401. using namespace OggVorbisNamespace;
  159402. ok = false;
  159403. vorbis_info_init (&vi);
  159404. if (vorbis_encode_init_vbr (&vi,
  159405. numChannels,
  159406. (int) sampleRate,
  159407. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159408. {
  159409. vorbis_comment_init (&vc);
  159410. if (JUCEApplication::getInstance() != 0)
  159411. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159412. vorbis_analysis_init (&vd, &vi);
  159413. vorbis_block_init (&vd, &vb);
  159414. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159415. ogg_packet header;
  159416. ogg_packet header_comm;
  159417. ogg_packet header_code;
  159418. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159419. ogg_stream_packetin (&os, &header);
  159420. ogg_stream_packetin (&os, &header_comm);
  159421. ogg_stream_packetin (&os, &header_code);
  159422. for (;;)
  159423. {
  159424. if (ogg_stream_flush (&os, &og) == 0)
  159425. break;
  159426. output->write (og.header, og.header_len);
  159427. output->write (og.body, og.body_len);
  159428. }
  159429. ok = true;
  159430. }
  159431. }
  159432. ~OggWriter()
  159433. {
  159434. using namespace OggVorbisNamespace;
  159435. if (ok)
  159436. {
  159437. // write a zero-length packet to show ogg that we're finished..
  159438. write (0, 0);
  159439. ogg_stream_clear (&os);
  159440. vorbis_block_clear (&vb);
  159441. vorbis_dsp_clear (&vd);
  159442. vorbis_comment_clear (&vc);
  159443. vorbis_info_clear (&vi);
  159444. output->flush();
  159445. }
  159446. else
  159447. {
  159448. vorbis_info_clear (&vi);
  159449. output = 0; // to stop the base class deleting this, as it needs to be returned
  159450. // to the caller of createWriter()
  159451. }
  159452. }
  159453. bool write (const int** samplesToWrite, int numSamples)
  159454. {
  159455. using namespace OggVorbisNamespace;
  159456. if (! ok)
  159457. return false;
  159458. if (numSamples > 0)
  159459. {
  159460. const double gain = 1.0 / 0x80000000u;
  159461. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159462. for (int i = numChannels; --i >= 0;)
  159463. {
  159464. float* const dst = vorbisBuffer[i];
  159465. const int* const src = samplesToWrite [i];
  159466. if (src != 0 && dst != 0)
  159467. {
  159468. for (int j = 0; j < numSamples; ++j)
  159469. dst[j] = (float) (src[j] * gain);
  159470. }
  159471. }
  159472. }
  159473. vorbis_analysis_wrote (&vd, numSamples);
  159474. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159475. {
  159476. vorbis_analysis (&vb, 0);
  159477. vorbis_bitrate_addblock (&vb);
  159478. while (vorbis_bitrate_flushpacket (&vd, &op))
  159479. {
  159480. ogg_stream_packetin (&os, &op);
  159481. for (;;)
  159482. {
  159483. if (ogg_stream_pageout (&os, &og) == 0)
  159484. break;
  159485. output->write (og.header, og.header_len);
  159486. output->write (og.body, og.body_len);
  159487. if (ogg_page_eos (&og))
  159488. break;
  159489. }
  159490. }
  159491. }
  159492. return true;
  159493. }
  159494. juce_UseDebuggingNewOperator
  159495. };
  159496. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159497. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159498. {
  159499. }
  159500. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159501. {
  159502. }
  159503. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159504. {
  159505. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159506. return Array <int> (rates);
  159507. }
  159508. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159509. {
  159510. const int depths[] = { 32, 0 };
  159511. return Array <int> (depths);
  159512. }
  159513. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159514. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159515. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159516. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159517. const bool deleteStreamIfOpeningFails)
  159518. {
  159519. ScopedPointer <OggReader> r (new OggReader (in));
  159520. if (r->sampleRate != 0)
  159521. return r.release();
  159522. if (! deleteStreamIfOpeningFails)
  159523. r->input = 0;
  159524. return 0;
  159525. }
  159526. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159527. double sampleRate,
  159528. unsigned int numChannels,
  159529. int bitsPerSample,
  159530. const StringPairArray& /*metadataValues*/,
  159531. int qualityOptionIndex)
  159532. {
  159533. ScopedPointer <OggWriter> w (new OggWriter (out,
  159534. sampleRate,
  159535. numChannels,
  159536. bitsPerSample,
  159537. qualityOptionIndex));
  159538. return w->ok ? w.release() : 0;
  159539. }
  159540. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159541. {
  159542. StringArray s;
  159543. s.add ("Low Quality");
  159544. s.add ("Medium Quality");
  159545. s.add ("High Quality");
  159546. return s;
  159547. }
  159548. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159549. {
  159550. FileInputStream* const in = source.createInputStream();
  159551. if (in != 0)
  159552. {
  159553. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159554. if (r != 0)
  159555. {
  159556. const int64 numSamps = r->lengthInSamples;
  159557. r = 0;
  159558. const int64 fileNumSamps = source.getSize() / 4;
  159559. const double ratio = numSamps / (double) fileNumSamps;
  159560. if (ratio > 12.0)
  159561. return 0;
  159562. else if (ratio > 6.0)
  159563. return 1;
  159564. else
  159565. return 2;
  159566. }
  159567. }
  159568. return 1;
  159569. }
  159570. END_JUCE_NAMESPACE
  159571. #endif
  159572. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159573. #endif
  159574. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159575. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159576. #if JUCE_MSVC
  159577. #pragma warning (push)
  159578. #endif
  159579. namespace jpeglibNamespace
  159580. {
  159581. #if JUCE_INCLUDE_JPEGLIB_CODE
  159582. #if JUCE_MINGW
  159583. typedef unsigned char boolean;
  159584. #endif
  159585. #define JPEG_INTERNALS
  159586. #undef FAR
  159587. /*** Start of inlined file: jpeglib.h ***/
  159588. #ifndef JPEGLIB_H
  159589. #define JPEGLIB_H
  159590. /*
  159591. * First we include the configuration files that record how this
  159592. * installation of the JPEG library is set up. jconfig.h can be
  159593. * generated automatically for many systems. jmorecfg.h contains
  159594. * manual configuration options that most people need not worry about.
  159595. */
  159596. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159597. /*** Start of inlined file: jconfig.h ***/
  159598. /* see jconfig.doc for explanations */
  159599. // disable all the warnings under MSVC
  159600. #ifdef _MSC_VER
  159601. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159602. #endif
  159603. #ifdef __BORLANDC__
  159604. #pragma warn -8057
  159605. #pragma warn -8019
  159606. #pragma warn -8004
  159607. #pragma warn -8008
  159608. #endif
  159609. #define HAVE_PROTOTYPES
  159610. #define HAVE_UNSIGNED_CHAR
  159611. #define HAVE_UNSIGNED_SHORT
  159612. /* #define void char */
  159613. /* #define const */
  159614. #undef CHAR_IS_UNSIGNED
  159615. #define HAVE_STDDEF_H
  159616. #define HAVE_STDLIB_H
  159617. #undef NEED_BSD_STRINGS
  159618. #undef NEED_SYS_TYPES_H
  159619. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159620. #undef NEED_SHORT_EXTERNAL_NAMES
  159621. #undef INCOMPLETE_TYPES_BROKEN
  159622. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159623. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159624. typedef unsigned char boolean;
  159625. #endif
  159626. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159627. #ifdef JPEG_INTERNALS
  159628. #undef RIGHT_SHIFT_IS_UNSIGNED
  159629. #endif /* JPEG_INTERNALS */
  159630. #ifdef JPEG_CJPEG_DJPEG
  159631. #define BMP_SUPPORTED /* BMP image file format */
  159632. #define GIF_SUPPORTED /* GIF image file format */
  159633. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159634. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159635. #define TARGA_SUPPORTED /* Targa image file format */
  159636. #define TWO_FILE_COMMANDLINE /* optional */
  159637. #define USE_SETMODE /* Microsoft has setmode() */
  159638. #undef NEED_SIGNAL_CATCHER
  159639. #undef DONT_USE_B_MODE
  159640. #undef PROGRESS_REPORT /* optional */
  159641. #endif /* JPEG_CJPEG_DJPEG */
  159642. /*** End of inlined file: jconfig.h ***/
  159643. /* widely used configuration options */
  159644. #endif
  159645. /*** Start of inlined file: jmorecfg.h ***/
  159646. /*
  159647. * Define BITS_IN_JSAMPLE as either
  159648. * 8 for 8-bit sample values (the usual setting)
  159649. * 12 for 12-bit sample values
  159650. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159651. * JPEG standard, and the IJG code does not support anything else!
  159652. * We do not support run-time selection of data precision, sorry.
  159653. */
  159654. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159655. /*
  159656. * Maximum number of components (color channels) allowed in JPEG image.
  159657. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159658. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159659. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159660. * really short on memory. (Each allowed component costs a hundred or so
  159661. * bytes of storage, whether actually used in an image or not.)
  159662. */
  159663. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159664. /*
  159665. * Basic data types.
  159666. * You may need to change these if you have a machine with unusual data
  159667. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159668. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159669. * but it had better be at least 16.
  159670. */
  159671. /* Representation of a single sample (pixel element value).
  159672. * We frequently allocate large arrays of these, so it's important to keep
  159673. * them small. But if you have memory to burn and access to char or short
  159674. * arrays is very slow on your hardware, you might want to change these.
  159675. */
  159676. #if BITS_IN_JSAMPLE == 8
  159677. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159678. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159679. */
  159680. #ifdef HAVE_UNSIGNED_CHAR
  159681. typedef unsigned char JSAMPLE;
  159682. #define GETJSAMPLE(value) ((int) (value))
  159683. #else /* not HAVE_UNSIGNED_CHAR */
  159684. typedef char JSAMPLE;
  159685. #ifdef CHAR_IS_UNSIGNED
  159686. #define GETJSAMPLE(value) ((int) (value))
  159687. #else
  159688. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159689. #endif /* CHAR_IS_UNSIGNED */
  159690. #endif /* HAVE_UNSIGNED_CHAR */
  159691. #define MAXJSAMPLE 255
  159692. #define CENTERJSAMPLE 128
  159693. #endif /* BITS_IN_JSAMPLE == 8 */
  159694. #if BITS_IN_JSAMPLE == 12
  159695. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159696. * On nearly all machines "short" will do nicely.
  159697. */
  159698. typedef short JSAMPLE;
  159699. #define GETJSAMPLE(value) ((int) (value))
  159700. #define MAXJSAMPLE 4095
  159701. #define CENTERJSAMPLE 2048
  159702. #endif /* BITS_IN_JSAMPLE == 12 */
  159703. /* Representation of a DCT frequency coefficient.
  159704. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159705. * Again, we allocate large arrays of these, but you can change to int
  159706. * if you have memory to burn and "short" is really slow.
  159707. */
  159708. typedef short JCOEF;
  159709. /* Compressed datastreams are represented as arrays of JOCTET.
  159710. * These must be EXACTLY 8 bits wide, at least once they are written to
  159711. * external storage. Note that when using the stdio data source/destination
  159712. * managers, this is also the data type passed to fread/fwrite.
  159713. */
  159714. #ifdef HAVE_UNSIGNED_CHAR
  159715. typedef unsigned char JOCTET;
  159716. #define GETJOCTET(value) (value)
  159717. #else /* not HAVE_UNSIGNED_CHAR */
  159718. typedef char JOCTET;
  159719. #ifdef CHAR_IS_UNSIGNED
  159720. #define GETJOCTET(value) (value)
  159721. #else
  159722. #define GETJOCTET(value) ((value) & 0xFF)
  159723. #endif /* CHAR_IS_UNSIGNED */
  159724. #endif /* HAVE_UNSIGNED_CHAR */
  159725. /* These typedefs are used for various table entries and so forth.
  159726. * They must be at least as wide as specified; but making them too big
  159727. * won't cost a huge amount of memory, so we don't provide special
  159728. * extraction code like we did for JSAMPLE. (In other words, these
  159729. * typedefs live at a different point on the speed/space tradeoff curve.)
  159730. */
  159731. /* UINT8 must hold at least the values 0..255. */
  159732. #ifdef HAVE_UNSIGNED_CHAR
  159733. typedef unsigned char UINT8;
  159734. #else /* not HAVE_UNSIGNED_CHAR */
  159735. #ifdef CHAR_IS_UNSIGNED
  159736. typedef char UINT8;
  159737. #else /* not CHAR_IS_UNSIGNED */
  159738. typedef short UINT8;
  159739. #endif /* CHAR_IS_UNSIGNED */
  159740. #endif /* HAVE_UNSIGNED_CHAR */
  159741. /* UINT16 must hold at least the values 0..65535. */
  159742. #ifdef HAVE_UNSIGNED_SHORT
  159743. typedef unsigned short UINT16;
  159744. #else /* not HAVE_UNSIGNED_SHORT */
  159745. typedef unsigned int UINT16;
  159746. #endif /* HAVE_UNSIGNED_SHORT */
  159747. /* INT16 must hold at least the values -32768..32767. */
  159748. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159749. typedef short INT16;
  159750. #endif
  159751. /* INT32 must hold at least signed 32-bit values. */
  159752. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159753. typedef long INT32;
  159754. #endif
  159755. /* Datatype used for image dimensions. The JPEG standard only supports
  159756. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159757. * "unsigned int" is sufficient on all machines. However, if you need to
  159758. * handle larger images and you don't mind deviating from the spec, you
  159759. * can change this datatype.
  159760. */
  159761. typedef unsigned int JDIMENSION;
  159762. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159763. /* These macros are used in all function definitions and extern declarations.
  159764. * You could modify them if you need to change function linkage conventions;
  159765. * in particular, you'll need to do that to make the library a Windows DLL.
  159766. * Another application is to make all functions global for use with debuggers
  159767. * or code profilers that require it.
  159768. */
  159769. /* a function called through method pointers: */
  159770. #define METHODDEF(type) static type
  159771. /* a function used only in its module: */
  159772. #define LOCAL(type) static type
  159773. /* a function referenced thru EXTERNs: */
  159774. #define GLOBAL(type) type
  159775. /* a reference to a GLOBAL function: */
  159776. #define EXTERN(type) extern type
  159777. /* This macro is used to declare a "method", that is, a function pointer.
  159778. * We want to supply prototype parameters if the compiler can cope.
  159779. * Note that the arglist parameter must be parenthesized!
  159780. * Again, you can customize this if you need special linkage keywords.
  159781. */
  159782. #ifdef HAVE_PROTOTYPES
  159783. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159784. #else
  159785. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159786. #endif
  159787. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159788. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159789. * by just saying "FAR *" where such a pointer is needed. In a few places
  159790. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159791. */
  159792. #ifdef NEED_FAR_POINTERS
  159793. #define FAR far
  159794. #else
  159795. #define FAR
  159796. #endif
  159797. /*
  159798. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159799. * in standard header files. Or you may have conflicts with application-
  159800. * specific header files that you want to include together with these files.
  159801. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159802. */
  159803. #ifndef HAVE_BOOLEAN
  159804. typedef int boolean;
  159805. #endif
  159806. #ifndef FALSE /* in case these macros already exist */
  159807. #define FALSE 0 /* values of boolean */
  159808. #endif
  159809. #ifndef TRUE
  159810. #define TRUE 1
  159811. #endif
  159812. /*
  159813. * The remaining options affect code selection within the JPEG library,
  159814. * but they don't need to be visible to most applications using the library.
  159815. * To minimize application namespace pollution, the symbols won't be
  159816. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159817. */
  159818. #ifdef JPEG_INTERNALS
  159819. #define JPEG_INTERNAL_OPTIONS
  159820. #endif
  159821. #ifdef JPEG_INTERNAL_OPTIONS
  159822. /*
  159823. * These defines indicate whether to include various optional functions.
  159824. * Undefining some of these symbols will produce a smaller but less capable
  159825. * library. Note that you can leave certain source files out of the
  159826. * compilation/linking process if you've #undef'd the corresponding symbols.
  159827. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159828. */
  159829. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159830. /* Capability options common to encoder and decoder: */
  159831. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159832. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159833. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159834. /* Encoder capability options: */
  159835. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159836. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159837. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159838. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159839. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159840. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159841. * precision, so jchuff.c normally uses entropy optimization to compute
  159842. * usable tables for higher precision. If you don't want to do optimization,
  159843. * you'll have to supply different default Huffman tables.
  159844. * The exact same statements apply for progressive JPEG: the default tables
  159845. * don't work for progressive mode. (This may get fixed, however.)
  159846. */
  159847. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159848. /* Decoder capability options: */
  159849. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159850. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159851. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159852. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159853. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159854. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159855. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159856. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159857. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159858. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159859. /* more capability options later, no doubt */
  159860. /*
  159861. * Ordering of RGB data in scanlines passed to or from the application.
  159862. * If your application wants to deal with data in the order B,G,R, just
  159863. * change these macros. You can also deal with formats such as R,G,B,X
  159864. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159865. * the offsets will also change the order in which colormap data is organized.
  159866. * RESTRICTIONS:
  159867. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159868. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159869. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159870. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159871. * is not 3 (they don't understand about dummy color components!). So you
  159872. * can't use color quantization if you change that value.
  159873. */
  159874. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159875. #define RGB_GREEN 1 /* Offset of Green */
  159876. #define RGB_BLUE 2 /* Offset of Blue */
  159877. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159878. /* Definitions for speed-related optimizations. */
  159879. /* If your compiler supports inline functions, define INLINE
  159880. * as the inline keyword; otherwise define it as empty.
  159881. */
  159882. #ifndef INLINE
  159883. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159884. #define INLINE __inline__
  159885. #endif
  159886. #ifndef INLINE
  159887. #define INLINE /* default is to define it as empty */
  159888. #endif
  159889. #endif
  159890. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159891. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159892. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159893. */
  159894. #ifndef MULTIPLIER
  159895. #define MULTIPLIER int /* type for fastest integer multiply */
  159896. #endif
  159897. /* FAST_FLOAT should be either float or double, whichever is done faster
  159898. * by your compiler. (Note that this type is only used in the floating point
  159899. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159900. * Typically, float is faster in ANSI C compilers, while double is faster in
  159901. * pre-ANSI compilers (because they insist on converting to double anyway).
  159902. * The code below therefore chooses float if we have ANSI-style prototypes.
  159903. */
  159904. #ifndef FAST_FLOAT
  159905. #ifdef HAVE_PROTOTYPES
  159906. #define FAST_FLOAT float
  159907. #else
  159908. #define FAST_FLOAT double
  159909. #endif
  159910. #endif
  159911. #endif /* JPEG_INTERNAL_OPTIONS */
  159912. /*** End of inlined file: jmorecfg.h ***/
  159913. /* seldom changed options */
  159914. /* Version ID for the JPEG library.
  159915. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159916. */
  159917. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159918. /* Various constants determining the sizes of things.
  159919. * All of these are specified by the JPEG standard, so don't change them
  159920. * if you want to be compatible.
  159921. */
  159922. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159923. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159924. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159925. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159926. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159927. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159928. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159929. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159930. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159931. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159932. * to handle it. We even let you do this from the jconfig.h file. However,
  159933. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159934. * sometimes emits noncompliant files doesn't mean you should too.
  159935. */
  159936. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159937. #ifndef D_MAX_BLOCKS_IN_MCU
  159938. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159939. #endif
  159940. /* Data structures for images (arrays of samples and of DCT coefficients).
  159941. * On 80x86 machines, the image arrays are too big for near pointers,
  159942. * but the pointer arrays can fit in near memory.
  159943. */
  159944. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159945. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159946. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159947. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159948. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159949. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159950. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159951. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159952. /* Types for JPEG compression parameters and working tables. */
  159953. /* DCT coefficient quantization tables. */
  159954. typedef struct {
  159955. /* This array gives the coefficient quantizers in natural array order
  159956. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159957. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159958. */
  159959. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159960. /* This field is used only during compression. It's initialized FALSE when
  159961. * the table is created, and set TRUE when it's been output to the file.
  159962. * You could suppress output of a table by setting this to TRUE.
  159963. * (See jpeg_suppress_tables for an example.)
  159964. */
  159965. boolean sent_table; /* TRUE when table has been output */
  159966. } JQUANT_TBL;
  159967. /* Huffman coding tables. */
  159968. typedef struct {
  159969. /* These two fields directly represent the contents of a JPEG DHT marker */
  159970. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159971. /* length k bits; bits[0] is unused */
  159972. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159973. /* This field is used only during compression. It's initialized FALSE when
  159974. * the table is created, and set TRUE when it's been output to the file.
  159975. * You could suppress output of a table by setting this to TRUE.
  159976. * (See jpeg_suppress_tables for an example.)
  159977. */
  159978. boolean sent_table; /* TRUE when table has been output */
  159979. } JHUFF_TBL;
  159980. /* Basic info about one component (color channel). */
  159981. typedef struct {
  159982. /* These values are fixed over the whole image. */
  159983. /* For compression, they must be supplied by parameter setup; */
  159984. /* for decompression, they are read from the SOF marker. */
  159985. int component_id; /* identifier for this component (0..255) */
  159986. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159987. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159988. int v_samp_factor; /* vertical sampling factor (1..4) */
  159989. int quant_tbl_no; /* quantization table selector (0..3) */
  159990. /* These values may vary between scans. */
  159991. /* For compression, they must be supplied by parameter setup; */
  159992. /* for decompression, they are read from the SOS marker. */
  159993. /* The decompressor output side may not use these variables. */
  159994. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159995. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159996. /* Remaining fields should be treated as private by applications. */
  159997. /* These values are computed during compression or decompression startup: */
  159998. /* Component's size in DCT blocks.
  159999. * Any dummy blocks added to complete an MCU are not counted; therefore
  160000. * these values do not depend on whether a scan is interleaved or not.
  160001. */
  160002. JDIMENSION width_in_blocks;
  160003. JDIMENSION height_in_blocks;
  160004. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160005. * For decompression this is the size of the output from one DCT block,
  160006. * reflecting any scaling we choose to apply during the IDCT step.
  160007. * Values of 1,2,4,8 are likely to be supported. Note that different
  160008. * components may receive different IDCT scalings.
  160009. */
  160010. int DCT_scaled_size;
  160011. /* The downsampled dimensions are the component's actual, unpadded number
  160012. * of samples at the main buffer (preprocessing/compression interface), thus
  160013. * downsampled_width = ceil(image_width * Hi/Hmax)
  160014. * and similarly for height. For decompression, IDCT scaling is included, so
  160015. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160016. */
  160017. JDIMENSION downsampled_width; /* actual width in samples */
  160018. JDIMENSION downsampled_height; /* actual height in samples */
  160019. /* This flag is used only for decompression. In cases where some of the
  160020. * components will be ignored (eg grayscale output from YCbCr image),
  160021. * we can skip most computations for the unused components.
  160022. */
  160023. boolean component_needed; /* do we need the value of this component? */
  160024. /* These values are computed before starting a scan of the component. */
  160025. /* The decompressor output side may not use these variables. */
  160026. int MCU_width; /* number of blocks per MCU, horizontally */
  160027. int MCU_height; /* number of blocks per MCU, vertically */
  160028. int MCU_blocks; /* MCU_width * MCU_height */
  160029. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160030. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160031. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160032. /* Saved quantization table for component; NULL if none yet saved.
  160033. * See jdinput.c comments about the need for this information.
  160034. * This field is currently used only for decompression.
  160035. */
  160036. JQUANT_TBL * quant_table;
  160037. /* Private per-component storage for DCT or IDCT subsystem. */
  160038. void * dct_table;
  160039. } jpeg_component_info;
  160040. /* The script for encoding a multiple-scan file is an array of these: */
  160041. typedef struct {
  160042. int comps_in_scan; /* number of components encoded in this scan */
  160043. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160044. int Ss, Se; /* progressive JPEG spectral selection parms */
  160045. int Ah, Al; /* progressive JPEG successive approx. parms */
  160046. } jpeg_scan_info;
  160047. /* The decompressor can save APPn and COM markers in a list of these: */
  160048. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160049. struct jpeg_marker_struct {
  160050. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160051. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160052. unsigned int original_length; /* # bytes of data in the file */
  160053. unsigned int data_length; /* # bytes of data saved at data[] */
  160054. JOCTET FAR * data; /* the data contained in the marker */
  160055. /* the marker length word is not counted in data_length or original_length */
  160056. };
  160057. /* Known color spaces. */
  160058. typedef enum {
  160059. JCS_UNKNOWN, /* error/unspecified */
  160060. JCS_GRAYSCALE, /* monochrome */
  160061. JCS_RGB, /* red/green/blue */
  160062. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160063. JCS_CMYK, /* C/M/Y/K */
  160064. JCS_YCCK /* Y/Cb/Cr/K */
  160065. } J_COLOR_SPACE;
  160066. /* DCT/IDCT algorithm options. */
  160067. typedef enum {
  160068. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160069. JDCT_IFAST, /* faster, less accurate integer method */
  160070. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160071. } J_DCT_METHOD;
  160072. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160073. #define JDCT_DEFAULT JDCT_ISLOW
  160074. #endif
  160075. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160076. #define JDCT_FASTEST JDCT_IFAST
  160077. #endif
  160078. /* Dithering options for decompression. */
  160079. typedef enum {
  160080. JDITHER_NONE, /* no dithering */
  160081. JDITHER_ORDERED, /* simple ordered dither */
  160082. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160083. } J_DITHER_MODE;
  160084. /* Common fields between JPEG compression and decompression master structs. */
  160085. #define jpeg_common_fields \
  160086. struct jpeg_error_mgr * err; /* Error handler module */\
  160087. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160088. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160089. void * client_data; /* Available for use by application */\
  160090. boolean is_decompressor; /* So common code can tell which is which */\
  160091. int global_state /* For checking call sequence validity */
  160092. /* Routines that are to be used by both halves of the library are declared
  160093. * to receive a pointer to this structure. There are no actual instances of
  160094. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160095. */
  160096. struct jpeg_common_struct {
  160097. jpeg_common_fields; /* Fields common to both master struct types */
  160098. /* Additional fields follow in an actual jpeg_compress_struct or
  160099. * jpeg_decompress_struct. All three structs must agree on these
  160100. * initial fields! (This would be a lot cleaner in C++.)
  160101. */
  160102. };
  160103. typedef struct jpeg_common_struct * j_common_ptr;
  160104. typedef struct jpeg_compress_struct * j_compress_ptr;
  160105. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160106. /* Master record for a compression instance */
  160107. struct jpeg_compress_struct {
  160108. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160109. /* Destination for compressed data */
  160110. struct jpeg_destination_mgr * dest;
  160111. /* Description of source image --- these fields must be filled in by
  160112. * outer application before starting compression. in_color_space must
  160113. * be correct before you can even call jpeg_set_defaults().
  160114. */
  160115. JDIMENSION image_width; /* input image width */
  160116. JDIMENSION image_height; /* input image height */
  160117. int input_components; /* # of color components in input image */
  160118. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160119. double input_gamma; /* image gamma of input image */
  160120. /* Compression parameters --- these fields must be set before calling
  160121. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160122. * initialize everything to reasonable defaults, then changing anything
  160123. * the application specifically wants to change. That way you won't get
  160124. * burnt when new parameters are added. Also note that there are several
  160125. * helper routines to simplify changing parameters.
  160126. */
  160127. int data_precision; /* bits of precision in image data */
  160128. int num_components; /* # of color components in JPEG image */
  160129. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160130. jpeg_component_info * comp_info;
  160131. /* comp_info[i] describes component that appears i'th in SOF */
  160132. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160133. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160134. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160135. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160136. /* ptrs to Huffman coding tables, or NULL if not defined */
  160137. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160138. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160139. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160140. int num_scans; /* # of entries in scan_info array */
  160141. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160142. /* The default value of scan_info is NULL, which causes a single-scan
  160143. * sequential JPEG file to be emitted. To create a multi-scan file,
  160144. * set num_scans and scan_info to point to an array of scan definitions.
  160145. */
  160146. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160147. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160148. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160149. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160150. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160151. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160152. /* The restart interval can be specified in absolute MCUs by setting
  160153. * restart_interval, or in MCU rows by setting restart_in_rows
  160154. * (in which case the correct restart_interval will be figured
  160155. * for each scan).
  160156. */
  160157. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160158. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160159. /* Parameters controlling emission of special markers. */
  160160. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160161. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160162. UINT8 JFIF_minor_version;
  160163. /* These three values are not used by the JPEG code, merely copied */
  160164. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160165. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160166. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160167. UINT8 density_unit; /* JFIF code for pixel size units */
  160168. UINT16 X_density; /* Horizontal pixel density */
  160169. UINT16 Y_density; /* Vertical pixel density */
  160170. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160171. /* State variable: index of next scanline to be written to
  160172. * jpeg_write_scanlines(). Application may use this to control its
  160173. * processing loop, e.g., "while (next_scanline < image_height)".
  160174. */
  160175. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160176. /* Remaining fields are known throughout compressor, but generally
  160177. * should not be touched by a surrounding application.
  160178. */
  160179. /*
  160180. * These fields are computed during compression startup
  160181. */
  160182. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160183. int max_h_samp_factor; /* largest h_samp_factor */
  160184. int max_v_samp_factor; /* largest v_samp_factor */
  160185. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160186. /* The coefficient controller receives data in units of MCU rows as defined
  160187. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160188. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160189. * "iMCU" (interleaved MCU) row.
  160190. */
  160191. /*
  160192. * These fields are valid during any one scan.
  160193. * They describe the components and MCUs actually appearing in the scan.
  160194. */
  160195. int comps_in_scan; /* # of JPEG components in this scan */
  160196. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160197. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160198. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160199. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160200. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160201. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160202. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160203. /* i'th block in an MCU */
  160204. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160205. /*
  160206. * Links to compression subobjects (methods and private variables of modules)
  160207. */
  160208. struct jpeg_comp_master * master;
  160209. struct jpeg_c_main_controller * main;
  160210. struct jpeg_c_prep_controller * prep;
  160211. struct jpeg_c_coef_controller * coef;
  160212. struct jpeg_marker_writer * marker;
  160213. struct jpeg_color_converter * cconvert;
  160214. struct jpeg_downsampler * downsample;
  160215. struct jpeg_forward_dct * fdct;
  160216. struct jpeg_entropy_encoder * entropy;
  160217. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160218. int script_space_size;
  160219. };
  160220. /* Master record for a decompression instance */
  160221. struct jpeg_decompress_struct {
  160222. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160223. /* Source of compressed data */
  160224. struct jpeg_source_mgr * src;
  160225. /* Basic description of image --- filled in by jpeg_read_header(). */
  160226. /* Application may inspect these values to decide how to process image. */
  160227. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160228. JDIMENSION image_height; /* nominal image height */
  160229. int num_components; /* # of color components in JPEG image */
  160230. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160231. /* Decompression processing parameters --- these fields must be set before
  160232. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160233. * them to default values.
  160234. */
  160235. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160236. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160237. double output_gamma; /* image gamma wanted in output */
  160238. boolean buffered_image; /* TRUE=multiple output passes */
  160239. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160240. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160241. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160242. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160243. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160244. /* the following are ignored if not quantize_colors: */
  160245. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160246. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160247. int desired_number_of_colors; /* max # colors to use in created colormap */
  160248. /* these are significant only in buffered-image mode: */
  160249. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160250. boolean enable_external_quant;/* enable future use of external colormap */
  160251. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160252. /* Description of actual output image that will be returned to application.
  160253. * These fields are computed by jpeg_start_decompress().
  160254. * You can also use jpeg_calc_output_dimensions() to determine these values
  160255. * in advance of calling jpeg_start_decompress().
  160256. */
  160257. JDIMENSION output_width; /* scaled image width */
  160258. JDIMENSION output_height; /* scaled image height */
  160259. int out_color_components; /* # of color components in out_color_space */
  160260. int output_components; /* # of color components returned */
  160261. /* output_components is 1 (a colormap index) when quantizing colors;
  160262. * otherwise it equals out_color_components.
  160263. */
  160264. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160265. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160266. * high, space and time will be wasted due to unnecessary data copying.
  160267. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160268. */
  160269. /* When quantizing colors, the output colormap is described by these fields.
  160270. * The application can supply a colormap by setting colormap non-NULL before
  160271. * calling jpeg_start_decompress; otherwise a colormap is created during
  160272. * jpeg_start_decompress or jpeg_start_output.
  160273. * The map has out_color_components rows and actual_number_of_colors columns.
  160274. */
  160275. int actual_number_of_colors; /* number of entries in use */
  160276. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160277. /* State variables: these variables indicate the progress of decompression.
  160278. * The application may examine these but must not modify them.
  160279. */
  160280. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160281. * Application may use this to control its processing loop, e.g.,
  160282. * "while (output_scanline < output_height)".
  160283. */
  160284. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160285. /* Current input scan number and number of iMCU rows completed in scan.
  160286. * These indicate the progress of the decompressor input side.
  160287. */
  160288. int input_scan_number; /* Number of SOS markers seen so far */
  160289. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160290. /* The "output scan number" is the notional scan being displayed by the
  160291. * output side. The decompressor will not allow output scan/row number
  160292. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160293. */
  160294. int output_scan_number; /* Nominal scan number being displayed */
  160295. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160296. /* Current progression status. coef_bits[c][i] indicates the precision
  160297. * with which component c's DCT coefficient i (in zigzag order) is known.
  160298. * It is -1 when no data has yet been received, otherwise it is the point
  160299. * transform (shift) value for the most recent scan of the coefficient
  160300. * (thus, 0 at completion of the progression).
  160301. * This pointer is NULL when reading a non-progressive file.
  160302. */
  160303. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160304. /* Internal JPEG parameters --- the application usually need not look at
  160305. * these fields. Note that the decompressor output side may not use
  160306. * any parameters that can change between scans.
  160307. */
  160308. /* Quantization and Huffman tables are carried forward across input
  160309. * datastreams when processing abbreviated JPEG datastreams.
  160310. */
  160311. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160312. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160313. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160314. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160315. /* ptrs to Huffman coding tables, or NULL if not defined */
  160316. /* These parameters are never carried across datastreams, since they
  160317. * are given in SOF/SOS markers or defined to be reset by SOI.
  160318. */
  160319. int data_precision; /* bits of precision in image data */
  160320. jpeg_component_info * comp_info;
  160321. /* comp_info[i] describes component that appears i'th in SOF */
  160322. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160323. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160324. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160325. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160326. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160327. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160328. /* These fields record data obtained from optional markers recognized by
  160329. * the JPEG library.
  160330. */
  160331. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160332. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160333. UINT8 JFIF_major_version; /* JFIF version number */
  160334. UINT8 JFIF_minor_version;
  160335. UINT8 density_unit; /* JFIF code for pixel size units */
  160336. UINT16 X_density; /* Horizontal pixel density */
  160337. UINT16 Y_density; /* Vertical pixel density */
  160338. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160339. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160340. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160341. /* Aside from the specific data retained from APPn markers known to the
  160342. * library, the uninterpreted contents of any or all APPn and COM markers
  160343. * can be saved in a list for examination by the application.
  160344. */
  160345. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160346. /* Remaining fields are known throughout decompressor, but generally
  160347. * should not be touched by a surrounding application.
  160348. */
  160349. /*
  160350. * These fields are computed during decompression startup
  160351. */
  160352. int max_h_samp_factor; /* largest h_samp_factor */
  160353. int max_v_samp_factor; /* largest v_samp_factor */
  160354. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160355. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160356. /* The coefficient controller's input and output progress is measured in
  160357. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160358. * in fully interleaved JPEG scans, but are used whether the scan is
  160359. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160360. * rows of each component. Therefore, the IDCT output contains
  160361. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160362. */
  160363. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160364. /*
  160365. * These fields are valid during any one scan.
  160366. * They describe the components and MCUs actually appearing in the scan.
  160367. * Note that the decompressor output side must not use these fields.
  160368. */
  160369. int comps_in_scan; /* # of JPEG components in this scan */
  160370. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160371. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160372. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160373. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160374. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160375. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160376. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160377. /* i'th block in an MCU */
  160378. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160379. /* This field is shared between entropy decoder and marker parser.
  160380. * It is either zero or the code of a JPEG marker that has been
  160381. * read from the data source, but has not yet been processed.
  160382. */
  160383. int unread_marker;
  160384. /*
  160385. * Links to decompression subobjects (methods, private variables of modules)
  160386. */
  160387. struct jpeg_decomp_master * master;
  160388. struct jpeg_d_main_controller * main;
  160389. struct jpeg_d_coef_controller * coef;
  160390. struct jpeg_d_post_controller * post;
  160391. struct jpeg_input_controller * inputctl;
  160392. struct jpeg_marker_reader * marker;
  160393. struct jpeg_entropy_decoder * entropy;
  160394. struct jpeg_inverse_dct * idct;
  160395. struct jpeg_upsampler * upsample;
  160396. struct jpeg_color_deconverter * cconvert;
  160397. struct jpeg_color_quantizer * cquantize;
  160398. };
  160399. /* "Object" declarations for JPEG modules that may be supplied or called
  160400. * directly by the surrounding application.
  160401. * As with all objects in the JPEG library, these structs only define the
  160402. * publicly visible methods and state variables of a module. Additional
  160403. * private fields may exist after the public ones.
  160404. */
  160405. /* Error handler object */
  160406. struct jpeg_error_mgr {
  160407. /* Error exit handler: does not return to caller */
  160408. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160409. /* Conditionally emit a trace or warning message */
  160410. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160411. /* Routine that actually outputs a trace or error message */
  160412. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160413. /* Format a message string for the most recent JPEG error or message */
  160414. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160415. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160416. /* Reset error state variables at start of a new image */
  160417. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160418. /* The message ID code and any parameters are saved here.
  160419. * A message can have one string parameter or up to 8 int parameters.
  160420. */
  160421. int msg_code;
  160422. #define JMSG_STR_PARM_MAX 80
  160423. union {
  160424. int i[8];
  160425. char s[JMSG_STR_PARM_MAX];
  160426. } msg_parm;
  160427. /* Standard state variables for error facility */
  160428. int trace_level; /* max msg_level that will be displayed */
  160429. /* For recoverable corrupt-data errors, we emit a warning message,
  160430. * but keep going unless emit_message chooses to abort. emit_message
  160431. * should count warnings in num_warnings. The surrounding application
  160432. * can check for bad data by seeing if num_warnings is nonzero at the
  160433. * end of processing.
  160434. */
  160435. long num_warnings; /* number of corrupt-data warnings */
  160436. /* These fields point to the table(s) of error message strings.
  160437. * An application can change the table pointer to switch to a different
  160438. * message list (typically, to change the language in which errors are
  160439. * reported). Some applications may wish to add additional error codes
  160440. * that will be handled by the JPEG library error mechanism; the second
  160441. * table pointer is used for this purpose.
  160442. *
  160443. * First table includes all errors generated by JPEG library itself.
  160444. * Error code 0 is reserved for a "no such error string" message.
  160445. */
  160446. const char * const * jpeg_message_table; /* Library errors */
  160447. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160448. /* Second table can be added by application (see cjpeg/djpeg for example).
  160449. * It contains strings numbered first_addon_message..last_addon_message.
  160450. */
  160451. const char * const * addon_message_table; /* Non-library errors */
  160452. int first_addon_message; /* code for first string in addon table */
  160453. int last_addon_message; /* code for last string in addon table */
  160454. };
  160455. /* Progress monitor object */
  160456. struct jpeg_progress_mgr {
  160457. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160458. long pass_counter; /* work units completed in this pass */
  160459. long pass_limit; /* total number of work units in this pass */
  160460. int completed_passes; /* passes completed so far */
  160461. int total_passes; /* total number of passes expected */
  160462. };
  160463. /* Data destination object for compression */
  160464. struct jpeg_destination_mgr {
  160465. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160466. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160467. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160468. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160469. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160470. };
  160471. /* Data source object for decompression */
  160472. struct jpeg_source_mgr {
  160473. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160474. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160475. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160476. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160477. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160478. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160479. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160480. };
  160481. /* Memory manager object.
  160482. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160483. * and "really big" objects (virtual arrays with backing store if needed).
  160484. * The memory manager does not allow individual objects to be freed; rather,
  160485. * each created object is assigned to a pool, and whole pools can be freed
  160486. * at once. This is faster and more convenient than remembering exactly what
  160487. * to free, especially where malloc()/free() are not too speedy.
  160488. * NB: alloc routines never return NULL. They exit to error_exit if not
  160489. * successful.
  160490. */
  160491. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160492. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160493. #define JPOOL_NUMPOOLS 2
  160494. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160495. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160496. struct jpeg_memory_mgr {
  160497. /* Method pointers */
  160498. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160499. size_t sizeofobject));
  160500. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160501. size_t sizeofobject));
  160502. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160503. JDIMENSION samplesperrow,
  160504. JDIMENSION numrows));
  160505. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160506. JDIMENSION blocksperrow,
  160507. JDIMENSION numrows));
  160508. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160509. int pool_id,
  160510. boolean pre_zero,
  160511. JDIMENSION samplesperrow,
  160512. JDIMENSION numrows,
  160513. JDIMENSION maxaccess));
  160514. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160515. int pool_id,
  160516. boolean pre_zero,
  160517. JDIMENSION blocksperrow,
  160518. JDIMENSION numrows,
  160519. JDIMENSION maxaccess));
  160520. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160521. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160522. jvirt_sarray_ptr ptr,
  160523. JDIMENSION start_row,
  160524. JDIMENSION num_rows,
  160525. boolean writable));
  160526. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160527. jvirt_barray_ptr ptr,
  160528. JDIMENSION start_row,
  160529. JDIMENSION num_rows,
  160530. boolean writable));
  160531. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160532. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160533. /* Limit on memory allocation for this JPEG object. (Note that this is
  160534. * merely advisory, not a guaranteed maximum; it only affects the space
  160535. * used for virtual-array buffers.) May be changed by outer application
  160536. * after creating the JPEG object.
  160537. */
  160538. long max_memory_to_use;
  160539. /* Maximum allocation request accepted by alloc_large. */
  160540. long max_alloc_chunk;
  160541. };
  160542. /* Routine signature for application-supplied marker processing methods.
  160543. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160544. */
  160545. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160546. /* Declarations for routines called by application.
  160547. * The JPP macro hides prototype parameters from compilers that can't cope.
  160548. * Note JPP requires double parentheses.
  160549. */
  160550. #ifdef HAVE_PROTOTYPES
  160551. #define JPP(arglist) arglist
  160552. #else
  160553. #define JPP(arglist) ()
  160554. #endif
  160555. /* Short forms of external names for systems with brain-damaged linkers.
  160556. * We shorten external names to be unique in the first six letters, which
  160557. * is good enough for all known systems.
  160558. * (If your compiler itself needs names to be unique in less than 15
  160559. * characters, you are out of luck. Get a better compiler.)
  160560. */
  160561. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160562. #define jpeg_std_error jStdError
  160563. #define jpeg_CreateCompress jCreaCompress
  160564. #define jpeg_CreateDecompress jCreaDecompress
  160565. #define jpeg_destroy_compress jDestCompress
  160566. #define jpeg_destroy_decompress jDestDecompress
  160567. #define jpeg_stdio_dest jStdDest
  160568. #define jpeg_stdio_src jStdSrc
  160569. #define jpeg_set_defaults jSetDefaults
  160570. #define jpeg_set_colorspace jSetColorspace
  160571. #define jpeg_default_colorspace jDefColorspace
  160572. #define jpeg_set_quality jSetQuality
  160573. #define jpeg_set_linear_quality jSetLQuality
  160574. #define jpeg_add_quant_table jAddQuantTable
  160575. #define jpeg_quality_scaling jQualityScaling
  160576. #define jpeg_simple_progression jSimProgress
  160577. #define jpeg_suppress_tables jSuppressTables
  160578. #define jpeg_alloc_quant_table jAlcQTable
  160579. #define jpeg_alloc_huff_table jAlcHTable
  160580. #define jpeg_start_compress jStrtCompress
  160581. #define jpeg_write_scanlines jWrtScanlines
  160582. #define jpeg_finish_compress jFinCompress
  160583. #define jpeg_write_raw_data jWrtRawData
  160584. #define jpeg_write_marker jWrtMarker
  160585. #define jpeg_write_m_header jWrtMHeader
  160586. #define jpeg_write_m_byte jWrtMByte
  160587. #define jpeg_write_tables jWrtTables
  160588. #define jpeg_read_header jReadHeader
  160589. #define jpeg_start_decompress jStrtDecompress
  160590. #define jpeg_read_scanlines jReadScanlines
  160591. #define jpeg_finish_decompress jFinDecompress
  160592. #define jpeg_read_raw_data jReadRawData
  160593. #define jpeg_has_multiple_scans jHasMultScn
  160594. #define jpeg_start_output jStrtOutput
  160595. #define jpeg_finish_output jFinOutput
  160596. #define jpeg_input_complete jInComplete
  160597. #define jpeg_new_colormap jNewCMap
  160598. #define jpeg_consume_input jConsumeInput
  160599. #define jpeg_calc_output_dimensions jCalcDimensions
  160600. #define jpeg_save_markers jSaveMarkers
  160601. #define jpeg_set_marker_processor jSetMarker
  160602. #define jpeg_read_coefficients jReadCoefs
  160603. #define jpeg_write_coefficients jWrtCoefs
  160604. #define jpeg_copy_critical_parameters jCopyCrit
  160605. #define jpeg_abort_compress jAbrtCompress
  160606. #define jpeg_abort_decompress jAbrtDecompress
  160607. #define jpeg_abort jAbort
  160608. #define jpeg_destroy jDestroy
  160609. #define jpeg_resync_to_restart jResyncRestart
  160610. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160611. /* Default error-management setup */
  160612. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160613. JPP((struct jpeg_error_mgr * err));
  160614. /* Initialization of JPEG compression objects.
  160615. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160616. * names that applications should call. These expand to calls on
  160617. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160618. * passed for version mismatch checking.
  160619. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160620. */
  160621. #define jpeg_create_compress(cinfo) \
  160622. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160623. (size_t) sizeof(struct jpeg_compress_struct))
  160624. #define jpeg_create_decompress(cinfo) \
  160625. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160626. (size_t) sizeof(struct jpeg_decompress_struct))
  160627. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160628. int version, size_t structsize));
  160629. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160630. int version, size_t structsize));
  160631. /* Destruction of JPEG compression objects */
  160632. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160633. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160634. /* Standard data source and destination managers: stdio streams. */
  160635. /* Caller is responsible for opening the file before and closing after. */
  160636. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160637. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160638. /* Default parameter setup for compression */
  160639. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160640. /* Compression parameter setup aids */
  160641. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160642. J_COLOR_SPACE colorspace));
  160643. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160644. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160645. boolean force_baseline));
  160646. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160647. int scale_factor,
  160648. boolean force_baseline));
  160649. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160650. const unsigned int *basic_table,
  160651. int scale_factor,
  160652. boolean force_baseline));
  160653. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160654. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160655. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160656. boolean suppress));
  160657. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160658. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160659. /* Main entry points for compression */
  160660. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160661. boolean write_all_tables));
  160662. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160663. JSAMPARRAY scanlines,
  160664. JDIMENSION num_lines));
  160665. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160666. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160667. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160668. JSAMPIMAGE data,
  160669. JDIMENSION num_lines));
  160670. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160671. EXTERN(void) jpeg_write_marker
  160672. JPP((j_compress_ptr cinfo, int marker,
  160673. const JOCTET * dataptr, unsigned int datalen));
  160674. /* Same, but piecemeal. */
  160675. EXTERN(void) jpeg_write_m_header
  160676. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160677. EXTERN(void) jpeg_write_m_byte
  160678. JPP((j_compress_ptr cinfo, int val));
  160679. /* Alternate compression function: just write an abbreviated table file */
  160680. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160681. /* Decompression startup: read start of JPEG datastream to see what's there */
  160682. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160683. boolean require_image));
  160684. /* Return value is one of: */
  160685. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160686. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160687. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160688. /* If you pass require_image = TRUE (normal case), you need not check for
  160689. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160690. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160691. * give a suspension return (the stdio source module doesn't).
  160692. */
  160693. /* Main entry points for decompression */
  160694. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160695. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160696. JSAMPARRAY scanlines,
  160697. JDIMENSION max_lines));
  160698. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160699. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160700. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160701. JSAMPIMAGE data,
  160702. JDIMENSION max_lines));
  160703. /* Additional entry points for buffered-image mode. */
  160704. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160705. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160706. int scan_number));
  160707. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160708. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160709. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160710. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160711. /* Return value is one of: */
  160712. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160713. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160714. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160715. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160716. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160717. /* Precalculate output dimensions for current decompression parameters. */
  160718. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160719. /* Control saving of COM and APPn markers into marker_list. */
  160720. EXTERN(void) jpeg_save_markers
  160721. JPP((j_decompress_ptr cinfo, int marker_code,
  160722. unsigned int length_limit));
  160723. /* Install a special processing method for COM or APPn markers. */
  160724. EXTERN(void) jpeg_set_marker_processor
  160725. JPP((j_decompress_ptr cinfo, int marker_code,
  160726. jpeg_marker_parser_method routine));
  160727. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160728. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160729. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160730. jvirt_barray_ptr * coef_arrays));
  160731. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160732. j_compress_ptr dstinfo));
  160733. /* If you choose to abort compression or decompression before completing
  160734. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160735. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160736. * if you're done with the JPEG object, but if you want to clean it up and
  160737. * reuse it, call this:
  160738. */
  160739. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160740. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160741. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160742. * flavor of JPEG object. These may be more convenient in some places.
  160743. */
  160744. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160745. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160746. /* Default restart-marker-resync procedure for use by data source modules */
  160747. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160748. int desired));
  160749. /* These marker codes are exported since applications and data source modules
  160750. * are likely to want to use them.
  160751. */
  160752. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160753. #define JPEG_EOI 0xD9 /* EOI marker code */
  160754. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160755. #define JPEG_COM 0xFE /* COM marker code */
  160756. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160757. * for structure definitions that are never filled in, keep it quiet by
  160758. * supplying dummy definitions for the various substructures.
  160759. */
  160760. #ifdef INCOMPLETE_TYPES_BROKEN
  160761. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160762. struct jvirt_sarray_control { long dummy; };
  160763. struct jvirt_barray_control { long dummy; };
  160764. struct jpeg_comp_master { long dummy; };
  160765. struct jpeg_c_main_controller { long dummy; };
  160766. struct jpeg_c_prep_controller { long dummy; };
  160767. struct jpeg_c_coef_controller { long dummy; };
  160768. struct jpeg_marker_writer { long dummy; };
  160769. struct jpeg_color_converter { long dummy; };
  160770. struct jpeg_downsampler { long dummy; };
  160771. struct jpeg_forward_dct { long dummy; };
  160772. struct jpeg_entropy_encoder { long dummy; };
  160773. struct jpeg_decomp_master { long dummy; };
  160774. struct jpeg_d_main_controller { long dummy; };
  160775. struct jpeg_d_coef_controller { long dummy; };
  160776. struct jpeg_d_post_controller { long dummy; };
  160777. struct jpeg_input_controller { long dummy; };
  160778. struct jpeg_marker_reader { long dummy; };
  160779. struct jpeg_entropy_decoder { long dummy; };
  160780. struct jpeg_inverse_dct { long dummy; };
  160781. struct jpeg_upsampler { long dummy; };
  160782. struct jpeg_color_deconverter { long dummy; };
  160783. struct jpeg_color_quantizer { long dummy; };
  160784. #endif /* JPEG_INTERNALS */
  160785. #endif /* INCOMPLETE_TYPES_BROKEN */
  160786. /*
  160787. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160788. * The internal structure declarations are read only when that is true.
  160789. * Applications using the library should not include jpegint.h, but may wish
  160790. * to include jerror.h.
  160791. */
  160792. #ifdef JPEG_INTERNALS
  160793. /*** Start of inlined file: jpegint.h ***/
  160794. /* Declarations for both compression & decompression */
  160795. typedef enum { /* Operating modes for buffer controllers */
  160796. JBUF_PASS_THRU, /* Plain stripwise operation */
  160797. /* Remaining modes require a full-image buffer to have been created */
  160798. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160799. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160800. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160801. } J_BUF_MODE;
  160802. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160803. #define CSTATE_START 100 /* after create_compress */
  160804. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160805. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160806. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160807. #define DSTATE_START 200 /* after create_decompress */
  160808. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160809. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160810. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160811. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160812. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160813. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160814. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160815. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160816. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160817. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160818. /* Declarations for compression modules */
  160819. /* Master control module */
  160820. struct jpeg_comp_master {
  160821. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160822. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160823. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160824. /* State variables made visible to other modules */
  160825. boolean call_pass_startup; /* True if pass_startup must be called */
  160826. boolean is_last_pass; /* True during last pass */
  160827. };
  160828. /* Main buffer control (downsampled-data buffer) */
  160829. struct jpeg_c_main_controller {
  160830. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160831. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160832. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160833. JDIMENSION in_rows_avail));
  160834. };
  160835. /* Compression preprocessing (downsampling input buffer control) */
  160836. struct jpeg_c_prep_controller {
  160837. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160838. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160839. JSAMPARRAY input_buf,
  160840. JDIMENSION *in_row_ctr,
  160841. JDIMENSION in_rows_avail,
  160842. JSAMPIMAGE output_buf,
  160843. JDIMENSION *out_row_group_ctr,
  160844. JDIMENSION out_row_groups_avail));
  160845. };
  160846. /* Coefficient buffer control */
  160847. struct jpeg_c_coef_controller {
  160848. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160849. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160850. JSAMPIMAGE input_buf));
  160851. };
  160852. /* Colorspace conversion */
  160853. struct jpeg_color_converter {
  160854. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160855. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160856. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160857. JDIMENSION output_row, int num_rows));
  160858. };
  160859. /* Downsampling */
  160860. struct jpeg_downsampler {
  160861. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160862. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160863. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160864. JSAMPIMAGE output_buf,
  160865. JDIMENSION out_row_group_index));
  160866. boolean need_context_rows; /* TRUE if need rows above & below */
  160867. };
  160868. /* Forward DCT (also controls coefficient quantization) */
  160869. struct jpeg_forward_dct {
  160870. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160871. /* perhaps this should be an array??? */
  160872. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160873. jpeg_component_info * compptr,
  160874. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160875. JDIMENSION start_row, JDIMENSION start_col,
  160876. JDIMENSION num_blocks));
  160877. };
  160878. /* Entropy encoding */
  160879. struct jpeg_entropy_encoder {
  160880. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160881. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160882. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160883. };
  160884. /* Marker writing */
  160885. struct jpeg_marker_writer {
  160886. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160887. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160888. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160889. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160890. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160891. /* These routines are exported to allow insertion of extra markers */
  160892. /* Probably only COM and APPn markers should be written this way */
  160893. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160894. unsigned int datalen));
  160895. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160896. };
  160897. /* Declarations for decompression modules */
  160898. /* Master control module */
  160899. struct jpeg_decomp_master {
  160900. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160901. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160902. /* State variables made visible to other modules */
  160903. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160904. };
  160905. /* Input control module */
  160906. struct jpeg_input_controller {
  160907. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160908. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160909. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160910. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160911. /* State variables made visible to other modules */
  160912. boolean has_multiple_scans; /* True if file has multiple scans */
  160913. boolean eoi_reached; /* True when EOI has been consumed */
  160914. };
  160915. /* Main buffer control (downsampled-data buffer) */
  160916. struct jpeg_d_main_controller {
  160917. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160918. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160919. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160920. JDIMENSION out_rows_avail));
  160921. };
  160922. /* Coefficient buffer control */
  160923. struct jpeg_d_coef_controller {
  160924. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160925. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160926. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160927. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160928. JSAMPIMAGE output_buf));
  160929. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160930. jvirt_barray_ptr *coef_arrays;
  160931. };
  160932. /* Decompression postprocessing (color quantization buffer control) */
  160933. struct jpeg_d_post_controller {
  160934. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160935. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160936. JSAMPIMAGE input_buf,
  160937. JDIMENSION *in_row_group_ctr,
  160938. JDIMENSION in_row_groups_avail,
  160939. JSAMPARRAY output_buf,
  160940. JDIMENSION *out_row_ctr,
  160941. JDIMENSION out_rows_avail));
  160942. };
  160943. /* Marker reading & parsing */
  160944. struct jpeg_marker_reader {
  160945. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160946. /* Read markers until SOS or EOI.
  160947. * Returns same codes as are defined for jpeg_consume_input:
  160948. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160949. */
  160950. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160951. /* Read a restart marker --- exported for use by entropy decoder only */
  160952. jpeg_marker_parser_method read_restart_marker;
  160953. /* State of marker reader --- nominally internal, but applications
  160954. * supplying COM or APPn handlers might like to know the state.
  160955. */
  160956. boolean saw_SOI; /* found SOI? */
  160957. boolean saw_SOF; /* found SOF? */
  160958. int next_restart_num; /* next restart number expected (0-7) */
  160959. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160960. };
  160961. /* Entropy decoding */
  160962. struct jpeg_entropy_decoder {
  160963. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160964. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160965. JBLOCKROW *MCU_data));
  160966. /* This is here to share code between baseline and progressive decoders; */
  160967. /* other modules probably should not use it */
  160968. boolean insufficient_data; /* set TRUE after emitting warning */
  160969. };
  160970. /* Inverse DCT (also performs dequantization) */
  160971. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160972. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160973. JCOEFPTR coef_block,
  160974. JSAMPARRAY output_buf, JDIMENSION output_col));
  160975. struct jpeg_inverse_dct {
  160976. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160977. /* It is useful to allow each component to have a separate IDCT method. */
  160978. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160979. };
  160980. /* Upsampling (note that upsampler must also call color converter) */
  160981. struct jpeg_upsampler {
  160982. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160983. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160984. JSAMPIMAGE input_buf,
  160985. JDIMENSION *in_row_group_ctr,
  160986. JDIMENSION in_row_groups_avail,
  160987. JSAMPARRAY output_buf,
  160988. JDIMENSION *out_row_ctr,
  160989. JDIMENSION out_rows_avail));
  160990. boolean need_context_rows; /* TRUE if need rows above & below */
  160991. };
  160992. /* Colorspace conversion */
  160993. struct jpeg_color_deconverter {
  160994. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160995. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160996. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160997. JSAMPARRAY output_buf, int num_rows));
  160998. };
  160999. /* Color quantization or color precision reduction */
  161000. struct jpeg_color_quantizer {
  161001. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161002. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161003. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161004. int num_rows));
  161005. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161006. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161007. };
  161008. /* Miscellaneous useful macros */
  161009. #undef MAX
  161010. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161011. #undef MIN
  161012. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161013. /* We assume that right shift corresponds to signed division by 2 with
  161014. * rounding towards minus infinity. This is correct for typical "arithmetic
  161015. * shift" instructions that shift in copies of the sign bit. But some
  161016. * C compilers implement >> with an unsigned shift. For these machines you
  161017. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161018. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161019. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161020. * included in the variables of any routine using RIGHT_SHIFT.
  161021. */
  161022. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161023. #define SHIFT_TEMPS INT32 shift_temp;
  161024. #define RIGHT_SHIFT(x,shft) \
  161025. ((shift_temp = (x)) < 0 ? \
  161026. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161027. (shift_temp >> (shft)))
  161028. #else
  161029. #define SHIFT_TEMPS
  161030. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161031. #endif
  161032. /* Short forms of external names for systems with brain-damaged linkers. */
  161033. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161034. #define jinit_compress_master jICompress
  161035. #define jinit_c_master_control jICMaster
  161036. #define jinit_c_main_controller jICMainC
  161037. #define jinit_c_prep_controller jICPrepC
  161038. #define jinit_c_coef_controller jICCoefC
  161039. #define jinit_color_converter jICColor
  161040. #define jinit_downsampler jIDownsampler
  161041. #define jinit_forward_dct jIFDCT
  161042. #define jinit_huff_encoder jIHEncoder
  161043. #define jinit_phuff_encoder jIPHEncoder
  161044. #define jinit_marker_writer jIMWriter
  161045. #define jinit_master_decompress jIDMaster
  161046. #define jinit_d_main_controller jIDMainC
  161047. #define jinit_d_coef_controller jIDCoefC
  161048. #define jinit_d_post_controller jIDPostC
  161049. #define jinit_input_controller jIInCtlr
  161050. #define jinit_marker_reader jIMReader
  161051. #define jinit_huff_decoder jIHDecoder
  161052. #define jinit_phuff_decoder jIPHDecoder
  161053. #define jinit_inverse_dct jIIDCT
  161054. #define jinit_upsampler jIUpsampler
  161055. #define jinit_color_deconverter jIDColor
  161056. #define jinit_1pass_quantizer jI1Quant
  161057. #define jinit_2pass_quantizer jI2Quant
  161058. #define jinit_merged_upsampler jIMUpsampler
  161059. #define jinit_memory_mgr jIMemMgr
  161060. #define jdiv_round_up jDivRound
  161061. #define jround_up jRound
  161062. #define jcopy_sample_rows jCopySamples
  161063. #define jcopy_block_row jCopyBlocks
  161064. #define jzero_far jZeroFar
  161065. #define jpeg_zigzag_order jZIGTable
  161066. #define jpeg_natural_order jZAGTable
  161067. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161068. /* Compression module initialization routines */
  161069. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161070. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161071. boolean transcode_only));
  161072. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161073. boolean need_full_buffer));
  161074. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161075. boolean need_full_buffer));
  161076. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161077. boolean need_full_buffer));
  161078. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161079. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161080. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161081. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161082. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161083. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161084. /* Decompression module initialization routines */
  161085. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161086. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161087. boolean need_full_buffer));
  161088. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161089. boolean need_full_buffer));
  161090. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161091. boolean need_full_buffer));
  161092. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161093. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161094. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161095. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161096. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161097. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161098. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161099. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161100. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161101. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161102. /* Memory manager initialization */
  161103. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161104. /* Utility routines in jutils.c */
  161105. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161106. EXTERN(long) jround_up JPP((long a, long b));
  161107. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161108. JSAMPARRAY output_array, int dest_row,
  161109. int num_rows, JDIMENSION num_cols));
  161110. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161111. JDIMENSION num_blocks));
  161112. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161113. /* Constant tables in jutils.c */
  161114. #if 0 /* This table is not actually needed in v6a */
  161115. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161116. #endif
  161117. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161118. /* Suppress undefined-structure complaints if necessary. */
  161119. #ifdef INCOMPLETE_TYPES_BROKEN
  161120. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161121. struct jvirt_sarray_control { long dummy; };
  161122. struct jvirt_barray_control { long dummy; };
  161123. #endif
  161124. #endif /* INCOMPLETE_TYPES_BROKEN */
  161125. /*** End of inlined file: jpegint.h ***/
  161126. /* fetch private declarations */
  161127. /*** Start of inlined file: jerror.h ***/
  161128. /*
  161129. * To define the enum list of message codes, include this file without
  161130. * defining macro JMESSAGE. To create a message string table, include it
  161131. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161132. */
  161133. #ifndef JMESSAGE
  161134. #ifndef JERROR_H
  161135. /* First time through, define the enum list */
  161136. #define JMAKE_ENUM_LIST
  161137. #else
  161138. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161139. #define JMESSAGE(code,string)
  161140. #endif /* JERROR_H */
  161141. #endif /* JMESSAGE */
  161142. #ifdef JMAKE_ENUM_LIST
  161143. typedef enum {
  161144. #define JMESSAGE(code,string) code ,
  161145. #endif /* JMAKE_ENUM_LIST */
  161146. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161147. /* For maintenance convenience, list is alphabetical by message code name */
  161148. JMESSAGE(JERR_ARITH_NOTIMPL,
  161149. "Sorry, there are legal restrictions on arithmetic coding")
  161150. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161151. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161152. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161153. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161154. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161155. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161156. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161157. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161158. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161159. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161160. JMESSAGE(JERR_BAD_LIB_VERSION,
  161161. "Wrong JPEG library version: library is %d, caller expects %d")
  161162. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161163. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161164. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161165. JMESSAGE(JERR_BAD_PROGRESSION,
  161166. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161167. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161168. "Invalid progressive parameters at scan script entry %d")
  161169. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161170. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161171. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161172. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161173. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161174. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161175. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161176. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161177. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161178. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161179. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161180. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161181. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161182. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161183. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161184. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161185. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161186. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161187. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161188. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161189. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161190. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161191. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161192. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161193. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161194. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161195. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161196. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161197. "Cannot transcode due to multiple use of quantization table %d")
  161198. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161199. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161200. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161201. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161202. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161203. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161204. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161205. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161206. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161207. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161208. JMESSAGE(JERR_QUANT_COMPONENTS,
  161209. "Cannot quantize more than %d color components")
  161210. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161211. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161212. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161213. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161214. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161215. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161216. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161217. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161218. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161219. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161220. JMESSAGE(JERR_TFILE_WRITE,
  161221. "Write failed on temporary file --- out of disk space?")
  161222. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161223. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161224. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161225. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161226. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161227. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161228. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161229. JMESSAGE(JMSG_VERSION, JVERSION)
  161230. JMESSAGE(JTRC_16BIT_TABLES,
  161231. "Caution: quantization tables are too coarse for baseline JPEG")
  161232. JMESSAGE(JTRC_ADOBE,
  161233. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161234. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161235. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161236. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161237. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161238. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161239. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161240. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161241. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161242. JMESSAGE(JTRC_EOI, "End Of Image")
  161243. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161244. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161245. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161246. "Warning: thumbnail image size does not match data length %u")
  161247. JMESSAGE(JTRC_JFIF_EXTENSION,
  161248. "JFIF extension marker: type 0x%02x, length %u")
  161249. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161250. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161251. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161252. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161253. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161254. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161255. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161256. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161257. JMESSAGE(JTRC_RST, "RST%d")
  161258. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161259. "Smoothing not supported with nonstandard sampling ratios")
  161260. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161261. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161262. JMESSAGE(JTRC_SOI, "Start of Image")
  161263. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161264. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161265. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161266. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161267. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161268. JMESSAGE(JTRC_THUMB_JPEG,
  161269. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161270. JMESSAGE(JTRC_THUMB_PALETTE,
  161271. "JFIF extension marker: palette thumbnail image, length %u")
  161272. JMESSAGE(JTRC_THUMB_RGB,
  161273. "JFIF extension marker: RGB thumbnail image, length %u")
  161274. JMESSAGE(JTRC_UNKNOWN_IDS,
  161275. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161276. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161277. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161278. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161279. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161280. "Inconsistent progression sequence for component %d coefficient %d")
  161281. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161282. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161283. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161284. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161285. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161286. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161287. JMESSAGE(JWRN_MUST_RESYNC,
  161288. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161289. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161290. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161291. #ifdef JMAKE_ENUM_LIST
  161292. JMSG_LASTMSGCODE
  161293. } J_MESSAGE_CODE;
  161294. #undef JMAKE_ENUM_LIST
  161295. #endif /* JMAKE_ENUM_LIST */
  161296. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161297. #undef JMESSAGE
  161298. #ifndef JERROR_H
  161299. #define JERROR_H
  161300. /* Macros to simplify using the error and trace message stuff */
  161301. /* The first parameter is either type of cinfo pointer */
  161302. /* Fatal errors (print message and exit) */
  161303. #define ERREXIT(cinfo,code) \
  161304. ((cinfo)->err->msg_code = (code), \
  161305. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161306. #define ERREXIT1(cinfo,code,p1) \
  161307. ((cinfo)->err->msg_code = (code), \
  161308. (cinfo)->err->msg_parm.i[0] = (p1), \
  161309. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161310. #define ERREXIT2(cinfo,code,p1,p2) \
  161311. ((cinfo)->err->msg_code = (code), \
  161312. (cinfo)->err->msg_parm.i[0] = (p1), \
  161313. (cinfo)->err->msg_parm.i[1] = (p2), \
  161314. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161315. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161316. ((cinfo)->err->msg_code = (code), \
  161317. (cinfo)->err->msg_parm.i[0] = (p1), \
  161318. (cinfo)->err->msg_parm.i[1] = (p2), \
  161319. (cinfo)->err->msg_parm.i[2] = (p3), \
  161320. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161321. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161322. ((cinfo)->err->msg_code = (code), \
  161323. (cinfo)->err->msg_parm.i[0] = (p1), \
  161324. (cinfo)->err->msg_parm.i[1] = (p2), \
  161325. (cinfo)->err->msg_parm.i[2] = (p3), \
  161326. (cinfo)->err->msg_parm.i[3] = (p4), \
  161327. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161328. #define ERREXITS(cinfo,code,str) \
  161329. ((cinfo)->err->msg_code = (code), \
  161330. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161331. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161332. #define MAKESTMT(stuff) do { stuff } while (0)
  161333. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161334. #define WARNMS(cinfo,code) \
  161335. ((cinfo)->err->msg_code = (code), \
  161336. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161337. #define WARNMS1(cinfo,code,p1) \
  161338. ((cinfo)->err->msg_code = (code), \
  161339. (cinfo)->err->msg_parm.i[0] = (p1), \
  161340. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161341. #define WARNMS2(cinfo,code,p1,p2) \
  161342. ((cinfo)->err->msg_code = (code), \
  161343. (cinfo)->err->msg_parm.i[0] = (p1), \
  161344. (cinfo)->err->msg_parm.i[1] = (p2), \
  161345. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161346. /* Informational/debugging messages */
  161347. #define TRACEMS(cinfo,lvl,code) \
  161348. ((cinfo)->err->msg_code = (code), \
  161349. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161350. #define TRACEMS1(cinfo,lvl,code,p1) \
  161351. ((cinfo)->err->msg_code = (code), \
  161352. (cinfo)->err->msg_parm.i[0] = (p1), \
  161353. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161354. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161355. ((cinfo)->err->msg_code = (code), \
  161356. (cinfo)->err->msg_parm.i[0] = (p1), \
  161357. (cinfo)->err->msg_parm.i[1] = (p2), \
  161358. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161359. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161360. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161361. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161362. (cinfo)->err->msg_code = (code); \
  161363. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161364. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161365. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161366. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161367. (cinfo)->err->msg_code = (code); \
  161368. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161369. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161370. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161371. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161372. _mp[4] = (p5); \
  161373. (cinfo)->err->msg_code = (code); \
  161374. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161375. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161376. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161377. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161378. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161379. (cinfo)->err->msg_code = (code); \
  161380. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161381. #define TRACEMSS(cinfo,lvl,code,str) \
  161382. ((cinfo)->err->msg_code = (code), \
  161383. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161384. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161385. #endif /* JERROR_H */
  161386. /*** End of inlined file: jerror.h ***/
  161387. /* fetch error codes too */
  161388. #endif
  161389. #endif /* JPEGLIB_H */
  161390. /*** End of inlined file: jpeglib.h ***/
  161391. /*** Start of inlined file: jcapimin.c ***/
  161392. #define JPEG_INTERNALS
  161393. /*** Start of inlined file: jinclude.h ***/
  161394. /* Include auto-config file to find out which system include files we need. */
  161395. #ifndef __jinclude_h__
  161396. #define __jinclude_h__
  161397. /*** Start of inlined file: jconfig.h ***/
  161398. /* see jconfig.doc for explanations */
  161399. // disable all the warnings under MSVC
  161400. #ifdef _MSC_VER
  161401. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161402. #endif
  161403. #ifdef __BORLANDC__
  161404. #pragma warn -8057
  161405. #pragma warn -8019
  161406. #pragma warn -8004
  161407. #pragma warn -8008
  161408. #endif
  161409. #define HAVE_PROTOTYPES
  161410. #define HAVE_UNSIGNED_CHAR
  161411. #define HAVE_UNSIGNED_SHORT
  161412. /* #define void char */
  161413. /* #define const */
  161414. #undef CHAR_IS_UNSIGNED
  161415. #define HAVE_STDDEF_H
  161416. #define HAVE_STDLIB_H
  161417. #undef NEED_BSD_STRINGS
  161418. #undef NEED_SYS_TYPES_H
  161419. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161420. #undef NEED_SHORT_EXTERNAL_NAMES
  161421. #undef INCOMPLETE_TYPES_BROKEN
  161422. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161423. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161424. typedef unsigned char boolean;
  161425. #endif
  161426. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161427. #ifdef JPEG_INTERNALS
  161428. #undef RIGHT_SHIFT_IS_UNSIGNED
  161429. #endif /* JPEG_INTERNALS */
  161430. #ifdef JPEG_CJPEG_DJPEG
  161431. #define BMP_SUPPORTED /* BMP image file format */
  161432. #define GIF_SUPPORTED /* GIF image file format */
  161433. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161434. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161435. #define TARGA_SUPPORTED /* Targa image file format */
  161436. #define TWO_FILE_COMMANDLINE /* optional */
  161437. #define USE_SETMODE /* Microsoft has setmode() */
  161438. #undef NEED_SIGNAL_CATCHER
  161439. #undef DONT_USE_B_MODE
  161440. #undef PROGRESS_REPORT /* optional */
  161441. #endif /* JPEG_CJPEG_DJPEG */
  161442. /*** End of inlined file: jconfig.h ***/
  161443. /* auto configuration options */
  161444. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161445. /*
  161446. * We need the NULL macro and size_t typedef.
  161447. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161448. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161449. * pull in <sys/types.h> as well.
  161450. * Note that the core JPEG library does not require <stdio.h>;
  161451. * only the default error handler and data source/destination modules do.
  161452. * But we must pull it in because of the references to FILE in jpeglib.h.
  161453. * You can remove those references if you want to compile without <stdio.h>.
  161454. */
  161455. #ifdef HAVE_STDDEF_H
  161456. #include <stddef.h>
  161457. #endif
  161458. #ifdef HAVE_STDLIB_H
  161459. #include <stdlib.h>
  161460. #endif
  161461. #ifdef NEED_SYS_TYPES_H
  161462. #include <sys/types.h>
  161463. #endif
  161464. #include <stdio.h>
  161465. /*
  161466. * We need memory copying and zeroing functions, plus strncpy().
  161467. * ANSI and System V implementations declare these in <string.h>.
  161468. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161469. * Some systems may declare memset and memcpy in <memory.h>.
  161470. *
  161471. * NOTE: we assume the size parameters to these functions are of type size_t.
  161472. * Change the casts in these macros if not!
  161473. */
  161474. #ifdef NEED_BSD_STRINGS
  161475. #include <strings.h>
  161476. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161477. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161478. #else /* not BSD, assume ANSI/SysV string lib */
  161479. #include <string.h>
  161480. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161481. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161482. #endif
  161483. /*
  161484. * In ANSI C, and indeed any rational implementation, size_t is also the
  161485. * type returned by sizeof(). However, it seems there are some irrational
  161486. * implementations out there, in which sizeof() returns an int even though
  161487. * size_t is defined as long or unsigned long. To ensure consistent results
  161488. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161489. */
  161490. #define SIZEOF(object) ((size_t) sizeof(object))
  161491. /*
  161492. * The modules that use fread() and fwrite() always invoke them through
  161493. * these macros. On some systems you may need to twiddle the argument casts.
  161494. * CAUTION: argument order is different from underlying functions!
  161495. */
  161496. #define JFREAD(file,buf,sizeofbuf) \
  161497. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161498. #define JFWRITE(file,buf,sizeofbuf) \
  161499. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161500. typedef enum { /* JPEG marker codes */
  161501. M_SOF0 = 0xc0,
  161502. M_SOF1 = 0xc1,
  161503. M_SOF2 = 0xc2,
  161504. M_SOF3 = 0xc3,
  161505. M_SOF5 = 0xc5,
  161506. M_SOF6 = 0xc6,
  161507. M_SOF7 = 0xc7,
  161508. M_JPG = 0xc8,
  161509. M_SOF9 = 0xc9,
  161510. M_SOF10 = 0xca,
  161511. M_SOF11 = 0xcb,
  161512. M_SOF13 = 0xcd,
  161513. M_SOF14 = 0xce,
  161514. M_SOF15 = 0xcf,
  161515. M_DHT = 0xc4,
  161516. M_DAC = 0xcc,
  161517. M_RST0 = 0xd0,
  161518. M_RST1 = 0xd1,
  161519. M_RST2 = 0xd2,
  161520. M_RST3 = 0xd3,
  161521. M_RST4 = 0xd4,
  161522. M_RST5 = 0xd5,
  161523. M_RST6 = 0xd6,
  161524. M_RST7 = 0xd7,
  161525. M_SOI = 0xd8,
  161526. M_EOI = 0xd9,
  161527. M_SOS = 0xda,
  161528. M_DQT = 0xdb,
  161529. M_DNL = 0xdc,
  161530. M_DRI = 0xdd,
  161531. M_DHP = 0xde,
  161532. M_EXP = 0xdf,
  161533. M_APP0 = 0xe0,
  161534. M_APP1 = 0xe1,
  161535. M_APP2 = 0xe2,
  161536. M_APP3 = 0xe3,
  161537. M_APP4 = 0xe4,
  161538. M_APP5 = 0xe5,
  161539. M_APP6 = 0xe6,
  161540. M_APP7 = 0xe7,
  161541. M_APP8 = 0xe8,
  161542. M_APP9 = 0xe9,
  161543. M_APP10 = 0xea,
  161544. M_APP11 = 0xeb,
  161545. M_APP12 = 0xec,
  161546. M_APP13 = 0xed,
  161547. M_APP14 = 0xee,
  161548. M_APP15 = 0xef,
  161549. M_JPG0 = 0xf0,
  161550. M_JPG13 = 0xfd,
  161551. M_COM = 0xfe,
  161552. M_TEM = 0x01,
  161553. M_ERROR = 0x100
  161554. } JPEG_MARKER;
  161555. /*
  161556. * Figure F.12: extend sign bit.
  161557. * On some machines, a shift and add will be faster than a table lookup.
  161558. */
  161559. #ifdef AVOID_TABLES
  161560. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161561. #else
  161562. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161563. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161564. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161565. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161566. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161567. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161568. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161569. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161570. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161571. #endif /* AVOID_TABLES */
  161572. #endif
  161573. /*** End of inlined file: jinclude.h ***/
  161574. /*
  161575. * Initialization of a JPEG compression object.
  161576. * The error manager must already be set up (in case memory manager fails).
  161577. */
  161578. GLOBAL(void)
  161579. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161580. {
  161581. int i;
  161582. /* Guard against version mismatches between library and caller. */
  161583. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161584. if (version != JPEG_LIB_VERSION)
  161585. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161586. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161587. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161588. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161589. /* For debugging purposes, we zero the whole master structure.
  161590. * But the application has already set the err pointer, and may have set
  161591. * client_data, so we have to save and restore those fields.
  161592. * Note: if application hasn't set client_data, tools like Purify may
  161593. * complain here.
  161594. */
  161595. {
  161596. struct jpeg_error_mgr * err = cinfo->err;
  161597. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161598. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161599. cinfo->err = err;
  161600. cinfo->client_data = client_data;
  161601. }
  161602. cinfo->is_decompressor = FALSE;
  161603. /* Initialize a memory manager instance for this object */
  161604. jinit_memory_mgr((j_common_ptr) cinfo);
  161605. /* Zero out pointers to permanent structures. */
  161606. cinfo->progress = NULL;
  161607. cinfo->dest = NULL;
  161608. cinfo->comp_info = NULL;
  161609. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161610. cinfo->quant_tbl_ptrs[i] = NULL;
  161611. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161612. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161613. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161614. }
  161615. cinfo->script_space = NULL;
  161616. cinfo->input_gamma = 1.0; /* in case application forgets */
  161617. /* OK, I'm ready */
  161618. cinfo->global_state = CSTATE_START;
  161619. }
  161620. /*
  161621. * Destruction of a JPEG compression object
  161622. */
  161623. GLOBAL(void)
  161624. jpeg_destroy_compress (j_compress_ptr cinfo)
  161625. {
  161626. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161627. }
  161628. /*
  161629. * Abort processing of a JPEG compression operation,
  161630. * but don't destroy the object itself.
  161631. */
  161632. GLOBAL(void)
  161633. jpeg_abort_compress (j_compress_ptr cinfo)
  161634. {
  161635. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161636. }
  161637. /*
  161638. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161639. * Marks all currently defined tables as already written (if suppress)
  161640. * or not written (if !suppress). This will control whether they get emitted
  161641. * by a subsequent jpeg_start_compress call.
  161642. *
  161643. * This routine is exported for use by applications that want to produce
  161644. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161645. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161646. * jcparam.o would be linked whether the application used it or not.
  161647. */
  161648. GLOBAL(void)
  161649. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161650. {
  161651. int i;
  161652. JQUANT_TBL * qtbl;
  161653. JHUFF_TBL * htbl;
  161654. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161655. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161656. qtbl->sent_table = suppress;
  161657. }
  161658. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161659. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161660. htbl->sent_table = suppress;
  161661. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161662. htbl->sent_table = suppress;
  161663. }
  161664. }
  161665. /*
  161666. * Finish JPEG compression.
  161667. *
  161668. * If a multipass operating mode was selected, this may do a great deal of
  161669. * work including most of the actual output.
  161670. */
  161671. GLOBAL(void)
  161672. jpeg_finish_compress (j_compress_ptr cinfo)
  161673. {
  161674. JDIMENSION iMCU_row;
  161675. if (cinfo->global_state == CSTATE_SCANNING ||
  161676. cinfo->global_state == CSTATE_RAW_OK) {
  161677. /* Terminate first pass */
  161678. if (cinfo->next_scanline < cinfo->image_height)
  161679. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161680. (*cinfo->master->finish_pass) (cinfo);
  161681. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161682. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161683. /* Perform any remaining passes */
  161684. while (! cinfo->master->is_last_pass) {
  161685. (*cinfo->master->prepare_for_pass) (cinfo);
  161686. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161687. if (cinfo->progress != NULL) {
  161688. cinfo->progress->pass_counter = (long) iMCU_row;
  161689. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161690. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161691. }
  161692. /* We bypass the main controller and invoke coef controller directly;
  161693. * all work is being done from the coefficient buffer.
  161694. */
  161695. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161696. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161697. }
  161698. (*cinfo->master->finish_pass) (cinfo);
  161699. }
  161700. /* Write EOI, do final cleanup */
  161701. (*cinfo->marker->write_file_trailer) (cinfo);
  161702. (*cinfo->dest->term_destination) (cinfo);
  161703. /* We can use jpeg_abort to release memory and reset global_state */
  161704. jpeg_abort((j_common_ptr) cinfo);
  161705. }
  161706. /*
  161707. * Write a special marker.
  161708. * This is only recommended for writing COM or APPn markers.
  161709. * Must be called after jpeg_start_compress() and before
  161710. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161711. */
  161712. GLOBAL(void)
  161713. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161714. const JOCTET *dataptr, unsigned int datalen)
  161715. {
  161716. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161717. if (cinfo->next_scanline != 0 ||
  161718. (cinfo->global_state != CSTATE_SCANNING &&
  161719. cinfo->global_state != CSTATE_RAW_OK &&
  161720. cinfo->global_state != CSTATE_WRCOEFS))
  161721. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161722. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161723. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161724. while (datalen--) {
  161725. (*write_marker_byte) (cinfo, *dataptr);
  161726. dataptr++;
  161727. }
  161728. }
  161729. /* Same, but piecemeal. */
  161730. GLOBAL(void)
  161731. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161732. {
  161733. if (cinfo->next_scanline != 0 ||
  161734. (cinfo->global_state != CSTATE_SCANNING &&
  161735. cinfo->global_state != CSTATE_RAW_OK &&
  161736. cinfo->global_state != CSTATE_WRCOEFS))
  161737. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161738. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161739. }
  161740. GLOBAL(void)
  161741. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161742. {
  161743. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161744. }
  161745. /*
  161746. * Alternate compression function: just write an abbreviated table file.
  161747. * Before calling this, all parameters and a data destination must be set up.
  161748. *
  161749. * To produce a pair of files containing abbreviated tables and abbreviated
  161750. * image data, one would proceed as follows:
  161751. *
  161752. * initialize JPEG object
  161753. * set JPEG parameters
  161754. * set destination to table file
  161755. * jpeg_write_tables(cinfo);
  161756. * set destination to image file
  161757. * jpeg_start_compress(cinfo, FALSE);
  161758. * write data...
  161759. * jpeg_finish_compress(cinfo);
  161760. *
  161761. * jpeg_write_tables has the side effect of marking all tables written
  161762. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161763. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161764. */
  161765. GLOBAL(void)
  161766. jpeg_write_tables (j_compress_ptr cinfo)
  161767. {
  161768. if (cinfo->global_state != CSTATE_START)
  161769. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161770. /* (Re)initialize error mgr and destination modules */
  161771. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161772. (*cinfo->dest->init_destination) (cinfo);
  161773. /* Initialize the marker writer ... bit of a crock to do it here. */
  161774. jinit_marker_writer(cinfo);
  161775. /* Write them tables! */
  161776. (*cinfo->marker->write_tables_only) (cinfo);
  161777. /* And clean up. */
  161778. (*cinfo->dest->term_destination) (cinfo);
  161779. /*
  161780. * In library releases up through v6a, we called jpeg_abort() here to free
  161781. * any working memory allocated by the destination manager and marker
  161782. * writer. Some applications had a problem with that: they allocated space
  161783. * of their own from the library memory manager, and didn't want it to go
  161784. * away during write_tables. So now we do nothing. This will cause a
  161785. * memory leak if an app calls write_tables repeatedly without doing a full
  161786. * compression cycle or otherwise resetting the JPEG object. However, that
  161787. * seems less bad than unexpectedly freeing memory in the normal case.
  161788. * An app that prefers the old behavior can call jpeg_abort for itself after
  161789. * each call to jpeg_write_tables().
  161790. */
  161791. }
  161792. /*** End of inlined file: jcapimin.c ***/
  161793. /*** Start of inlined file: jcapistd.c ***/
  161794. #define JPEG_INTERNALS
  161795. /*
  161796. * Compression initialization.
  161797. * Before calling this, all parameters and a data destination must be set up.
  161798. *
  161799. * We require a write_all_tables parameter as a failsafe check when writing
  161800. * multiple datastreams from the same compression object. Since prior runs
  161801. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161802. * would emit an abbreviated stream (no tables) by default. This may be what
  161803. * is wanted, but for safety's sake it should not be the default behavior:
  161804. * programmers should have to make a deliberate choice to emit abbreviated
  161805. * images. Therefore the documentation and examples should encourage people
  161806. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161807. * wrong thing.
  161808. */
  161809. GLOBAL(void)
  161810. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161811. {
  161812. if (cinfo->global_state != CSTATE_START)
  161813. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161814. if (write_all_tables)
  161815. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161816. /* (Re)initialize error mgr and destination modules */
  161817. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161818. (*cinfo->dest->init_destination) (cinfo);
  161819. /* Perform master selection of active modules */
  161820. jinit_compress_master(cinfo);
  161821. /* Set up for the first pass */
  161822. (*cinfo->master->prepare_for_pass) (cinfo);
  161823. /* Ready for application to drive first pass through jpeg_write_scanlines
  161824. * or jpeg_write_raw_data.
  161825. */
  161826. cinfo->next_scanline = 0;
  161827. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161828. }
  161829. /*
  161830. * Write some scanlines of data to the JPEG compressor.
  161831. *
  161832. * The return value will be the number of lines actually written.
  161833. * This should be less than the supplied num_lines only in case that
  161834. * the data destination module has requested suspension of the compressor,
  161835. * or if more than image_height scanlines are passed in.
  161836. *
  161837. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161838. * this likely signals an application programmer error. However,
  161839. * excess scanlines passed in the last valid call are *silently* ignored,
  161840. * so that the application need not adjust num_lines for end-of-image
  161841. * when using a multiple-scanline buffer.
  161842. */
  161843. GLOBAL(JDIMENSION)
  161844. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161845. JDIMENSION num_lines)
  161846. {
  161847. JDIMENSION row_ctr, rows_left;
  161848. if (cinfo->global_state != CSTATE_SCANNING)
  161849. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161850. if (cinfo->next_scanline >= cinfo->image_height)
  161851. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161852. /* Call progress monitor hook if present */
  161853. if (cinfo->progress != NULL) {
  161854. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161855. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161856. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161857. }
  161858. /* Give master control module another chance if this is first call to
  161859. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161860. * delayed so that application can write COM, etc, markers between
  161861. * jpeg_start_compress and jpeg_write_scanlines.
  161862. */
  161863. if (cinfo->master->call_pass_startup)
  161864. (*cinfo->master->pass_startup) (cinfo);
  161865. /* Ignore any extra scanlines at bottom of image. */
  161866. rows_left = cinfo->image_height - cinfo->next_scanline;
  161867. if (num_lines > rows_left)
  161868. num_lines = rows_left;
  161869. row_ctr = 0;
  161870. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161871. cinfo->next_scanline += row_ctr;
  161872. return row_ctr;
  161873. }
  161874. /*
  161875. * Alternate entry point to write raw data.
  161876. * Processes exactly one iMCU row per call, unless suspended.
  161877. */
  161878. GLOBAL(JDIMENSION)
  161879. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161880. JDIMENSION num_lines)
  161881. {
  161882. JDIMENSION lines_per_iMCU_row;
  161883. if (cinfo->global_state != CSTATE_RAW_OK)
  161884. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161885. if (cinfo->next_scanline >= cinfo->image_height) {
  161886. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161887. return 0;
  161888. }
  161889. /* Call progress monitor hook if present */
  161890. if (cinfo->progress != NULL) {
  161891. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161892. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161893. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161894. }
  161895. /* Give master control module another chance if this is first call to
  161896. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161897. * delayed so that application can write COM, etc, markers between
  161898. * jpeg_start_compress and jpeg_write_raw_data.
  161899. */
  161900. if (cinfo->master->call_pass_startup)
  161901. (*cinfo->master->pass_startup) (cinfo);
  161902. /* Verify that at least one iMCU row has been passed. */
  161903. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161904. if (num_lines < lines_per_iMCU_row)
  161905. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161906. /* Directly compress the row. */
  161907. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161908. /* If compressor did not consume the whole row, suspend processing. */
  161909. return 0;
  161910. }
  161911. /* OK, we processed one iMCU row. */
  161912. cinfo->next_scanline += lines_per_iMCU_row;
  161913. return lines_per_iMCU_row;
  161914. }
  161915. /*** End of inlined file: jcapistd.c ***/
  161916. /*** Start of inlined file: jccoefct.c ***/
  161917. #define JPEG_INTERNALS
  161918. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161919. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161920. * step is run during the first pass, and subsequent passes need only read
  161921. * the buffered coefficients.
  161922. */
  161923. #ifdef ENTROPY_OPT_SUPPORTED
  161924. #define FULL_COEF_BUFFER_SUPPORTED
  161925. #else
  161926. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161927. #define FULL_COEF_BUFFER_SUPPORTED
  161928. #endif
  161929. #endif
  161930. /* Private buffer controller object */
  161931. typedef struct {
  161932. struct jpeg_c_coef_controller pub; /* public fields */
  161933. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161934. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161935. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161936. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161937. /* For single-pass compression, it's sufficient to buffer just one MCU
  161938. * (although this may prove a bit slow in practice). We allocate a
  161939. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161940. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161941. * it's not really very big; this is to keep the module interfaces unchanged
  161942. * when a large coefficient buffer is necessary.)
  161943. * In multi-pass modes, this array points to the current MCU's blocks
  161944. * within the virtual arrays.
  161945. */
  161946. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161947. /* In multi-pass modes, we need a virtual block array for each component. */
  161948. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161949. } my_coef_controller;
  161950. typedef my_coef_controller * my_coef_ptr;
  161951. /* Forward declarations */
  161952. METHODDEF(boolean) compress_data
  161953. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161954. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161955. METHODDEF(boolean) compress_first_pass
  161956. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161957. METHODDEF(boolean) compress_output
  161958. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161959. #endif
  161960. LOCAL(void)
  161961. start_iMCU_row (j_compress_ptr cinfo)
  161962. /* Reset within-iMCU-row counters for a new row */
  161963. {
  161964. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161965. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161966. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161967. * But at the bottom of the image, process only what's left.
  161968. */
  161969. if (cinfo->comps_in_scan > 1) {
  161970. coef->MCU_rows_per_iMCU_row = 1;
  161971. } else {
  161972. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161973. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161974. else
  161975. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161976. }
  161977. coef->mcu_ctr = 0;
  161978. coef->MCU_vert_offset = 0;
  161979. }
  161980. /*
  161981. * Initialize for a processing pass.
  161982. */
  161983. METHODDEF(void)
  161984. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161985. {
  161986. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161987. coef->iMCU_row_num = 0;
  161988. start_iMCU_row(cinfo);
  161989. switch (pass_mode) {
  161990. case JBUF_PASS_THRU:
  161991. if (coef->whole_image[0] != NULL)
  161992. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161993. coef->pub.compress_data = compress_data;
  161994. break;
  161995. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161996. case JBUF_SAVE_AND_PASS:
  161997. if (coef->whole_image[0] == NULL)
  161998. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161999. coef->pub.compress_data = compress_first_pass;
  162000. break;
  162001. case JBUF_CRANK_DEST:
  162002. if (coef->whole_image[0] == NULL)
  162003. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162004. coef->pub.compress_data = compress_output;
  162005. break;
  162006. #endif
  162007. default:
  162008. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162009. break;
  162010. }
  162011. }
  162012. /*
  162013. * Process some data in the single-pass case.
  162014. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162015. * per call, ie, v_samp_factor block rows for each component in the image.
  162016. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162017. *
  162018. * NB: input_buf contains a plane for each component in image,
  162019. * which we index according to the component's SOF position.
  162020. */
  162021. METHODDEF(boolean)
  162022. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162023. {
  162024. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162025. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162026. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162027. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162028. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162029. JDIMENSION ypos, xpos;
  162030. jpeg_component_info *compptr;
  162031. /* Loop to write as much as one whole iMCU row */
  162032. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162033. yoffset++) {
  162034. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162035. MCU_col_num++) {
  162036. /* Determine where data comes from in input_buf and do the DCT thing.
  162037. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162038. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162039. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162040. * specially. The data in them does not matter for image reconstruction,
  162041. * so we fill them with values that will encode to the smallest amount of
  162042. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162043. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162044. */
  162045. blkn = 0;
  162046. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162047. compptr = cinfo->cur_comp_info[ci];
  162048. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162049. : compptr->last_col_width;
  162050. xpos = MCU_col_num * compptr->MCU_sample_width;
  162051. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162052. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162053. if (coef->iMCU_row_num < last_iMCU_row ||
  162054. yoffset+yindex < compptr->last_row_height) {
  162055. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162056. input_buf[compptr->component_index],
  162057. coef->MCU_buffer[blkn],
  162058. ypos, xpos, (JDIMENSION) blockcnt);
  162059. if (blockcnt < compptr->MCU_width) {
  162060. /* Create some dummy blocks at the right edge of the image. */
  162061. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162062. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162063. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162064. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162065. }
  162066. }
  162067. } else {
  162068. /* Create a row of dummy blocks at the bottom of the image. */
  162069. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162070. compptr->MCU_width * SIZEOF(JBLOCK));
  162071. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162072. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162073. }
  162074. }
  162075. blkn += compptr->MCU_width;
  162076. ypos += DCTSIZE;
  162077. }
  162078. }
  162079. /* Try to write the MCU. In event of a suspension failure, we will
  162080. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162081. */
  162082. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162083. /* Suspension forced; update state counters and exit */
  162084. coef->MCU_vert_offset = yoffset;
  162085. coef->mcu_ctr = MCU_col_num;
  162086. return FALSE;
  162087. }
  162088. }
  162089. /* Completed an MCU row, but perhaps not an iMCU row */
  162090. coef->mcu_ctr = 0;
  162091. }
  162092. /* Completed the iMCU row, advance counters for next one */
  162093. coef->iMCU_row_num++;
  162094. start_iMCU_row(cinfo);
  162095. return TRUE;
  162096. }
  162097. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162098. /*
  162099. * Process some data in the first pass of a multi-pass case.
  162100. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162101. * per call, ie, v_samp_factor block rows for each component in the image.
  162102. * This amount of data is read from the source buffer, DCT'd and quantized,
  162103. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162104. * as needed at the right and lower edges. (The dummy blocks are constructed
  162105. * in the virtual arrays, which have been padded appropriately.) This makes
  162106. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162107. *
  162108. * We must also emit the data to the entropy encoder. This is conveniently
  162109. * done by calling compress_output() after we've loaded the current strip
  162110. * of the virtual arrays.
  162111. *
  162112. * NB: input_buf contains a plane for each component in image. All
  162113. * components are DCT'd and loaded into the virtual arrays in this pass.
  162114. * However, it may be that only a subset of the components are emitted to
  162115. * the entropy encoder during this first pass; be careful about looking
  162116. * at the scan-dependent variables (MCU dimensions, etc).
  162117. */
  162118. METHODDEF(boolean)
  162119. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162120. {
  162121. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162122. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162123. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162124. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162125. JCOEF lastDC;
  162126. jpeg_component_info *compptr;
  162127. JBLOCKARRAY buffer;
  162128. JBLOCKROW thisblockrow, lastblockrow;
  162129. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162130. ci++, compptr++) {
  162131. /* Align the virtual buffer for this component. */
  162132. buffer = (*cinfo->mem->access_virt_barray)
  162133. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162134. coef->iMCU_row_num * compptr->v_samp_factor,
  162135. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162136. /* Count non-dummy DCT block rows in this iMCU row. */
  162137. if (coef->iMCU_row_num < last_iMCU_row)
  162138. block_rows = compptr->v_samp_factor;
  162139. else {
  162140. /* NB: can't use last_row_height here, since may not be set! */
  162141. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162142. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162143. }
  162144. blocks_across = compptr->width_in_blocks;
  162145. h_samp_factor = compptr->h_samp_factor;
  162146. /* Count number of dummy blocks to be added at the right margin. */
  162147. ndummy = (int) (blocks_across % h_samp_factor);
  162148. if (ndummy > 0)
  162149. ndummy = h_samp_factor - ndummy;
  162150. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162151. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162152. */
  162153. for (block_row = 0; block_row < block_rows; block_row++) {
  162154. thisblockrow = buffer[block_row];
  162155. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162156. input_buf[ci], thisblockrow,
  162157. (JDIMENSION) (block_row * DCTSIZE),
  162158. (JDIMENSION) 0, blocks_across);
  162159. if (ndummy > 0) {
  162160. /* Create dummy blocks at the right edge of the image. */
  162161. thisblockrow += blocks_across; /* => first dummy block */
  162162. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162163. lastDC = thisblockrow[-1][0];
  162164. for (bi = 0; bi < ndummy; bi++) {
  162165. thisblockrow[bi][0] = lastDC;
  162166. }
  162167. }
  162168. }
  162169. /* If at end of image, create dummy block rows as needed.
  162170. * The tricky part here is that within each MCU, we want the DC values
  162171. * of the dummy blocks to match the last real block's DC value.
  162172. * This squeezes a few more bytes out of the resulting file...
  162173. */
  162174. if (coef->iMCU_row_num == last_iMCU_row) {
  162175. blocks_across += ndummy; /* include lower right corner */
  162176. MCUs_across = blocks_across / h_samp_factor;
  162177. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162178. block_row++) {
  162179. thisblockrow = buffer[block_row];
  162180. lastblockrow = buffer[block_row-1];
  162181. jzero_far((void FAR *) thisblockrow,
  162182. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162183. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162184. lastDC = lastblockrow[h_samp_factor-1][0];
  162185. for (bi = 0; bi < h_samp_factor; bi++) {
  162186. thisblockrow[bi][0] = lastDC;
  162187. }
  162188. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162189. lastblockrow += h_samp_factor;
  162190. }
  162191. }
  162192. }
  162193. }
  162194. /* NB: compress_output will increment iMCU_row_num if successful.
  162195. * A suspension return will result in redoing all the work above next time.
  162196. */
  162197. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162198. return compress_output(cinfo, input_buf);
  162199. }
  162200. /*
  162201. * Process some data in subsequent passes of a multi-pass case.
  162202. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162203. * per call, ie, v_samp_factor block rows for each component in the scan.
  162204. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162205. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162206. *
  162207. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162208. */
  162209. METHODDEF(boolean)
  162210. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162211. {
  162212. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162213. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162214. int blkn, ci, xindex, yindex, yoffset;
  162215. JDIMENSION start_col;
  162216. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162217. JBLOCKROW buffer_ptr;
  162218. jpeg_component_info *compptr;
  162219. /* Align the virtual buffers for the components used in this scan.
  162220. * NB: during first pass, this is safe only because the buffers will
  162221. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162222. */
  162223. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162224. compptr = cinfo->cur_comp_info[ci];
  162225. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162226. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162227. coef->iMCU_row_num * compptr->v_samp_factor,
  162228. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162229. }
  162230. /* Loop to process one whole iMCU row */
  162231. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162232. yoffset++) {
  162233. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162234. MCU_col_num++) {
  162235. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162236. blkn = 0; /* index of current DCT block within MCU */
  162237. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162238. compptr = cinfo->cur_comp_info[ci];
  162239. start_col = MCU_col_num * compptr->MCU_width;
  162240. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162241. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162242. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162243. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162244. }
  162245. }
  162246. }
  162247. /* Try to write the MCU. */
  162248. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162249. /* Suspension forced; update state counters and exit */
  162250. coef->MCU_vert_offset = yoffset;
  162251. coef->mcu_ctr = MCU_col_num;
  162252. return FALSE;
  162253. }
  162254. }
  162255. /* Completed an MCU row, but perhaps not an iMCU row */
  162256. coef->mcu_ctr = 0;
  162257. }
  162258. /* Completed the iMCU row, advance counters for next one */
  162259. coef->iMCU_row_num++;
  162260. start_iMCU_row(cinfo);
  162261. return TRUE;
  162262. }
  162263. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162264. /*
  162265. * Initialize coefficient buffer controller.
  162266. */
  162267. GLOBAL(void)
  162268. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162269. {
  162270. my_coef_ptr coef;
  162271. coef = (my_coef_ptr)
  162272. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162273. SIZEOF(my_coef_controller));
  162274. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162275. coef->pub.start_pass = start_pass_coef;
  162276. /* Create the coefficient buffer. */
  162277. if (need_full_buffer) {
  162278. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162279. /* Allocate a full-image virtual array for each component, */
  162280. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162281. int ci;
  162282. jpeg_component_info *compptr;
  162283. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162284. ci++, compptr++) {
  162285. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162286. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162287. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162288. (long) compptr->h_samp_factor),
  162289. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162290. (long) compptr->v_samp_factor),
  162291. (JDIMENSION) compptr->v_samp_factor);
  162292. }
  162293. #else
  162294. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162295. #endif
  162296. } else {
  162297. /* We only need a single-MCU buffer. */
  162298. JBLOCKROW buffer;
  162299. int i;
  162300. buffer = (JBLOCKROW)
  162301. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162302. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162303. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162304. coef->MCU_buffer[i] = buffer + i;
  162305. }
  162306. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162307. }
  162308. }
  162309. /*** End of inlined file: jccoefct.c ***/
  162310. /*** Start of inlined file: jccolor.c ***/
  162311. #define JPEG_INTERNALS
  162312. /* Private subobject */
  162313. typedef struct {
  162314. struct jpeg_color_converter pub; /* public fields */
  162315. /* Private state for RGB->YCC conversion */
  162316. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162317. } my_color_converter;
  162318. typedef my_color_converter * my_cconvert_ptr;
  162319. /**************** RGB -> YCbCr conversion: most common case **************/
  162320. /*
  162321. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162322. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162323. * The conversion equations to be implemented are therefore
  162324. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162325. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162326. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162327. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162328. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162329. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162330. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162331. * were not represented exactly. Now we sacrifice exact representation of
  162332. * maximum red and maximum blue in order to get exact grayscales.
  162333. *
  162334. * To avoid floating-point arithmetic, we represent the fractional constants
  162335. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162336. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162337. *
  162338. * For even more speed, we avoid doing any multiplications in the inner loop
  162339. * by precalculating the constants times R,G,B for all possible values.
  162340. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162341. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162342. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162343. * colorspace anyway.
  162344. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162345. * in the tables to save adding them separately in the inner loop.
  162346. */
  162347. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162348. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162349. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162350. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162351. /* We allocate one big table and divide it up into eight parts, instead of
  162352. * doing eight alloc_small requests. This lets us use a single table base
  162353. * address, which can be held in a register in the inner loops on many
  162354. * machines (more than can hold all eight addresses, anyway).
  162355. */
  162356. #define R_Y_OFF 0 /* offset to R => Y section */
  162357. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162358. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162359. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162360. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162361. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162362. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162363. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162364. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162365. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162366. /*
  162367. * Initialize for RGB->YCC colorspace conversion.
  162368. */
  162369. METHODDEF(void)
  162370. rgb_ycc_start (j_compress_ptr cinfo)
  162371. {
  162372. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162373. INT32 * rgb_ycc_tab;
  162374. INT32 i;
  162375. /* Allocate and fill in the conversion tables. */
  162376. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162377. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162378. (TABLE_SIZE * SIZEOF(INT32)));
  162379. for (i = 0; i <= MAXJSAMPLE; i++) {
  162380. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162381. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162382. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162383. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162384. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162385. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162386. * This ensures that the maximum output will round to MAXJSAMPLE
  162387. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162388. */
  162389. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162390. /* B=>Cb and R=>Cr tables are the same
  162391. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162392. */
  162393. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162394. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162395. }
  162396. }
  162397. /*
  162398. * Convert some rows of samples to the JPEG colorspace.
  162399. *
  162400. * Note that we change from the application's interleaved-pixel format
  162401. * to our internal noninterleaved, one-plane-per-component format.
  162402. * The input buffer is therefore three times as wide as the output buffer.
  162403. *
  162404. * A starting row offset is provided only for the output buffer. The caller
  162405. * can easily adjust the passed input_buf value to accommodate any row
  162406. * offset required on that side.
  162407. */
  162408. METHODDEF(void)
  162409. rgb_ycc_convert (j_compress_ptr cinfo,
  162410. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162411. JDIMENSION output_row, int num_rows)
  162412. {
  162413. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162414. register int r, g, b;
  162415. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162416. register JSAMPROW inptr;
  162417. register JSAMPROW outptr0, outptr1, outptr2;
  162418. register JDIMENSION col;
  162419. JDIMENSION num_cols = cinfo->image_width;
  162420. while (--num_rows >= 0) {
  162421. inptr = *input_buf++;
  162422. outptr0 = output_buf[0][output_row];
  162423. outptr1 = output_buf[1][output_row];
  162424. outptr2 = output_buf[2][output_row];
  162425. output_row++;
  162426. for (col = 0; col < num_cols; col++) {
  162427. r = GETJSAMPLE(inptr[RGB_RED]);
  162428. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162429. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162430. inptr += RGB_PIXELSIZE;
  162431. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162432. * must be too; we do not need an explicit range-limiting operation.
  162433. * Hence the value being shifted is never negative, and we don't
  162434. * need the general RIGHT_SHIFT macro.
  162435. */
  162436. /* Y */
  162437. outptr0[col] = (JSAMPLE)
  162438. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162439. >> SCALEBITS);
  162440. /* Cb */
  162441. outptr1[col] = (JSAMPLE)
  162442. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162443. >> SCALEBITS);
  162444. /* Cr */
  162445. outptr2[col] = (JSAMPLE)
  162446. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162447. >> SCALEBITS);
  162448. }
  162449. }
  162450. }
  162451. /**************** Cases other than RGB -> YCbCr **************/
  162452. /*
  162453. * Convert some rows of samples to the JPEG colorspace.
  162454. * This version handles RGB->grayscale conversion, which is the same
  162455. * as the RGB->Y portion of RGB->YCbCr.
  162456. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162457. */
  162458. METHODDEF(void)
  162459. rgb_gray_convert (j_compress_ptr cinfo,
  162460. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162461. JDIMENSION output_row, int num_rows)
  162462. {
  162463. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162464. register int r, g, b;
  162465. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162466. register JSAMPROW inptr;
  162467. register JSAMPROW outptr;
  162468. register JDIMENSION col;
  162469. JDIMENSION num_cols = cinfo->image_width;
  162470. while (--num_rows >= 0) {
  162471. inptr = *input_buf++;
  162472. outptr = output_buf[0][output_row];
  162473. output_row++;
  162474. for (col = 0; col < num_cols; col++) {
  162475. r = GETJSAMPLE(inptr[RGB_RED]);
  162476. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162477. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162478. inptr += RGB_PIXELSIZE;
  162479. /* Y */
  162480. outptr[col] = (JSAMPLE)
  162481. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162482. >> SCALEBITS);
  162483. }
  162484. }
  162485. }
  162486. /*
  162487. * Convert some rows of samples to the JPEG colorspace.
  162488. * This version handles Adobe-style CMYK->YCCK conversion,
  162489. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162490. * conversion as above, while passing K (black) unchanged.
  162491. * We assume rgb_ycc_start has been called.
  162492. */
  162493. METHODDEF(void)
  162494. cmyk_ycck_convert (j_compress_ptr cinfo,
  162495. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162496. JDIMENSION output_row, int num_rows)
  162497. {
  162498. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162499. register int r, g, b;
  162500. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162501. register JSAMPROW inptr;
  162502. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162503. register JDIMENSION col;
  162504. JDIMENSION num_cols = cinfo->image_width;
  162505. while (--num_rows >= 0) {
  162506. inptr = *input_buf++;
  162507. outptr0 = output_buf[0][output_row];
  162508. outptr1 = output_buf[1][output_row];
  162509. outptr2 = output_buf[2][output_row];
  162510. outptr3 = output_buf[3][output_row];
  162511. output_row++;
  162512. for (col = 0; col < num_cols; col++) {
  162513. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162514. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162515. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162516. /* K passes through as-is */
  162517. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162518. inptr += 4;
  162519. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162520. * must be too; we do not need an explicit range-limiting operation.
  162521. * Hence the value being shifted is never negative, and we don't
  162522. * need the general RIGHT_SHIFT macro.
  162523. */
  162524. /* Y */
  162525. outptr0[col] = (JSAMPLE)
  162526. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162527. >> SCALEBITS);
  162528. /* Cb */
  162529. outptr1[col] = (JSAMPLE)
  162530. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162531. >> SCALEBITS);
  162532. /* Cr */
  162533. outptr2[col] = (JSAMPLE)
  162534. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162535. >> SCALEBITS);
  162536. }
  162537. }
  162538. }
  162539. /*
  162540. * Convert some rows of samples to the JPEG colorspace.
  162541. * This version handles grayscale output with no conversion.
  162542. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162543. */
  162544. METHODDEF(void)
  162545. grayscale_convert (j_compress_ptr cinfo,
  162546. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162547. JDIMENSION output_row, int num_rows)
  162548. {
  162549. register JSAMPROW inptr;
  162550. register JSAMPROW outptr;
  162551. register JDIMENSION col;
  162552. JDIMENSION num_cols = cinfo->image_width;
  162553. int instride = cinfo->input_components;
  162554. while (--num_rows >= 0) {
  162555. inptr = *input_buf++;
  162556. outptr = output_buf[0][output_row];
  162557. output_row++;
  162558. for (col = 0; col < num_cols; col++) {
  162559. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162560. inptr += instride;
  162561. }
  162562. }
  162563. }
  162564. /*
  162565. * Convert some rows of samples to the JPEG colorspace.
  162566. * This version handles multi-component colorspaces without conversion.
  162567. * We assume input_components == num_components.
  162568. */
  162569. METHODDEF(void)
  162570. null_convert (j_compress_ptr cinfo,
  162571. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162572. JDIMENSION output_row, int num_rows)
  162573. {
  162574. register JSAMPROW inptr;
  162575. register JSAMPROW outptr;
  162576. register JDIMENSION col;
  162577. register int ci;
  162578. int nc = cinfo->num_components;
  162579. JDIMENSION num_cols = cinfo->image_width;
  162580. while (--num_rows >= 0) {
  162581. /* It seems fastest to make a separate pass for each component. */
  162582. for (ci = 0; ci < nc; ci++) {
  162583. inptr = *input_buf;
  162584. outptr = output_buf[ci][output_row];
  162585. for (col = 0; col < num_cols; col++) {
  162586. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162587. inptr += nc;
  162588. }
  162589. }
  162590. input_buf++;
  162591. output_row++;
  162592. }
  162593. }
  162594. /*
  162595. * Empty method for start_pass.
  162596. */
  162597. METHODDEF(void)
  162598. null_method (j_compress_ptr)
  162599. {
  162600. /* no work needed */
  162601. }
  162602. /*
  162603. * Module initialization routine for input colorspace conversion.
  162604. */
  162605. GLOBAL(void)
  162606. jinit_color_converter (j_compress_ptr cinfo)
  162607. {
  162608. my_cconvert_ptr cconvert;
  162609. cconvert = (my_cconvert_ptr)
  162610. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162611. SIZEOF(my_color_converter));
  162612. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162613. /* set start_pass to null method until we find out differently */
  162614. cconvert->pub.start_pass = null_method;
  162615. /* Make sure input_components agrees with in_color_space */
  162616. switch (cinfo->in_color_space) {
  162617. case JCS_GRAYSCALE:
  162618. if (cinfo->input_components != 1)
  162619. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162620. break;
  162621. case JCS_RGB:
  162622. #if RGB_PIXELSIZE != 3
  162623. if (cinfo->input_components != RGB_PIXELSIZE)
  162624. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162625. break;
  162626. #endif /* else share code with YCbCr */
  162627. case JCS_YCbCr:
  162628. if (cinfo->input_components != 3)
  162629. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162630. break;
  162631. case JCS_CMYK:
  162632. case JCS_YCCK:
  162633. if (cinfo->input_components != 4)
  162634. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162635. break;
  162636. default: /* JCS_UNKNOWN can be anything */
  162637. if (cinfo->input_components < 1)
  162638. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162639. break;
  162640. }
  162641. /* Check num_components, set conversion method based on requested space */
  162642. switch (cinfo->jpeg_color_space) {
  162643. case JCS_GRAYSCALE:
  162644. if (cinfo->num_components != 1)
  162645. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162646. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162647. cconvert->pub.color_convert = grayscale_convert;
  162648. else if (cinfo->in_color_space == JCS_RGB) {
  162649. cconvert->pub.start_pass = rgb_ycc_start;
  162650. cconvert->pub.color_convert = rgb_gray_convert;
  162651. } else if (cinfo->in_color_space == JCS_YCbCr)
  162652. cconvert->pub.color_convert = grayscale_convert;
  162653. else
  162654. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162655. break;
  162656. case JCS_RGB:
  162657. if (cinfo->num_components != 3)
  162658. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162659. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162660. cconvert->pub.color_convert = null_convert;
  162661. else
  162662. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162663. break;
  162664. case JCS_YCbCr:
  162665. if (cinfo->num_components != 3)
  162666. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162667. if (cinfo->in_color_space == JCS_RGB) {
  162668. cconvert->pub.start_pass = rgb_ycc_start;
  162669. cconvert->pub.color_convert = rgb_ycc_convert;
  162670. } else if (cinfo->in_color_space == JCS_YCbCr)
  162671. cconvert->pub.color_convert = null_convert;
  162672. else
  162673. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162674. break;
  162675. case JCS_CMYK:
  162676. if (cinfo->num_components != 4)
  162677. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162678. if (cinfo->in_color_space == JCS_CMYK)
  162679. cconvert->pub.color_convert = null_convert;
  162680. else
  162681. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162682. break;
  162683. case JCS_YCCK:
  162684. if (cinfo->num_components != 4)
  162685. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162686. if (cinfo->in_color_space == JCS_CMYK) {
  162687. cconvert->pub.start_pass = rgb_ycc_start;
  162688. cconvert->pub.color_convert = cmyk_ycck_convert;
  162689. } else if (cinfo->in_color_space == JCS_YCCK)
  162690. cconvert->pub.color_convert = null_convert;
  162691. else
  162692. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162693. break;
  162694. default: /* allow null conversion of JCS_UNKNOWN */
  162695. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162696. cinfo->num_components != cinfo->input_components)
  162697. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162698. cconvert->pub.color_convert = null_convert;
  162699. break;
  162700. }
  162701. }
  162702. /*** End of inlined file: jccolor.c ***/
  162703. #undef FIX
  162704. /*** Start of inlined file: jcdctmgr.c ***/
  162705. #define JPEG_INTERNALS
  162706. /*** Start of inlined file: jdct.h ***/
  162707. /*
  162708. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162709. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162710. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162711. * implementations use an array of type FAST_FLOAT, instead.)
  162712. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162713. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162714. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162715. * convention improves accuracy in integer implementations and saves some
  162716. * work in floating-point ones.
  162717. * Quantization of the output coefficients is done by jcdctmgr.c.
  162718. */
  162719. #ifndef __jdct_h__
  162720. #define __jdct_h__
  162721. #if BITS_IN_JSAMPLE == 8
  162722. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162723. #else
  162724. typedef INT32 DCTELEM; /* must have 32 bits */
  162725. #endif
  162726. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162727. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162728. /*
  162729. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162730. * to an output sample array. The routine must dequantize the input data as
  162731. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162732. * pointed to by compptr->dct_table. The output data is to be placed into the
  162733. * sample array starting at a specified column. (Any row offset needed will
  162734. * be applied to the array pointer before it is passed to the IDCT code.)
  162735. * Note that the number of samples emitted by the IDCT routine is
  162736. * DCT_scaled_size * DCT_scaled_size.
  162737. */
  162738. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162739. /*
  162740. * Each IDCT routine has its own ideas about the best dct_table element type.
  162741. */
  162742. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162743. #if BITS_IN_JSAMPLE == 8
  162744. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162745. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162746. #else
  162747. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162748. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162749. #endif
  162750. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162751. /*
  162752. * Each IDCT routine is responsible for range-limiting its results and
  162753. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162754. * be quite far out of range if the input data is corrupt, so a bulletproof
  162755. * range-limiting step is required. We use a mask-and-table-lookup method
  162756. * to do the combined operations quickly. See the comments with
  162757. * prepare_range_limit_table (in jdmaster.c) for more info.
  162758. */
  162759. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162760. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162761. /* Short forms of external names for systems with brain-damaged linkers. */
  162762. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162763. #define jpeg_fdct_islow jFDislow
  162764. #define jpeg_fdct_ifast jFDifast
  162765. #define jpeg_fdct_float jFDfloat
  162766. #define jpeg_idct_islow jRDislow
  162767. #define jpeg_idct_ifast jRDifast
  162768. #define jpeg_idct_float jRDfloat
  162769. #define jpeg_idct_4x4 jRD4x4
  162770. #define jpeg_idct_2x2 jRD2x2
  162771. #define jpeg_idct_1x1 jRD1x1
  162772. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162773. /* Extern declarations for the forward and inverse DCT routines. */
  162774. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162775. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162776. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162777. EXTERN(void) jpeg_idct_islow
  162778. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162779. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162780. EXTERN(void) jpeg_idct_ifast
  162781. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162782. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162783. EXTERN(void) jpeg_idct_float
  162784. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162785. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162786. EXTERN(void) jpeg_idct_4x4
  162787. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162788. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162789. EXTERN(void) jpeg_idct_2x2
  162790. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162791. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162792. EXTERN(void) jpeg_idct_1x1
  162793. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162794. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162795. /*
  162796. * Macros for handling fixed-point arithmetic; these are used by many
  162797. * but not all of the DCT/IDCT modules.
  162798. *
  162799. * All values are expected to be of type INT32.
  162800. * Fractional constants are scaled left by CONST_BITS bits.
  162801. * CONST_BITS is defined within each module using these macros,
  162802. * and may differ from one module to the next.
  162803. */
  162804. #define ONE ((INT32) 1)
  162805. #define CONST_SCALE (ONE << CONST_BITS)
  162806. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162807. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162808. * thus causing a lot of useless floating-point operations at run time.
  162809. */
  162810. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162811. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162812. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162813. * the fudge factor is correct for either sign of X.
  162814. */
  162815. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162816. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162817. * This macro is used only when the two inputs will actually be no more than
  162818. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162819. * full 32x32 multiply. This provides a useful speedup on many machines.
  162820. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162821. * in C, but some C compilers will do the right thing if you provide the
  162822. * correct combination of casts.
  162823. */
  162824. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162825. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162826. #endif
  162827. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162828. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162829. #endif
  162830. #ifndef MULTIPLY16C16 /* default definition */
  162831. #define MULTIPLY16C16(var,const) ((var) * (const))
  162832. #endif
  162833. /* Same except both inputs are variables. */
  162834. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162835. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162836. #endif
  162837. #ifndef MULTIPLY16V16 /* default definition */
  162838. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162839. #endif
  162840. #endif
  162841. /*** End of inlined file: jdct.h ***/
  162842. /* Private declarations for DCT subsystem */
  162843. /* Private subobject for this module */
  162844. typedef struct {
  162845. struct jpeg_forward_dct pub; /* public fields */
  162846. /* Pointer to the DCT routine actually in use */
  162847. forward_DCT_method_ptr do_dct;
  162848. /* The actual post-DCT divisors --- not identical to the quant table
  162849. * entries, because of scaling (especially for an unnormalized DCT).
  162850. * Each table is given in normal array order.
  162851. */
  162852. DCTELEM * divisors[NUM_QUANT_TBLS];
  162853. #ifdef DCT_FLOAT_SUPPORTED
  162854. /* Same as above for the floating-point case. */
  162855. float_DCT_method_ptr do_float_dct;
  162856. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162857. #endif
  162858. } my_fdct_controller;
  162859. typedef my_fdct_controller * my_fdct_ptr;
  162860. /*
  162861. * Initialize for a processing pass.
  162862. * Verify that all referenced Q-tables are present, and set up
  162863. * the divisor table for each one.
  162864. * In the current implementation, DCT of all components is done during
  162865. * the first pass, even if only some components will be output in the
  162866. * first scan. Hence all components should be examined here.
  162867. */
  162868. METHODDEF(void)
  162869. start_pass_fdctmgr (j_compress_ptr cinfo)
  162870. {
  162871. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162872. int ci, qtblno, i;
  162873. jpeg_component_info *compptr;
  162874. JQUANT_TBL * qtbl;
  162875. DCTELEM * dtbl;
  162876. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162877. ci++, compptr++) {
  162878. qtblno = compptr->quant_tbl_no;
  162879. /* Make sure specified quantization table is present */
  162880. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162881. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162882. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162883. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162884. /* Compute divisors for this quant table */
  162885. /* We may do this more than once for same table, but it's not a big deal */
  162886. switch (cinfo->dct_method) {
  162887. #ifdef DCT_ISLOW_SUPPORTED
  162888. case JDCT_ISLOW:
  162889. /* For LL&M IDCT method, divisors are equal to raw quantization
  162890. * coefficients multiplied by 8 (to counteract scaling).
  162891. */
  162892. if (fdct->divisors[qtblno] == NULL) {
  162893. fdct->divisors[qtblno] = (DCTELEM *)
  162894. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162895. DCTSIZE2 * SIZEOF(DCTELEM));
  162896. }
  162897. dtbl = fdct->divisors[qtblno];
  162898. for (i = 0; i < DCTSIZE2; i++) {
  162899. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162900. }
  162901. break;
  162902. #endif
  162903. #ifdef DCT_IFAST_SUPPORTED
  162904. case JDCT_IFAST:
  162905. {
  162906. /* For AA&N IDCT method, divisors are equal to quantization
  162907. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162908. * scalefactor[0] = 1
  162909. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162910. * We apply a further scale factor of 8.
  162911. */
  162912. #define CONST_BITS 14
  162913. static const INT16 aanscales[DCTSIZE2] = {
  162914. /* precomputed values scaled up by 14 bits */
  162915. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162916. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162917. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162918. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162919. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162920. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162921. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162922. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162923. };
  162924. SHIFT_TEMPS
  162925. if (fdct->divisors[qtblno] == NULL) {
  162926. fdct->divisors[qtblno] = (DCTELEM *)
  162927. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162928. DCTSIZE2 * SIZEOF(DCTELEM));
  162929. }
  162930. dtbl = fdct->divisors[qtblno];
  162931. for (i = 0; i < DCTSIZE2; i++) {
  162932. dtbl[i] = (DCTELEM)
  162933. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162934. (INT32) aanscales[i]),
  162935. CONST_BITS-3);
  162936. }
  162937. }
  162938. break;
  162939. #endif
  162940. #ifdef DCT_FLOAT_SUPPORTED
  162941. case JDCT_FLOAT:
  162942. {
  162943. /* For float AA&N IDCT method, divisors are equal to quantization
  162944. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162945. * scalefactor[0] = 1
  162946. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162947. * We apply a further scale factor of 8.
  162948. * What's actually stored is 1/divisor so that the inner loop can
  162949. * use a multiplication rather than a division.
  162950. */
  162951. FAST_FLOAT * fdtbl;
  162952. int row, col;
  162953. static const double aanscalefactor[DCTSIZE] = {
  162954. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162955. 1.0, 0.785694958, 0.541196100, 0.275899379
  162956. };
  162957. if (fdct->float_divisors[qtblno] == NULL) {
  162958. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162959. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162960. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162961. }
  162962. fdtbl = fdct->float_divisors[qtblno];
  162963. i = 0;
  162964. for (row = 0; row < DCTSIZE; row++) {
  162965. for (col = 0; col < DCTSIZE; col++) {
  162966. fdtbl[i] = (FAST_FLOAT)
  162967. (1.0 / (((double) qtbl->quantval[i] *
  162968. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162969. i++;
  162970. }
  162971. }
  162972. }
  162973. break;
  162974. #endif
  162975. default:
  162976. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162977. break;
  162978. }
  162979. }
  162980. }
  162981. /*
  162982. * Perform forward DCT on one or more blocks of a component.
  162983. *
  162984. * The input samples are taken from the sample_data[] array starting at
  162985. * position start_row/start_col, and moving to the right for any additional
  162986. * blocks. The quantized coefficients are returned in coef_blocks[].
  162987. */
  162988. METHODDEF(void)
  162989. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162990. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162991. JDIMENSION start_row, JDIMENSION start_col,
  162992. JDIMENSION num_blocks)
  162993. /* This version is used for integer DCT implementations. */
  162994. {
  162995. /* This routine is heavily used, so it's worth coding it tightly. */
  162996. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162997. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162998. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162999. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163000. JDIMENSION bi;
  163001. sample_data += start_row; /* fold in the vertical offset once */
  163002. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163003. /* Load data into workspace, applying unsigned->signed conversion */
  163004. { register DCTELEM *workspaceptr;
  163005. register JSAMPROW elemptr;
  163006. register int elemr;
  163007. workspaceptr = workspace;
  163008. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163009. elemptr = sample_data[elemr] + start_col;
  163010. #if DCTSIZE == 8 /* unroll the inner loop */
  163011. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163012. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163013. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163014. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163015. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163016. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163017. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163018. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163019. #else
  163020. { register int elemc;
  163021. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163022. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163023. }
  163024. }
  163025. #endif
  163026. }
  163027. }
  163028. /* Perform the DCT */
  163029. (*do_dct) (workspace);
  163030. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163031. { register DCTELEM temp, qval;
  163032. register int i;
  163033. register JCOEFPTR output_ptr = coef_blocks[bi];
  163034. for (i = 0; i < DCTSIZE2; i++) {
  163035. qval = divisors[i];
  163036. temp = workspace[i];
  163037. /* Divide the coefficient value by qval, ensuring proper rounding.
  163038. * Since C does not specify the direction of rounding for negative
  163039. * quotients, we have to force the dividend positive for portability.
  163040. *
  163041. * In most files, at least half of the output values will be zero
  163042. * (at default quantization settings, more like three-quarters...)
  163043. * so we should ensure that this case is fast. On many machines,
  163044. * a comparison is enough cheaper than a divide to make a special test
  163045. * a win. Since both inputs will be nonnegative, we need only test
  163046. * for a < b to discover whether a/b is 0.
  163047. * If your machine's division is fast enough, define FAST_DIVIDE.
  163048. */
  163049. #ifdef FAST_DIVIDE
  163050. #define DIVIDE_BY(a,b) a /= b
  163051. #else
  163052. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163053. #endif
  163054. if (temp < 0) {
  163055. temp = -temp;
  163056. temp += qval>>1; /* for rounding */
  163057. DIVIDE_BY(temp, qval);
  163058. temp = -temp;
  163059. } else {
  163060. temp += qval>>1; /* for rounding */
  163061. DIVIDE_BY(temp, qval);
  163062. }
  163063. output_ptr[i] = (JCOEF) temp;
  163064. }
  163065. }
  163066. }
  163067. }
  163068. #ifdef DCT_FLOAT_SUPPORTED
  163069. METHODDEF(void)
  163070. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163071. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163072. JDIMENSION start_row, JDIMENSION start_col,
  163073. JDIMENSION num_blocks)
  163074. /* This version is used for floating-point DCT implementations. */
  163075. {
  163076. /* This routine is heavily used, so it's worth coding it tightly. */
  163077. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163078. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163079. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163080. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163081. JDIMENSION bi;
  163082. sample_data += start_row; /* fold in the vertical offset once */
  163083. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163084. /* Load data into workspace, applying unsigned->signed conversion */
  163085. { register FAST_FLOAT *workspaceptr;
  163086. register JSAMPROW elemptr;
  163087. register int elemr;
  163088. workspaceptr = workspace;
  163089. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163090. elemptr = sample_data[elemr] + start_col;
  163091. #if DCTSIZE == 8 /* unroll the inner loop */
  163092. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163093. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163094. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163095. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163096. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163097. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163098. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163099. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163100. #else
  163101. { register int elemc;
  163102. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163103. *workspaceptr++ = (FAST_FLOAT)
  163104. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163105. }
  163106. }
  163107. #endif
  163108. }
  163109. }
  163110. /* Perform the DCT */
  163111. (*do_dct) (workspace);
  163112. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163113. { register FAST_FLOAT temp;
  163114. register int i;
  163115. register JCOEFPTR output_ptr = coef_blocks[bi];
  163116. for (i = 0; i < DCTSIZE2; i++) {
  163117. /* Apply the quantization and scaling factor */
  163118. temp = workspace[i] * divisors[i];
  163119. /* Round to nearest integer.
  163120. * Since C does not specify the direction of rounding for negative
  163121. * quotients, we have to force the dividend positive for portability.
  163122. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163123. * code should work for either 16-bit or 32-bit ints.
  163124. */
  163125. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163126. }
  163127. }
  163128. }
  163129. }
  163130. #endif /* DCT_FLOAT_SUPPORTED */
  163131. /*
  163132. * Initialize FDCT manager.
  163133. */
  163134. GLOBAL(void)
  163135. jinit_forward_dct (j_compress_ptr cinfo)
  163136. {
  163137. my_fdct_ptr fdct;
  163138. int i;
  163139. fdct = (my_fdct_ptr)
  163140. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163141. SIZEOF(my_fdct_controller));
  163142. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163143. fdct->pub.start_pass = start_pass_fdctmgr;
  163144. switch (cinfo->dct_method) {
  163145. #ifdef DCT_ISLOW_SUPPORTED
  163146. case JDCT_ISLOW:
  163147. fdct->pub.forward_DCT = forward_DCT;
  163148. fdct->do_dct = jpeg_fdct_islow;
  163149. break;
  163150. #endif
  163151. #ifdef DCT_IFAST_SUPPORTED
  163152. case JDCT_IFAST:
  163153. fdct->pub.forward_DCT = forward_DCT;
  163154. fdct->do_dct = jpeg_fdct_ifast;
  163155. break;
  163156. #endif
  163157. #ifdef DCT_FLOAT_SUPPORTED
  163158. case JDCT_FLOAT:
  163159. fdct->pub.forward_DCT = forward_DCT_float;
  163160. fdct->do_float_dct = jpeg_fdct_float;
  163161. break;
  163162. #endif
  163163. default:
  163164. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163165. break;
  163166. }
  163167. /* Mark divisor tables unallocated */
  163168. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163169. fdct->divisors[i] = NULL;
  163170. #ifdef DCT_FLOAT_SUPPORTED
  163171. fdct->float_divisors[i] = NULL;
  163172. #endif
  163173. }
  163174. }
  163175. /*** End of inlined file: jcdctmgr.c ***/
  163176. #undef CONST_BITS
  163177. /*** Start of inlined file: jchuff.c ***/
  163178. #define JPEG_INTERNALS
  163179. /*** Start of inlined file: jchuff.h ***/
  163180. /* The legal range of a DCT coefficient is
  163181. * -1024 .. +1023 for 8-bit data;
  163182. * -16384 .. +16383 for 12-bit data.
  163183. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163184. */
  163185. #ifndef _jchuff_h_
  163186. #define _jchuff_h_
  163187. #if BITS_IN_JSAMPLE == 8
  163188. #define MAX_COEF_BITS 10
  163189. #else
  163190. #define MAX_COEF_BITS 14
  163191. #endif
  163192. /* Derived data constructed for each Huffman table */
  163193. typedef struct {
  163194. unsigned int ehufco[256]; /* code for each symbol */
  163195. char ehufsi[256]; /* length of code for each symbol */
  163196. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163197. } c_derived_tbl;
  163198. /* Short forms of external names for systems with brain-damaged linkers. */
  163199. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163200. #define jpeg_make_c_derived_tbl jMkCDerived
  163201. #define jpeg_gen_optimal_table jGenOptTbl
  163202. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163203. /* Expand a Huffman table definition into the derived format */
  163204. EXTERN(void) jpeg_make_c_derived_tbl
  163205. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163206. c_derived_tbl ** pdtbl));
  163207. /* Generate an optimal table definition given the specified counts */
  163208. EXTERN(void) jpeg_gen_optimal_table
  163209. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163210. #endif
  163211. /*** End of inlined file: jchuff.h ***/
  163212. /* Declarations shared with jcphuff.c */
  163213. /* Expanded entropy encoder object for Huffman encoding.
  163214. *
  163215. * The savable_state subrecord contains fields that change within an MCU,
  163216. * but must not be updated permanently until we complete the MCU.
  163217. */
  163218. typedef struct {
  163219. INT32 put_buffer; /* current bit-accumulation buffer */
  163220. int put_bits; /* # of bits now in it */
  163221. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163222. } savable_state;
  163223. /* This macro is to work around compilers with missing or broken
  163224. * structure assignment. You'll need to fix this code if you have
  163225. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163226. */
  163227. #ifndef NO_STRUCT_ASSIGN
  163228. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163229. #else
  163230. #if MAX_COMPS_IN_SCAN == 4
  163231. #define ASSIGN_STATE(dest,src) \
  163232. ((dest).put_buffer = (src).put_buffer, \
  163233. (dest).put_bits = (src).put_bits, \
  163234. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163235. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163236. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163237. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163238. #endif
  163239. #endif
  163240. typedef struct {
  163241. struct jpeg_entropy_encoder pub; /* public fields */
  163242. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163243. /* These fields are NOT loaded into local working state. */
  163244. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163245. int next_restart_num; /* next restart number to write (0-7) */
  163246. /* Pointers to derived tables (these workspaces have image lifespan) */
  163247. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163248. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163249. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163250. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163251. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163252. #endif
  163253. } huff_entropy_encoder;
  163254. typedef huff_entropy_encoder * huff_entropy_ptr;
  163255. /* Working state while writing an MCU.
  163256. * This struct contains all the fields that are needed by subroutines.
  163257. */
  163258. typedef struct {
  163259. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163260. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163261. savable_state cur; /* Current bit buffer & DC state */
  163262. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163263. } working_state;
  163264. /* Forward declarations */
  163265. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163266. JBLOCKROW *MCU_data));
  163267. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163268. #ifdef ENTROPY_OPT_SUPPORTED
  163269. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163270. JBLOCKROW *MCU_data));
  163271. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163272. #endif
  163273. /*
  163274. * Initialize for a Huffman-compressed scan.
  163275. * If gather_statistics is TRUE, we do not output anything during the scan,
  163276. * just count the Huffman symbols used and generate Huffman code tables.
  163277. */
  163278. METHODDEF(void)
  163279. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163280. {
  163281. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163282. int ci, dctbl, actbl;
  163283. jpeg_component_info * compptr;
  163284. if (gather_statistics) {
  163285. #ifdef ENTROPY_OPT_SUPPORTED
  163286. entropy->pub.encode_mcu = encode_mcu_gather;
  163287. entropy->pub.finish_pass = finish_pass_gather;
  163288. #else
  163289. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163290. #endif
  163291. } else {
  163292. entropy->pub.encode_mcu = encode_mcu_huff;
  163293. entropy->pub.finish_pass = finish_pass_huff;
  163294. }
  163295. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163296. compptr = cinfo->cur_comp_info[ci];
  163297. dctbl = compptr->dc_tbl_no;
  163298. actbl = compptr->ac_tbl_no;
  163299. if (gather_statistics) {
  163300. #ifdef ENTROPY_OPT_SUPPORTED
  163301. /* Check for invalid table indexes */
  163302. /* (make_c_derived_tbl does this in the other path) */
  163303. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163304. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163305. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163306. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163307. /* Allocate and zero the statistics tables */
  163308. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163309. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163310. entropy->dc_count_ptrs[dctbl] = (long *)
  163311. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163312. 257 * SIZEOF(long));
  163313. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163314. if (entropy->ac_count_ptrs[actbl] == NULL)
  163315. entropy->ac_count_ptrs[actbl] = (long *)
  163316. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163317. 257 * SIZEOF(long));
  163318. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163319. #endif
  163320. } else {
  163321. /* Compute derived values for Huffman tables */
  163322. /* We may do this more than once for a table, but it's not expensive */
  163323. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163324. & entropy->dc_derived_tbls[dctbl]);
  163325. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163326. & entropy->ac_derived_tbls[actbl]);
  163327. }
  163328. /* Initialize DC predictions to 0 */
  163329. entropy->saved.last_dc_val[ci] = 0;
  163330. }
  163331. /* Initialize bit buffer to empty */
  163332. entropy->saved.put_buffer = 0;
  163333. entropy->saved.put_bits = 0;
  163334. /* Initialize restart stuff */
  163335. entropy->restarts_to_go = cinfo->restart_interval;
  163336. entropy->next_restart_num = 0;
  163337. }
  163338. /*
  163339. * Compute the derived values for a Huffman table.
  163340. * This routine also performs some validation checks on the table.
  163341. *
  163342. * Note this is also used by jcphuff.c.
  163343. */
  163344. GLOBAL(void)
  163345. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163346. c_derived_tbl ** pdtbl)
  163347. {
  163348. JHUFF_TBL *htbl;
  163349. c_derived_tbl *dtbl;
  163350. int p, i, l, lastp, si, maxsymbol;
  163351. char huffsize[257];
  163352. unsigned int huffcode[257];
  163353. unsigned int code;
  163354. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163355. * paralleling the order of the symbols themselves in htbl->huffval[].
  163356. */
  163357. /* Find the input Huffman table */
  163358. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163359. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163360. htbl =
  163361. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163362. if (htbl == NULL)
  163363. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163364. /* Allocate a workspace if we haven't already done so. */
  163365. if (*pdtbl == NULL)
  163366. *pdtbl = (c_derived_tbl *)
  163367. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163368. SIZEOF(c_derived_tbl));
  163369. dtbl = *pdtbl;
  163370. /* Figure C.1: make table of Huffman code length for each symbol */
  163371. p = 0;
  163372. for (l = 1; l <= 16; l++) {
  163373. i = (int) htbl->bits[l];
  163374. if (i < 0 || p + i > 256) /* protect against table overrun */
  163375. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163376. while (i--)
  163377. huffsize[p++] = (char) l;
  163378. }
  163379. huffsize[p] = 0;
  163380. lastp = p;
  163381. /* Figure C.2: generate the codes themselves */
  163382. /* We also validate that the counts represent a legal Huffman code tree. */
  163383. code = 0;
  163384. si = huffsize[0];
  163385. p = 0;
  163386. while (huffsize[p]) {
  163387. while (((int) huffsize[p]) == si) {
  163388. huffcode[p++] = code;
  163389. code++;
  163390. }
  163391. /* code is now 1 more than the last code used for codelength si; but
  163392. * it must still fit in si bits, since no code is allowed to be all ones.
  163393. */
  163394. if (((INT32) code) >= (((INT32) 1) << si))
  163395. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163396. code <<= 1;
  163397. si++;
  163398. }
  163399. /* Figure C.3: generate encoding tables */
  163400. /* These are code and size indexed by symbol value */
  163401. /* Set all codeless symbols to have code length 0;
  163402. * this lets us detect duplicate VAL entries here, and later
  163403. * allows emit_bits to detect any attempt to emit such symbols.
  163404. */
  163405. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163406. /* This is also a convenient place to check for out-of-range
  163407. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163408. * but only 0..15 for DC. (We could constrain them further
  163409. * based on data depth and mode, but this seems enough.)
  163410. */
  163411. maxsymbol = isDC ? 15 : 255;
  163412. for (p = 0; p < lastp; p++) {
  163413. i = htbl->huffval[p];
  163414. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163415. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163416. dtbl->ehufco[i] = huffcode[p];
  163417. dtbl->ehufsi[i] = huffsize[p];
  163418. }
  163419. }
  163420. /* Outputting bytes to the file */
  163421. /* Emit a byte, taking 'action' if must suspend. */
  163422. #define emit_byte(state,val,action) \
  163423. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163424. if (--(state)->free_in_buffer == 0) \
  163425. if (! dump_buffer(state)) \
  163426. { action; } }
  163427. LOCAL(boolean)
  163428. dump_buffer (working_state * state)
  163429. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163430. {
  163431. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163432. if (! (*dest->empty_output_buffer) (state->cinfo))
  163433. return FALSE;
  163434. /* After a successful buffer dump, must reset buffer pointers */
  163435. state->next_output_byte = dest->next_output_byte;
  163436. state->free_in_buffer = dest->free_in_buffer;
  163437. return TRUE;
  163438. }
  163439. /* Outputting bits to the file */
  163440. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163441. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163442. * in one call, and we never retain more than 7 bits in put_buffer
  163443. * between calls, so 24 bits are sufficient.
  163444. */
  163445. INLINE
  163446. LOCAL(boolean)
  163447. emit_bits (working_state * state, unsigned int code, int size)
  163448. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163449. {
  163450. /* This routine is heavily used, so it's worth coding tightly. */
  163451. register INT32 put_buffer = (INT32) code;
  163452. register int put_bits = state->cur.put_bits;
  163453. /* if size is 0, caller used an invalid Huffman table entry */
  163454. if (size == 0)
  163455. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163456. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163457. put_bits += size; /* new number of bits in buffer */
  163458. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163459. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163460. while (put_bits >= 8) {
  163461. int c = (int) ((put_buffer >> 16) & 0xFF);
  163462. emit_byte(state, c, return FALSE);
  163463. if (c == 0xFF) { /* need to stuff a zero byte? */
  163464. emit_byte(state, 0, return FALSE);
  163465. }
  163466. put_buffer <<= 8;
  163467. put_bits -= 8;
  163468. }
  163469. state->cur.put_buffer = put_buffer; /* update state variables */
  163470. state->cur.put_bits = put_bits;
  163471. return TRUE;
  163472. }
  163473. LOCAL(boolean)
  163474. flush_bits (working_state * state)
  163475. {
  163476. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163477. return FALSE;
  163478. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163479. state->cur.put_bits = 0;
  163480. return TRUE;
  163481. }
  163482. /* Encode a single block's worth of coefficients */
  163483. LOCAL(boolean)
  163484. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163485. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163486. {
  163487. register int temp, temp2;
  163488. register int nbits;
  163489. register int k, r, i;
  163490. /* Encode the DC coefficient difference per section F.1.2.1 */
  163491. temp = temp2 = block[0] - last_dc_val;
  163492. if (temp < 0) {
  163493. temp = -temp; /* temp is abs value of input */
  163494. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163495. /* This code assumes we are on a two's complement machine */
  163496. temp2--;
  163497. }
  163498. /* Find the number of bits needed for the magnitude of the coefficient */
  163499. nbits = 0;
  163500. while (temp) {
  163501. nbits++;
  163502. temp >>= 1;
  163503. }
  163504. /* Check for out-of-range coefficient values.
  163505. * Since we're encoding a difference, the range limit is twice as much.
  163506. */
  163507. if (nbits > MAX_COEF_BITS+1)
  163508. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163509. /* Emit the Huffman-coded symbol for the number of bits */
  163510. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163511. return FALSE;
  163512. /* Emit that number of bits of the value, if positive, */
  163513. /* or the complement of its magnitude, if negative. */
  163514. if (nbits) /* emit_bits rejects calls with size 0 */
  163515. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163516. return FALSE;
  163517. /* Encode the AC coefficients per section F.1.2.2 */
  163518. r = 0; /* r = run length of zeros */
  163519. for (k = 1; k < DCTSIZE2; k++) {
  163520. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163521. r++;
  163522. } else {
  163523. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163524. while (r > 15) {
  163525. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163526. return FALSE;
  163527. r -= 16;
  163528. }
  163529. temp2 = temp;
  163530. if (temp < 0) {
  163531. temp = -temp; /* temp is abs value of input */
  163532. /* This code assumes we are on a two's complement machine */
  163533. temp2--;
  163534. }
  163535. /* Find the number of bits needed for the magnitude of the coefficient */
  163536. nbits = 1; /* there must be at least one 1 bit */
  163537. while ((temp >>= 1))
  163538. nbits++;
  163539. /* Check for out-of-range coefficient values */
  163540. if (nbits > MAX_COEF_BITS)
  163541. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163542. /* Emit Huffman symbol for run length / number of bits */
  163543. i = (r << 4) + nbits;
  163544. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163545. return FALSE;
  163546. /* Emit that number of bits of the value, if positive, */
  163547. /* or the complement of its magnitude, if negative. */
  163548. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163549. return FALSE;
  163550. r = 0;
  163551. }
  163552. }
  163553. /* If the last coef(s) were zero, emit an end-of-block code */
  163554. if (r > 0)
  163555. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163556. return FALSE;
  163557. return TRUE;
  163558. }
  163559. /*
  163560. * Emit a restart marker & resynchronize predictions.
  163561. */
  163562. LOCAL(boolean)
  163563. emit_restart (working_state * state, int restart_num)
  163564. {
  163565. int ci;
  163566. if (! flush_bits(state))
  163567. return FALSE;
  163568. emit_byte(state, 0xFF, return FALSE);
  163569. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163570. /* Re-initialize DC predictions to 0 */
  163571. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163572. state->cur.last_dc_val[ci] = 0;
  163573. /* The restart counter is not updated until we successfully write the MCU. */
  163574. return TRUE;
  163575. }
  163576. /*
  163577. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163578. */
  163579. METHODDEF(boolean)
  163580. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163581. {
  163582. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163583. working_state state;
  163584. int blkn, ci;
  163585. jpeg_component_info * compptr;
  163586. /* Load up working state */
  163587. state.next_output_byte = cinfo->dest->next_output_byte;
  163588. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163589. ASSIGN_STATE(state.cur, entropy->saved);
  163590. state.cinfo = cinfo;
  163591. /* Emit restart marker if needed */
  163592. if (cinfo->restart_interval) {
  163593. if (entropy->restarts_to_go == 0)
  163594. if (! emit_restart(&state, entropy->next_restart_num))
  163595. return FALSE;
  163596. }
  163597. /* Encode the MCU data blocks */
  163598. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163599. ci = cinfo->MCU_membership[blkn];
  163600. compptr = cinfo->cur_comp_info[ci];
  163601. if (! encode_one_block(&state,
  163602. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163603. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163604. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163605. return FALSE;
  163606. /* Update last_dc_val */
  163607. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163608. }
  163609. /* Completed MCU, so update state */
  163610. cinfo->dest->next_output_byte = state.next_output_byte;
  163611. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163612. ASSIGN_STATE(entropy->saved, state.cur);
  163613. /* Update restart-interval state too */
  163614. if (cinfo->restart_interval) {
  163615. if (entropy->restarts_to_go == 0) {
  163616. entropy->restarts_to_go = cinfo->restart_interval;
  163617. entropy->next_restart_num++;
  163618. entropy->next_restart_num &= 7;
  163619. }
  163620. entropy->restarts_to_go--;
  163621. }
  163622. return TRUE;
  163623. }
  163624. /*
  163625. * Finish up at the end of a Huffman-compressed scan.
  163626. */
  163627. METHODDEF(void)
  163628. finish_pass_huff (j_compress_ptr cinfo)
  163629. {
  163630. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163631. working_state state;
  163632. /* Load up working state ... flush_bits needs it */
  163633. state.next_output_byte = cinfo->dest->next_output_byte;
  163634. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163635. ASSIGN_STATE(state.cur, entropy->saved);
  163636. state.cinfo = cinfo;
  163637. /* Flush out the last data */
  163638. if (! flush_bits(&state))
  163639. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163640. /* Update state */
  163641. cinfo->dest->next_output_byte = state.next_output_byte;
  163642. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163643. ASSIGN_STATE(entropy->saved, state.cur);
  163644. }
  163645. /*
  163646. * Huffman coding optimization.
  163647. *
  163648. * We first scan the supplied data and count the number of uses of each symbol
  163649. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163650. * Then we build a Huffman coding tree for the observed counts.
  163651. * Symbols which are not needed at all for the particular image are not
  163652. * assigned any code, which saves space in the DHT marker as well as in
  163653. * the compressed data.
  163654. */
  163655. #ifdef ENTROPY_OPT_SUPPORTED
  163656. /* Process a single block's worth of coefficients */
  163657. LOCAL(void)
  163658. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163659. long dc_counts[], long ac_counts[])
  163660. {
  163661. register int temp;
  163662. register int nbits;
  163663. register int k, r;
  163664. /* Encode the DC coefficient difference per section F.1.2.1 */
  163665. temp = block[0] - last_dc_val;
  163666. if (temp < 0)
  163667. temp = -temp;
  163668. /* Find the number of bits needed for the magnitude of the coefficient */
  163669. nbits = 0;
  163670. while (temp) {
  163671. nbits++;
  163672. temp >>= 1;
  163673. }
  163674. /* Check for out-of-range coefficient values.
  163675. * Since we're encoding a difference, the range limit is twice as much.
  163676. */
  163677. if (nbits > MAX_COEF_BITS+1)
  163678. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163679. /* Count the Huffman symbol for the number of bits */
  163680. dc_counts[nbits]++;
  163681. /* Encode the AC coefficients per section F.1.2.2 */
  163682. r = 0; /* r = run length of zeros */
  163683. for (k = 1; k < DCTSIZE2; k++) {
  163684. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163685. r++;
  163686. } else {
  163687. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163688. while (r > 15) {
  163689. ac_counts[0xF0]++;
  163690. r -= 16;
  163691. }
  163692. /* Find the number of bits needed for the magnitude of the coefficient */
  163693. if (temp < 0)
  163694. temp = -temp;
  163695. /* Find the number of bits needed for the magnitude of the coefficient */
  163696. nbits = 1; /* there must be at least one 1 bit */
  163697. while ((temp >>= 1))
  163698. nbits++;
  163699. /* Check for out-of-range coefficient values */
  163700. if (nbits > MAX_COEF_BITS)
  163701. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163702. /* Count Huffman symbol for run length / number of bits */
  163703. ac_counts[(r << 4) + nbits]++;
  163704. r = 0;
  163705. }
  163706. }
  163707. /* If the last coef(s) were zero, emit an end-of-block code */
  163708. if (r > 0)
  163709. ac_counts[0]++;
  163710. }
  163711. /*
  163712. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163713. * No data is actually output, so no suspension return is possible.
  163714. */
  163715. METHODDEF(boolean)
  163716. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163717. {
  163718. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163719. int blkn, ci;
  163720. jpeg_component_info * compptr;
  163721. /* Take care of restart intervals if needed */
  163722. if (cinfo->restart_interval) {
  163723. if (entropy->restarts_to_go == 0) {
  163724. /* Re-initialize DC predictions to 0 */
  163725. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163726. entropy->saved.last_dc_val[ci] = 0;
  163727. /* Update restart state */
  163728. entropy->restarts_to_go = cinfo->restart_interval;
  163729. }
  163730. entropy->restarts_to_go--;
  163731. }
  163732. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163733. ci = cinfo->MCU_membership[blkn];
  163734. compptr = cinfo->cur_comp_info[ci];
  163735. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163736. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163737. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163738. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163739. }
  163740. return TRUE;
  163741. }
  163742. /*
  163743. * Generate the best Huffman code table for the given counts, fill htbl.
  163744. * Note this is also used by jcphuff.c.
  163745. *
  163746. * The JPEG standard requires that no symbol be assigned a codeword of all
  163747. * one bits (so that padding bits added at the end of a compressed segment
  163748. * can't look like a valid code). Because of the canonical ordering of
  163749. * codewords, this just means that there must be an unused slot in the
  163750. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163751. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163752. * with count 1. In theory that's not optimal; giving it count zero but
  163753. * including it in the symbol set anyway should give a better Huffman code.
  163754. * But the theoretically better code actually seems to come out worse in
  163755. * practice, because it produces more all-ones bytes (which incur stuffed
  163756. * zero bytes in the final file). In any case the difference is tiny.
  163757. *
  163758. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163759. * If some symbols have a very small but nonzero probability, the Huffman tree
  163760. * must be adjusted to meet the code length restriction. We currently use
  163761. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163762. * optimal; it may not choose the best possible limited-length code. But
  163763. * typically only very-low-frequency symbols will be given less-than-optimal
  163764. * lengths, so the code is almost optimal. Experimental comparisons against
  163765. * an optimal limited-length-code algorithm indicate that the difference is
  163766. * microscopic --- usually less than a hundredth of a percent of total size.
  163767. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163768. */
  163769. GLOBAL(void)
  163770. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163771. {
  163772. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163773. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163774. int codesize[257]; /* codesize[k] = code length of symbol k */
  163775. int others[257]; /* next symbol in current branch of tree */
  163776. int c1, c2;
  163777. int p, i, j;
  163778. long v;
  163779. /* This algorithm is explained in section K.2 of the JPEG standard */
  163780. MEMZERO(bits, SIZEOF(bits));
  163781. MEMZERO(codesize, SIZEOF(codesize));
  163782. for (i = 0; i < 257; i++)
  163783. others[i] = -1; /* init links to empty */
  163784. freq[256] = 1; /* make sure 256 has a nonzero count */
  163785. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163786. * that no real symbol is given code-value of all ones, because 256
  163787. * will be placed last in the largest codeword category.
  163788. */
  163789. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163790. for (;;) {
  163791. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163792. /* In case of ties, take the larger symbol number */
  163793. c1 = -1;
  163794. v = 1000000000L;
  163795. for (i = 0; i <= 256; i++) {
  163796. if (freq[i] && freq[i] <= v) {
  163797. v = freq[i];
  163798. c1 = i;
  163799. }
  163800. }
  163801. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163802. /* In case of ties, take the larger symbol number */
  163803. c2 = -1;
  163804. v = 1000000000L;
  163805. for (i = 0; i <= 256; i++) {
  163806. if (freq[i] && freq[i] <= v && i != c1) {
  163807. v = freq[i];
  163808. c2 = i;
  163809. }
  163810. }
  163811. /* Done if we've merged everything into one frequency */
  163812. if (c2 < 0)
  163813. break;
  163814. /* Else merge the two counts/trees */
  163815. freq[c1] += freq[c2];
  163816. freq[c2] = 0;
  163817. /* Increment the codesize of everything in c1's tree branch */
  163818. codesize[c1]++;
  163819. while (others[c1] >= 0) {
  163820. c1 = others[c1];
  163821. codesize[c1]++;
  163822. }
  163823. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163824. /* Increment the codesize of everything in c2's tree branch */
  163825. codesize[c2]++;
  163826. while (others[c2] >= 0) {
  163827. c2 = others[c2];
  163828. codesize[c2]++;
  163829. }
  163830. }
  163831. /* Now count the number of symbols of each code length */
  163832. for (i = 0; i <= 256; i++) {
  163833. if (codesize[i]) {
  163834. /* The JPEG standard seems to think that this can't happen, */
  163835. /* but I'm paranoid... */
  163836. if (codesize[i] > MAX_CLEN)
  163837. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163838. bits[codesize[i]]++;
  163839. }
  163840. }
  163841. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163842. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163843. * Here is what the JPEG spec says about how this next bit works:
  163844. * Since symbols are paired for the longest Huffman code, the symbols are
  163845. * removed from this length category two at a time. The prefix for the pair
  163846. * (which is one bit shorter) is allocated to one of the pair; then,
  163847. * skipping the BITS entry for that prefix length, a code word from the next
  163848. * shortest nonzero BITS entry is converted into a prefix for two code words
  163849. * one bit longer.
  163850. */
  163851. for (i = MAX_CLEN; i > 16; i--) {
  163852. while (bits[i] > 0) {
  163853. j = i - 2; /* find length of new prefix to be used */
  163854. while (bits[j] == 0)
  163855. j--;
  163856. bits[i] -= 2; /* remove two symbols */
  163857. bits[i-1]++; /* one goes in this length */
  163858. bits[j+1] += 2; /* two new symbols in this length */
  163859. bits[j]--; /* symbol of this length is now a prefix */
  163860. }
  163861. }
  163862. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163863. while (bits[i] == 0) /* find largest codelength still in use */
  163864. i--;
  163865. bits[i]--;
  163866. /* Return final symbol counts (only for lengths 0..16) */
  163867. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163868. /* Return a list of the symbols sorted by code length */
  163869. /* It's not real clear to me why we don't need to consider the codelength
  163870. * changes made above, but the JPEG spec seems to think this works.
  163871. */
  163872. p = 0;
  163873. for (i = 1; i <= MAX_CLEN; i++) {
  163874. for (j = 0; j <= 255; j++) {
  163875. if (codesize[j] == i) {
  163876. htbl->huffval[p] = (UINT8) j;
  163877. p++;
  163878. }
  163879. }
  163880. }
  163881. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163882. htbl->sent_table = FALSE;
  163883. }
  163884. /*
  163885. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163886. */
  163887. METHODDEF(void)
  163888. finish_pass_gather (j_compress_ptr cinfo)
  163889. {
  163890. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163891. int ci, dctbl, actbl;
  163892. jpeg_component_info * compptr;
  163893. JHUFF_TBL **htblptr;
  163894. boolean did_dc[NUM_HUFF_TBLS];
  163895. boolean did_ac[NUM_HUFF_TBLS];
  163896. /* It's important not to apply jpeg_gen_optimal_table more than once
  163897. * per table, because it clobbers the input frequency counts!
  163898. */
  163899. MEMZERO(did_dc, SIZEOF(did_dc));
  163900. MEMZERO(did_ac, SIZEOF(did_ac));
  163901. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163902. compptr = cinfo->cur_comp_info[ci];
  163903. dctbl = compptr->dc_tbl_no;
  163904. actbl = compptr->ac_tbl_no;
  163905. if (! did_dc[dctbl]) {
  163906. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163907. if (*htblptr == NULL)
  163908. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163909. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163910. did_dc[dctbl] = TRUE;
  163911. }
  163912. if (! did_ac[actbl]) {
  163913. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163914. if (*htblptr == NULL)
  163915. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163916. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163917. did_ac[actbl] = TRUE;
  163918. }
  163919. }
  163920. }
  163921. #endif /* ENTROPY_OPT_SUPPORTED */
  163922. /*
  163923. * Module initialization routine for Huffman entropy encoding.
  163924. */
  163925. GLOBAL(void)
  163926. jinit_huff_encoder (j_compress_ptr cinfo)
  163927. {
  163928. huff_entropy_ptr entropy;
  163929. int i;
  163930. entropy = (huff_entropy_ptr)
  163931. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163932. SIZEOF(huff_entropy_encoder));
  163933. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163934. entropy->pub.start_pass = start_pass_huff;
  163935. /* Mark tables unallocated */
  163936. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163937. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163938. #ifdef ENTROPY_OPT_SUPPORTED
  163939. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163940. #endif
  163941. }
  163942. }
  163943. /*** End of inlined file: jchuff.c ***/
  163944. #undef emit_byte
  163945. /*** Start of inlined file: jcinit.c ***/
  163946. #define JPEG_INTERNALS
  163947. /*
  163948. * Master selection of compression modules.
  163949. * This is done once at the start of processing an image. We determine
  163950. * which modules will be used and give them appropriate initialization calls.
  163951. */
  163952. GLOBAL(void)
  163953. jinit_compress_master (j_compress_ptr cinfo)
  163954. {
  163955. /* Initialize master control (includes parameter checking/processing) */
  163956. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163957. /* Preprocessing */
  163958. if (! cinfo->raw_data_in) {
  163959. jinit_color_converter(cinfo);
  163960. jinit_downsampler(cinfo);
  163961. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163962. }
  163963. /* Forward DCT */
  163964. jinit_forward_dct(cinfo);
  163965. /* Entropy encoding: either Huffman or arithmetic coding. */
  163966. if (cinfo->arith_code) {
  163967. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163968. } else {
  163969. if (cinfo->progressive_mode) {
  163970. #ifdef C_PROGRESSIVE_SUPPORTED
  163971. jinit_phuff_encoder(cinfo);
  163972. #else
  163973. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163974. #endif
  163975. } else
  163976. jinit_huff_encoder(cinfo);
  163977. }
  163978. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163979. jinit_c_coef_controller(cinfo,
  163980. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163981. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163982. jinit_marker_writer(cinfo);
  163983. /* We can now tell the memory manager to allocate virtual arrays. */
  163984. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163985. /* Write the datastream header (SOI) immediately.
  163986. * Frame and scan headers are postponed till later.
  163987. * This lets application insert special markers after the SOI.
  163988. */
  163989. (*cinfo->marker->write_file_header) (cinfo);
  163990. }
  163991. /*** End of inlined file: jcinit.c ***/
  163992. /*** Start of inlined file: jcmainct.c ***/
  163993. #define JPEG_INTERNALS
  163994. /* Note: currently, there is no operating mode in which a full-image buffer
  163995. * is needed at this step. If there were, that mode could not be used with
  163996. * "raw data" input, since this module is bypassed in that case. However,
  163997. * we've left the code here for possible use in special applications.
  163998. */
  163999. #undef FULL_MAIN_BUFFER_SUPPORTED
  164000. /* Private buffer controller object */
  164001. typedef struct {
  164002. struct jpeg_c_main_controller pub; /* public fields */
  164003. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164004. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164005. boolean suspended; /* remember if we suspended output */
  164006. J_BUF_MODE pass_mode; /* current operating mode */
  164007. /* If using just a strip buffer, this points to the entire set of buffers
  164008. * (we allocate one for each component). In the full-image case, this
  164009. * points to the currently accessible strips of the virtual arrays.
  164010. */
  164011. JSAMPARRAY buffer[MAX_COMPONENTS];
  164012. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164013. /* If using full-image storage, this array holds pointers to virtual-array
  164014. * control blocks for each component. Unused if not full-image storage.
  164015. */
  164016. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164017. #endif
  164018. } my_main_controller;
  164019. typedef my_main_controller * my_main_ptr;
  164020. /* Forward declarations */
  164021. METHODDEF(void) process_data_simple_main
  164022. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164023. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164024. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164025. METHODDEF(void) process_data_buffer_main
  164026. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164027. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164028. #endif
  164029. /*
  164030. * Initialize for a processing pass.
  164031. */
  164032. METHODDEF(void)
  164033. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164034. {
  164035. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164036. /* Do nothing in raw-data mode. */
  164037. if (cinfo->raw_data_in)
  164038. return;
  164039. main_->cur_iMCU_row = 0; /* initialize counters */
  164040. main_->rowgroup_ctr = 0;
  164041. main_->suspended = FALSE;
  164042. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164043. switch (pass_mode) {
  164044. case JBUF_PASS_THRU:
  164045. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164046. if (main_->whole_image[0] != NULL)
  164047. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164048. #endif
  164049. main_->pub.process_data = process_data_simple_main;
  164050. break;
  164051. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164052. case JBUF_SAVE_SOURCE:
  164053. case JBUF_CRANK_DEST:
  164054. case JBUF_SAVE_AND_PASS:
  164055. if (main_->whole_image[0] == NULL)
  164056. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164057. main_->pub.process_data = process_data_buffer_main;
  164058. break;
  164059. #endif
  164060. default:
  164061. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164062. break;
  164063. }
  164064. }
  164065. /*
  164066. * Process some data.
  164067. * This routine handles the simple pass-through mode,
  164068. * where we have only a strip buffer.
  164069. */
  164070. METHODDEF(void)
  164071. process_data_simple_main (j_compress_ptr cinfo,
  164072. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164073. JDIMENSION in_rows_avail)
  164074. {
  164075. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164076. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164077. /* Read input data if we haven't filled the main buffer yet */
  164078. if (main_->rowgroup_ctr < DCTSIZE)
  164079. (*cinfo->prep->pre_process_data) (cinfo,
  164080. input_buf, in_row_ctr, in_rows_avail,
  164081. main_->buffer, &main_->rowgroup_ctr,
  164082. (JDIMENSION) DCTSIZE);
  164083. /* If we don't have a full iMCU row buffered, return to application for
  164084. * more data. Note that preprocessor will always pad to fill the iMCU row
  164085. * at the bottom of the image.
  164086. */
  164087. if (main_->rowgroup_ctr != DCTSIZE)
  164088. return;
  164089. /* Send the completed row to the compressor */
  164090. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164091. /* If compressor did not consume the whole row, then we must need to
  164092. * suspend processing and return to the application. In this situation
  164093. * we pretend we didn't yet consume the last input row; otherwise, if
  164094. * it happened to be the last row of the image, the application would
  164095. * think we were done.
  164096. */
  164097. if (! main_->suspended) {
  164098. (*in_row_ctr)--;
  164099. main_->suspended = TRUE;
  164100. }
  164101. return;
  164102. }
  164103. /* We did finish the row. Undo our little suspension hack if a previous
  164104. * call suspended; then mark the main buffer empty.
  164105. */
  164106. if (main_->suspended) {
  164107. (*in_row_ctr)++;
  164108. main_->suspended = FALSE;
  164109. }
  164110. main_->rowgroup_ctr = 0;
  164111. main_->cur_iMCU_row++;
  164112. }
  164113. }
  164114. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164115. /*
  164116. * Process some data.
  164117. * This routine handles all of the modes that use a full-size buffer.
  164118. */
  164119. METHODDEF(void)
  164120. process_data_buffer_main (j_compress_ptr cinfo,
  164121. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164122. JDIMENSION in_rows_avail)
  164123. {
  164124. my_main_ptr main = (my_main_ptr) cinfo->main;
  164125. int ci;
  164126. jpeg_component_info *compptr;
  164127. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164128. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164129. /* Realign the virtual buffers if at the start of an iMCU row. */
  164130. if (main->rowgroup_ctr == 0) {
  164131. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164132. ci++, compptr++) {
  164133. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164134. ((j_common_ptr) cinfo, main->whole_image[ci],
  164135. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164136. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164137. }
  164138. /* In a read pass, pretend we just read some source data. */
  164139. if (! writing) {
  164140. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164141. main->rowgroup_ctr = DCTSIZE;
  164142. }
  164143. }
  164144. /* If a write pass, read input data until the current iMCU row is full. */
  164145. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164146. if (writing) {
  164147. (*cinfo->prep->pre_process_data) (cinfo,
  164148. input_buf, in_row_ctr, in_rows_avail,
  164149. main->buffer, &main->rowgroup_ctr,
  164150. (JDIMENSION) DCTSIZE);
  164151. /* Return to application if we need more data to fill the iMCU row. */
  164152. if (main->rowgroup_ctr < DCTSIZE)
  164153. return;
  164154. }
  164155. /* Emit data, unless this is a sink-only pass. */
  164156. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164157. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164158. /* If compressor did not consume the whole row, then we must need to
  164159. * suspend processing and return to the application. In this situation
  164160. * we pretend we didn't yet consume the last input row; otherwise, if
  164161. * it happened to be the last row of the image, the application would
  164162. * think we were done.
  164163. */
  164164. if (! main->suspended) {
  164165. (*in_row_ctr)--;
  164166. main->suspended = TRUE;
  164167. }
  164168. return;
  164169. }
  164170. /* We did finish the row. Undo our little suspension hack if a previous
  164171. * call suspended; then mark the main buffer empty.
  164172. */
  164173. if (main->suspended) {
  164174. (*in_row_ctr)++;
  164175. main->suspended = FALSE;
  164176. }
  164177. }
  164178. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164179. main->rowgroup_ctr = 0;
  164180. main->cur_iMCU_row++;
  164181. }
  164182. }
  164183. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164184. /*
  164185. * Initialize main buffer controller.
  164186. */
  164187. GLOBAL(void)
  164188. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164189. {
  164190. my_main_ptr main_;
  164191. int ci;
  164192. jpeg_component_info *compptr;
  164193. main_ = (my_main_ptr)
  164194. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164195. SIZEOF(my_main_controller));
  164196. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164197. main_->pub.start_pass = start_pass_main;
  164198. /* We don't need to create a buffer in raw-data mode. */
  164199. if (cinfo->raw_data_in)
  164200. return;
  164201. /* Create the buffer. It holds downsampled data, so each component
  164202. * may be of a different size.
  164203. */
  164204. if (need_full_buffer) {
  164205. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164206. /* Allocate a full-image virtual array for each component */
  164207. /* Note we pad the bottom to a multiple of the iMCU height */
  164208. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164209. ci++, compptr++) {
  164210. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164211. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164212. compptr->width_in_blocks * DCTSIZE,
  164213. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164214. (long) compptr->v_samp_factor) * DCTSIZE,
  164215. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164216. }
  164217. #else
  164218. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164219. #endif
  164220. } else {
  164221. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164222. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164223. #endif
  164224. /* Allocate a strip buffer for each component */
  164225. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164226. ci++, compptr++) {
  164227. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164228. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164229. compptr->width_in_blocks * DCTSIZE,
  164230. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164231. }
  164232. }
  164233. }
  164234. /*** End of inlined file: jcmainct.c ***/
  164235. /*** Start of inlined file: jcmarker.c ***/
  164236. #define JPEG_INTERNALS
  164237. /* Private state */
  164238. typedef struct {
  164239. struct jpeg_marker_writer pub; /* public fields */
  164240. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164241. } my_marker_writer;
  164242. typedef my_marker_writer * my_marker_ptr;
  164243. /*
  164244. * Basic output routines.
  164245. *
  164246. * Note that we do not support suspension while writing a marker.
  164247. * Therefore, an application using suspension must ensure that there is
  164248. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164249. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164250. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164251. * modes are not supported at all with suspension, so those two are the only
  164252. * points where markers will be written.
  164253. */
  164254. LOCAL(void)
  164255. emit_byte (j_compress_ptr cinfo, int val)
  164256. /* Emit a byte */
  164257. {
  164258. struct jpeg_destination_mgr * dest = cinfo->dest;
  164259. *(dest->next_output_byte)++ = (JOCTET) val;
  164260. if (--dest->free_in_buffer == 0) {
  164261. if (! (*dest->empty_output_buffer) (cinfo))
  164262. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164263. }
  164264. }
  164265. LOCAL(void)
  164266. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164267. /* Emit a marker code */
  164268. {
  164269. emit_byte(cinfo, 0xFF);
  164270. emit_byte(cinfo, (int) mark);
  164271. }
  164272. LOCAL(void)
  164273. emit_2bytes (j_compress_ptr cinfo, int value)
  164274. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164275. {
  164276. emit_byte(cinfo, (value >> 8) & 0xFF);
  164277. emit_byte(cinfo, value & 0xFF);
  164278. }
  164279. /*
  164280. * Routines to write specific marker types.
  164281. */
  164282. LOCAL(int)
  164283. emit_dqt (j_compress_ptr cinfo, int index)
  164284. /* Emit a DQT marker */
  164285. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164286. {
  164287. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164288. int prec;
  164289. int i;
  164290. if (qtbl == NULL)
  164291. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164292. prec = 0;
  164293. for (i = 0; i < DCTSIZE2; i++) {
  164294. if (qtbl->quantval[i] > 255)
  164295. prec = 1;
  164296. }
  164297. if (! qtbl->sent_table) {
  164298. emit_marker(cinfo, M_DQT);
  164299. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164300. emit_byte(cinfo, index + (prec<<4));
  164301. for (i = 0; i < DCTSIZE2; i++) {
  164302. /* The table entries must be emitted in zigzag order. */
  164303. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164304. if (prec)
  164305. emit_byte(cinfo, (int) (qval >> 8));
  164306. emit_byte(cinfo, (int) (qval & 0xFF));
  164307. }
  164308. qtbl->sent_table = TRUE;
  164309. }
  164310. return prec;
  164311. }
  164312. LOCAL(void)
  164313. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164314. /* Emit a DHT marker */
  164315. {
  164316. JHUFF_TBL * htbl;
  164317. int length, i;
  164318. if (is_ac) {
  164319. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164320. index += 0x10; /* output index has AC bit set */
  164321. } else {
  164322. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164323. }
  164324. if (htbl == NULL)
  164325. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164326. if (! htbl->sent_table) {
  164327. emit_marker(cinfo, M_DHT);
  164328. length = 0;
  164329. for (i = 1; i <= 16; i++)
  164330. length += htbl->bits[i];
  164331. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164332. emit_byte(cinfo, index);
  164333. for (i = 1; i <= 16; i++)
  164334. emit_byte(cinfo, htbl->bits[i]);
  164335. for (i = 0; i < length; i++)
  164336. emit_byte(cinfo, htbl->huffval[i]);
  164337. htbl->sent_table = TRUE;
  164338. }
  164339. }
  164340. LOCAL(void)
  164341. emit_dac (j_compress_ptr)
  164342. /* Emit a DAC marker */
  164343. /* Since the useful info is so small, we want to emit all the tables in */
  164344. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164345. {
  164346. #ifdef C_ARITH_CODING_SUPPORTED
  164347. char dc_in_use[NUM_ARITH_TBLS];
  164348. char ac_in_use[NUM_ARITH_TBLS];
  164349. int length, i;
  164350. jpeg_component_info *compptr;
  164351. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164352. dc_in_use[i] = ac_in_use[i] = 0;
  164353. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164354. compptr = cinfo->cur_comp_info[i];
  164355. dc_in_use[compptr->dc_tbl_no] = 1;
  164356. ac_in_use[compptr->ac_tbl_no] = 1;
  164357. }
  164358. length = 0;
  164359. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164360. length += dc_in_use[i] + ac_in_use[i];
  164361. emit_marker(cinfo, M_DAC);
  164362. emit_2bytes(cinfo, length*2 + 2);
  164363. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164364. if (dc_in_use[i]) {
  164365. emit_byte(cinfo, i);
  164366. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164367. }
  164368. if (ac_in_use[i]) {
  164369. emit_byte(cinfo, i + 0x10);
  164370. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164371. }
  164372. }
  164373. #endif /* C_ARITH_CODING_SUPPORTED */
  164374. }
  164375. LOCAL(void)
  164376. emit_dri (j_compress_ptr cinfo)
  164377. /* Emit a DRI marker */
  164378. {
  164379. emit_marker(cinfo, M_DRI);
  164380. emit_2bytes(cinfo, 4); /* fixed length */
  164381. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164382. }
  164383. LOCAL(void)
  164384. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164385. /* Emit a SOF marker */
  164386. {
  164387. int ci;
  164388. jpeg_component_info *compptr;
  164389. emit_marker(cinfo, code);
  164390. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164391. /* Make sure image isn't bigger than SOF field can handle */
  164392. if ((long) cinfo->image_height > 65535L ||
  164393. (long) cinfo->image_width > 65535L)
  164394. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164395. emit_byte(cinfo, cinfo->data_precision);
  164396. emit_2bytes(cinfo, (int) cinfo->image_height);
  164397. emit_2bytes(cinfo, (int) cinfo->image_width);
  164398. emit_byte(cinfo, cinfo->num_components);
  164399. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164400. ci++, compptr++) {
  164401. emit_byte(cinfo, compptr->component_id);
  164402. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164403. emit_byte(cinfo, compptr->quant_tbl_no);
  164404. }
  164405. }
  164406. LOCAL(void)
  164407. emit_sos (j_compress_ptr cinfo)
  164408. /* Emit a SOS marker */
  164409. {
  164410. int i, td, ta;
  164411. jpeg_component_info *compptr;
  164412. emit_marker(cinfo, M_SOS);
  164413. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164414. emit_byte(cinfo, cinfo->comps_in_scan);
  164415. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164416. compptr = cinfo->cur_comp_info[i];
  164417. emit_byte(cinfo, compptr->component_id);
  164418. td = compptr->dc_tbl_no;
  164419. ta = compptr->ac_tbl_no;
  164420. if (cinfo->progressive_mode) {
  164421. /* Progressive mode: only DC or only AC tables are used in one scan;
  164422. * furthermore, Huffman coding of DC refinement uses no table at all.
  164423. * We emit 0 for unused field(s); this is recommended by the P&M text
  164424. * but does not seem to be specified in the standard.
  164425. */
  164426. if (cinfo->Ss == 0) {
  164427. ta = 0; /* DC scan */
  164428. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164429. td = 0; /* no DC table either */
  164430. } else {
  164431. td = 0; /* AC scan */
  164432. }
  164433. }
  164434. emit_byte(cinfo, (td << 4) + ta);
  164435. }
  164436. emit_byte(cinfo, cinfo->Ss);
  164437. emit_byte(cinfo, cinfo->Se);
  164438. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164439. }
  164440. LOCAL(void)
  164441. emit_jfif_app0 (j_compress_ptr cinfo)
  164442. /* Emit a JFIF-compliant APP0 marker */
  164443. {
  164444. /*
  164445. * Length of APP0 block (2 bytes)
  164446. * Block ID (4 bytes - ASCII "JFIF")
  164447. * Zero byte (1 byte to terminate the ID string)
  164448. * Version Major, Minor (2 bytes - major first)
  164449. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164450. * Xdpu (2 bytes - dots per unit horizontal)
  164451. * Ydpu (2 bytes - dots per unit vertical)
  164452. * Thumbnail X size (1 byte)
  164453. * Thumbnail Y size (1 byte)
  164454. */
  164455. emit_marker(cinfo, M_APP0);
  164456. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164457. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164458. emit_byte(cinfo, 0x46);
  164459. emit_byte(cinfo, 0x49);
  164460. emit_byte(cinfo, 0x46);
  164461. emit_byte(cinfo, 0);
  164462. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164463. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164464. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164465. emit_2bytes(cinfo, (int) cinfo->X_density);
  164466. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164467. emit_byte(cinfo, 0); /* No thumbnail image */
  164468. emit_byte(cinfo, 0);
  164469. }
  164470. LOCAL(void)
  164471. emit_adobe_app14 (j_compress_ptr cinfo)
  164472. /* Emit an Adobe APP14 marker */
  164473. {
  164474. /*
  164475. * Length of APP14 block (2 bytes)
  164476. * Block ID (5 bytes - ASCII "Adobe")
  164477. * Version Number (2 bytes - currently 100)
  164478. * Flags0 (2 bytes - currently 0)
  164479. * Flags1 (2 bytes - currently 0)
  164480. * Color transform (1 byte)
  164481. *
  164482. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164483. * now in circulation seem to use Version = 100, so that's what we write.
  164484. *
  164485. * We write the color transform byte as 1 if the JPEG color space is
  164486. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164487. * whether the encoder performed a transformation, which is pretty useless.
  164488. */
  164489. emit_marker(cinfo, M_APP14);
  164490. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164491. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164492. emit_byte(cinfo, 0x64);
  164493. emit_byte(cinfo, 0x6F);
  164494. emit_byte(cinfo, 0x62);
  164495. emit_byte(cinfo, 0x65);
  164496. emit_2bytes(cinfo, 100); /* Version */
  164497. emit_2bytes(cinfo, 0); /* Flags0 */
  164498. emit_2bytes(cinfo, 0); /* Flags1 */
  164499. switch (cinfo->jpeg_color_space) {
  164500. case JCS_YCbCr:
  164501. emit_byte(cinfo, 1); /* Color transform = 1 */
  164502. break;
  164503. case JCS_YCCK:
  164504. emit_byte(cinfo, 2); /* Color transform = 2 */
  164505. break;
  164506. default:
  164507. emit_byte(cinfo, 0); /* Color transform = 0 */
  164508. break;
  164509. }
  164510. }
  164511. /*
  164512. * These routines allow writing an arbitrary marker with parameters.
  164513. * The only intended use is to emit COM or APPn markers after calling
  164514. * write_file_header and before calling write_frame_header.
  164515. * Other uses are not guaranteed to produce desirable results.
  164516. * Counting the parameter bytes properly is the caller's responsibility.
  164517. */
  164518. METHODDEF(void)
  164519. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164520. /* Emit an arbitrary marker header */
  164521. {
  164522. if (datalen > (unsigned int) 65533) /* safety check */
  164523. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164524. emit_marker(cinfo, (JPEG_MARKER) marker);
  164525. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164526. }
  164527. METHODDEF(void)
  164528. write_marker_byte (j_compress_ptr cinfo, int val)
  164529. /* Emit one byte of marker parameters following write_marker_header */
  164530. {
  164531. emit_byte(cinfo, val);
  164532. }
  164533. /*
  164534. * Write datastream header.
  164535. * This consists of an SOI and optional APPn markers.
  164536. * We recommend use of the JFIF marker, but not the Adobe marker,
  164537. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164538. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164539. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164540. * Note that an application can write additional header markers after
  164541. * jpeg_start_compress returns.
  164542. */
  164543. METHODDEF(void)
  164544. write_file_header (j_compress_ptr cinfo)
  164545. {
  164546. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164547. emit_marker(cinfo, M_SOI); /* first the SOI */
  164548. /* SOI is defined to reset restart interval to 0 */
  164549. marker->last_restart_interval = 0;
  164550. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164551. emit_jfif_app0(cinfo);
  164552. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164553. emit_adobe_app14(cinfo);
  164554. }
  164555. /*
  164556. * Write frame header.
  164557. * This consists of DQT and SOFn markers.
  164558. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164559. * This avoids compatibility problems with incorrect implementations that
  164560. * try to error-check the quant table numbers as soon as they see the SOF.
  164561. */
  164562. METHODDEF(void)
  164563. write_frame_header (j_compress_ptr cinfo)
  164564. {
  164565. int ci, prec;
  164566. boolean is_baseline;
  164567. jpeg_component_info *compptr;
  164568. /* Emit DQT for each quantization table.
  164569. * Note that emit_dqt() suppresses any duplicate tables.
  164570. */
  164571. prec = 0;
  164572. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164573. ci++, compptr++) {
  164574. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164575. }
  164576. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164577. /* Check for a non-baseline specification.
  164578. * Note we assume that Huffman table numbers won't be changed later.
  164579. */
  164580. if (cinfo->arith_code || cinfo->progressive_mode ||
  164581. cinfo->data_precision != 8) {
  164582. is_baseline = FALSE;
  164583. } else {
  164584. is_baseline = TRUE;
  164585. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164586. ci++, compptr++) {
  164587. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164588. is_baseline = FALSE;
  164589. }
  164590. if (prec && is_baseline) {
  164591. is_baseline = FALSE;
  164592. /* If it's baseline except for quantizer size, warn the user */
  164593. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164594. }
  164595. }
  164596. /* Emit the proper SOF marker */
  164597. if (cinfo->arith_code) {
  164598. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164599. } else {
  164600. if (cinfo->progressive_mode)
  164601. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164602. else if (is_baseline)
  164603. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164604. else
  164605. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164606. }
  164607. }
  164608. /*
  164609. * Write scan header.
  164610. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164611. * Compressed data will be written following the SOS.
  164612. */
  164613. METHODDEF(void)
  164614. write_scan_header (j_compress_ptr cinfo)
  164615. {
  164616. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164617. int i;
  164618. jpeg_component_info *compptr;
  164619. if (cinfo->arith_code) {
  164620. /* Emit arith conditioning info. We may have some duplication
  164621. * if the file has multiple scans, but it's so small it's hardly
  164622. * worth worrying about.
  164623. */
  164624. emit_dac(cinfo);
  164625. } else {
  164626. /* Emit Huffman tables.
  164627. * Note that emit_dht() suppresses any duplicate tables.
  164628. */
  164629. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164630. compptr = cinfo->cur_comp_info[i];
  164631. if (cinfo->progressive_mode) {
  164632. /* Progressive mode: only DC or only AC tables are used in one scan */
  164633. if (cinfo->Ss == 0) {
  164634. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164635. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164636. } else {
  164637. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164638. }
  164639. } else {
  164640. /* Sequential mode: need both DC and AC tables */
  164641. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164642. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164643. }
  164644. }
  164645. }
  164646. /* Emit DRI if required --- note that DRI value could change for each scan.
  164647. * We avoid wasting space with unnecessary DRIs, however.
  164648. */
  164649. if (cinfo->restart_interval != marker->last_restart_interval) {
  164650. emit_dri(cinfo);
  164651. marker->last_restart_interval = cinfo->restart_interval;
  164652. }
  164653. emit_sos(cinfo);
  164654. }
  164655. /*
  164656. * Write datastream trailer.
  164657. */
  164658. METHODDEF(void)
  164659. write_file_trailer (j_compress_ptr cinfo)
  164660. {
  164661. emit_marker(cinfo, M_EOI);
  164662. }
  164663. /*
  164664. * Write an abbreviated table-specification datastream.
  164665. * This consists of SOI, DQT and DHT tables, and EOI.
  164666. * Any table that is defined and not marked sent_table = TRUE will be
  164667. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164668. */
  164669. METHODDEF(void)
  164670. write_tables_only (j_compress_ptr cinfo)
  164671. {
  164672. int i;
  164673. emit_marker(cinfo, M_SOI);
  164674. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164675. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164676. (void) emit_dqt(cinfo, i);
  164677. }
  164678. if (! cinfo->arith_code) {
  164679. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164680. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164681. emit_dht(cinfo, i, FALSE);
  164682. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164683. emit_dht(cinfo, i, TRUE);
  164684. }
  164685. }
  164686. emit_marker(cinfo, M_EOI);
  164687. }
  164688. /*
  164689. * Initialize the marker writer module.
  164690. */
  164691. GLOBAL(void)
  164692. jinit_marker_writer (j_compress_ptr cinfo)
  164693. {
  164694. my_marker_ptr marker;
  164695. /* Create the subobject */
  164696. marker = (my_marker_ptr)
  164697. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164698. SIZEOF(my_marker_writer));
  164699. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164700. /* Initialize method pointers */
  164701. marker->pub.write_file_header = write_file_header;
  164702. marker->pub.write_frame_header = write_frame_header;
  164703. marker->pub.write_scan_header = write_scan_header;
  164704. marker->pub.write_file_trailer = write_file_trailer;
  164705. marker->pub.write_tables_only = write_tables_only;
  164706. marker->pub.write_marker_header = write_marker_header;
  164707. marker->pub.write_marker_byte = write_marker_byte;
  164708. /* Initialize private state */
  164709. marker->last_restart_interval = 0;
  164710. }
  164711. /*** End of inlined file: jcmarker.c ***/
  164712. /*** Start of inlined file: jcmaster.c ***/
  164713. #define JPEG_INTERNALS
  164714. /* Private state */
  164715. typedef enum {
  164716. main_pass, /* input data, also do first output step */
  164717. huff_opt_pass, /* Huffman code optimization pass */
  164718. output_pass /* data output pass */
  164719. } c_pass_type;
  164720. typedef struct {
  164721. struct jpeg_comp_master pub; /* public fields */
  164722. c_pass_type pass_type; /* the type of the current pass */
  164723. int pass_number; /* # of passes completed */
  164724. int total_passes; /* total # of passes needed */
  164725. int scan_number; /* current index in scan_info[] */
  164726. } my_comp_master;
  164727. typedef my_comp_master * my_master_ptr;
  164728. /*
  164729. * Support routines that do various essential calculations.
  164730. */
  164731. LOCAL(void)
  164732. initial_setup (j_compress_ptr cinfo)
  164733. /* Do computations that are needed before master selection phase */
  164734. {
  164735. int ci;
  164736. jpeg_component_info *compptr;
  164737. long samplesperrow;
  164738. JDIMENSION jd_samplesperrow;
  164739. /* Sanity check on image dimensions */
  164740. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164741. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164742. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164743. /* Make sure image isn't bigger than I can handle */
  164744. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164745. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164746. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164747. /* Width of an input scanline must be representable as JDIMENSION. */
  164748. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164749. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164750. if ((long) jd_samplesperrow != samplesperrow)
  164751. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164752. /* For now, precision must match compiled-in value... */
  164753. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164754. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164755. /* Check that number of components won't exceed internal array sizes */
  164756. if (cinfo->num_components > MAX_COMPONENTS)
  164757. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164758. MAX_COMPONENTS);
  164759. /* Compute maximum sampling factors; check factor validity */
  164760. cinfo->max_h_samp_factor = 1;
  164761. cinfo->max_v_samp_factor = 1;
  164762. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164763. ci++, compptr++) {
  164764. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164765. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164766. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164767. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164768. compptr->h_samp_factor);
  164769. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164770. compptr->v_samp_factor);
  164771. }
  164772. /* Compute dimensions of components */
  164773. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164774. ci++, compptr++) {
  164775. /* Fill in the correct component_index value; don't rely on application */
  164776. compptr->component_index = ci;
  164777. /* For compression, we never do DCT scaling. */
  164778. compptr->DCT_scaled_size = DCTSIZE;
  164779. /* Size in DCT blocks */
  164780. compptr->width_in_blocks = (JDIMENSION)
  164781. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164782. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164783. compptr->height_in_blocks = (JDIMENSION)
  164784. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164785. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164786. /* Size in samples */
  164787. compptr->downsampled_width = (JDIMENSION)
  164788. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164789. (long) cinfo->max_h_samp_factor);
  164790. compptr->downsampled_height = (JDIMENSION)
  164791. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164792. (long) cinfo->max_v_samp_factor);
  164793. /* Mark component needed (this flag isn't actually used for compression) */
  164794. compptr->component_needed = TRUE;
  164795. }
  164796. /* Compute number of fully interleaved MCU rows (number of times that
  164797. * main controller will call coefficient controller).
  164798. */
  164799. cinfo->total_iMCU_rows = (JDIMENSION)
  164800. jdiv_round_up((long) cinfo->image_height,
  164801. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164802. }
  164803. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164804. LOCAL(void)
  164805. validate_script (j_compress_ptr cinfo)
  164806. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164807. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164808. */
  164809. {
  164810. const jpeg_scan_info * scanptr;
  164811. int scanno, ncomps, ci, coefi, thisi;
  164812. int Ss, Se, Ah, Al;
  164813. boolean component_sent[MAX_COMPONENTS];
  164814. #ifdef C_PROGRESSIVE_SUPPORTED
  164815. int * last_bitpos_ptr;
  164816. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164817. /* -1 until that coefficient has been seen; then last Al for it */
  164818. #endif
  164819. if (cinfo->num_scans <= 0)
  164820. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164821. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164822. * for progressive JPEG, no scan can have this.
  164823. */
  164824. scanptr = cinfo->scan_info;
  164825. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164826. #ifdef C_PROGRESSIVE_SUPPORTED
  164827. cinfo->progressive_mode = TRUE;
  164828. last_bitpos_ptr = & last_bitpos[0][0];
  164829. for (ci = 0; ci < cinfo->num_components; ci++)
  164830. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164831. *last_bitpos_ptr++ = -1;
  164832. #else
  164833. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164834. #endif
  164835. } else {
  164836. cinfo->progressive_mode = FALSE;
  164837. for (ci = 0; ci < cinfo->num_components; ci++)
  164838. component_sent[ci] = FALSE;
  164839. }
  164840. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164841. /* Validate component indexes */
  164842. ncomps = scanptr->comps_in_scan;
  164843. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164844. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164845. for (ci = 0; ci < ncomps; ci++) {
  164846. thisi = scanptr->component_index[ci];
  164847. if (thisi < 0 || thisi >= cinfo->num_components)
  164848. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164849. /* Components must appear in SOF order within each scan */
  164850. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164851. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164852. }
  164853. /* Validate progression parameters */
  164854. Ss = scanptr->Ss;
  164855. Se = scanptr->Se;
  164856. Ah = scanptr->Ah;
  164857. Al = scanptr->Al;
  164858. if (cinfo->progressive_mode) {
  164859. #ifdef C_PROGRESSIVE_SUPPORTED
  164860. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164861. * seems wrong: the upper bound ought to depend on data precision.
  164862. * Perhaps they really meant 0..N+1 for N-bit precision.
  164863. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164864. * out-of-range reconstructed DC values during the first DC scan,
  164865. * which might cause problems for some decoders.
  164866. */
  164867. #if BITS_IN_JSAMPLE == 8
  164868. #define MAX_AH_AL 10
  164869. #else
  164870. #define MAX_AH_AL 13
  164871. #endif
  164872. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164873. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164874. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164875. if (Ss == 0) {
  164876. if (Se != 0) /* DC and AC together not OK */
  164877. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164878. } else {
  164879. if (ncomps != 1) /* AC scans must be for only one component */
  164880. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164881. }
  164882. for (ci = 0; ci < ncomps; ci++) {
  164883. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164884. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164885. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164886. for (coefi = Ss; coefi <= Se; coefi++) {
  164887. if (last_bitpos_ptr[coefi] < 0) {
  164888. /* first scan of this coefficient */
  164889. if (Ah != 0)
  164890. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164891. } else {
  164892. /* not first scan */
  164893. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164894. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164895. }
  164896. last_bitpos_ptr[coefi] = Al;
  164897. }
  164898. }
  164899. #endif
  164900. } else {
  164901. /* For sequential JPEG, all progression parameters must be these: */
  164902. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164903. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164904. /* Make sure components are not sent twice */
  164905. for (ci = 0; ci < ncomps; ci++) {
  164906. thisi = scanptr->component_index[ci];
  164907. if (component_sent[thisi])
  164908. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164909. component_sent[thisi] = TRUE;
  164910. }
  164911. }
  164912. }
  164913. /* Now verify that everything got sent. */
  164914. if (cinfo->progressive_mode) {
  164915. #ifdef C_PROGRESSIVE_SUPPORTED
  164916. /* For progressive mode, we only check that at least some DC data
  164917. * got sent for each component; the spec does not require that all bits
  164918. * of all coefficients be transmitted. Would it be wiser to enforce
  164919. * transmission of all coefficient bits??
  164920. */
  164921. for (ci = 0; ci < cinfo->num_components; ci++) {
  164922. if (last_bitpos[ci][0] < 0)
  164923. ERREXIT(cinfo, JERR_MISSING_DATA);
  164924. }
  164925. #endif
  164926. } else {
  164927. for (ci = 0; ci < cinfo->num_components; ci++) {
  164928. if (! component_sent[ci])
  164929. ERREXIT(cinfo, JERR_MISSING_DATA);
  164930. }
  164931. }
  164932. }
  164933. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164934. LOCAL(void)
  164935. select_scan_parameters (j_compress_ptr cinfo)
  164936. /* Set up the scan parameters for the current scan */
  164937. {
  164938. int ci;
  164939. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164940. if (cinfo->scan_info != NULL) {
  164941. /* Prepare for current scan --- the script is already validated */
  164942. my_master_ptr master = (my_master_ptr) cinfo->master;
  164943. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164944. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164945. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164946. cinfo->cur_comp_info[ci] =
  164947. &cinfo->comp_info[scanptr->component_index[ci]];
  164948. }
  164949. cinfo->Ss = scanptr->Ss;
  164950. cinfo->Se = scanptr->Se;
  164951. cinfo->Ah = scanptr->Ah;
  164952. cinfo->Al = scanptr->Al;
  164953. }
  164954. else
  164955. #endif
  164956. {
  164957. /* Prepare for single sequential-JPEG scan containing all components */
  164958. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164959. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164960. MAX_COMPS_IN_SCAN);
  164961. cinfo->comps_in_scan = cinfo->num_components;
  164962. for (ci = 0; ci < cinfo->num_components; ci++) {
  164963. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164964. }
  164965. cinfo->Ss = 0;
  164966. cinfo->Se = DCTSIZE2-1;
  164967. cinfo->Ah = 0;
  164968. cinfo->Al = 0;
  164969. }
  164970. }
  164971. LOCAL(void)
  164972. per_scan_setup (j_compress_ptr cinfo)
  164973. /* Do computations that are needed before processing a JPEG scan */
  164974. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164975. {
  164976. int ci, mcublks, tmp;
  164977. jpeg_component_info *compptr;
  164978. if (cinfo->comps_in_scan == 1) {
  164979. /* Noninterleaved (single-component) scan */
  164980. compptr = cinfo->cur_comp_info[0];
  164981. /* Overall image size in MCUs */
  164982. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164983. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164984. /* For noninterleaved scan, always one block per MCU */
  164985. compptr->MCU_width = 1;
  164986. compptr->MCU_height = 1;
  164987. compptr->MCU_blocks = 1;
  164988. compptr->MCU_sample_width = DCTSIZE;
  164989. compptr->last_col_width = 1;
  164990. /* For noninterleaved scans, it is convenient to define last_row_height
  164991. * as the number of block rows present in the last iMCU row.
  164992. */
  164993. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164994. if (tmp == 0) tmp = compptr->v_samp_factor;
  164995. compptr->last_row_height = tmp;
  164996. /* Prepare array describing MCU composition */
  164997. cinfo->blocks_in_MCU = 1;
  164998. cinfo->MCU_membership[0] = 0;
  164999. } else {
  165000. /* Interleaved (multi-component) scan */
  165001. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165002. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165003. MAX_COMPS_IN_SCAN);
  165004. /* Overall image size in MCUs */
  165005. cinfo->MCUs_per_row = (JDIMENSION)
  165006. jdiv_round_up((long) cinfo->image_width,
  165007. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165008. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165009. jdiv_round_up((long) cinfo->image_height,
  165010. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165011. cinfo->blocks_in_MCU = 0;
  165012. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165013. compptr = cinfo->cur_comp_info[ci];
  165014. /* Sampling factors give # of blocks of component in each MCU */
  165015. compptr->MCU_width = compptr->h_samp_factor;
  165016. compptr->MCU_height = compptr->v_samp_factor;
  165017. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165018. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165019. /* Figure number of non-dummy blocks in last MCU column & row */
  165020. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165021. if (tmp == 0) tmp = compptr->MCU_width;
  165022. compptr->last_col_width = tmp;
  165023. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165024. if (tmp == 0) tmp = compptr->MCU_height;
  165025. compptr->last_row_height = tmp;
  165026. /* Prepare array describing MCU composition */
  165027. mcublks = compptr->MCU_blocks;
  165028. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165029. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165030. while (mcublks-- > 0) {
  165031. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165032. }
  165033. }
  165034. }
  165035. /* Convert restart specified in rows to actual MCU count. */
  165036. /* Note that count must fit in 16 bits, so we provide limiting. */
  165037. if (cinfo->restart_in_rows > 0) {
  165038. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165039. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165040. }
  165041. }
  165042. /*
  165043. * Per-pass setup.
  165044. * This is called at the beginning of each pass. We determine which modules
  165045. * will be active during this pass and give them appropriate start_pass calls.
  165046. * We also set is_last_pass to indicate whether any more passes will be
  165047. * required.
  165048. */
  165049. METHODDEF(void)
  165050. prepare_for_pass (j_compress_ptr cinfo)
  165051. {
  165052. my_master_ptr master = (my_master_ptr) cinfo->master;
  165053. switch (master->pass_type) {
  165054. case main_pass:
  165055. /* Initial pass: will collect input data, and do either Huffman
  165056. * optimization or data output for the first scan.
  165057. */
  165058. select_scan_parameters(cinfo);
  165059. per_scan_setup(cinfo);
  165060. if (! cinfo->raw_data_in) {
  165061. (*cinfo->cconvert->start_pass) (cinfo);
  165062. (*cinfo->downsample->start_pass) (cinfo);
  165063. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165064. }
  165065. (*cinfo->fdct->start_pass) (cinfo);
  165066. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165067. (*cinfo->coef->start_pass) (cinfo,
  165068. (master->total_passes > 1 ?
  165069. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165070. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165071. if (cinfo->optimize_coding) {
  165072. /* No immediate data output; postpone writing frame/scan headers */
  165073. master->pub.call_pass_startup = FALSE;
  165074. } else {
  165075. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165076. master->pub.call_pass_startup = TRUE;
  165077. }
  165078. break;
  165079. #ifdef ENTROPY_OPT_SUPPORTED
  165080. case huff_opt_pass:
  165081. /* Do Huffman optimization for a scan after the first one. */
  165082. select_scan_parameters(cinfo);
  165083. per_scan_setup(cinfo);
  165084. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165085. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165086. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165087. master->pub.call_pass_startup = FALSE;
  165088. break;
  165089. }
  165090. /* Special case: Huffman DC refinement scans need no Huffman table
  165091. * and therefore we can skip the optimization pass for them.
  165092. */
  165093. master->pass_type = output_pass;
  165094. master->pass_number++;
  165095. /*FALLTHROUGH*/
  165096. #endif
  165097. case output_pass:
  165098. /* Do a data-output pass. */
  165099. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165100. if (! cinfo->optimize_coding) {
  165101. select_scan_parameters(cinfo);
  165102. per_scan_setup(cinfo);
  165103. }
  165104. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165105. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165106. /* We emit frame/scan headers now */
  165107. if (master->scan_number == 0)
  165108. (*cinfo->marker->write_frame_header) (cinfo);
  165109. (*cinfo->marker->write_scan_header) (cinfo);
  165110. master->pub.call_pass_startup = FALSE;
  165111. break;
  165112. default:
  165113. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165114. }
  165115. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165116. /* Set up progress monitor's pass info if present */
  165117. if (cinfo->progress != NULL) {
  165118. cinfo->progress->completed_passes = master->pass_number;
  165119. cinfo->progress->total_passes = master->total_passes;
  165120. }
  165121. }
  165122. /*
  165123. * Special start-of-pass hook.
  165124. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165125. * In single-pass processing, we need this hook because we don't want to
  165126. * write frame/scan headers during jpeg_start_compress; we want to let the
  165127. * application write COM markers etc. between jpeg_start_compress and the
  165128. * jpeg_write_scanlines loop.
  165129. * In multi-pass processing, this routine is not used.
  165130. */
  165131. METHODDEF(void)
  165132. pass_startup (j_compress_ptr cinfo)
  165133. {
  165134. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165135. (*cinfo->marker->write_frame_header) (cinfo);
  165136. (*cinfo->marker->write_scan_header) (cinfo);
  165137. }
  165138. /*
  165139. * Finish up at end of pass.
  165140. */
  165141. METHODDEF(void)
  165142. finish_pass_master (j_compress_ptr cinfo)
  165143. {
  165144. my_master_ptr master = (my_master_ptr) cinfo->master;
  165145. /* The entropy coder always needs an end-of-pass call,
  165146. * either to analyze statistics or to flush its output buffer.
  165147. */
  165148. (*cinfo->entropy->finish_pass) (cinfo);
  165149. /* Update state for next pass */
  165150. switch (master->pass_type) {
  165151. case main_pass:
  165152. /* next pass is either output of scan 0 (after optimization)
  165153. * or output of scan 1 (if no optimization).
  165154. */
  165155. master->pass_type = output_pass;
  165156. if (! cinfo->optimize_coding)
  165157. master->scan_number++;
  165158. break;
  165159. case huff_opt_pass:
  165160. /* next pass is always output of current scan */
  165161. master->pass_type = output_pass;
  165162. break;
  165163. case output_pass:
  165164. /* next pass is either optimization or output of next scan */
  165165. if (cinfo->optimize_coding)
  165166. master->pass_type = huff_opt_pass;
  165167. master->scan_number++;
  165168. break;
  165169. }
  165170. master->pass_number++;
  165171. }
  165172. /*
  165173. * Initialize master compression control.
  165174. */
  165175. GLOBAL(void)
  165176. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165177. {
  165178. my_master_ptr master;
  165179. master = (my_master_ptr)
  165180. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165181. SIZEOF(my_comp_master));
  165182. cinfo->master = (struct jpeg_comp_master *) master;
  165183. master->pub.prepare_for_pass = prepare_for_pass;
  165184. master->pub.pass_startup = pass_startup;
  165185. master->pub.finish_pass = finish_pass_master;
  165186. master->pub.is_last_pass = FALSE;
  165187. /* Validate parameters, determine derived values */
  165188. initial_setup(cinfo);
  165189. if (cinfo->scan_info != NULL) {
  165190. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165191. validate_script(cinfo);
  165192. #else
  165193. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165194. #endif
  165195. } else {
  165196. cinfo->progressive_mode = FALSE;
  165197. cinfo->num_scans = 1;
  165198. }
  165199. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165200. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165201. /* Initialize my private state */
  165202. if (transcode_only) {
  165203. /* no main pass in transcoding */
  165204. if (cinfo->optimize_coding)
  165205. master->pass_type = huff_opt_pass;
  165206. else
  165207. master->pass_type = output_pass;
  165208. } else {
  165209. /* for normal compression, first pass is always this type: */
  165210. master->pass_type = main_pass;
  165211. }
  165212. master->scan_number = 0;
  165213. master->pass_number = 0;
  165214. if (cinfo->optimize_coding)
  165215. master->total_passes = cinfo->num_scans * 2;
  165216. else
  165217. master->total_passes = cinfo->num_scans;
  165218. }
  165219. /*** End of inlined file: jcmaster.c ***/
  165220. /*** Start of inlined file: jcomapi.c ***/
  165221. #define JPEG_INTERNALS
  165222. /*
  165223. * Abort processing of a JPEG compression or decompression operation,
  165224. * but don't destroy the object itself.
  165225. *
  165226. * For this, we merely clean up all the nonpermanent memory pools.
  165227. * Note that temp files (virtual arrays) are not allowed to belong to
  165228. * the permanent pool, so we will be able to close all temp files here.
  165229. * Closing a data source or destination, if necessary, is the application's
  165230. * responsibility.
  165231. */
  165232. GLOBAL(void)
  165233. jpeg_abort (j_common_ptr cinfo)
  165234. {
  165235. int pool;
  165236. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165237. if (cinfo->mem == NULL)
  165238. return;
  165239. /* Releasing pools in reverse order might help avoid fragmentation
  165240. * with some (brain-damaged) malloc libraries.
  165241. */
  165242. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165243. (*cinfo->mem->free_pool) (cinfo, pool);
  165244. }
  165245. /* Reset overall state for possible reuse of object */
  165246. if (cinfo->is_decompressor) {
  165247. cinfo->global_state = DSTATE_START;
  165248. /* Try to keep application from accessing now-deleted marker list.
  165249. * A bit kludgy to do it here, but this is the most central place.
  165250. */
  165251. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165252. } else {
  165253. cinfo->global_state = CSTATE_START;
  165254. }
  165255. }
  165256. /*
  165257. * Destruction of a JPEG object.
  165258. *
  165259. * Everything gets deallocated except the master jpeg_compress_struct itself
  165260. * and the error manager struct. Both of these are supplied by the application
  165261. * and must be freed, if necessary, by the application. (Often they are on
  165262. * the stack and so don't need to be freed anyway.)
  165263. * Closing a data source or destination, if necessary, is the application's
  165264. * responsibility.
  165265. */
  165266. GLOBAL(void)
  165267. jpeg_destroy (j_common_ptr cinfo)
  165268. {
  165269. /* We need only tell the memory manager to release everything. */
  165270. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165271. if (cinfo->mem != NULL)
  165272. (*cinfo->mem->self_destruct) (cinfo);
  165273. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165274. cinfo->global_state = 0; /* mark it destroyed */
  165275. }
  165276. /*
  165277. * Convenience routines for allocating quantization and Huffman tables.
  165278. * (Would jutils.c be a more reasonable place to put these?)
  165279. */
  165280. GLOBAL(JQUANT_TBL *)
  165281. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165282. {
  165283. JQUANT_TBL *tbl;
  165284. tbl = (JQUANT_TBL *)
  165285. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165286. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165287. return tbl;
  165288. }
  165289. GLOBAL(JHUFF_TBL *)
  165290. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165291. {
  165292. JHUFF_TBL *tbl;
  165293. tbl = (JHUFF_TBL *)
  165294. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165295. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165296. return tbl;
  165297. }
  165298. /*** End of inlined file: jcomapi.c ***/
  165299. /*** Start of inlined file: jcparam.c ***/
  165300. #define JPEG_INTERNALS
  165301. /*
  165302. * Quantization table setup routines
  165303. */
  165304. GLOBAL(void)
  165305. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165306. const unsigned int *basic_table,
  165307. int scale_factor, boolean force_baseline)
  165308. /* Define a quantization table equal to the basic_table times
  165309. * a scale factor (given as a percentage).
  165310. * If force_baseline is TRUE, the computed quantization table entries
  165311. * are limited to 1..255 for JPEG baseline compatibility.
  165312. */
  165313. {
  165314. JQUANT_TBL ** qtblptr;
  165315. int i;
  165316. long temp;
  165317. /* Safety check to ensure start_compress not called yet. */
  165318. if (cinfo->global_state != CSTATE_START)
  165319. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165320. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165321. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165322. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165323. if (*qtblptr == NULL)
  165324. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165325. for (i = 0; i < DCTSIZE2; i++) {
  165326. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165327. /* limit the values to the valid range */
  165328. if (temp <= 0L) temp = 1L;
  165329. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165330. if (force_baseline && temp > 255L)
  165331. temp = 255L; /* limit to baseline range if requested */
  165332. (*qtblptr)->quantval[i] = (UINT16) temp;
  165333. }
  165334. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165335. (*qtblptr)->sent_table = FALSE;
  165336. }
  165337. GLOBAL(void)
  165338. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165339. boolean force_baseline)
  165340. /* Set or change the 'quality' (quantization) setting, using default tables
  165341. * and a straight percentage-scaling quality scale. In most cases it's better
  165342. * to use jpeg_set_quality (below); this entry point is provided for
  165343. * applications that insist on a linear percentage scaling.
  165344. */
  165345. {
  165346. /* These are the sample quantization tables given in JPEG spec section K.1.
  165347. * The spec says that the values given produce "good" quality, and
  165348. * when divided by 2, "very good" quality.
  165349. */
  165350. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165351. 16, 11, 10, 16, 24, 40, 51, 61,
  165352. 12, 12, 14, 19, 26, 58, 60, 55,
  165353. 14, 13, 16, 24, 40, 57, 69, 56,
  165354. 14, 17, 22, 29, 51, 87, 80, 62,
  165355. 18, 22, 37, 56, 68, 109, 103, 77,
  165356. 24, 35, 55, 64, 81, 104, 113, 92,
  165357. 49, 64, 78, 87, 103, 121, 120, 101,
  165358. 72, 92, 95, 98, 112, 100, 103, 99
  165359. };
  165360. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165361. 17, 18, 24, 47, 99, 99, 99, 99,
  165362. 18, 21, 26, 66, 99, 99, 99, 99,
  165363. 24, 26, 56, 99, 99, 99, 99, 99,
  165364. 47, 66, 99, 99, 99, 99, 99, 99,
  165365. 99, 99, 99, 99, 99, 99, 99, 99,
  165366. 99, 99, 99, 99, 99, 99, 99, 99,
  165367. 99, 99, 99, 99, 99, 99, 99, 99,
  165368. 99, 99, 99, 99, 99, 99, 99, 99
  165369. };
  165370. /* Set up two quantization tables using the specified scaling */
  165371. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165372. scale_factor, force_baseline);
  165373. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165374. scale_factor, force_baseline);
  165375. }
  165376. GLOBAL(int)
  165377. jpeg_quality_scaling (int quality)
  165378. /* Convert a user-specified quality rating to a percentage scaling factor
  165379. * for an underlying quantization table, using our recommended scaling curve.
  165380. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165381. */
  165382. {
  165383. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165384. if (quality <= 0) quality = 1;
  165385. if (quality > 100) quality = 100;
  165386. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165387. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165388. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165389. * to make all the table entries 1 (hence, minimum quantization loss).
  165390. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165391. */
  165392. if (quality < 50)
  165393. quality = 5000 / quality;
  165394. else
  165395. quality = 200 - quality*2;
  165396. return quality;
  165397. }
  165398. GLOBAL(void)
  165399. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165400. /* Set or change the 'quality' (quantization) setting, using default tables.
  165401. * This is the standard quality-adjusting entry point for typical user
  165402. * interfaces; only those who want detailed control over quantization tables
  165403. * would use the preceding three routines directly.
  165404. */
  165405. {
  165406. /* Convert user 0-100 rating to percentage scaling */
  165407. quality = jpeg_quality_scaling(quality);
  165408. /* Set up standard quality tables */
  165409. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165410. }
  165411. /*
  165412. * Huffman table setup routines
  165413. */
  165414. LOCAL(void)
  165415. add_huff_table (j_compress_ptr cinfo,
  165416. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165417. /* Define a Huffman table */
  165418. {
  165419. int nsymbols, len;
  165420. if (*htblptr == NULL)
  165421. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165422. /* Copy the number-of-symbols-of-each-code-length counts */
  165423. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165424. /* Validate the counts. We do this here mainly so we can copy the right
  165425. * number of symbols from the val[] array, without risking marching off
  165426. * the end of memory. jchuff.c will do a more thorough test later.
  165427. */
  165428. nsymbols = 0;
  165429. for (len = 1; len <= 16; len++)
  165430. nsymbols += bits[len];
  165431. if (nsymbols < 1 || nsymbols > 256)
  165432. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165433. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165434. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165435. (*htblptr)->sent_table = FALSE;
  165436. }
  165437. LOCAL(void)
  165438. std_huff_tables (j_compress_ptr cinfo)
  165439. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165440. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165441. {
  165442. static const UINT8 bits_dc_luminance[17] =
  165443. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165444. static const UINT8 val_dc_luminance[] =
  165445. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165446. static const UINT8 bits_dc_chrominance[17] =
  165447. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165448. static const UINT8 val_dc_chrominance[] =
  165449. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165450. static const UINT8 bits_ac_luminance[17] =
  165451. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165452. static const UINT8 val_ac_luminance[] =
  165453. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165454. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165455. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165456. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165457. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165458. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165459. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165460. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165461. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165462. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165463. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165464. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165465. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165466. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165467. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165468. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165469. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165470. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165471. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165472. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165473. 0xf9, 0xfa };
  165474. static const UINT8 bits_ac_chrominance[17] =
  165475. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165476. static const UINT8 val_ac_chrominance[] =
  165477. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165478. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165479. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165480. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165481. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165482. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165483. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165484. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165485. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165486. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165487. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165488. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165489. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165490. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165491. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165492. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165493. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165494. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165495. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165496. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165497. 0xf9, 0xfa };
  165498. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165499. bits_dc_luminance, val_dc_luminance);
  165500. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165501. bits_ac_luminance, val_ac_luminance);
  165502. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165503. bits_dc_chrominance, val_dc_chrominance);
  165504. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165505. bits_ac_chrominance, val_ac_chrominance);
  165506. }
  165507. /*
  165508. * Default parameter setup for compression.
  165509. *
  165510. * Applications that don't choose to use this routine must do their
  165511. * own setup of all these parameters. Alternately, you can call this
  165512. * to establish defaults and then alter parameters selectively. This
  165513. * is the recommended approach since, if we add any new parameters,
  165514. * your code will still work (they'll be set to reasonable defaults).
  165515. */
  165516. GLOBAL(void)
  165517. jpeg_set_defaults (j_compress_ptr cinfo)
  165518. {
  165519. int i;
  165520. /* Safety check to ensure start_compress not called yet. */
  165521. if (cinfo->global_state != CSTATE_START)
  165522. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165523. /* Allocate comp_info array large enough for maximum component count.
  165524. * Array is made permanent in case application wants to compress
  165525. * multiple images at same param settings.
  165526. */
  165527. if (cinfo->comp_info == NULL)
  165528. cinfo->comp_info = (jpeg_component_info *)
  165529. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165530. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165531. /* Initialize everything not dependent on the color space */
  165532. cinfo->data_precision = BITS_IN_JSAMPLE;
  165533. /* Set up two quantization tables using default quality of 75 */
  165534. jpeg_set_quality(cinfo, 75, TRUE);
  165535. /* Set up two Huffman tables */
  165536. std_huff_tables(cinfo);
  165537. /* Initialize default arithmetic coding conditioning */
  165538. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165539. cinfo->arith_dc_L[i] = 0;
  165540. cinfo->arith_dc_U[i] = 1;
  165541. cinfo->arith_ac_K[i] = 5;
  165542. }
  165543. /* Default is no multiple-scan output */
  165544. cinfo->scan_info = NULL;
  165545. cinfo->num_scans = 0;
  165546. /* Expect normal source image, not raw downsampled data */
  165547. cinfo->raw_data_in = FALSE;
  165548. /* Use Huffman coding, not arithmetic coding, by default */
  165549. cinfo->arith_code = FALSE;
  165550. /* By default, don't do extra passes to optimize entropy coding */
  165551. cinfo->optimize_coding = FALSE;
  165552. /* The standard Huffman tables are only valid for 8-bit data precision.
  165553. * If the precision is higher, force optimization on so that usable
  165554. * tables will be computed. This test can be removed if default tables
  165555. * are supplied that are valid for the desired precision.
  165556. */
  165557. if (cinfo->data_precision > 8)
  165558. cinfo->optimize_coding = TRUE;
  165559. /* By default, use the simpler non-cosited sampling alignment */
  165560. cinfo->CCIR601_sampling = FALSE;
  165561. /* No input smoothing */
  165562. cinfo->smoothing_factor = 0;
  165563. /* DCT algorithm preference */
  165564. cinfo->dct_method = JDCT_DEFAULT;
  165565. /* No restart markers */
  165566. cinfo->restart_interval = 0;
  165567. cinfo->restart_in_rows = 0;
  165568. /* Fill in default JFIF marker parameters. Note that whether the marker
  165569. * will actually be written is determined by jpeg_set_colorspace.
  165570. *
  165571. * By default, the library emits JFIF version code 1.01.
  165572. * An application that wants to emit JFIF 1.02 extension markers should set
  165573. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165574. * to 1.02, but there may still be some decoders in use that will complain
  165575. * about that; saying 1.01 should minimize compatibility problems.
  165576. */
  165577. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165578. cinfo->JFIF_minor_version = 1;
  165579. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165580. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165581. cinfo->Y_density = 1;
  165582. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165583. jpeg_default_colorspace(cinfo);
  165584. }
  165585. /*
  165586. * Select an appropriate JPEG colorspace for in_color_space.
  165587. */
  165588. GLOBAL(void)
  165589. jpeg_default_colorspace (j_compress_ptr cinfo)
  165590. {
  165591. switch (cinfo->in_color_space) {
  165592. case JCS_GRAYSCALE:
  165593. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165594. break;
  165595. case JCS_RGB:
  165596. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165597. break;
  165598. case JCS_YCbCr:
  165599. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165600. break;
  165601. case JCS_CMYK:
  165602. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165603. break;
  165604. case JCS_YCCK:
  165605. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165606. break;
  165607. case JCS_UNKNOWN:
  165608. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165609. break;
  165610. default:
  165611. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165612. }
  165613. }
  165614. /*
  165615. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165616. */
  165617. GLOBAL(void)
  165618. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165619. {
  165620. jpeg_component_info * compptr;
  165621. int ci;
  165622. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165623. (compptr = &cinfo->comp_info[index], \
  165624. compptr->component_id = (id), \
  165625. compptr->h_samp_factor = (hsamp), \
  165626. compptr->v_samp_factor = (vsamp), \
  165627. compptr->quant_tbl_no = (quant), \
  165628. compptr->dc_tbl_no = (dctbl), \
  165629. compptr->ac_tbl_no = (actbl) )
  165630. /* Safety check to ensure start_compress not called yet. */
  165631. if (cinfo->global_state != CSTATE_START)
  165632. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165633. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165634. * tables 1 for chrominance components.
  165635. */
  165636. cinfo->jpeg_color_space = colorspace;
  165637. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165638. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165639. switch (colorspace) {
  165640. case JCS_GRAYSCALE:
  165641. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165642. cinfo->num_components = 1;
  165643. /* JFIF specifies component ID 1 */
  165644. SET_COMP(0, 1, 1,1, 0, 0,0);
  165645. break;
  165646. case JCS_RGB:
  165647. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165648. cinfo->num_components = 3;
  165649. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165650. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165651. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165652. break;
  165653. case JCS_YCbCr:
  165654. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165655. cinfo->num_components = 3;
  165656. /* JFIF specifies component IDs 1,2,3 */
  165657. /* We default to 2x2 subsamples of chrominance */
  165658. SET_COMP(0, 1, 2,2, 0, 0,0);
  165659. SET_COMP(1, 2, 1,1, 1, 1,1);
  165660. SET_COMP(2, 3, 1,1, 1, 1,1);
  165661. break;
  165662. case JCS_CMYK:
  165663. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165664. cinfo->num_components = 4;
  165665. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165666. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165667. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165668. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165669. break;
  165670. case JCS_YCCK:
  165671. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165672. cinfo->num_components = 4;
  165673. SET_COMP(0, 1, 2,2, 0, 0,0);
  165674. SET_COMP(1, 2, 1,1, 1, 1,1);
  165675. SET_COMP(2, 3, 1,1, 1, 1,1);
  165676. SET_COMP(3, 4, 2,2, 0, 0,0);
  165677. break;
  165678. case JCS_UNKNOWN:
  165679. cinfo->num_components = cinfo->input_components;
  165680. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165681. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165682. MAX_COMPONENTS);
  165683. for (ci = 0; ci < cinfo->num_components; ci++) {
  165684. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165685. }
  165686. break;
  165687. default:
  165688. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165689. }
  165690. }
  165691. #ifdef C_PROGRESSIVE_SUPPORTED
  165692. LOCAL(jpeg_scan_info *)
  165693. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165694. int Ss, int Se, int Ah, int Al)
  165695. /* Support routine: generate one scan for specified component */
  165696. {
  165697. scanptr->comps_in_scan = 1;
  165698. scanptr->component_index[0] = ci;
  165699. scanptr->Ss = Ss;
  165700. scanptr->Se = Se;
  165701. scanptr->Ah = Ah;
  165702. scanptr->Al = Al;
  165703. scanptr++;
  165704. return scanptr;
  165705. }
  165706. LOCAL(jpeg_scan_info *)
  165707. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165708. int Ss, int Se, int Ah, int Al)
  165709. /* Support routine: generate one scan for each component */
  165710. {
  165711. int ci;
  165712. for (ci = 0; ci < ncomps; ci++) {
  165713. scanptr->comps_in_scan = 1;
  165714. scanptr->component_index[0] = ci;
  165715. scanptr->Ss = Ss;
  165716. scanptr->Se = Se;
  165717. scanptr->Ah = Ah;
  165718. scanptr->Al = Al;
  165719. scanptr++;
  165720. }
  165721. return scanptr;
  165722. }
  165723. LOCAL(jpeg_scan_info *)
  165724. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165725. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165726. {
  165727. int ci;
  165728. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165729. /* Single interleaved DC scan */
  165730. scanptr->comps_in_scan = ncomps;
  165731. for (ci = 0; ci < ncomps; ci++)
  165732. scanptr->component_index[ci] = ci;
  165733. scanptr->Ss = scanptr->Se = 0;
  165734. scanptr->Ah = Ah;
  165735. scanptr->Al = Al;
  165736. scanptr++;
  165737. } else {
  165738. /* Noninterleaved DC scan for each component */
  165739. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165740. }
  165741. return scanptr;
  165742. }
  165743. /*
  165744. * Create a recommended progressive-JPEG script.
  165745. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165746. */
  165747. GLOBAL(void)
  165748. jpeg_simple_progression (j_compress_ptr cinfo)
  165749. {
  165750. int ncomps = cinfo->num_components;
  165751. int nscans;
  165752. jpeg_scan_info * scanptr;
  165753. /* Safety check to ensure start_compress not called yet. */
  165754. if (cinfo->global_state != CSTATE_START)
  165755. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165756. /* Figure space needed for script. Calculation must match code below! */
  165757. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165758. /* Custom script for YCbCr color images. */
  165759. nscans = 10;
  165760. } else {
  165761. /* All-purpose script for other color spaces. */
  165762. if (ncomps > MAX_COMPS_IN_SCAN)
  165763. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165764. else
  165765. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165766. }
  165767. /* Allocate space for script.
  165768. * We need to put it in the permanent pool in case the application performs
  165769. * multiple compressions without changing the settings. To avoid a memory
  165770. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165771. * object, we try to re-use previously allocated space, and we allocate
  165772. * enough space to handle YCbCr even if initially asked for grayscale.
  165773. */
  165774. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165775. cinfo->script_space_size = MAX(nscans, 10);
  165776. cinfo->script_space = (jpeg_scan_info *)
  165777. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165778. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165779. }
  165780. scanptr = cinfo->script_space;
  165781. cinfo->scan_info = scanptr;
  165782. cinfo->num_scans = nscans;
  165783. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165784. /* Custom script for YCbCr color images. */
  165785. /* Initial DC scan */
  165786. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165787. /* Initial AC scan: get some luma data out in a hurry */
  165788. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165789. /* Chroma data is too small to be worth expending many scans on */
  165790. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165791. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165792. /* Complete spectral selection for luma AC */
  165793. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165794. /* Refine next bit of luma AC */
  165795. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165796. /* Finish DC successive approximation */
  165797. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165798. /* Finish AC successive approximation */
  165799. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165800. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165801. /* Luma bottom bit comes last since it's usually largest scan */
  165802. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165803. } else {
  165804. /* All-purpose script for other color spaces. */
  165805. /* Successive approximation first pass */
  165806. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165807. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165808. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165809. /* Successive approximation second pass */
  165810. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165811. /* Successive approximation final pass */
  165812. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165813. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165814. }
  165815. }
  165816. #endif /* C_PROGRESSIVE_SUPPORTED */
  165817. /*** End of inlined file: jcparam.c ***/
  165818. /*** Start of inlined file: jcphuff.c ***/
  165819. #define JPEG_INTERNALS
  165820. #ifdef C_PROGRESSIVE_SUPPORTED
  165821. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165822. typedef struct {
  165823. struct jpeg_entropy_encoder pub; /* public fields */
  165824. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165825. boolean gather_statistics;
  165826. /* Bit-level coding status.
  165827. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165828. */
  165829. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165830. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165831. INT32 put_buffer; /* current bit-accumulation buffer */
  165832. int put_bits; /* # of bits now in it */
  165833. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165834. /* Coding status for DC components */
  165835. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165836. /* Coding status for AC components */
  165837. int ac_tbl_no; /* the table number of the single component */
  165838. unsigned int EOBRUN; /* run length of EOBs */
  165839. unsigned int BE; /* # of buffered correction bits before MCU */
  165840. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165841. /* packing correction bits tightly would save some space but cost time... */
  165842. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165843. int next_restart_num; /* next restart number to write (0-7) */
  165844. /* Pointers to derived tables (these workspaces have image lifespan).
  165845. * Since any one scan codes only DC or only AC, we only need one set
  165846. * of tables, not one for DC and one for AC.
  165847. */
  165848. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165849. /* Statistics tables for optimization; again, one set is enough */
  165850. long * count_ptrs[NUM_HUFF_TBLS];
  165851. } phuff_entropy_encoder;
  165852. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165853. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165854. * buffer can hold. Larger sizes may slightly improve compression, but
  165855. * 1000 is already well into the realm of overkill.
  165856. * The minimum safe size is 64 bits.
  165857. */
  165858. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165859. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165860. * We assume that int right shift is unsigned if INT32 right shift is,
  165861. * which should be safe.
  165862. */
  165863. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165864. #define ISHIFT_TEMPS int ishift_temp;
  165865. #define IRIGHT_SHIFT(x,shft) \
  165866. ((ishift_temp = (x)) < 0 ? \
  165867. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165868. (ishift_temp >> (shft)))
  165869. #else
  165870. #define ISHIFT_TEMPS
  165871. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165872. #endif
  165873. /* Forward declarations */
  165874. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165875. JBLOCKROW *MCU_data));
  165876. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165877. JBLOCKROW *MCU_data));
  165878. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165879. JBLOCKROW *MCU_data));
  165880. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165881. JBLOCKROW *MCU_data));
  165882. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165883. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165884. /*
  165885. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165886. */
  165887. METHODDEF(void)
  165888. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165889. {
  165890. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165891. boolean is_DC_band;
  165892. int ci, tbl;
  165893. jpeg_component_info * compptr;
  165894. entropy->cinfo = cinfo;
  165895. entropy->gather_statistics = gather_statistics;
  165896. is_DC_band = (cinfo->Ss == 0);
  165897. /* We assume jcmaster.c already validated the scan parameters. */
  165898. /* Select execution routines */
  165899. if (cinfo->Ah == 0) {
  165900. if (is_DC_band)
  165901. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165902. else
  165903. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165904. } else {
  165905. if (is_DC_band)
  165906. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165907. else {
  165908. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165909. /* AC refinement needs a correction bit buffer */
  165910. if (entropy->bit_buffer == NULL)
  165911. entropy->bit_buffer = (char *)
  165912. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165913. MAX_CORR_BITS * SIZEOF(char));
  165914. }
  165915. }
  165916. if (gather_statistics)
  165917. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165918. else
  165919. entropy->pub.finish_pass = finish_pass_phuff;
  165920. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165921. * for AC coefficients.
  165922. */
  165923. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165924. compptr = cinfo->cur_comp_info[ci];
  165925. /* Initialize DC predictions to 0 */
  165926. entropy->last_dc_val[ci] = 0;
  165927. /* Get table index */
  165928. if (is_DC_band) {
  165929. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165930. continue;
  165931. tbl = compptr->dc_tbl_no;
  165932. } else {
  165933. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165934. }
  165935. if (gather_statistics) {
  165936. /* Check for invalid table index */
  165937. /* (make_c_derived_tbl does this in the other path) */
  165938. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165939. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165940. /* Allocate and zero the statistics tables */
  165941. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165942. if (entropy->count_ptrs[tbl] == NULL)
  165943. entropy->count_ptrs[tbl] = (long *)
  165944. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165945. 257 * SIZEOF(long));
  165946. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165947. } else {
  165948. /* Compute derived values for Huffman table */
  165949. /* We may do this more than once for a table, but it's not expensive */
  165950. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165951. & entropy->derived_tbls[tbl]);
  165952. }
  165953. }
  165954. /* Initialize AC stuff */
  165955. entropy->EOBRUN = 0;
  165956. entropy->BE = 0;
  165957. /* Initialize bit buffer to empty */
  165958. entropy->put_buffer = 0;
  165959. entropy->put_bits = 0;
  165960. /* Initialize restart stuff */
  165961. entropy->restarts_to_go = cinfo->restart_interval;
  165962. entropy->next_restart_num = 0;
  165963. }
  165964. /* Outputting bytes to the file.
  165965. * NB: these must be called only when actually outputting,
  165966. * that is, entropy->gather_statistics == FALSE.
  165967. */
  165968. /* Emit a byte */
  165969. #define emit_byte(entropy,val) \
  165970. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165971. if (--(entropy)->free_in_buffer == 0) \
  165972. dump_buffer_p(entropy); }
  165973. LOCAL(void)
  165974. dump_buffer_p (phuff_entropy_ptr entropy)
  165975. /* Empty the output buffer; we do not support suspension in this module. */
  165976. {
  165977. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165978. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165979. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165980. /* After a successful buffer dump, must reset buffer pointers */
  165981. entropy->next_output_byte = dest->next_output_byte;
  165982. entropy->free_in_buffer = dest->free_in_buffer;
  165983. }
  165984. /* Outputting bits to the file */
  165985. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165986. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165987. * in one call, and we never retain more than 7 bits in put_buffer
  165988. * between calls, so 24 bits are sufficient.
  165989. */
  165990. INLINE
  165991. LOCAL(void)
  165992. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165993. /* Emit some bits, unless we are in gather mode */
  165994. {
  165995. /* This routine is heavily used, so it's worth coding tightly. */
  165996. register INT32 put_buffer = (INT32) code;
  165997. register int put_bits = entropy->put_bits;
  165998. /* if size is 0, caller used an invalid Huffman table entry */
  165999. if (size == 0)
  166000. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166001. if (entropy->gather_statistics)
  166002. return; /* do nothing if we're only getting stats */
  166003. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166004. put_bits += size; /* new number of bits in buffer */
  166005. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166006. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166007. while (put_bits >= 8) {
  166008. int c = (int) ((put_buffer >> 16) & 0xFF);
  166009. emit_byte(entropy, c);
  166010. if (c == 0xFF) { /* need to stuff a zero byte? */
  166011. emit_byte(entropy, 0);
  166012. }
  166013. put_buffer <<= 8;
  166014. put_bits -= 8;
  166015. }
  166016. entropy->put_buffer = put_buffer; /* update variables */
  166017. entropy->put_bits = put_bits;
  166018. }
  166019. LOCAL(void)
  166020. flush_bits_p (phuff_entropy_ptr entropy)
  166021. {
  166022. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166023. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166024. entropy->put_bits = 0;
  166025. }
  166026. /*
  166027. * Emit (or just count) a Huffman symbol.
  166028. */
  166029. INLINE
  166030. LOCAL(void)
  166031. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166032. {
  166033. if (entropy->gather_statistics)
  166034. entropy->count_ptrs[tbl_no][symbol]++;
  166035. else {
  166036. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166037. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166038. }
  166039. }
  166040. /*
  166041. * Emit bits from a correction bit buffer.
  166042. */
  166043. LOCAL(void)
  166044. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166045. unsigned int nbits)
  166046. {
  166047. if (entropy->gather_statistics)
  166048. return; /* no real work */
  166049. while (nbits > 0) {
  166050. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166051. bufstart++;
  166052. nbits--;
  166053. }
  166054. }
  166055. /*
  166056. * Emit any pending EOBRUN symbol.
  166057. */
  166058. LOCAL(void)
  166059. emit_eobrun (phuff_entropy_ptr entropy)
  166060. {
  166061. register int temp, nbits;
  166062. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166063. temp = entropy->EOBRUN;
  166064. nbits = 0;
  166065. while ((temp >>= 1))
  166066. nbits++;
  166067. /* safety check: shouldn't happen given limited correction-bit buffer */
  166068. if (nbits > 14)
  166069. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166070. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166071. if (nbits)
  166072. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166073. entropy->EOBRUN = 0;
  166074. /* Emit any buffered correction bits */
  166075. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166076. entropy->BE = 0;
  166077. }
  166078. }
  166079. /*
  166080. * Emit a restart marker & resynchronize predictions.
  166081. */
  166082. LOCAL(void)
  166083. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166084. {
  166085. int ci;
  166086. emit_eobrun(entropy);
  166087. if (! entropy->gather_statistics) {
  166088. flush_bits_p(entropy);
  166089. emit_byte(entropy, 0xFF);
  166090. emit_byte(entropy, JPEG_RST0 + restart_num);
  166091. }
  166092. if (entropy->cinfo->Ss == 0) {
  166093. /* Re-initialize DC predictions to 0 */
  166094. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166095. entropy->last_dc_val[ci] = 0;
  166096. } else {
  166097. /* Re-initialize all AC-related fields to 0 */
  166098. entropy->EOBRUN = 0;
  166099. entropy->BE = 0;
  166100. }
  166101. }
  166102. /*
  166103. * MCU encoding for DC initial scan (either spectral selection,
  166104. * or first pass of successive approximation).
  166105. */
  166106. METHODDEF(boolean)
  166107. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166108. {
  166109. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166110. register int temp, temp2;
  166111. register int nbits;
  166112. int blkn, ci;
  166113. int Al = cinfo->Al;
  166114. JBLOCKROW block;
  166115. jpeg_component_info * compptr;
  166116. ISHIFT_TEMPS
  166117. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166118. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166119. /* Emit restart marker if needed */
  166120. if (cinfo->restart_interval)
  166121. if (entropy->restarts_to_go == 0)
  166122. emit_restart_p(entropy, entropy->next_restart_num);
  166123. /* Encode the MCU data blocks */
  166124. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166125. block = MCU_data[blkn];
  166126. ci = cinfo->MCU_membership[blkn];
  166127. compptr = cinfo->cur_comp_info[ci];
  166128. /* Compute the DC value after the required point transform by Al.
  166129. * This is simply an arithmetic right shift.
  166130. */
  166131. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166132. /* DC differences are figured on the point-transformed values. */
  166133. temp = temp2 - entropy->last_dc_val[ci];
  166134. entropy->last_dc_val[ci] = temp2;
  166135. /* Encode the DC coefficient difference per section G.1.2.1 */
  166136. temp2 = temp;
  166137. if (temp < 0) {
  166138. temp = -temp; /* temp is abs value of input */
  166139. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166140. /* This code assumes we are on a two's complement machine */
  166141. temp2--;
  166142. }
  166143. /* Find the number of bits needed for the magnitude of the coefficient */
  166144. nbits = 0;
  166145. while (temp) {
  166146. nbits++;
  166147. temp >>= 1;
  166148. }
  166149. /* Check for out-of-range coefficient values.
  166150. * Since we're encoding a difference, the range limit is twice as much.
  166151. */
  166152. if (nbits > MAX_COEF_BITS+1)
  166153. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166154. /* Count/emit the Huffman-coded symbol for the number of bits */
  166155. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166156. /* Emit that number of bits of the value, if positive, */
  166157. /* or the complement of its magnitude, if negative. */
  166158. if (nbits) /* emit_bits rejects calls with size 0 */
  166159. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166160. }
  166161. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166162. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166163. /* Update restart-interval state too */
  166164. if (cinfo->restart_interval) {
  166165. if (entropy->restarts_to_go == 0) {
  166166. entropy->restarts_to_go = cinfo->restart_interval;
  166167. entropy->next_restart_num++;
  166168. entropy->next_restart_num &= 7;
  166169. }
  166170. entropy->restarts_to_go--;
  166171. }
  166172. return TRUE;
  166173. }
  166174. /*
  166175. * MCU encoding for AC initial scan (either spectral selection,
  166176. * or first pass of successive approximation).
  166177. */
  166178. METHODDEF(boolean)
  166179. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166180. {
  166181. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166182. register int temp, temp2;
  166183. register int nbits;
  166184. register int r, k;
  166185. int Se = cinfo->Se;
  166186. int Al = cinfo->Al;
  166187. JBLOCKROW block;
  166188. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166189. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166190. /* Emit restart marker if needed */
  166191. if (cinfo->restart_interval)
  166192. if (entropy->restarts_to_go == 0)
  166193. emit_restart_p(entropy, entropy->next_restart_num);
  166194. /* Encode the MCU data block */
  166195. block = MCU_data[0];
  166196. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166197. r = 0; /* r = run length of zeros */
  166198. for (k = cinfo->Ss; k <= Se; k++) {
  166199. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166200. r++;
  166201. continue;
  166202. }
  166203. /* We must apply the point transform by Al. For AC coefficients this
  166204. * is an integer division with rounding towards 0. To do this portably
  166205. * in C, we shift after obtaining the absolute value; so the code is
  166206. * interwoven with finding the abs value (temp) and output bits (temp2).
  166207. */
  166208. if (temp < 0) {
  166209. temp = -temp; /* temp is abs value of input */
  166210. temp >>= Al; /* apply the point transform */
  166211. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166212. temp2 = ~temp;
  166213. } else {
  166214. temp >>= Al; /* apply the point transform */
  166215. temp2 = temp;
  166216. }
  166217. /* Watch out for case that nonzero coef is zero after point transform */
  166218. if (temp == 0) {
  166219. r++;
  166220. continue;
  166221. }
  166222. /* Emit any pending EOBRUN */
  166223. if (entropy->EOBRUN > 0)
  166224. emit_eobrun(entropy);
  166225. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166226. while (r > 15) {
  166227. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166228. r -= 16;
  166229. }
  166230. /* Find the number of bits needed for the magnitude of the coefficient */
  166231. nbits = 1; /* there must be at least one 1 bit */
  166232. while ((temp >>= 1))
  166233. nbits++;
  166234. /* Check for out-of-range coefficient values */
  166235. if (nbits > MAX_COEF_BITS)
  166236. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166237. /* Count/emit Huffman symbol for run length / number of bits */
  166238. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166239. /* Emit that number of bits of the value, if positive, */
  166240. /* or the complement of its magnitude, if negative. */
  166241. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166242. r = 0; /* reset zero run length */
  166243. }
  166244. if (r > 0) { /* If there are trailing zeroes, */
  166245. entropy->EOBRUN++; /* count an EOB */
  166246. if (entropy->EOBRUN == 0x7FFF)
  166247. emit_eobrun(entropy); /* force it out to avoid overflow */
  166248. }
  166249. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166250. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166251. /* Update restart-interval state too */
  166252. if (cinfo->restart_interval) {
  166253. if (entropy->restarts_to_go == 0) {
  166254. entropy->restarts_to_go = cinfo->restart_interval;
  166255. entropy->next_restart_num++;
  166256. entropy->next_restart_num &= 7;
  166257. }
  166258. entropy->restarts_to_go--;
  166259. }
  166260. return TRUE;
  166261. }
  166262. /*
  166263. * MCU encoding for DC successive approximation refinement scan.
  166264. * Note: we assume such scans can be multi-component, although the spec
  166265. * is not very clear on the point.
  166266. */
  166267. METHODDEF(boolean)
  166268. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166269. {
  166270. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166271. register int temp;
  166272. int blkn;
  166273. int Al = cinfo->Al;
  166274. JBLOCKROW block;
  166275. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166276. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166277. /* Emit restart marker if needed */
  166278. if (cinfo->restart_interval)
  166279. if (entropy->restarts_to_go == 0)
  166280. emit_restart_p(entropy, entropy->next_restart_num);
  166281. /* Encode the MCU data blocks */
  166282. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166283. block = MCU_data[blkn];
  166284. /* We simply emit the Al'th bit of the DC coefficient value. */
  166285. temp = (*block)[0];
  166286. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166287. }
  166288. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166289. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166290. /* Update restart-interval state too */
  166291. if (cinfo->restart_interval) {
  166292. if (entropy->restarts_to_go == 0) {
  166293. entropy->restarts_to_go = cinfo->restart_interval;
  166294. entropy->next_restart_num++;
  166295. entropy->next_restart_num &= 7;
  166296. }
  166297. entropy->restarts_to_go--;
  166298. }
  166299. return TRUE;
  166300. }
  166301. /*
  166302. * MCU encoding for AC successive approximation refinement scan.
  166303. */
  166304. METHODDEF(boolean)
  166305. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166306. {
  166307. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166308. register int temp;
  166309. register int r, k;
  166310. int EOB;
  166311. char *BR_buffer;
  166312. unsigned int BR;
  166313. int Se = cinfo->Se;
  166314. int Al = cinfo->Al;
  166315. JBLOCKROW block;
  166316. int absvalues[DCTSIZE2];
  166317. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166318. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166319. /* Emit restart marker if needed */
  166320. if (cinfo->restart_interval)
  166321. if (entropy->restarts_to_go == 0)
  166322. emit_restart_p(entropy, entropy->next_restart_num);
  166323. /* Encode the MCU data block */
  166324. block = MCU_data[0];
  166325. /* It is convenient to make a pre-pass to determine the transformed
  166326. * coefficients' absolute values and the EOB position.
  166327. */
  166328. EOB = 0;
  166329. for (k = cinfo->Ss; k <= Se; k++) {
  166330. temp = (*block)[jpeg_natural_order[k]];
  166331. /* We must apply the point transform by Al. For AC coefficients this
  166332. * is an integer division with rounding towards 0. To do this portably
  166333. * in C, we shift after obtaining the absolute value.
  166334. */
  166335. if (temp < 0)
  166336. temp = -temp; /* temp is abs value of input */
  166337. temp >>= Al; /* apply the point transform */
  166338. absvalues[k] = temp; /* save abs value for main pass */
  166339. if (temp == 1)
  166340. EOB = k; /* EOB = index of last newly-nonzero coef */
  166341. }
  166342. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166343. r = 0; /* r = run length of zeros */
  166344. BR = 0; /* BR = count of buffered bits added now */
  166345. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166346. for (k = cinfo->Ss; k <= Se; k++) {
  166347. if ((temp = absvalues[k]) == 0) {
  166348. r++;
  166349. continue;
  166350. }
  166351. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166352. while (r > 15 && k <= EOB) {
  166353. /* emit any pending EOBRUN and the BE correction bits */
  166354. emit_eobrun(entropy);
  166355. /* Emit ZRL */
  166356. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166357. r -= 16;
  166358. /* Emit buffered correction bits that must be associated with ZRL */
  166359. emit_buffered_bits(entropy, BR_buffer, BR);
  166360. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166361. BR = 0;
  166362. }
  166363. /* If the coef was previously nonzero, it only needs a correction bit.
  166364. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166365. * that we also need to test r > 15. But if r > 15, we can only get here
  166366. * if k > EOB, which implies that this coefficient is not 1.
  166367. */
  166368. if (temp > 1) {
  166369. /* The correction bit is the next bit of the absolute value. */
  166370. BR_buffer[BR++] = (char) (temp & 1);
  166371. continue;
  166372. }
  166373. /* Emit any pending EOBRUN and the BE correction bits */
  166374. emit_eobrun(entropy);
  166375. /* Count/emit Huffman symbol for run length / number of bits */
  166376. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166377. /* Emit output bit for newly-nonzero coef */
  166378. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166379. emit_bits_p(entropy, (unsigned int) temp, 1);
  166380. /* Emit buffered correction bits that must be associated with this code */
  166381. emit_buffered_bits(entropy, BR_buffer, BR);
  166382. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166383. BR = 0;
  166384. r = 0; /* reset zero run length */
  166385. }
  166386. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166387. entropy->EOBRUN++; /* count an EOB */
  166388. entropy->BE += BR; /* concat my correction bits to older ones */
  166389. /* We force out the EOB if we risk either:
  166390. * 1. overflow of the EOB counter;
  166391. * 2. overflow of the correction bit buffer during the next MCU.
  166392. */
  166393. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166394. emit_eobrun(entropy);
  166395. }
  166396. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166397. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166398. /* Update restart-interval state too */
  166399. if (cinfo->restart_interval) {
  166400. if (entropy->restarts_to_go == 0) {
  166401. entropy->restarts_to_go = cinfo->restart_interval;
  166402. entropy->next_restart_num++;
  166403. entropy->next_restart_num &= 7;
  166404. }
  166405. entropy->restarts_to_go--;
  166406. }
  166407. return TRUE;
  166408. }
  166409. /*
  166410. * Finish up at the end of a Huffman-compressed progressive scan.
  166411. */
  166412. METHODDEF(void)
  166413. finish_pass_phuff (j_compress_ptr cinfo)
  166414. {
  166415. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166416. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166417. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166418. /* Flush out any buffered data */
  166419. emit_eobrun(entropy);
  166420. flush_bits_p(entropy);
  166421. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166422. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166423. }
  166424. /*
  166425. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166426. */
  166427. METHODDEF(void)
  166428. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166429. {
  166430. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166431. boolean is_DC_band;
  166432. int ci, tbl;
  166433. jpeg_component_info * compptr;
  166434. JHUFF_TBL **htblptr;
  166435. boolean did[NUM_HUFF_TBLS];
  166436. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166437. emit_eobrun(entropy);
  166438. is_DC_band = (cinfo->Ss == 0);
  166439. /* It's important not to apply jpeg_gen_optimal_table more than once
  166440. * per table, because it clobbers the input frequency counts!
  166441. */
  166442. MEMZERO(did, SIZEOF(did));
  166443. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166444. compptr = cinfo->cur_comp_info[ci];
  166445. if (is_DC_band) {
  166446. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166447. continue;
  166448. tbl = compptr->dc_tbl_no;
  166449. } else {
  166450. tbl = compptr->ac_tbl_no;
  166451. }
  166452. if (! did[tbl]) {
  166453. if (is_DC_band)
  166454. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166455. else
  166456. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166457. if (*htblptr == NULL)
  166458. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166459. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166460. did[tbl] = TRUE;
  166461. }
  166462. }
  166463. }
  166464. /*
  166465. * Module initialization routine for progressive Huffman entropy encoding.
  166466. */
  166467. GLOBAL(void)
  166468. jinit_phuff_encoder (j_compress_ptr cinfo)
  166469. {
  166470. phuff_entropy_ptr entropy;
  166471. int i;
  166472. entropy = (phuff_entropy_ptr)
  166473. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166474. SIZEOF(phuff_entropy_encoder));
  166475. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166476. entropy->pub.start_pass = start_pass_phuff;
  166477. /* Mark tables unallocated */
  166478. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166479. entropy->derived_tbls[i] = NULL;
  166480. entropy->count_ptrs[i] = NULL;
  166481. }
  166482. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166483. }
  166484. #endif /* C_PROGRESSIVE_SUPPORTED */
  166485. /*** End of inlined file: jcphuff.c ***/
  166486. /*** Start of inlined file: jcprepct.c ***/
  166487. #define JPEG_INTERNALS
  166488. /* At present, jcsample.c can request context rows only for smoothing.
  166489. * In the future, we might also need context rows for CCIR601 sampling
  166490. * or other more-complex downsampling procedures. The code to support
  166491. * context rows should be compiled only if needed.
  166492. */
  166493. #ifdef INPUT_SMOOTHING_SUPPORTED
  166494. #define CONTEXT_ROWS_SUPPORTED
  166495. #endif
  166496. /*
  166497. * For the simple (no-context-row) case, we just need to buffer one
  166498. * row group's worth of pixels for the downsampling step. At the bottom of
  166499. * the image, we pad to a full row group by replicating the last pixel row.
  166500. * The downsampler's last output row is then replicated if needed to pad
  166501. * out to a full iMCU row.
  166502. *
  166503. * When providing context rows, we must buffer three row groups' worth of
  166504. * pixels. Three row groups are physically allocated, but the row pointer
  166505. * arrays are made five row groups high, with the extra pointers above and
  166506. * below "wrapping around" to point to the last and first real row groups.
  166507. * This allows the downsampler to access the proper context rows.
  166508. * At the top and bottom of the image, we create dummy context rows by
  166509. * copying the first or last real pixel row. This copying could be avoided
  166510. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166511. * trouble on the compression side.
  166512. */
  166513. /* Private buffer controller object */
  166514. typedef struct {
  166515. struct jpeg_c_prep_controller pub; /* public fields */
  166516. /* Downsampling input buffer. This buffer holds color-converted data
  166517. * until we have enough to do a downsample step.
  166518. */
  166519. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166520. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166521. int next_buf_row; /* index of next row to store in color_buf */
  166522. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166523. int this_row_group; /* starting row index of group to process */
  166524. int next_buf_stop; /* downsample when we reach this index */
  166525. #endif
  166526. } my_prep_controller;
  166527. typedef my_prep_controller * my_prep_ptr;
  166528. /*
  166529. * Initialize for a processing pass.
  166530. */
  166531. METHODDEF(void)
  166532. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166533. {
  166534. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166535. if (pass_mode != JBUF_PASS_THRU)
  166536. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166537. /* Initialize total-height counter for detecting bottom of image */
  166538. prep->rows_to_go = cinfo->image_height;
  166539. /* Mark the conversion buffer empty */
  166540. prep->next_buf_row = 0;
  166541. #ifdef CONTEXT_ROWS_SUPPORTED
  166542. /* Preset additional state variables for context mode.
  166543. * These aren't used in non-context mode, so we needn't test which mode.
  166544. */
  166545. prep->this_row_group = 0;
  166546. /* Set next_buf_stop to stop after two row groups have been read in. */
  166547. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166548. #endif
  166549. }
  166550. /*
  166551. * Expand an image vertically from height input_rows to height output_rows,
  166552. * by duplicating the bottom row.
  166553. */
  166554. LOCAL(void)
  166555. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166556. int input_rows, int output_rows)
  166557. {
  166558. register int row;
  166559. for (row = input_rows; row < output_rows; row++) {
  166560. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166561. 1, num_cols);
  166562. }
  166563. }
  166564. /*
  166565. * Process some data in the simple no-context case.
  166566. *
  166567. * Preprocessor output data is counted in "row groups". A row group
  166568. * is defined to be v_samp_factor sample rows of each component.
  166569. * Downsampling will produce this much data from each max_v_samp_factor
  166570. * input rows.
  166571. */
  166572. METHODDEF(void)
  166573. pre_process_data (j_compress_ptr cinfo,
  166574. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166575. JDIMENSION in_rows_avail,
  166576. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166577. JDIMENSION out_row_groups_avail)
  166578. {
  166579. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166580. int numrows, ci;
  166581. JDIMENSION inrows;
  166582. jpeg_component_info * compptr;
  166583. while (*in_row_ctr < in_rows_avail &&
  166584. *out_row_group_ctr < out_row_groups_avail) {
  166585. /* Do color conversion to fill the conversion buffer. */
  166586. inrows = in_rows_avail - *in_row_ctr;
  166587. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166588. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166589. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166590. prep->color_buf,
  166591. (JDIMENSION) prep->next_buf_row,
  166592. numrows);
  166593. *in_row_ctr += numrows;
  166594. prep->next_buf_row += numrows;
  166595. prep->rows_to_go -= numrows;
  166596. /* If at bottom of image, pad to fill the conversion buffer. */
  166597. if (prep->rows_to_go == 0 &&
  166598. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166599. for (ci = 0; ci < cinfo->num_components; ci++) {
  166600. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166601. prep->next_buf_row, cinfo->max_v_samp_factor);
  166602. }
  166603. prep->next_buf_row = cinfo->max_v_samp_factor;
  166604. }
  166605. /* If we've filled the conversion buffer, empty it. */
  166606. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166607. (*cinfo->downsample->downsample) (cinfo,
  166608. prep->color_buf, (JDIMENSION) 0,
  166609. output_buf, *out_row_group_ctr);
  166610. prep->next_buf_row = 0;
  166611. (*out_row_group_ctr)++;
  166612. }
  166613. /* If at bottom of image, pad the output to a full iMCU height.
  166614. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166615. */
  166616. if (prep->rows_to_go == 0 &&
  166617. *out_row_group_ctr < out_row_groups_avail) {
  166618. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166619. ci++, compptr++) {
  166620. expand_bottom_edge(output_buf[ci],
  166621. compptr->width_in_blocks * DCTSIZE,
  166622. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166623. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166624. }
  166625. *out_row_group_ctr = out_row_groups_avail;
  166626. break; /* can exit outer loop without test */
  166627. }
  166628. }
  166629. }
  166630. #ifdef CONTEXT_ROWS_SUPPORTED
  166631. /*
  166632. * Process some data in the context case.
  166633. */
  166634. METHODDEF(void)
  166635. pre_process_context (j_compress_ptr cinfo,
  166636. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166637. JDIMENSION in_rows_avail,
  166638. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166639. JDIMENSION out_row_groups_avail)
  166640. {
  166641. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166642. int numrows, ci;
  166643. int buf_height = cinfo->max_v_samp_factor * 3;
  166644. JDIMENSION inrows;
  166645. while (*out_row_group_ctr < out_row_groups_avail) {
  166646. if (*in_row_ctr < in_rows_avail) {
  166647. /* Do color conversion to fill the conversion buffer. */
  166648. inrows = in_rows_avail - *in_row_ctr;
  166649. numrows = prep->next_buf_stop - prep->next_buf_row;
  166650. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166651. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166652. prep->color_buf,
  166653. (JDIMENSION) prep->next_buf_row,
  166654. numrows);
  166655. /* Pad at top of image, if first time through */
  166656. if (prep->rows_to_go == cinfo->image_height) {
  166657. for (ci = 0; ci < cinfo->num_components; ci++) {
  166658. int row;
  166659. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166660. jcopy_sample_rows(prep->color_buf[ci], 0,
  166661. prep->color_buf[ci], -row,
  166662. 1, cinfo->image_width);
  166663. }
  166664. }
  166665. }
  166666. *in_row_ctr += numrows;
  166667. prep->next_buf_row += numrows;
  166668. prep->rows_to_go -= numrows;
  166669. } else {
  166670. /* Return for more data, unless we are at the bottom of the image. */
  166671. if (prep->rows_to_go != 0)
  166672. break;
  166673. /* When at bottom of image, pad to fill the conversion buffer. */
  166674. if (prep->next_buf_row < prep->next_buf_stop) {
  166675. for (ci = 0; ci < cinfo->num_components; ci++) {
  166676. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166677. prep->next_buf_row, prep->next_buf_stop);
  166678. }
  166679. prep->next_buf_row = prep->next_buf_stop;
  166680. }
  166681. }
  166682. /* If we've gotten enough data, downsample a row group. */
  166683. if (prep->next_buf_row == prep->next_buf_stop) {
  166684. (*cinfo->downsample->downsample) (cinfo,
  166685. prep->color_buf,
  166686. (JDIMENSION) prep->this_row_group,
  166687. output_buf, *out_row_group_ctr);
  166688. (*out_row_group_ctr)++;
  166689. /* Advance pointers with wraparound as necessary. */
  166690. prep->this_row_group += cinfo->max_v_samp_factor;
  166691. if (prep->this_row_group >= buf_height)
  166692. prep->this_row_group = 0;
  166693. if (prep->next_buf_row >= buf_height)
  166694. prep->next_buf_row = 0;
  166695. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166696. }
  166697. }
  166698. }
  166699. /*
  166700. * Create the wrapped-around downsampling input buffer needed for context mode.
  166701. */
  166702. LOCAL(void)
  166703. create_context_buffer (j_compress_ptr cinfo)
  166704. {
  166705. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166706. int rgroup_height = cinfo->max_v_samp_factor;
  166707. int ci, i;
  166708. jpeg_component_info * compptr;
  166709. JSAMPARRAY true_buffer, fake_buffer;
  166710. /* Grab enough space for fake row pointers for all the components;
  166711. * we need five row groups' worth of pointers for each component.
  166712. */
  166713. fake_buffer = (JSAMPARRAY)
  166714. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166715. (cinfo->num_components * 5 * rgroup_height) *
  166716. SIZEOF(JSAMPROW));
  166717. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166718. ci++, compptr++) {
  166719. /* Allocate the actual buffer space (3 row groups) for this component.
  166720. * We make the buffer wide enough to allow the downsampler to edge-expand
  166721. * horizontally within the buffer, if it so chooses.
  166722. */
  166723. true_buffer = (*cinfo->mem->alloc_sarray)
  166724. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166725. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166726. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166727. (JDIMENSION) (3 * rgroup_height));
  166728. /* Copy true buffer row pointers into the middle of the fake row array */
  166729. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166730. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166731. /* Fill in the above and below wraparound pointers */
  166732. for (i = 0; i < rgroup_height; i++) {
  166733. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166734. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166735. }
  166736. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166737. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166738. }
  166739. }
  166740. #endif /* CONTEXT_ROWS_SUPPORTED */
  166741. /*
  166742. * Initialize preprocessing controller.
  166743. */
  166744. GLOBAL(void)
  166745. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166746. {
  166747. my_prep_ptr prep;
  166748. int ci;
  166749. jpeg_component_info * compptr;
  166750. if (need_full_buffer) /* safety check */
  166751. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166752. prep = (my_prep_ptr)
  166753. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166754. SIZEOF(my_prep_controller));
  166755. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166756. prep->pub.start_pass = start_pass_prep;
  166757. /* Allocate the color conversion buffer.
  166758. * We make the buffer wide enough to allow the downsampler to edge-expand
  166759. * horizontally within the buffer, if it so chooses.
  166760. */
  166761. if (cinfo->downsample->need_context_rows) {
  166762. /* Set up to provide context rows */
  166763. #ifdef CONTEXT_ROWS_SUPPORTED
  166764. prep->pub.pre_process_data = pre_process_context;
  166765. create_context_buffer(cinfo);
  166766. #else
  166767. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166768. #endif
  166769. } else {
  166770. /* No context, just make it tall enough for one row group */
  166771. prep->pub.pre_process_data = pre_process_data;
  166772. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166773. ci++, compptr++) {
  166774. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166775. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166776. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166777. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166778. (JDIMENSION) cinfo->max_v_samp_factor);
  166779. }
  166780. }
  166781. }
  166782. /*** End of inlined file: jcprepct.c ***/
  166783. /*** Start of inlined file: jcsample.c ***/
  166784. #define JPEG_INTERNALS
  166785. /* Pointer to routine to downsample a single component */
  166786. typedef JMETHOD(void, downsample1_ptr,
  166787. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166788. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166789. /* Private subobject */
  166790. typedef struct {
  166791. struct jpeg_downsampler pub; /* public fields */
  166792. /* Downsampling method pointers, one per component */
  166793. downsample1_ptr methods[MAX_COMPONENTS];
  166794. } my_downsampler;
  166795. typedef my_downsampler * my_downsample_ptr;
  166796. /*
  166797. * Initialize for a downsampling pass.
  166798. */
  166799. METHODDEF(void)
  166800. start_pass_downsample (j_compress_ptr)
  166801. {
  166802. /* no work for now */
  166803. }
  166804. /*
  166805. * Expand a component horizontally from width input_cols to width output_cols,
  166806. * by duplicating the rightmost samples.
  166807. */
  166808. LOCAL(void)
  166809. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166810. JDIMENSION input_cols, JDIMENSION output_cols)
  166811. {
  166812. register JSAMPROW ptr;
  166813. register JSAMPLE pixval;
  166814. register int count;
  166815. int row;
  166816. int numcols = (int) (output_cols - input_cols);
  166817. if (numcols > 0) {
  166818. for (row = 0; row < num_rows; row++) {
  166819. ptr = image_data[row] + input_cols;
  166820. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166821. for (count = numcols; count > 0; count--)
  166822. *ptr++ = pixval;
  166823. }
  166824. }
  166825. }
  166826. /*
  166827. * Do downsampling for a whole row group (all components).
  166828. *
  166829. * In this version we simply downsample each component independently.
  166830. */
  166831. METHODDEF(void)
  166832. sep_downsample (j_compress_ptr cinfo,
  166833. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166834. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166835. {
  166836. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166837. int ci;
  166838. jpeg_component_info * compptr;
  166839. JSAMPARRAY in_ptr, out_ptr;
  166840. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166841. ci++, compptr++) {
  166842. in_ptr = input_buf[ci] + in_row_index;
  166843. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166844. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166845. }
  166846. }
  166847. /*
  166848. * Downsample pixel values of a single component.
  166849. * One row group is processed per call.
  166850. * This version handles arbitrary integral sampling ratios, without smoothing.
  166851. * Note that this version is not actually used for customary sampling ratios.
  166852. */
  166853. METHODDEF(void)
  166854. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166855. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166856. {
  166857. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166858. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166859. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166860. JSAMPROW inptr, outptr;
  166861. INT32 outvalue;
  166862. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166863. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166864. numpix = h_expand * v_expand;
  166865. numpix2 = numpix/2;
  166866. /* Expand input data enough to let all the output samples be generated
  166867. * by the standard loop. Special-casing padded output would be more
  166868. * efficient.
  166869. */
  166870. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166871. cinfo->image_width, output_cols * h_expand);
  166872. inrow = 0;
  166873. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166874. outptr = output_data[outrow];
  166875. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166876. outcol++, outcol_h += h_expand) {
  166877. outvalue = 0;
  166878. for (v = 0; v < v_expand; v++) {
  166879. inptr = input_data[inrow+v] + outcol_h;
  166880. for (h = 0; h < h_expand; h++) {
  166881. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166882. }
  166883. }
  166884. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166885. }
  166886. inrow += v_expand;
  166887. }
  166888. }
  166889. /*
  166890. * Downsample pixel values of a single component.
  166891. * This version handles the special case of a full-size component,
  166892. * without smoothing.
  166893. */
  166894. METHODDEF(void)
  166895. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166896. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166897. {
  166898. /* Copy the data */
  166899. jcopy_sample_rows(input_data, 0, output_data, 0,
  166900. cinfo->max_v_samp_factor, cinfo->image_width);
  166901. /* Edge-expand */
  166902. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166903. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166904. }
  166905. /*
  166906. * Downsample pixel values of a single component.
  166907. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166908. * without smoothing.
  166909. *
  166910. * A note about the "bias" calculations: when rounding fractional values to
  166911. * integer, we do not want to always round 0.5 up to the next integer.
  166912. * If we did that, we'd introduce a noticeable bias towards larger values.
  166913. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166914. * alternate pixel locations (a simple ordered dither pattern).
  166915. */
  166916. METHODDEF(void)
  166917. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166918. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166919. {
  166920. int outrow;
  166921. JDIMENSION outcol;
  166922. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166923. register JSAMPROW inptr, outptr;
  166924. register int bias;
  166925. /* Expand input data enough to let all the output samples be generated
  166926. * by the standard loop. Special-casing padded output would be more
  166927. * efficient.
  166928. */
  166929. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166930. cinfo->image_width, output_cols * 2);
  166931. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166932. outptr = output_data[outrow];
  166933. inptr = input_data[outrow];
  166934. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166935. for (outcol = 0; outcol < output_cols; outcol++) {
  166936. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166937. + bias) >> 1);
  166938. bias ^= 1; /* 0=>1, 1=>0 */
  166939. inptr += 2;
  166940. }
  166941. }
  166942. }
  166943. /*
  166944. * Downsample pixel values of a single component.
  166945. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166946. * without smoothing.
  166947. */
  166948. METHODDEF(void)
  166949. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166950. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166951. {
  166952. int inrow, outrow;
  166953. JDIMENSION outcol;
  166954. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166955. register JSAMPROW inptr0, inptr1, outptr;
  166956. register int bias;
  166957. /* Expand input data enough to let all the output samples be generated
  166958. * by the standard loop. Special-casing padded output would be more
  166959. * efficient.
  166960. */
  166961. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166962. cinfo->image_width, output_cols * 2);
  166963. inrow = 0;
  166964. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166965. outptr = output_data[outrow];
  166966. inptr0 = input_data[inrow];
  166967. inptr1 = input_data[inrow+1];
  166968. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166969. for (outcol = 0; outcol < output_cols; outcol++) {
  166970. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166971. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166972. + bias) >> 2);
  166973. bias ^= 3; /* 1=>2, 2=>1 */
  166974. inptr0 += 2; inptr1 += 2;
  166975. }
  166976. inrow += 2;
  166977. }
  166978. }
  166979. #ifdef INPUT_SMOOTHING_SUPPORTED
  166980. /*
  166981. * Downsample pixel values of a single component.
  166982. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166983. * with smoothing. One row of context is required.
  166984. */
  166985. METHODDEF(void)
  166986. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166987. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166988. {
  166989. int inrow, outrow;
  166990. JDIMENSION colctr;
  166991. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166992. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166993. INT32 membersum, neighsum, memberscale, neighscale;
  166994. /* Expand input data enough to let all the output samples be generated
  166995. * by the standard loop. Special-casing padded output would be more
  166996. * efficient.
  166997. */
  166998. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166999. cinfo->image_width, output_cols * 2);
  167000. /* We don't bother to form the individual "smoothed" input pixel values;
  167001. * we can directly compute the output which is the average of the four
  167002. * smoothed values. Each of the four member pixels contributes a fraction
  167003. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167004. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167005. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167006. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167007. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167008. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167009. * factors are scaled by 2^16 = 65536.
  167010. * Also recall that SF = smoothing_factor / 1024.
  167011. */
  167012. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167013. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167014. inrow = 0;
  167015. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167016. outptr = output_data[outrow];
  167017. inptr0 = input_data[inrow];
  167018. inptr1 = input_data[inrow+1];
  167019. above_ptr = input_data[inrow-1];
  167020. below_ptr = input_data[inrow+2];
  167021. /* Special case for first column: pretend column -1 is same as column 0 */
  167022. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167023. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167024. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167025. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167026. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167027. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167028. neighsum += neighsum;
  167029. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167030. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167031. membersum = membersum * memberscale + neighsum * neighscale;
  167032. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167033. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167034. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167035. /* sum of pixels directly mapped to this output element */
  167036. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167037. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167038. /* sum of edge-neighbor pixels */
  167039. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167040. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167041. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167042. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167043. /* The edge-neighbors count twice as much as corner-neighbors */
  167044. neighsum += neighsum;
  167045. /* Add in the corner-neighbors */
  167046. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167047. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167048. /* form final output scaled up by 2^16 */
  167049. membersum = membersum * memberscale + neighsum * neighscale;
  167050. /* round, descale and output it */
  167051. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167052. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167053. }
  167054. /* Special case for last column */
  167055. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167056. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167057. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167058. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167059. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167060. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167061. neighsum += neighsum;
  167062. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167063. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167064. membersum = membersum * memberscale + neighsum * neighscale;
  167065. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167066. inrow += 2;
  167067. }
  167068. }
  167069. /*
  167070. * Downsample pixel values of a single component.
  167071. * This version handles the special case of a full-size component,
  167072. * with smoothing. One row of context is required.
  167073. */
  167074. METHODDEF(void)
  167075. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167076. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167077. {
  167078. int outrow;
  167079. JDIMENSION colctr;
  167080. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167081. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167082. INT32 membersum, neighsum, memberscale, neighscale;
  167083. int colsum, lastcolsum, nextcolsum;
  167084. /* Expand input data enough to let all the output samples be generated
  167085. * by the standard loop. Special-casing padded output would be more
  167086. * efficient.
  167087. */
  167088. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167089. cinfo->image_width, output_cols);
  167090. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167091. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167092. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167093. * Also recall that SF = smoothing_factor / 1024.
  167094. */
  167095. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167096. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167097. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167098. outptr = output_data[outrow];
  167099. inptr = input_data[outrow];
  167100. above_ptr = input_data[outrow-1];
  167101. below_ptr = input_data[outrow+1];
  167102. /* Special case for first column */
  167103. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167104. GETJSAMPLE(*inptr);
  167105. membersum = GETJSAMPLE(*inptr++);
  167106. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167107. GETJSAMPLE(*inptr);
  167108. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167109. membersum = membersum * memberscale + neighsum * neighscale;
  167110. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167111. lastcolsum = colsum; colsum = nextcolsum;
  167112. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167113. membersum = GETJSAMPLE(*inptr++);
  167114. above_ptr++; below_ptr++;
  167115. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167116. GETJSAMPLE(*inptr);
  167117. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167118. membersum = membersum * memberscale + neighsum * neighscale;
  167119. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167120. lastcolsum = colsum; colsum = nextcolsum;
  167121. }
  167122. /* Special case for last column */
  167123. membersum = GETJSAMPLE(*inptr);
  167124. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167125. membersum = membersum * memberscale + neighsum * neighscale;
  167126. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167127. }
  167128. }
  167129. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167130. /*
  167131. * Module initialization routine for downsampling.
  167132. * Note that we must select a routine for each component.
  167133. */
  167134. GLOBAL(void)
  167135. jinit_downsampler (j_compress_ptr cinfo)
  167136. {
  167137. my_downsample_ptr downsample;
  167138. int ci;
  167139. jpeg_component_info * compptr;
  167140. boolean smoothok = TRUE;
  167141. downsample = (my_downsample_ptr)
  167142. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167143. SIZEOF(my_downsampler));
  167144. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167145. downsample->pub.start_pass = start_pass_downsample;
  167146. downsample->pub.downsample = sep_downsample;
  167147. downsample->pub.need_context_rows = FALSE;
  167148. if (cinfo->CCIR601_sampling)
  167149. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167150. /* Verify we can handle the sampling factors, and set up method pointers */
  167151. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167152. ci++, compptr++) {
  167153. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167154. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167155. #ifdef INPUT_SMOOTHING_SUPPORTED
  167156. if (cinfo->smoothing_factor) {
  167157. downsample->methods[ci] = fullsize_smooth_downsample;
  167158. downsample->pub.need_context_rows = TRUE;
  167159. } else
  167160. #endif
  167161. downsample->methods[ci] = fullsize_downsample;
  167162. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167163. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167164. smoothok = FALSE;
  167165. downsample->methods[ci] = h2v1_downsample;
  167166. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167167. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167168. #ifdef INPUT_SMOOTHING_SUPPORTED
  167169. if (cinfo->smoothing_factor) {
  167170. downsample->methods[ci] = h2v2_smooth_downsample;
  167171. downsample->pub.need_context_rows = TRUE;
  167172. } else
  167173. #endif
  167174. downsample->methods[ci] = h2v2_downsample;
  167175. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167176. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167177. smoothok = FALSE;
  167178. downsample->methods[ci] = int_downsample;
  167179. } else
  167180. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167181. }
  167182. #ifdef INPUT_SMOOTHING_SUPPORTED
  167183. if (cinfo->smoothing_factor && !smoothok)
  167184. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167185. #endif
  167186. }
  167187. /*** End of inlined file: jcsample.c ***/
  167188. /*** Start of inlined file: jctrans.c ***/
  167189. #define JPEG_INTERNALS
  167190. /* Forward declarations */
  167191. LOCAL(void) transencode_master_selection
  167192. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167193. LOCAL(void) transencode_coef_controller
  167194. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167195. /*
  167196. * Compression initialization for writing raw-coefficient data.
  167197. * Before calling this, all parameters and a data destination must be set up.
  167198. * Call jpeg_finish_compress() to actually write the data.
  167199. *
  167200. * The number of passed virtual arrays must match cinfo->num_components.
  167201. * Note that the virtual arrays need not be filled or even realized at
  167202. * the time write_coefficients is called; indeed, if the virtual arrays
  167203. * were requested from this compression object's memory manager, they
  167204. * typically will be realized during this routine and filled afterwards.
  167205. */
  167206. GLOBAL(void)
  167207. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167208. {
  167209. if (cinfo->global_state != CSTATE_START)
  167210. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167211. /* Mark all tables to be written */
  167212. jpeg_suppress_tables(cinfo, FALSE);
  167213. /* (Re)initialize error mgr and destination modules */
  167214. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167215. (*cinfo->dest->init_destination) (cinfo);
  167216. /* Perform master selection of active modules */
  167217. transencode_master_selection(cinfo, coef_arrays);
  167218. /* Wait for jpeg_finish_compress() call */
  167219. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167220. cinfo->global_state = CSTATE_WRCOEFS;
  167221. }
  167222. /*
  167223. * Initialize the compression object with default parameters,
  167224. * then copy from the source object all parameters needed for lossless
  167225. * transcoding. Parameters that can be varied without loss (such as
  167226. * scan script and Huffman optimization) are left in their default states.
  167227. */
  167228. GLOBAL(void)
  167229. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167230. j_compress_ptr dstinfo)
  167231. {
  167232. JQUANT_TBL ** qtblptr;
  167233. jpeg_component_info *incomp, *outcomp;
  167234. JQUANT_TBL *c_quant, *slot_quant;
  167235. int tblno, ci, coefi;
  167236. /* Safety check to ensure start_compress not called yet. */
  167237. if (dstinfo->global_state != CSTATE_START)
  167238. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167239. /* Copy fundamental image dimensions */
  167240. dstinfo->image_width = srcinfo->image_width;
  167241. dstinfo->image_height = srcinfo->image_height;
  167242. dstinfo->input_components = srcinfo->num_components;
  167243. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167244. /* Initialize all parameters to default values */
  167245. jpeg_set_defaults(dstinfo);
  167246. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167247. * Fix it to get the right header markers for the image colorspace.
  167248. */
  167249. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167250. dstinfo->data_precision = srcinfo->data_precision;
  167251. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167252. /* Copy the source's quantization tables. */
  167253. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167254. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167255. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167256. if (*qtblptr == NULL)
  167257. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167258. MEMCOPY((*qtblptr)->quantval,
  167259. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167260. SIZEOF((*qtblptr)->quantval));
  167261. (*qtblptr)->sent_table = FALSE;
  167262. }
  167263. }
  167264. /* Copy the source's per-component info.
  167265. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167266. */
  167267. dstinfo->num_components = srcinfo->num_components;
  167268. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167269. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167270. MAX_COMPONENTS);
  167271. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167272. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167273. outcomp->component_id = incomp->component_id;
  167274. outcomp->h_samp_factor = incomp->h_samp_factor;
  167275. outcomp->v_samp_factor = incomp->v_samp_factor;
  167276. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167277. /* Make sure saved quantization table for component matches the qtable
  167278. * slot. If not, the input file re-used this qtable slot.
  167279. * IJG encoder currently cannot duplicate this.
  167280. */
  167281. tblno = outcomp->quant_tbl_no;
  167282. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167283. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167284. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167285. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167286. c_quant = incomp->quant_table;
  167287. if (c_quant != NULL) {
  167288. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167289. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167290. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167291. }
  167292. }
  167293. /* Note: we do not copy the source's Huffman table assignments;
  167294. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167295. */
  167296. }
  167297. /* Also copy JFIF version and resolution information, if available.
  167298. * Strictly speaking this isn't "critical" info, but it's nearly
  167299. * always appropriate to copy it if available. In particular,
  167300. * if the application chooses to copy JFIF 1.02 extension markers from
  167301. * the source file, we need to copy the version to make sure we don't
  167302. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167303. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167304. */
  167305. if (srcinfo->saw_JFIF_marker) {
  167306. if (srcinfo->JFIF_major_version == 1) {
  167307. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167308. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167309. }
  167310. dstinfo->density_unit = srcinfo->density_unit;
  167311. dstinfo->X_density = srcinfo->X_density;
  167312. dstinfo->Y_density = srcinfo->Y_density;
  167313. }
  167314. }
  167315. /*
  167316. * Master selection of compression modules for transcoding.
  167317. * This substitutes for jcinit.c's initialization of the full compressor.
  167318. */
  167319. LOCAL(void)
  167320. transencode_master_selection (j_compress_ptr cinfo,
  167321. jvirt_barray_ptr * coef_arrays)
  167322. {
  167323. /* Although we don't actually use input_components for transcoding,
  167324. * jcmaster.c's initial_setup will complain if input_components is 0.
  167325. */
  167326. cinfo->input_components = 1;
  167327. /* Initialize master control (includes parameter checking/processing) */
  167328. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167329. /* Entropy encoding: either Huffman or arithmetic coding. */
  167330. if (cinfo->arith_code) {
  167331. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167332. } else {
  167333. if (cinfo->progressive_mode) {
  167334. #ifdef C_PROGRESSIVE_SUPPORTED
  167335. jinit_phuff_encoder(cinfo);
  167336. #else
  167337. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167338. #endif
  167339. } else
  167340. jinit_huff_encoder(cinfo);
  167341. }
  167342. /* We need a special coefficient buffer controller. */
  167343. transencode_coef_controller(cinfo, coef_arrays);
  167344. jinit_marker_writer(cinfo);
  167345. /* We can now tell the memory manager to allocate virtual arrays. */
  167346. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167347. /* Write the datastream header (SOI, JFIF) immediately.
  167348. * Frame and scan headers are postponed till later.
  167349. * This lets application insert special markers after the SOI.
  167350. */
  167351. (*cinfo->marker->write_file_header) (cinfo);
  167352. }
  167353. /*
  167354. * The rest of this file is a special implementation of the coefficient
  167355. * buffer controller. This is similar to jccoefct.c, but it handles only
  167356. * output from presupplied virtual arrays. Furthermore, we generate any
  167357. * dummy padding blocks on-the-fly rather than expecting them to be present
  167358. * in the arrays.
  167359. */
  167360. /* Private buffer controller object */
  167361. typedef struct {
  167362. struct jpeg_c_coef_controller pub; /* public fields */
  167363. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167364. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167365. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167366. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167367. /* Virtual block array for each component. */
  167368. jvirt_barray_ptr * whole_image;
  167369. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167370. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167371. } my_coef_controller2;
  167372. typedef my_coef_controller2 * my_coef_ptr2;
  167373. LOCAL(void)
  167374. start_iMCU_row2 (j_compress_ptr cinfo)
  167375. /* Reset within-iMCU-row counters for a new row */
  167376. {
  167377. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167378. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167379. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167380. * But at the bottom of the image, process only what's left.
  167381. */
  167382. if (cinfo->comps_in_scan > 1) {
  167383. coef->MCU_rows_per_iMCU_row = 1;
  167384. } else {
  167385. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167386. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167387. else
  167388. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167389. }
  167390. coef->mcu_ctr = 0;
  167391. coef->MCU_vert_offset = 0;
  167392. }
  167393. /*
  167394. * Initialize for a processing pass.
  167395. */
  167396. METHODDEF(void)
  167397. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167398. {
  167399. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167400. if (pass_mode != JBUF_CRANK_DEST)
  167401. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167402. coef->iMCU_row_num = 0;
  167403. start_iMCU_row2(cinfo);
  167404. }
  167405. /*
  167406. * Process some data.
  167407. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167408. * per call, ie, v_samp_factor block rows for each component in the scan.
  167409. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167410. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167411. *
  167412. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167413. */
  167414. METHODDEF(boolean)
  167415. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167416. {
  167417. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167418. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167419. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167420. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167421. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167422. JDIMENSION start_col;
  167423. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167424. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167425. JBLOCKROW buffer_ptr;
  167426. jpeg_component_info *compptr;
  167427. /* Align the virtual buffers for the components used in this scan. */
  167428. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167429. compptr = cinfo->cur_comp_info[ci];
  167430. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167431. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167432. coef->iMCU_row_num * compptr->v_samp_factor,
  167433. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167434. }
  167435. /* Loop to process one whole iMCU row */
  167436. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167437. yoffset++) {
  167438. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167439. MCU_col_num++) {
  167440. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167441. blkn = 0; /* index of current DCT block within MCU */
  167442. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167443. compptr = cinfo->cur_comp_info[ci];
  167444. start_col = MCU_col_num * compptr->MCU_width;
  167445. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167446. : compptr->last_col_width;
  167447. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167448. if (coef->iMCU_row_num < last_iMCU_row ||
  167449. yindex+yoffset < compptr->last_row_height) {
  167450. /* Fill in pointers to real blocks in this row */
  167451. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167452. for (xindex = 0; xindex < blockcnt; xindex++)
  167453. MCU_buffer[blkn++] = buffer_ptr++;
  167454. } else {
  167455. /* At bottom of image, need a whole row of dummy blocks */
  167456. xindex = 0;
  167457. }
  167458. /* Fill in any dummy blocks needed in this row.
  167459. * Dummy blocks are filled in the same way as in jccoefct.c:
  167460. * all zeroes in the AC entries, DC entries equal to previous
  167461. * block's DC value. The init routine has already zeroed the
  167462. * AC entries, so we need only set the DC entries correctly.
  167463. */
  167464. for (; xindex < compptr->MCU_width; xindex++) {
  167465. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167466. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167467. blkn++;
  167468. }
  167469. }
  167470. }
  167471. /* Try to write the MCU. */
  167472. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167473. /* Suspension forced; update state counters and exit */
  167474. coef->MCU_vert_offset = yoffset;
  167475. coef->mcu_ctr = MCU_col_num;
  167476. return FALSE;
  167477. }
  167478. }
  167479. /* Completed an MCU row, but perhaps not an iMCU row */
  167480. coef->mcu_ctr = 0;
  167481. }
  167482. /* Completed the iMCU row, advance counters for next one */
  167483. coef->iMCU_row_num++;
  167484. start_iMCU_row2(cinfo);
  167485. return TRUE;
  167486. }
  167487. /*
  167488. * Initialize coefficient buffer controller.
  167489. *
  167490. * Each passed coefficient array must be the right size for that
  167491. * coefficient: width_in_blocks wide and height_in_blocks high,
  167492. * with unitheight at least v_samp_factor.
  167493. */
  167494. LOCAL(void)
  167495. transencode_coef_controller (j_compress_ptr cinfo,
  167496. jvirt_barray_ptr * coef_arrays)
  167497. {
  167498. my_coef_ptr2 coef;
  167499. JBLOCKROW buffer;
  167500. int i;
  167501. coef = (my_coef_ptr2)
  167502. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167503. SIZEOF(my_coef_controller2));
  167504. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167505. coef->pub.start_pass = start_pass_coef2;
  167506. coef->pub.compress_data = compress_output2;
  167507. /* Save pointer to virtual arrays */
  167508. coef->whole_image = coef_arrays;
  167509. /* Allocate and pre-zero space for dummy DCT blocks. */
  167510. buffer = (JBLOCKROW)
  167511. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167512. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167513. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167514. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167515. coef->dummy_buffer[i] = buffer + i;
  167516. }
  167517. }
  167518. /*** End of inlined file: jctrans.c ***/
  167519. /*** Start of inlined file: jdapistd.c ***/
  167520. #define JPEG_INTERNALS
  167521. /* Forward declarations */
  167522. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167523. /*
  167524. * Decompression initialization.
  167525. * jpeg_read_header must be completed before calling this.
  167526. *
  167527. * If a multipass operating mode was selected, this will do all but the
  167528. * last pass, and thus may take a great deal of time.
  167529. *
  167530. * Returns FALSE if suspended. The return value need be inspected only if
  167531. * a suspending data source is used.
  167532. */
  167533. GLOBAL(boolean)
  167534. jpeg_start_decompress (j_decompress_ptr cinfo)
  167535. {
  167536. if (cinfo->global_state == DSTATE_READY) {
  167537. /* First call: initialize master control, select active modules */
  167538. jinit_master_decompress(cinfo);
  167539. if (cinfo->buffered_image) {
  167540. /* No more work here; expecting jpeg_start_output next */
  167541. cinfo->global_state = DSTATE_BUFIMAGE;
  167542. return TRUE;
  167543. }
  167544. cinfo->global_state = DSTATE_PRELOAD;
  167545. }
  167546. if (cinfo->global_state == DSTATE_PRELOAD) {
  167547. /* If file has multiple scans, absorb them all into the coef buffer */
  167548. if (cinfo->inputctl->has_multiple_scans) {
  167549. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167550. for (;;) {
  167551. int retcode;
  167552. /* Call progress monitor hook if present */
  167553. if (cinfo->progress != NULL)
  167554. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167555. /* Absorb some more input */
  167556. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167557. if (retcode == JPEG_SUSPENDED)
  167558. return FALSE;
  167559. if (retcode == JPEG_REACHED_EOI)
  167560. break;
  167561. /* Advance progress counter if appropriate */
  167562. if (cinfo->progress != NULL &&
  167563. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167564. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167565. /* jdmaster underestimated number of scans; ratchet up one scan */
  167566. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167567. }
  167568. }
  167569. }
  167570. #else
  167571. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167572. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167573. }
  167574. cinfo->output_scan_number = cinfo->input_scan_number;
  167575. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167576. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167577. /* Perform any dummy output passes, and set up for the final pass */
  167578. return output_pass_setup(cinfo);
  167579. }
  167580. /*
  167581. * Set up for an output pass, and perform any dummy pass(es) needed.
  167582. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167583. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167584. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167585. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167586. */
  167587. LOCAL(boolean)
  167588. output_pass_setup (j_decompress_ptr cinfo)
  167589. {
  167590. if (cinfo->global_state != DSTATE_PRESCAN) {
  167591. /* First call: do pass setup */
  167592. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167593. cinfo->output_scanline = 0;
  167594. cinfo->global_state = DSTATE_PRESCAN;
  167595. }
  167596. /* Loop over any required dummy passes */
  167597. while (cinfo->master->is_dummy_pass) {
  167598. #ifdef QUANT_2PASS_SUPPORTED
  167599. /* Crank through the dummy pass */
  167600. while (cinfo->output_scanline < cinfo->output_height) {
  167601. JDIMENSION last_scanline;
  167602. /* Call progress monitor hook if present */
  167603. if (cinfo->progress != NULL) {
  167604. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167605. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167606. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167607. }
  167608. /* Process some data */
  167609. last_scanline = cinfo->output_scanline;
  167610. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167611. &cinfo->output_scanline, (JDIMENSION) 0);
  167612. if (cinfo->output_scanline == last_scanline)
  167613. return FALSE; /* No progress made, must suspend */
  167614. }
  167615. /* Finish up dummy pass, and set up for another one */
  167616. (*cinfo->master->finish_output_pass) (cinfo);
  167617. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167618. cinfo->output_scanline = 0;
  167619. #else
  167620. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167621. #endif /* QUANT_2PASS_SUPPORTED */
  167622. }
  167623. /* Ready for application to drive output pass through
  167624. * jpeg_read_scanlines or jpeg_read_raw_data.
  167625. */
  167626. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167627. return TRUE;
  167628. }
  167629. /*
  167630. * Read some scanlines of data from the JPEG decompressor.
  167631. *
  167632. * The return value will be the number of lines actually read.
  167633. * This may be less than the number requested in several cases,
  167634. * including bottom of image, data source suspension, and operating
  167635. * modes that emit multiple scanlines at a time.
  167636. *
  167637. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167638. * this likely signals an application programmer error. However,
  167639. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167640. */
  167641. GLOBAL(JDIMENSION)
  167642. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167643. JDIMENSION max_lines)
  167644. {
  167645. JDIMENSION row_ctr;
  167646. if (cinfo->global_state != DSTATE_SCANNING)
  167647. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167648. if (cinfo->output_scanline >= cinfo->output_height) {
  167649. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167650. return 0;
  167651. }
  167652. /* Call progress monitor hook if present */
  167653. if (cinfo->progress != NULL) {
  167654. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167655. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167656. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167657. }
  167658. /* Process some data */
  167659. row_ctr = 0;
  167660. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167661. cinfo->output_scanline += row_ctr;
  167662. return row_ctr;
  167663. }
  167664. /*
  167665. * Alternate entry point to read raw data.
  167666. * Processes exactly one iMCU row per call, unless suspended.
  167667. */
  167668. GLOBAL(JDIMENSION)
  167669. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167670. JDIMENSION max_lines)
  167671. {
  167672. JDIMENSION lines_per_iMCU_row;
  167673. if (cinfo->global_state != DSTATE_RAW_OK)
  167674. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167675. if (cinfo->output_scanline >= cinfo->output_height) {
  167676. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167677. return 0;
  167678. }
  167679. /* Call progress monitor hook if present */
  167680. if (cinfo->progress != NULL) {
  167681. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167682. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167683. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167684. }
  167685. /* Verify that at least one iMCU row can be returned. */
  167686. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167687. if (max_lines < lines_per_iMCU_row)
  167688. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167689. /* Decompress directly into user's buffer. */
  167690. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167691. return 0; /* suspension forced, can do nothing more */
  167692. /* OK, we processed one iMCU row. */
  167693. cinfo->output_scanline += lines_per_iMCU_row;
  167694. return lines_per_iMCU_row;
  167695. }
  167696. /* Additional entry points for buffered-image mode. */
  167697. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167698. /*
  167699. * Initialize for an output pass in buffered-image mode.
  167700. */
  167701. GLOBAL(boolean)
  167702. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167703. {
  167704. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167705. cinfo->global_state != DSTATE_PRESCAN)
  167706. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167707. /* Limit scan number to valid range */
  167708. if (scan_number <= 0)
  167709. scan_number = 1;
  167710. if (cinfo->inputctl->eoi_reached &&
  167711. scan_number > cinfo->input_scan_number)
  167712. scan_number = cinfo->input_scan_number;
  167713. cinfo->output_scan_number = scan_number;
  167714. /* Perform any dummy output passes, and set up for the real pass */
  167715. return output_pass_setup(cinfo);
  167716. }
  167717. /*
  167718. * Finish up after an output pass in buffered-image mode.
  167719. *
  167720. * Returns FALSE if suspended. The return value need be inspected only if
  167721. * a suspending data source is used.
  167722. */
  167723. GLOBAL(boolean)
  167724. jpeg_finish_output (j_decompress_ptr cinfo)
  167725. {
  167726. if ((cinfo->global_state == DSTATE_SCANNING ||
  167727. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167728. /* Terminate this pass. */
  167729. /* We do not require the whole pass to have been completed. */
  167730. (*cinfo->master->finish_output_pass) (cinfo);
  167731. cinfo->global_state = DSTATE_BUFPOST;
  167732. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167733. /* BUFPOST = repeat call after a suspension, anything else is error */
  167734. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167735. }
  167736. /* Read markers looking for SOS or EOI */
  167737. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167738. ! cinfo->inputctl->eoi_reached) {
  167739. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167740. return FALSE; /* Suspend, come back later */
  167741. }
  167742. cinfo->global_state = DSTATE_BUFIMAGE;
  167743. return TRUE;
  167744. }
  167745. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167746. /*** End of inlined file: jdapistd.c ***/
  167747. /*** Start of inlined file: jdapimin.c ***/
  167748. #define JPEG_INTERNALS
  167749. /*
  167750. * Initialization of a JPEG decompression object.
  167751. * The error manager must already be set up (in case memory manager fails).
  167752. */
  167753. GLOBAL(void)
  167754. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167755. {
  167756. int i;
  167757. /* Guard against version mismatches between library and caller. */
  167758. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167759. if (version != JPEG_LIB_VERSION)
  167760. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167761. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167762. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167763. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167764. /* For debugging purposes, we zero the whole master structure.
  167765. * But the application has already set the err pointer, and may have set
  167766. * client_data, so we have to save and restore those fields.
  167767. * Note: if application hasn't set client_data, tools like Purify may
  167768. * complain here.
  167769. */
  167770. {
  167771. struct jpeg_error_mgr * err = cinfo->err;
  167772. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167773. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167774. cinfo->err = err;
  167775. cinfo->client_data = client_data;
  167776. }
  167777. cinfo->is_decompressor = TRUE;
  167778. /* Initialize a memory manager instance for this object */
  167779. jinit_memory_mgr((j_common_ptr) cinfo);
  167780. /* Zero out pointers to permanent structures. */
  167781. cinfo->progress = NULL;
  167782. cinfo->src = NULL;
  167783. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167784. cinfo->quant_tbl_ptrs[i] = NULL;
  167785. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167786. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167787. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167788. }
  167789. /* Initialize marker processor so application can override methods
  167790. * for COM, APPn markers before calling jpeg_read_header.
  167791. */
  167792. cinfo->marker_list = NULL;
  167793. jinit_marker_reader(cinfo);
  167794. /* And initialize the overall input controller. */
  167795. jinit_input_controller(cinfo);
  167796. /* OK, I'm ready */
  167797. cinfo->global_state = DSTATE_START;
  167798. }
  167799. /*
  167800. * Destruction of a JPEG decompression object
  167801. */
  167802. GLOBAL(void)
  167803. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167804. {
  167805. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167806. }
  167807. /*
  167808. * Abort processing of a JPEG decompression operation,
  167809. * but don't destroy the object itself.
  167810. */
  167811. GLOBAL(void)
  167812. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167813. {
  167814. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167815. }
  167816. /*
  167817. * Set default decompression parameters.
  167818. */
  167819. LOCAL(void)
  167820. default_decompress_parms (j_decompress_ptr cinfo)
  167821. {
  167822. /* Guess the input colorspace, and set output colorspace accordingly. */
  167823. /* (Wish JPEG committee had provided a real way to specify this...) */
  167824. /* Note application may override our guesses. */
  167825. switch (cinfo->num_components) {
  167826. case 1:
  167827. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167828. cinfo->out_color_space = JCS_GRAYSCALE;
  167829. break;
  167830. case 3:
  167831. if (cinfo->saw_JFIF_marker) {
  167832. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167833. } else if (cinfo->saw_Adobe_marker) {
  167834. switch (cinfo->Adobe_transform) {
  167835. case 0:
  167836. cinfo->jpeg_color_space = JCS_RGB;
  167837. break;
  167838. case 1:
  167839. cinfo->jpeg_color_space = JCS_YCbCr;
  167840. break;
  167841. default:
  167842. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167843. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167844. break;
  167845. }
  167846. } else {
  167847. /* Saw no special markers, try to guess from the component IDs */
  167848. int cid0 = cinfo->comp_info[0].component_id;
  167849. int cid1 = cinfo->comp_info[1].component_id;
  167850. int cid2 = cinfo->comp_info[2].component_id;
  167851. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167852. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167853. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167854. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167855. else {
  167856. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167857. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167858. }
  167859. }
  167860. /* Always guess RGB is proper output colorspace. */
  167861. cinfo->out_color_space = JCS_RGB;
  167862. break;
  167863. case 4:
  167864. if (cinfo->saw_Adobe_marker) {
  167865. switch (cinfo->Adobe_transform) {
  167866. case 0:
  167867. cinfo->jpeg_color_space = JCS_CMYK;
  167868. break;
  167869. case 2:
  167870. cinfo->jpeg_color_space = JCS_YCCK;
  167871. break;
  167872. default:
  167873. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167874. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167875. break;
  167876. }
  167877. } else {
  167878. /* No special markers, assume straight CMYK. */
  167879. cinfo->jpeg_color_space = JCS_CMYK;
  167880. }
  167881. cinfo->out_color_space = JCS_CMYK;
  167882. break;
  167883. default:
  167884. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167885. cinfo->out_color_space = JCS_UNKNOWN;
  167886. break;
  167887. }
  167888. /* Set defaults for other decompression parameters. */
  167889. cinfo->scale_num = 1; /* 1:1 scaling */
  167890. cinfo->scale_denom = 1;
  167891. cinfo->output_gamma = 1.0;
  167892. cinfo->buffered_image = FALSE;
  167893. cinfo->raw_data_out = FALSE;
  167894. cinfo->dct_method = JDCT_DEFAULT;
  167895. cinfo->do_fancy_upsampling = TRUE;
  167896. cinfo->do_block_smoothing = TRUE;
  167897. cinfo->quantize_colors = FALSE;
  167898. /* We set these in case application only sets quantize_colors. */
  167899. cinfo->dither_mode = JDITHER_FS;
  167900. #ifdef QUANT_2PASS_SUPPORTED
  167901. cinfo->two_pass_quantize = TRUE;
  167902. #else
  167903. cinfo->two_pass_quantize = FALSE;
  167904. #endif
  167905. cinfo->desired_number_of_colors = 256;
  167906. cinfo->colormap = NULL;
  167907. /* Initialize for no mode change in buffered-image mode. */
  167908. cinfo->enable_1pass_quant = FALSE;
  167909. cinfo->enable_external_quant = FALSE;
  167910. cinfo->enable_2pass_quant = FALSE;
  167911. }
  167912. /*
  167913. * Decompression startup: read start of JPEG datastream to see what's there.
  167914. * Need only initialize JPEG object and supply a data source before calling.
  167915. *
  167916. * This routine will read as far as the first SOS marker (ie, actual start of
  167917. * compressed data), and will save all tables and parameters in the JPEG
  167918. * object. It will also initialize the decompression parameters to default
  167919. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167920. * adjust the decompression parameters and then call jpeg_start_decompress.
  167921. * (Or, if the application only wanted to determine the image parameters,
  167922. * the data need not be decompressed. In that case, call jpeg_abort or
  167923. * jpeg_destroy to release any temporary space.)
  167924. * If an abbreviated (tables only) datastream is presented, the routine will
  167925. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167926. * re-use the JPEG object to read the abbreviated image datastream(s).
  167927. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167928. * The JPEG_SUSPENDED return code only occurs if the data source module
  167929. * requests suspension of the decompressor. In this case the application
  167930. * should load more source data and then re-call jpeg_read_header to resume
  167931. * processing.
  167932. * If a non-suspending data source is used and require_image is TRUE, then the
  167933. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167934. *
  167935. * This routine is now just a front end to jpeg_consume_input, with some
  167936. * extra error checking.
  167937. */
  167938. GLOBAL(int)
  167939. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167940. {
  167941. int retcode;
  167942. if (cinfo->global_state != DSTATE_START &&
  167943. cinfo->global_state != DSTATE_INHEADER)
  167944. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167945. retcode = jpeg_consume_input(cinfo);
  167946. switch (retcode) {
  167947. case JPEG_REACHED_SOS:
  167948. retcode = JPEG_HEADER_OK;
  167949. break;
  167950. case JPEG_REACHED_EOI:
  167951. if (require_image) /* Complain if application wanted an image */
  167952. ERREXIT(cinfo, JERR_NO_IMAGE);
  167953. /* Reset to start state; it would be safer to require the application to
  167954. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167955. * A side effect is to free any temporary memory (there shouldn't be any).
  167956. */
  167957. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167958. retcode = JPEG_HEADER_TABLES_ONLY;
  167959. break;
  167960. case JPEG_SUSPENDED:
  167961. /* no work */
  167962. break;
  167963. }
  167964. return retcode;
  167965. }
  167966. /*
  167967. * Consume data in advance of what the decompressor requires.
  167968. * This can be called at any time once the decompressor object has
  167969. * been created and a data source has been set up.
  167970. *
  167971. * This routine is essentially a state machine that handles a couple
  167972. * of critical state-transition actions, namely initial setup and
  167973. * transition from header scanning to ready-for-start_decompress.
  167974. * All the actual input is done via the input controller's consume_input
  167975. * method.
  167976. */
  167977. GLOBAL(int)
  167978. jpeg_consume_input (j_decompress_ptr cinfo)
  167979. {
  167980. int retcode = JPEG_SUSPENDED;
  167981. /* NB: every possible DSTATE value should be listed in this switch */
  167982. switch (cinfo->global_state) {
  167983. case DSTATE_START:
  167984. /* Start-of-datastream actions: reset appropriate modules */
  167985. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167986. /* Initialize application's data source module */
  167987. (*cinfo->src->init_source) (cinfo);
  167988. cinfo->global_state = DSTATE_INHEADER;
  167989. /*FALLTHROUGH*/
  167990. case DSTATE_INHEADER:
  167991. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167992. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167993. /* Set up default parameters based on header data */
  167994. default_decompress_parms(cinfo);
  167995. /* Set global state: ready for start_decompress */
  167996. cinfo->global_state = DSTATE_READY;
  167997. }
  167998. break;
  167999. case DSTATE_READY:
  168000. /* Can't advance past first SOS until start_decompress is called */
  168001. retcode = JPEG_REACHED_SOS;
  168002. break;
  168003. case DSTATE_PRELOAD:
  168004. case DSTATE_PRESCAN:
  168005. case DSTATE_SCANNING:
  168006. case DSTATE_RAW_OK:
  168007. case DSTATE_BUFIMAGE:
  168008. case DSTATE_BUFPOST:
  168009. case DSTATE_STOPPING:
  168010. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168011. break;
  168012. default:
  168013. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168014. }
  168015. return retcode;
  168016. }
  168017. /*
  168018. * Have we finished reading the input file?
  168019. */
  168020. GLOBAL(boolean)
  168021. jpeg_input_complete (j_decompress_ptr cinfo)
  168022. {
  168023. /* Check for valid jpeg object */
  168024. if (cinfo->global_state < DSTATE_START ||
  168025. cinfo->global_state > DSTATE_STOPPING)
  168026. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168027. return cinfo->inputctl->eoi_reached;
  168028. }
  168029. /*
  168030. * Is there more than one scan?
  168031. */
  168032. GLOBAL(boolean)
  168033. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168034. {
  168035. /* Only valid after jpeg_read_header completes */
  168036. if (cinfo->global_state < DSTATE_READY ||
  168037. cinfo->global_state > DSTATE_STOPPING)
  168038. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168039. return cinfo->inputctl->has_multiple_scans;
  168040. }
  168041. /*
  168042. * Finish JPEG decompression.
  168043. *
  168044. * This will normally just verify the file trailer and release temp storage.
  168045. *
  168046. * Returns FALSE if suspended. The return value need be inspected only if
  168047. * a suspending data source is used.
  168048. */
  168049. GLOBAL(boolean)
  168050. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168051. {
  168052. if ((cinfo->global_state == DSTATE_SCANNING ||
  168053. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168054. /* Terminate final pass of non-buffered mode */
  168055. if (cinfo->output_scanline < cinfo->output_height)
  168056. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168057. (*cinfo->master->finish_output_pass) (cinfo);
  168058. cinfo->global_state = DSTATE_STOPPING;
  168059. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168060. /* Finishing after a buffered-image operation */
  168061. cinfo->global_state = DSTATE_STOPPING;
  168062. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168063. /* STOPPING = repeat call after a suspension, anything else is error */
  168064. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168065. }
  168066. /* Read until EOI */
  168067. while (! cinfo->inputctl->eoi_reached) {
  168068. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168069. return FALSE; /* Suspend, come back later */
  168070. }
  168071. /* Do final cleanup */
  168072. (*cinfo->src->term_source) (cinfo);
  168073. /* We can use jpeg_abort to release memory and reset global_state */
  168074. jpeg_abort((j_common_ptr) cinfo);
  168075. return TRUE;
  168076. }
  168077. /*** End of inlined file: jdapimin.c ***/
  168078. /*** Start of inlined file: jdatasrc.c ***/
  168079. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168080. /*** Start of inlined file: jerror.h ***/
  168081. /*
  168082. * To define the enum list of message codes, include this file without
  168083. * defining macro JMESSAGE. To create a message string table, include it
  168084. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168085. */
  168086. #ifndef JMESSAGE
  168087. #ifndef JERROR_H
  168088. /* First time through, define the enum list */
  168089. #define JMAKE_ENUM_LIST
  168090. #else
  168091. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168092. #define JMESSAGE(code,string)
  168093. #endif /* JERROR_H */
  168094. #endif /* JMESSAGE */
  168095. #ifdef JMAKE_ENUM_LIST
  168096. typedef enum {
  168097. #define JMESSAGE(code,string) code ,
  168098. #endif /* JMAKE_ENUM_LIST */
  168099. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168100. /* For maintenance convenience, list is alphabetical by message code name */
  168101. JMESSAGE(JERR_ARITH_NOTIMPL,
  168102. "Sorry, there are legal restrictions on arithmetic coding")
  168103. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168104. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168105. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168106. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168107. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168108. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168109. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168110. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168111. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168112. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168113. JMESSAGE(JERR_BAD_LIB_VERSION,
  168114. "Wrong JPEG library version: library is %d, caller expects %d")
  168115. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168116. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168117. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168118. JMESSAGE(JERR_BAD_PROGRESSION,
  168119. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168120. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168121. "Invalid progressive parameters at scan script entry %d")
  168122. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168123. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168124. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168125. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168126. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168127. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168128. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168129. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168130. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168131. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168132. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168133. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168134. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168135. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168136. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168137. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168138. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168139. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168140. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168141. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168142. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168143. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168144. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168145. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168146. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168147. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168148. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168149. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168150. "Cannot transcode due to multiple use of quantization table %d")
  168151. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168152. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168153. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168154. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168155. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168156. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168157. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168158. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168159. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168160. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168161. JMESSAGE(JERR_QUANT_COMPONENTS,
  168162. "Cannot quantize more than %d color components")
  168163. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168164. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168165. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168166. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168167. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168168. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168169. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168170. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168171. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168172. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168173. JMESSAGE(JERR_TFILE_WRITE,
  168174. "Write failed on temporary file --- out of disk space?")
  168175. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168176. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168177. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168178. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168179. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168180. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168181. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168182. JMESSAGE(JMSG_VERSION, JVERSION)
  168183. JMESSAGE(JTRC_16BIT_TABLES,
  168184. "Caution: quantization tables are too coarse for baseline JPEG")
  168185. JMESSAGE(JTRC_ADOBE,
  168186. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168187. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168188. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168189. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168190. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168191. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168192. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168193. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168194. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168195. JMESSAGE(JTRC_EOI, "End Of Image")
  168196. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168197. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168198. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168199. "Warning: thumbnail image size does not match data length %u")
  168200. JMESSAGE(JTRC_JFIF_EXTENSION,
  168201. "JFIF extension marker: type 0x%02x, length %u")
  168202. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168203. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168204. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168205. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168206. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168207. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168208. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168209. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168210. JMESSAGE(JTRC_RST, "RST%d")
  168211. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168212. "Smoothing not supported with nonstandard sampling ratios")
  168213. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168214. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168215. JMESSAGE(JTRC_SOI, "Start of Image")
  168216. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168217. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168218. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168219. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168220. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168221. JMESSAGE(JTRC_THUMB_JPEG,
  168222. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168223. JMESSAGE(JTRC_THUMB_PALETTE,
  168224. "JFIF extension marker: palette thumbnail image, length %u")
  168225. JMESSAGE(JTRC_THUMB_RGB,
  168226. "JFIF extension marker: RGB thumbnail image, length %u")
  168227. JMESSAGE(JTRC_UNKNOWN_IDS,
  168228. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168229. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168230. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168231. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168232. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168233. "Inconsistent progression sequence for component %d coefficient %d")
  168234. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168235. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168236. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168237. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168238. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168239. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168240. JMESSAGE(JWRN_MUST_RESYNC,
  168241. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168242. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168243. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168244. #ifdef JMAKE_ENUM_LIST
  168245. JMSG_LASTMSGCODE
  168246. } J_MESSAGE_CODE;
  168247. #undef JMAKE_ENUM_LIST
  168248. #endif /* JMAKE_ENUM_LIST */
  168249. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168250. #undef JMESSAGE
  168251. #ifndef JERROR_H
  168252. #define JERROR_H
  168253. /* Macros to simplify using the error and trace message stuff */
  168254. /* The first parameter is either type of cinfo pointer */
  168255. /* Fatal errors (print message and exit) */
  168256. #define ERREXIT(cinfo,code) \
  168257. ((cinfo)->err->msg_code = (code), \
  168258. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168259. #define ERREXIT1(cinfo,code,p1) \
  168260. ((cinfo)->err->msg_code = (code), \
  168261. (cinfo)->err->msg_parm.i[0] = (p1), \
  168262. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168263. #define ERREXIT2(cinfo,code,p1,p2) \
  168264. ((cinfo)->err->msg_code = (code), \
  168265. (cinfo)->err->msg_parm.i[0] = (p1), \
  168266. (cinfo)->err->msg_parm.i[1] = (p2), \
  168267. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168268. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168269. ((cinfo)->err->msg_code = (code), \
  168270. (cinfo)->err->msg_parm.i[0] = (p1), \
  168271. (cinfo)->err->msg_parm.i[1] = (p2), \
  168272. (cinfo)->err->msg_parm.i[2] = (p3), \
  168273. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168274. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168275. ((cinfo)->err->msg_code = (code), \
  168276. (cinfo)->err->msg_parm.i[0] = (p1), \
  168277. (cinfo)->err->msg_parm.i[1] = (p2), \
  168278. (cinfo)->err->msg_parm.i[2] = (p3), \
  168279. (cinfo)->err->msg_parm.i[3] = (p4), \
  168280. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168281. #define ERREXITS(cinfo,code,str) \
  168282. ((cinfo)->err->msg_code = (code), \
  168283. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168284. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168285. #define MAKESTMT(stuff) do { stuff } while (0)
  168286. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168287. #define WARNMS(cinfo,code) \
  168288. ((cinfo)->err->msg_code = (code), \
  168289. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168290. #define WARNMS1(cinfo,code,p1) \
  168291. ((cinfo)->err->msg_code = (code), \
  168292. (cinfo)->err->msg_parm.i[0] = (p1), \
  168293. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168294. #define WARNMS2(cinfo,code,p1,p2) \
  168295. ((cinfo)->err->msg_code = (code), \
  168296. (cinfo)->err->msg_parm.i[0] = (p1), \
  168297. (cinfo)->err->msg_parm.i[1] = (p2), \
  168298. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168299. /* Informational/debugging messages */
  168300. #define TRACEMS(cinfo,lvl,code) \
  168301. ((cinfo)->err->msg_code = (code), \
  168302. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168303. #define TRACEMS1(cinfo,lvl,code,p1) \
  168304. ((cinfo)->err->msg_code = (code), \
  168305. (cinfo)->err->msg_parm.i[0] = (p1), \
  168306. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168307. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168308. ((cinfo)->err->msg_code = (code), \
  168309. (cinfo)->err->msg_parm.i[0] = (p1), \
  168310. (cinfo)->err->msg_parm.i[1] = (p2), \
  168311. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168312. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168313. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168314. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168315. (cinfo)->err->msg_code = (code); \
  168316. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168317. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168318. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168319. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168320. (cinfo)->err->msg_code = (code); \
  168321. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168322. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168323. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168324. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168325. _mp[4] = (p5); \
  168326. (cinfo)->err->msg_code = (code); \
  168327. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168328. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168329. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168330. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168331. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168332. (cinfo)->err->msg_code = (code); \
  168333. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168334. #define TRACEMSS(cinfo,lvl,code,str) \
  168335. ((cinfo)->err->msg_code = (code), \
  168336. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168337. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168338. #endif /* JERROR_H */
  168339. /*** End of inlined file: jerror.h ***/
  168340. /* Expanded data source object for stdio input */
  168341. typedef struct {
  168342. struct jpeg_source_mgr pub; /* public fields */
  168343. FILE * infile; /* source stream */
  168344. JOCTET * buffer; /* start of buffer */
  168345. boolean start_of_file; /* have we gotten any data yet? */
  168346. } my_source_mgr;
  168347. typedef my_source_mgr * my_src_ptr;
  168348. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168349. /*
  168350. * Initialize source --- called by jpeg_read_header
  168351. * before any data is actually read.
  168352. */
  168353. METHODDEF(void)
  168354. init_source (j_decompress_ptr cinfo)
  168355. {
  168356. my_src_ptr src = (my_src_ptr) cinfo->src;
  168357. /* We reset the empty-input-file flag for each image,
  168358. * but we don't clear the input buffer.
  168359. * This is correct behavior for reading a series of images from one source.
  168360. */
  168361. src->start_of_file = TRUE;
  168362. }
  168363. /*
  168364. * Fill the input buffer --- called whenever buffer is emptied.
  168365. *
  168366. * In typical applications, this should read fresh data into the buffer
  168367. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168368. * reset the pointer & count to the start of the buffer, and return TRUE
  168369. * indicating that the buffer has been reloaded. It is not necessary to
  168370. * fill the buffer entirely, only to obtain at least one more byte.
  168371. *
  168372. * There is no such thing as an EOF return. If the end of the file has been
  168373. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168374. * the buffer. In most cases, generating a warning message and inserting a
  168375. * fake EOI marker is the best course of action --- this will allow the
  168376. * decompressor to output however much of the image is there. However,
  168377. * the resulting error message is misleading if the real problem is an empty
  168378. * input file, so we handle that case specially.
  168379. *
  168380. * In applications that need to be able to suspend compression due to input
  168381. * not being available yet, a FALSE return indicates that no more data can be
  168382. * obtained right now, but more may be forthcoming later. In this situation,
  168383. * the decompressor will return to its caller (with an indication of the
  168384. * number of scanlines it has read, if any). The application should resume
  168385. * decompression after it has loaded more data into the input buffer. Note
  168386. * that there are substantial restrictions on the use of suspension --- see
  168387. * the documentation.
  168388. *
  168389. * When suspending, the decompressor will back up to a convenient restart point
  168390. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168391. * indicate where the restart point will be if the current call returns FALSE.
  168392. * Data beyond this point must be rescanned after resumption, so move it to
  168393. * the front of the buffer rather than discarding it.
  168394. */
  168395. METHODDEF(boolean)
  168396. fill_input_buffer (j_decompress_ptr cinfo)
  168397. {
  168398. my_src_ptr src = (my_src_ptr) cinfo->src;
  168399. size_t nbytes;
  168400. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168401. if (nbytes <= 0) {
  168402. if (src->start_of_file) /* Treat empty input file as fatal error */
  168403. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168404. WARNMS(cinfo, JWRN_JPEG_EOF);
  168405. /* Insert a fake EOI marker */
  168406. src->buffer[0] = (JOCTET) 0xFF;
  168407. src->buffer[1] = (JOCTET) JPEG_EOI;
  168408. nbytes = 2;
  168409. }
  168410. src->pub.next_input_byte = src->buffer;
  168411. src->pub.bytes_in_buffer = nbytes;
  168412. src->start_of_file = FALSE;
  168413. return TRUE;
  168414. }
  168415. /*
  168416. * Skip data --- used to skip over a potentially large amount of
  168417. * uninteresting data (such as an APPn marker).
  168418. *
  168419. * Writers of suspendable-input applications must note that skip_input_data
  168420. * is not granted the right to give a suspension return. If the skip extends
  168421. * beyond the data currently in the buffer, the buffer can be marked empty so
  168422. * that the next read will cause a fill_input_buffer call that can suspend.
  168423. * Arranging for additional bytes to be discarded before reloading the input
  168424. * buffer is the application writer's problem.
  168425. */
  168426. METHODDEF(void)
  168427. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168428. {
  168429. my_src_ptr src = (my_src_ptr) cinfo->src;
  168430. /* Just a dumb implementation for now. Could use fseek() except
  168431. * it doesn't work on pipes. Not clear that being smart is worth
  168432. * any trouble anyway --- large skips are infrequent.
  168433. */
  168434. if (num_bytes > 0) {
  168435. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168436. num_bytes -= (long) src->pub.bytes_in_buffer;
  168437. (void) fill_input_buffer(cinfo);
  168438. /* note we assume that fill_input_buffer will never return FALSE,
  168439. * so suspension need not be handled.
  168440. */
  168441. }
  168442. src->pub.next_input_byte += (size_t) num_bytes;
  168443. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168444. }
  168445. }
  168446. /*
  168447. * An additional method that can be provided by data source modules is the
  168448. * resync_to_restart method for error recovery in the presence of RST markers.
  168449. * For the moment, this source module just uses the default resync method
  168450. * provided by the JPEG library. That method assumes that no backtracking
  168451. * is possible.
  168452. */
  168453. /*
  168454. * Terminate source --- called by jpeg_finish_decompress
  168455. * after all data has been read. Often a no-op.
  168456. *
  168457. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168458. * application must deal with any cleanup that should happen even
  168459. * for error exit.
  168460. */
  168461. METHODDEF(void)
  168462. term_source (j_decompress_ptr)
  168463. {
  168464. /* no work necessary here */
  168465. }
  168466. /*
  168467. * Prepare for input from a stdio stream.
  168468. * The caller must have already opened the stream, and is responsible
  168469. * for closing it after finishing decompression.
  168470. */
  168471. GLOBAL(void)
  168472. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168473. {
  168474. my_src_ptr src;
  168475. /* The source object and input buffer are made permanent so that a series
  168476. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168477. * only before the first one. (If we discarded the buffer at the end of
  168478. * one image, we'd likely lose the start of the next one.)
  168479. * This makes it unsafe to use this manager and a different source
  168480. * manager serially with the same JPEG object. Caveat programmer.
  168481. */
  168482. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168483. cinfo->src = (struct jpeg_source_mgr *)
  168484. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168485. SIZEOF(my_source_mgr));
  168486. src = (my_src_ptr) cinfo->src;
  168487. src->buffer = (JOCTET *)
  168488. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168489. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168490. }
  168491. src = (my_src_ptr) cinfo->src;
  168492. src->pub.init_source = init_source;
  168493. src->pub.fill_input_buffer = fill_input_buffer;
  168494. src->pub.skip_input_data = skip_input_data;
  168495. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168496. src->pub.term_source = term_source;
  168497. src->infile = infile;
  168498. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168499. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168500. }
  168501. /*** End of inlined file: jdatasrc.c ***/
  168502. /*** Start of inlined file: jdcoefct.c ***/
  168503. #define JPEG_INTERNALS
  168504. /* Block smoothing is only applicable for progressive JPEG, so: */
  168505. #ifndef D_PROGRESSIVE_SUPPORTED
  168506. #undef BLOCK_SMOOTHING_SUPPORTED
  168507. #endif
  168508. /* Private buffer controller object */
  168509. typedef struct {
  168510. struct jpeg_d_coef_controller pub; /* public fields */
  168511. /* These variables keep track of the current location of the input side. */
  168512. /* cinfo->input_iMCU_row is also used for this. */
  168513. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168514. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168515. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168516. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168517. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168518. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168519. * and let the entropy decoder write into that workspace each time.
  168520. * (On 80x86, the workspace is FAR even though it's not really very big;
  168521. * this is to keep the module interfaces unchanged when a large coefficient
  168522. * buffer is necessary.)
  168523. * In multi-pass modes, this array points to the current MCU's blocks
  168524. * within the virtual arrays; it is used only by the input side.
  168525. */
  168526. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168527. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168528. /* In multi-pass modes, we need a virtual block array for each component. */
  168529. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168530. #endif
  168531. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168532. /* When doing block smoothing, we latch coefficient Al values here */
  168533. int * coef_bits_latch;
  168534. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168535. #endif
  168536. } my_coef_controller3;
  168537. typedef my_coef_controller3 * my_coef_ptr3;
  168538. /* Forward declarations */
  168539. METHODDEF(int) decompress_onepass
  168540. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168541. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168542. METHODDEF(int) decompress_data
  168543. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168544. #endif
  168545. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168546. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168547. METHODDEF(int) decompress_smooth_data
  168548. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168549. #endif
  168550. LOCAL(void)
  168551. start_iMCU_row3 (j_decompress_ptr cinfo)
  168552. /* Reset within-iMCU-row counters for a new row (input side) */
  168553. {
  168554. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168555. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168556. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168557. * But at the bottom of the image, process only what's left.
  168558. */
  168559. if (cinfo->comps_in_scan > 1) {
  168560. coef->MCU_rows_per_iMCU_row = 1;
  168561. } else {
  168562. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168563. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168564. else
  168565. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168566. }
  168567. coef->MCU_ctr = 0;
  168568. coef->MCU_vert_offset = 0;
  168569. }
  168570. /*
  168571. * Initialize for an input processing pass.
  168572. */
  168573. METHODDEF(void)
  168574. start_input_pass (j_decompress_ptr cinfo)
  168575. {
  168576. cinfo->input_iMCU_row = 0;
  168577. start_iMCU_row3(cinfo);
  168578. }
  168579. /*
  168580. * Initialize for an output processing pass.
  168581. */
  168582. METHODDEF(void)
  168583. start_output_pass (j_decompress_ptr cinfo)
  168584. {
  168585. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168586. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168587. /* If multipass, check to see whether to use block smoothing on this pass */
  168588. if (coef->pub.coef_arrays != NULL) {
  168589. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168590. coef->pub.decompress_data = decompress_smooth_data;
  168591. else
  168592. coef->pub.decompress_data = decompress_data;
  168593. }
  168594. #endif
  168595. cinfo->output_iMCU_row = 0;
  168596. }
  168597. /*
  168598. * Decompress and return some data in the single-pass case.
  168599. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168600. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168601. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168602. *
  168603. * NB: output_buf contains a plane for each component in image,
  168604. * which we index according to the component's SOF position.
  168605. */
  168606. METHODDEF(int)
  168607. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168608. {
  168609. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168610. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168611. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168612. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168613. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168614. JSAMPARRAY output_ptr;
  168615. JDIMENSION start_col, output_col;
  168616. jpeg_component_info *compptr;
  168617. inverse_DCT_method_ptr inverse_DCT;
  168618. /* Loop to process as much as one whole iMCU row */
  168619. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168620. yoffset++) {
  168621. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168622. MCU_col_num++) {
  168623. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168624. jzero_far((void FAR *) coef->MCU_buffer[0],
  168625. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168626. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168627. /* Suspension forced; update state counters and exit */
  168628. coef->MCU_vert_offset = yoffset;
  168629. coef->MCU_ctr = MCU_col_num;
  168630. return JPEG_SUSPENDED;
  168631. }
  168632. /* Determine where data should go in output_buf and do the IDCT thing.
  168633. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168634. * incremented past them!). Note the inner loop relies on having
  168635. * allocated the MCU_buffer[] blocks sequentially.
  168636. */
  168637. blkn = 0; /* index of current DCT block within MCU */
  168638. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168639. compptr = cinfo->cur_comp_info[ci];
  168640. /* Don't bother to IDCT an uninteresting component. */
  168641. if (! compptr->component_needed) {
  168642. blkn += compptr->MCU_blocks;
  168643. continue;
  168644. }
  168645. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168646. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168647. : compptr->last_col_width;
  168648. output_ptr = output_buf[compptr->component_index] +
  168649. yoffset * compptr->DCT_scaled_size;
  168650. start_col = MCU_col_num * compptr->MCU_sample_width;
  168651. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168652. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168653. yoffset+yindex < compptr->last_row_height) {
  168654. output_col = start_col;
  168655. for (xindex = 0; xindex < useful_width; xindex++) {
  168656. (*inverse_DCT) (cinfo, compptr,
  168657. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168658. output_ptr, output_col);
  168659. output_col += compptr->DCT_scaled_size;
  168660. }
  168661. }
  168662. blkn += compptr->MCU_width;
  168663. output_ptr += compptr->DCT_scaled_size;
  168664. }
  168665. }
  168666. }
  168667. /* Completed an MCU row, but perhaps not an iMCU row */
  168668. coef->MCU_ctr = 0;
  168669. }
  168670. /* Completed the iMCU row, advance counters for next one */
  168671. cinfo->output_iMCU_row++;
  168672. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168673. start_iMCU_row3(cinfo);
  168674. return JPEG_ROW_COMPLETED;
  168675. }
  168676. /* Completed the scan */
  168677. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168678. return JPEG_SCAN_COMPLETED;
  168679. }
  168680. /*
  168681. * Dummy consume-input routine for single-pass operation.
  168682. */
  168683. METHODDEF(int)
  168684. dummy_consume_data (j_decompress_ptr)
  168685. {
  168686. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168687. }
  168688. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168689. /*
  168690. * Consume input data and store it in the full-image coefficient buffer.
  168691. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168692. * ie, v_samp_factor block rows for each component in the scan.
  168693. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168694. */
  168695. METHODDEF(int)
  168696. consume_data (j_decompress_ptr cinfo)
  168697. {
  168698. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168699. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168700. int blkn, ci, xindex, yindex, yoffset;
  168701. JDIMENSION start_col;
  168702. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168703. JBLOCKROW buffer_ptr;
  168704. jpeg_component_info *compptr;
  168705. /* Align the virtual buffers for the components used in this scan. */
  168706. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168707. compptr = cinfo->cur_comp_info[ci];
  168708. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168709. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168710. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168711. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168712. /* Note: entropy decoder expects buffer to be zeroed,
  168713. * but this is handled automatically by the memory manager
  168714. * because we requested a pre-zeroed array.
  168715. */
  168716. }
  168717. /* Loop to process one whole iMCU row */
  168718. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168719. yoffset++) {
  168720. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168721. MCU_col_num++) {
  168722. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168723. blkn = 0; /* index of current DCT block within MCU */
  168724. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168725. compptr = cinfo->cur_comp_info[ci];
  168726. start_col = MCU_col_num * compptr->MCU_width;
  168727. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168728. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168729. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168730. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168731. }
  168732. }
  168733. }
  168734. /* Try to fetch the MCU. */
  168735. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168736. /* Suspension forced; update state counters and exit */
  168737. coef->MCU_vert_offset = yoffset;
  168738. coef->MCU_ctr = MCU_col_num;
  168739. return JPEG_SUSPENDED;
  168740. }
  168741. }
  168742. /* Completed an MCU row, but perhaps not an iMCU row */
  168743. coef->MCU_ctr = 0;
  168744. }
  168745. /* Completed the iMCU row, advance counters for next one */
  168746. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168747. start_iMCU_row3(cinfo);
  168748. return JPEG_ROW_COMPLETED;
  168749. }
  168750. /* Completed the scan */
  168751. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168752. return JPEG_SCAN_COMPLETED;
  168753. }
  168754. /*
  168755. * Decompress and return some data in the multi-pass case.
  168756. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168757. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168758. *
  168759. * NB: output_buf contains a plane for each component in image.
  168760. */
  168761. METHODDEF(int)
  168762. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168763. {
  168764. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168765. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168766. JDIMENSION block_num;
  168767. int ci, block_row, block_rows;
  168768. JBLOCKARRAY buffer;
  168769. JBLOCKROW buffer_ptr;
  168770. JSAMPARRAY output_ptr;
  168771. JDIMENSION output_col;
  168772. jpeg_component_info *compptr;
  168773. inverse_DCT_method_ptr inverse_DCT;
  168774. /* Force some input to be done if we are getting ahead of the input. */
  168775. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168776. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168777. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168778. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168779. return JPEG_SUSPENDED;
  168780. }
  168781. /* OK, output from the virtual arrays. */
  168782. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168783. ci++, compptr++) {
  168784. /* Don't bother to IDCT an uninteresting component. */
  168785. if (! compptr->component_needed)
  168786. continue;
  168787. /* Align the virtual buffer for this component. */
  168788. buffer = (*cinfo->mem->access_virt_barray)
  168789. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168790. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168791. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168792. /* Count non-dummy DCT block rows in this iMCU row. */
  168793. if (cinfo->output_iMCU_row < last_iMCU_row)
  168794. block_rows = compptr->v_samp_factor;
  168795. else {
  168796. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168797. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168798. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168799. }
  168800. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168801. output_ptr = output_buf[ci];
  168802. /* Loop over all DCT blocks to be processed. */
  168803. for (block_row = 0; block_row < block_rows; block_row++) {
  168804. buffer_ptr = buffer[block_row];
  168805. output_col = 0;
  168806. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168807. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168808. output_ptr, output_col);
  168809. buffer_ptr++;
  168810. output_col += compptr->DCT_scaled_size;
  168811. }
  168812. output_ptr += compptr->DCT_scaled_size;
  168813. }
  168814. }
  168815. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168816. return JPEG_ROW_COMPLETED;
  168817. return JPEG_SCAN_COMPLETED;
  168818. }
  168819. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168820. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168821. /*
  168822. * This code applies interblock smoothing as described by section K.8
  168823. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168824. * the DC values of a DCT block and its 8 neighboring blocks.
  168825. * We apply smoothing only for progressive JPEG decoding, and only if
  168826. * the coefficients it can estimate are not yet known to full precision.
  168827. */
  168828. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168829. #define Q01_POS 1
  168830. #define Q10_POS 8
  168831. #define Q20_POS 16
  168832. #define Q11_POS 9
  168833. #define Q02_POS 2
  168834. /*
  168835. * Determine whether block smoothing is applicable and safe.
  168836. * We also latch the current states of the coef_bits[] entries for the
  168837. * AC coefficients; otherwise, if the input side of the decompressor
  168838. * advances into a new scan, we might think the coefficients are known
  168839. * more accurately than they really are.
  168840. */
  168841. LOCAL(boolean)
  168842. smoothing_ok (j_decompress_ptr cinfo)
  168843. {
  168844. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168845. boolean smoothing_useful = FALSE;
  168846. int ci, coefi;
  168847. jpeg_component_info *compptr;
  168848. JQUANT_TBL * qtable;
  168849. int * coef_bits;
  168850. int * coef_bits_latch;
  168851. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168852. return FALSE;
  168853. /* Allocate latch area if not already done */
  168854. if (coef->coef_bits_latch == NULL)
  168855. coef->coef_bits_latch = (int *)
  168856. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168857. cinfo->num_components *
  168858. (SAVED_COEFS * SIZEOF(int)));
  168859. coef_bits_latch = coef->coef_bits_latch;
  168860. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168861. ci++, compptr++) {
  168862. /* All components' quantization values must already be latched. */
  168863. if ((qtable = compptr->quant_table) == NULL)
  168864. return FALSE;
  168865. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168866. if (qtable->quantval[0] == 0 ||
  168867. qtable->quantval[Q01_POS] == 0 ||
  168868. qtable->quantval[Q10_POS] == 0 ||
  168869. qtable->quantval[Q20_POS] == 0 ||
  168870. qtable->quantval[Q11_POS] == 0 ||
  168871. qtable->quantval[Q02_POS] == 0)
  168872. return FALSE;
  168873. /* DC values must be at least partly known for all components. */
  168874. coef_bits = cinfo->coef_bits[ci];
  168875. if (coef_bits[0] < 0)
  168876. return FALSE;
  168877. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168878. for (coefi = 1; coefi <= 5; coefi++) {
  168879. coef_bits_latch[coefi] = coef_bits[coefi];
  168880. if (coef_bits[coefi] != 0)
  168881. smoothing_useful = TRUE;
  168882. }
  168883. coef_bits_latch += SAVED_COEFS;
  168884. }
  168885. return smoothing_useful;
  168886. }
  168887. /*
  168888. * Variant of decompress_data for use when doing block smoothing.
  168889. */
  168890. METHODDEF(int)
  168891. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168892. {
  168893. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168894. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168895. JDIMENSION block_num, last_block_column;
  168896. int ci, block_row, block_rows, access_rows;
  168897. JBLOCKARRAY buffer;
  168898. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168899. JSAMPARRAY output_ptr;
  168900. JDIMENSION output_col;
  168901. jpeg_component_info *compptr;
  168902. inverse_DCT_method_ptr inverse_DCT;
  168903. boolean first_row, last_row;
  168904. JBLOCK workspace;
  168905. int *coef_bits;
  168906. JQUANT_TBL *quanttbl;
  168907. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168908. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168909. int Al, pred;
  168910. /* Force some input to be done if we are getting ahead of the input. */
  168911. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168912. ! cinfo->inputctl->eoi_reached) {
  168913. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168914. /* If input is working on current scan, we ordinarily want it to
  168915. * have completed the current row. But if input scan is DC,
  168916. * we want it to keep one row ahead so that next block row's DC
  168917. * values are up to date.
  168918. */
  168919. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168920. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168921. break;
  168922. }
  168923. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168924. return JPEG_SUSPENDED;
  168925. }
  168926. /* OK, output from the virtual arrays. */
  168927. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168928. ci++, compptr++) {
  168929. /* Don't bother to IDCT an uninteresting component. */
  168930. if (! compptr->component_needed)
  168931. continue;
  168932. /* Count non-dummy DCT block rows in this iMCU row. */
  168933. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168934. block_rows = compptr->v_samp_factor;
  168935. access_rows = block_rows * 2; /* this and next iMCU row */
  168936. last_row = FALSE;
  168937. } else {
  168938. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168939. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168940. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168941. access_rows = block_rows; /* this iMCU row only */
  168942. last_row = TRUE;
  168943. }
  168944. /* Align the virtual buffer for this component. */
  168945. if (cinfo->output_iMCU_row > 0) {
  168946. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168947. buffer = (*cinfo->mem->access_virt_barray)
  168948. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168949. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168950. (JDIMENSION) access_rows, FALSE);
  168951. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168952. first_row = FALSE;
  168953. } else {
  168954. buffer = (*cinfo->mem->access_virt_barray)
  168955. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168956. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168957. first_row = TRUE;
  168958. }
  168959. /* Fetch component-dependent info */
  168960. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168961. quanttbl = compptr->quant_table;
  168962. Q00 = quanttbl->quantval[0];
  168963. Q01 = quanttbl->quantval[Q01_POS];
  168964. Q10 = quanttbl->quantval[Q10_POS];
  168965. Q20 = quanttbl->quantval[Q20_POS];
  168966. Q11 = quanttbl->quantval[Q11_POS];
  168967. Q02 = quanttbl->quantval[Q02_POS];
  168968. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168969. output_ptr = output_buf[ci];
  168970. /* Loop over all DCT blocks to be processed. */
  168971. for (block_row = 0; block_row < block_rows; block_row++) {
  168972. buffer_ptr = buffer[block_row];
  168973. if (first_row && block_row == 0)
  168974. prev_block_row = buffer_ptr;
  168975. else
  168976. prev_block_row = buffer[block_row-1];
  168977. if (last_row && block_row == block_rows-1)
  168978. next_block_row = buffer_ptr;
  168979. else
  168980. next_block_row = buffer[block_row+1];
  168981. /* We fetch the surrounding DC values using a sliding-register approach.
  168982. * Initialize all nine here so as to do the right thing on narrow pics.
  168983. */
  168984. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168985. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168986. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168987. output_col = 0;
  168988. last_block_column = compptr->width_in_blocks - 1;
  168989. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168990. /* Fetch current DCT block into workspace so we can modify it. */
  168991. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168992. /* Update DC values */
  168993. if (block_num < last_block_column) {
  168994. DC3 = (int) prev_block_row[1][0];
  168995. DC6 = (int) buffer_ptr[1][0];
  168996. DC9 = (int) next_block_row[1][0];
  168997. }
  168998. /* Compute coefficient estimates per K.8.
  168999. * An estimate is applied only if coefficient is still zero,
  169000. * and is not known to be fully accurate.
  169001. */
  169002. /* AC01 */
  169003. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169004. num = 36 * Q00 * (DC4 - DC6);
  169005. if (num >= 0) {
  169006. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169007. if (Al > 0 && pred >= (1<<Al))
  169008. pred = (1<<Al)-1;
  169009. } else {
  169010. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169011. if (Al > 0 && pred >= (1<<Al))
  169012. pred = (1<<Al)-1;
  169013. pred = -pred;
  169014. }
  169015. workspace[1] = (JCOEF) pred;
  169016. }
  169017. /* AC10 */
  169018. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169019. num = 36 * Q00 * (DC2 - DC8);
  169020. if (num >= 0) {
  169021. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169022. if (Al > 0 && pred >= (1<<Al))
  169023. pred = (1<<Al)-1;
  169024. } else {
  169025. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169026. if (Al > 0 && pred >= (1<<Al))
  169027. pred = (1<<Al)-1;
  169028. pred = -pred;
  169029. }
  169030. workspace[8] = (JCOEF) pred;
  169031. }
  169032. /* AC20 */
  169033. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169034. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169035. if (num >= 0) {
  169036. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169037. if (Al > 0 && pred >= (1<<Al))
  169038. pred = (1<<Al)-1;
  169039. } else {
  169040. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169041. if (Al > 0 && pred >= (1<<Al))
  169042. pred = (1<<Al)-1;
  169043. pred = -pred;
  169044. }
  169045. workspace[16] = (JCOEF) pred;
  169046. }
  169047. /* AC11 */
  169048. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169049. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169050. if (num >= 0) {
  169051. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169052. if (Al > 0 && pred >= (1<<Al))
  169053. pred = (1<<Al)-1;
  169054. } else {
  169055. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169056. if (Al > 0 && pred >= (1<<Al))
  169057. pred = (1<<Al)-1;
  169058. pred = -pred;
  169059. }
  169060. workspace[9] = (JCOEF) pred;
  169061. }
  169062. /* AC02 */
  169063. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169064. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169065. if (num >= 0) {
  169066. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169067. if (Al > 0 && pred >= (1<<Al))
  169068. pred = (1<<Al)-1;
  169069. } else {
  169070. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169071. if (Al > 0 && pred >= (1<<Al))
  169072. pred = (1<<Al)-1;
  169073. pred = -pred;
  169074. }
  169075. workspace[2] = (JCOEF) pred;
  169076. }
  169077. /* OK, do the IDCT */
  169078. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169079. output_ptr, output_col);
  169080. /* Advance for next column */
  169081. DC1 = DC2; DC2 = DC3;
  169082. DC4 = DC5; DC5 = DC6;
  169083. DC7 = DC8; DC8 = DC9;
  169084. buffer_ptr++, prev_block_row++, next_block_row++;
  169085. output_col += compptr->DCT_scaled_size;
  169086. }
  169087. output_ptr += compptr->DCT_scaled_size;
  169088. }
  169089. }
  169090. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169091. return JPEG_ROW_COMPLETED;
  169092. return JPEG_SCAN_COMPLETED;
  169093. }
  169094. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169095. /*
  169096. * Initialize coefficient buffer controller.
  169097. */
  169098. GLOBAL(void)
  169099. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169100. {
  169101. my_coef_ptr3 coef;
  169102. coef = (my_coef_ptr3)
  169103. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169104. SIZEOF(my_coef_controller3));
  169105. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169106. coef->pub.start_input_pass = start_input_pass;
  169107. coef->pub.start_output_pass = start_output_pass;
  169108. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169109. coef->coef_bits_latch = NULL;
  169110. #endif
  169111. /* Create the coefficient buffer. */
  169112. if (need_full_buffer) {
  169113. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169114. /* Allocate a full-image virtual array for each component, */
  169115. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169116. /* Note we ask for a pre-zeroed array. */
  169117. int ci, access_rows;
  169118. jpeg_component_info *compptr;
  169119. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169120. ci++, compptr++) {
  169121. access_rows = compptr->v_samp_factor;
  169122. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169123. /* If block smoothing could be used, need a bigger window */
  169124. if (cinfo->progressive_mode)
  169125. access_rows *= 3;
  169126. #endif
  169127. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169128. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169129. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169130. (long) compptr->h_samp_factor),
  169131. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169132. (long) compptr->v_samp_factor),
  169133. (JDIMENSION) access_rows);
  169134. }
  169135. coef->pub.consume_data = consume_data;
  169136. coef->pub.decompress_data = decompress_data;
  169137. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169138. #else
  169139. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169140. #endif
  169141. } else {
  169142. /* We only need a single-MCU buffer. */
  169143. JBLOCKROW buffer;
  169144. int i;
  169145. buffer = (JBLOCKROW)
  169146. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169147. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169148. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169149. coef->MCU_buffer[i] = buffer + i;
  169150. }
  169151. coef->pub.consume_data = dummy_consume_data;
  169152. coef->pub.decompress_data = decompress_onepass;
  169153. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169154. }
  169155. }
  169156. /*** End of inlined file: jdcoefct.c ***/
  169157. #undef FIX
  169158. /*** Start of inlined file: jdcolor.c ***/
  169159. #define JPEG_INTERNALS
  169160. /* Private subobject */
  169161. typedef struct {
  169162. struct jpeg_color_deconverter pub; /* public fields */
  169163. /* Private state for YCC->RGB conversion */
  169164. int * Cr_r_tab; /* => table for Cr to R conversion */
  169165. int * Cb_b_tab; /* => table for Cb to B conversion */
  169166. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169167. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169168. } my_color_deconverter2;
  169169. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169170. /**************** YCbCr -> RGB conversion: most common case **************/
  169171. /*
  169172. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169173. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169174. * The conversion equations to be implemented are therefore
  169175. * R = Y + 1.40200 * Cr
  169176. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169177. * B = Y + 1.77200 * Cb
  169178. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169179. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169180. *
  169181. * To avoid floating-point arithmetic, we represent the fractional constants
  169182. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169183. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169184. * Notice that Y, being an integral input, does not contribute any fraction
  169185. * so it need not participate in the rounding.
  169186. *
  169187. * For even more speed, we avoid doing any multiplications in the inner loop
  169188. * by precalculating the constants times Cb and Cr for all possible values.
  169189. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169190. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169191. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169192. * colorspace anyway.
  169193. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169194. * values for the G calculation are left scaled up, since we must add them
  169195. * together before rounding.
  169196. */
  169197. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169198. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169199. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169200. /*
  169201. * Initialize tables for YCC->RGB colorspace conversion.
  169202. */
  169203. LOCAL(void)
  169204. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169205. {
  169206. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169207. int i;
  169208. INT32 x;
  169209. SHIFT_TEMPS
  169210. cconvert->Cr_r_tab = (int *)
  169211. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169212. (MAXJSAMPLE+1) * SIZEOF(int));
  169213. cconvert->Cb_b_tab = (int *)
  169214. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169215. (MAXJSAMPLE+1) * SIZEOF(int));
  169216. cconvert->Cr_g_tab = (INT32 *)
  169217. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169218. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169219. cconvert->Cb_g_tab = (INT32 *)
  169220. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169221. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169222. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169223. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169224. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169225. /* Cr=>R value is nearest int to 1.40200 * x */
  169226. cconvert->Cr_r_tab[i] = (int)
  169227. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169228. /* Cb=>B value is nearest int to 1.77200 * x */
  169229. cconvert->Cb_b_tab[i] = (int)
  169230. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169231. /* Cr=>G value is scaled-up -0.71414 * x */
  169232. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169233. /* Cb=>G value is scaled-up -0.34414 * x */
  169234. /* We also add in ONE_HALF so that need not do it in inner loop */
  169235. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169236. }
  169237. }
  169238. /*
  169239. * Convert some rows of samples to the output colorspace.
  169240. *
  169241. * Note that we change from noninterleaved, one-plane-per-component format
  169242. * to interleaved-pixel format. The output buffer is therefore three times
  169243. * as wide as the input buffer.
  169244. * A starting row offset is provided only for the input buffer. The caller
  169245. * can easily adjust the passed output_buf value to accommodate any row
  169246. * offset required on that side.
  169247. */
  169248. METHODDEF(void)
  169249. ycc_rgb_convert (j_decompress_ptr cinfo,
  169250. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169251. JSAMPARRAY output_buf, int num_rows)
  169252. {
  169253. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169254. register int y, cb, cr;
  169255. register JSAMPROW outptr;
  169256. register JSAMPROW inptr0, inptr1, inptr2;
  169257. register JDIMENSION col;
  169258. JDIMENSION num_cols = cinfo->output_width;
  169259. /* copy these pointers into registers if possible */
  169260. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169261. register int * Crrtab = cconvert->Cr_r_tab;
  169262. register int * Cbbtab = cconvert->Cb_b_tab;
  169263. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169264. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169265. SHIFT_TEMPS
  169266. while (--num_rows >= 0) {
  169267. inptr0 = input_buf[0][input_row];
  169268. inptr1 = input_buf[1][input_row];
  169269. inptr2 = input_buf[2][input_row];
  169270. input_row++;
  169271. outptr = *output_buf++;
  169272. for (col = 0; col < num_cols; col++) {
  169273. y = GETJSAMPLE(inptr0[col]);
  169274. cb = GETJSAMPLE(inptr1[col]);
  169275. cr = GETJSAMPLE(inptr2[col]);
  169276. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169277. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169278. outptr[RGB_GREEN] = range_limit[y +
  169279. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169280. SCALEBITS))];
  169281. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169282. outptr += RGB_PIXELSIZE;
  169283. }
  169284. }
  169285. }
  169286. /**************** Cases other than YCbCr -> RGB **************/
  169287. /*
  169288. * Color conversion for no colorspace change: just copy the data,
  169289. * converting from separate-planes to interleaved representation.
  169290. */
  169291. METHODDEF(void)
  169292. null_convert2 (j_decompress_ptr cinfo,
  169293. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169294. JSAMPARRAY output_buf, int num_rows)
  169295. {
  169296. register JSAMPROW inptr, outptr;
  169297. register JDIMENSION count;
  169298. register int num_components = cinfo->num_components;
  169299. JDIMENSION num_cols = cinfo->output_width;
  169300. int ci;
  169301. while (--num_rows >= 0) {
  169302. for (ci = 0; ci < num_components; ci++) {
  169303. inptr = input_buf[ci][input_row];
  169304. outptr = output_buf[0] + ci;
  169305. for (count = num_cols; count > 0; count--) {
  169306. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169307. outptr += num_components;
  169308. }
  169309. }
  169310. input_row++;
  169311. output_buf++;
  169312. }
  169313. }
  169314. /*
  169315. * Color conversion for grayscale: just copy the data.
  169316. * This also works for YCbCr -> grayscale conversion, in which
  169317. * we just copy the Y (luminance) component and ignore chrominance.
  169318. */
  169319. METHODDEF(void)
  169320. grayscale_convert2 (j_decompress_ptr cinfo,
  169321. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169322. JSAMPARRAY output_buf, int num_rows)
  169323. {
  169324. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169325. num_rows, cinfo->output_width);
  169326. }
  169327. /*
  169328. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169329. * This is provided to support applications that don't want to cope
  169330. * with grayscale as a separate case.
  169331. */
  169332. METHODDEF(void)
  169333. gray_rgb_convert (j_decompress_ptr cinfo,
  169334. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169335. JSAMPARRAY output_buf, int num_rows)
  169336. {
  169337. register JSAMPROW inptr, outptr;
  169338. register JDIMENSION col;
  169339. JDIMENSION num_cols = cinfo->output_width;
  169340. while (--num_rows >= 0) {
  169341. inptr = input_buf[0][input_row++];
  169342. outptr = *output_buf++;
  169343. for (col = 0; col < num_cols; col++) {
  169344. /* We can dispense with GETJSAMPLE() here */
  169345. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169346. outptr += RGB_PIXELSIZE;
  169347. }
  169348. }
  169349. }
  169350. /*
  169351. * Adobe-style YCCK->CMYK conversion.
  169352. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169353. * conversion as above, while passing K (black) unchanged.
  169354. * We assume build_ycc_rgb_table has been called.
  169355. */
  169356. METHODDEF(void)
  169357. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169358. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169359. JSAMPARRAY output_buf, int num_rows)
  169360. {
  169361. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169362. register int y, cb, cr;
  169363. register JSAMPROW outptr;
  169364. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169365. register JDIMENSION col;
  169366. JDIMENSION num_cols = cinfo->output_width;
  169367. /* copy these pointers into registers if possible */
  169368. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169369. register int * Crrtab = cconvert->Cr_r_tab;
  169370. register int * Cbbtab = cconvert->Cb_b_tab;
  169371. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169372. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169373. SHIFT_TEMPS
  169374. while (--num_rows >= 0) {
  169375. inptr0 = input_buf[0][input_row];
  169376. inptr1 = input_buf[1][input_row];
  169377. inptr2 = input_buf[2][input_row];
  169378. inptr3 = input_buf[3][input_row];
  169379. input_row++;
  169380. outptr = *output_buf++;
  169381. for (col = 0; col < num_cols; col++) {
  169382. y = GETJSAMPLE(inptr0[col]);
  169383. cb = GETJSAMPLE(inptr1[col]);
  169384. cr = GETJSAMPLE(inptr2[col]);
  169385. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169386. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169387. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169388. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169389. SCALEBITS)))];
  169390. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169391. /* K passes through unchanged */
  169392. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169393. outptr += 4;
  169394. }
  169395. }
  169396. }
  169397. /*
  169398. * Empty method for start_pass.
  169399. */
  169400. METHODDEF(void)
  169401. start_pass_dcolor (j_decompress_ptr)
  169402. {
  169403. /* no work needed */
  169404. }
  169405. /*
  169406. * Module initialization routine for output colorspace conversion.
  169407. */
  169408. GLOBAL(void)
  169409. jinit_color_deconverter (j_decompress_ptr cinfo)
  169410. {
  169411. my_cconvert_ptr2 cconvert;
  169412. int ci;
  169413. cconvert = (my_cconvert_ptr2)
  169414. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169415. SIZEOF(my_color_deconverter2));
  169416. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169417. cconvert->pub.start_pass = start_pass_dcolor;
  169418. /* Make sure num_components agrees with jpeg_color_space */
  169419. switch (cinfo->jpeg_color_space) {
  169420. case JCS_GRAYSCALE:
  169421. if (cinfo->num_components != 1)
  169422. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169423. break;
  169424. case JCS_RGB:
  169425. case JCS_YCbCr:
  169426. if (cinfo->num_components != 3)
  169427. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169428. break;
  169429. case JCS_CMYK:
  169430. case JCS_YCCK:
  169431. if (cinfo->num_components != 4)
  169432. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169433. break;
  169434. default: /* JCS_UNKNOWN can be anything */
  169435. if (cinfo->num_components < 1)
  169436. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169437. break;
  169438. }
  169439. /* Set out_color_components and conversion method based on requested space.
  169440. * Also clear the component_needed flags for any unused components,
  169441. * so that earlier pipeline stages can avoid useless computation.
  169442. */
  169443. switch (cinfo->out_color_space) {
  169444. case JCS_GRAYSCALE:
  169445. cinfo->out_color_components = 1;
  169446. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169447. cinfo->jpeg_color_space == JCS_YCbCr) {
  169448. cconvert->pub.color_convert = grayscale_convert2;
  169449. /* For color->grayscale conversion, only the Y (0) component is needed */
  169450. for (ci = 1; ci < cinfo->num_components; ci++)
  169451. cinfo->comp_info[ci].component_needed = FALSE;
  169452. } else
  169453. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169454. break;
  169455. case JCS_RGB:
  169456. cinfo->out_color_components = RGB_PIXELSIZE;
  169457. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169458. cconvert->pub.color_convert = ycc_rgb_convert;
  169459. build_ycc_rgb_table(cinfo);
  169460. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169461. cconvert->pub.color_convert = gray_rgb_convert;
  169462. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169463. cconvert->pub.color_convert = null_convert2;
  169464. } else
  169465. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169466. break;
  169467. case JCS_CMYK:
  169468. cinfo->out_color_components = 4;
  169469. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169470. cconvert->pub.color_convert = ycck_cmyk_convert;
  169471. build_ycc_rgb_table(cinfo);
  169472. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169473. cconvert->pub.color_convert = null_convert2;
  169474. } else
  169475. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169476. break;
  169477. default:
  169478. /* Permit null conversion to same output space */
  169479. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169480. cinfo->out_color_components = cinfo->num_components;
  169481. cconvert->pub.color_convert = null_convert2;
  169482. } else /* unsupported non-null conversion */
  169483. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169484. break;
  169485. }
  169486. if (cinfo->quantize_colors)
  169487. cinfo->output_components = 1; /* single colormapped output component */
  169488. else
  169489. cinfo->output_components = cinfo->out_color_components;
  169490. }
  169491. /*** End of inlined file: jdcolor.c ***/
  169492. #undef FIX
  169493. /*** Start of inlined file: jddctmgr.c ***/
  169494. #define JPEG_INTERNALS
  169495. /*
  169496. * The decompressor input side (jdinput.c) saves away the appropriate
  169497. * quantization table for each component at the start of the first scan
  169498. * involving that component. (This is necessary in order to correctly
  169499. * decode files that reuse Q-table slots.)
  169500. * When we are ready to make an output pass, the saved Q-table is converted
  169501. * to a multiplier table that will actually be used by the IDCT routine.
  169502. * The multiplier table contents are IDCT-method-dependent. To support
  169503. * application changes in IDCT method between scans, we can remake the
  169504. * multiplier tables if necessary.
  169505. * In buffered-image mode, the first output pass may occur before any data
  169506. * has been seen for some components, and thus before their Q-tables have
  169507. * been saved away. To handle this case, multiplier tables are preset
  169508. * to zeroes; the result of the IDCT will be a neutral gray level.
  169509. */
  169510. /* Private subobject for this module */
  169511. typedef struct {
  169512. struct jpeg_inverse_dct pub; /* public fields */
  169513. /* This array contains the IDCT method code that each multiplier table
  169514. * is currently set up for, or -1 if it's not yet set up.
  169515. * The actual multiplier tables are pointed to by dct_table in the
  169516. * per-component comp_info structures.
  169517. */
  169518. int cur_method[MAX_COMPONENTS];
  169519. } my_idct_controller;
  169520. typedef my_idct_controller * my_idct_ptr;
  169521. /* Allocated multiplier tables: big enough for any supported variant */
  169522. typedef union {
  169523. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169524. #ifdef DCT_IFAST_SUPPORTED
  169525. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169526. #endif
  169527. #ifdef DCT_FLOAT_SUPPORTED
  169528. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169529. #endif
  169530. } multiplier_table;
  169531. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169532. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169533. */
  169534. #ifdef DCT_ISLOW_SUPPORTED
  169535. #define PROVIDE_ISLOW_TABLES
  169536. #else
  169537. #ifdef IDCT_SCALING_SUPPORTED
  169538. #define PROVIDE_ISLOW_TABLES
  169539. #endif
  169540. #endif
  169541. /*
  169542. * Prepare for an output pass.
  169543. * Here we select the proper IDCT routine for each component and build
  169544. * a matching multiplier table.
  169545. */
  169546. METHODDEF(void)
  169547. start_pass (j_decompress_ptr cinfo)
  169548. {
  169549. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169550. int ci, i;
  169551. jpeg_component_info *compptr;
  169552. int method = 0;
  169553. inverse_DCT_method_ptr method_ptr = NULL;
  169554. JQUANT_TBL * qtbl;
  169555. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169556. ci++, compptr++) {
  169557. /* Select the proper IDCT routine for this component's scaling */
  169558. switch (compptr->DCT_scaled_size) {
  169559. #ifdef IDCT_SCALING_SUPPORTED
  169560. case 1:
  169561. method_ptr = jpeg_idct_1x1;
  169562. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169563. break;
  169564. case 2:
  169565. method_ptr = jpeg_idct_2x2;
  169566. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169567. break;
  169568. case 4:
  169569. method_ptr = jpeg_idct_4x4;
  169570. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169571. break;
  169572. #endif
  169573. case DCTSIZE:
  169574. switch (cinfo->dct_method) {
  169575. #ifdef DCT_ISLOW_SUPPORTED
  169576. case JDCT_ISLOW:
  169577. method_ptr = jpeg_idct_islow;
  169578. method = JDCT_ISLOW;
  169579. break;
  169580. #endif
  169581. #ifdef DCT_IFAST_SUPPORTED
  169582. case JDCT_IFAST:
  169583. method_ptr = jpeg_idct_ifast;
  169584. method = JDCT_IFAST;
  169585. break;
  169586. #endif
  169587. #ifdef DCT_FLOAT_SUPPORTED
  169588. case JDCT_FLOAT:
  169589. method_ptr = jpeg_idct_float;
  169590. method = JDCT_FLOAT;
  169591. break;
  169592. #endif
  169593. default:
  169594. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169595. break;
  169596. }
  169597. break;
  169598. default:
  169599. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169600. break;
  169601. }
  169602. idct->pub.inverse_DCT[ci] = method_ptr;
  169603. /* Create multiplier table from quant table.
  169604. * However, we can skip this if the component is uninteresting
  169605. * or if we already built the table. Also, if no quant table
  169606. * has yet been saved for the component, we leave the
  169607. * multiplier table all-zero; we'll be reading zeroes from the
  169608. * coefficient controller's buffer anyway.
  169609. */
  169610. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169611. continue;
  169612. qtbl = compptr->quant_table;
  169613. if (qtbl == NULL) /* happens if no data yet for component */
  169614. continue;
  169615. idct->cur_method[ci] = method;
  169616. switch (method) {
  169617. #ifdef PROVIDE_ISLOW_TABLES
  169618. case JDCT_ISLOW:
  169619. {
  169620. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169621. * coefficients, but are stored as ints to ensure access efficiency.
  169622. */
  169623. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169624. for (i = 0; i < DCTSIZE2; i++) {
  169625. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169626. }
  169627. }
  169628. break;
  169629. #endif
  169630. #ifdef DCT_IFAST_SUPPORTED
  169631. case JDCT_IFAST:
  169632. {
  169633. /* For AA&N IDCT method, multipliers are equal to quantization
  169634. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169635. * scalefactor[0] = 1
  169636. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169637. * For integer operation, the multiplier table is to be scaled by
  169638. * IFAST_SCALE_BITS.
  169639. */
  169640. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169641. #define CONST_BITS 14
  169642. static const INT16 aanscales[DCTSIZE2] = {
  169643. /* precomputed values scaled up by 14 bits */
  169644. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169645. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169646. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169647. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169648. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169649. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169650. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169651. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169652. };
  169653. SHIFT_TEMPS
  169654. for (i = 0; i < DCTSIZE2; i++) {
  169655. ifmtbl[i] = (IFAST_MULT_TYPE)
  169656. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169657. (INT32) aanscales[i]),
  169658. CONST_BITS-IFAST_SCALE_BITS);
  169659. }
  169660. }
  169661. break;
  169662. #endif
  169663. #ifdef DCT_FLOAT_SUPPORTED
  169664. case JDCT_FLOAT:
  169665. {
  169666. /* For float AA&N IDCT method, multipliers are equal to quantization
  169667. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169668. * scalefactor[0] = 1
  169669. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169670. */
  169671. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169672. int row, col;
  169673. static const double aanscalefactor[DCTSIZE] = {
  169674. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169675. 1.0, 0.785694958, 0.541196100, 0.275899379
  169676. };
  169677. i = 0;
  169678. for (row = 0; row < DCTSIZE; row++) {
  169679. for (col = 0; col < DCTSIZE; col++) {
  169680. fmtbl[i] = (FLOAT_MULT_TYPE)
  169681. ((double) qtbl->quantval[i] *
  169682. aanscalefactor[row] * aanscalefactor[col]);
  169683. i++;
  169684. }
  169685. }
  169686. }
  169687. break;
  169688. #endif
  169689. default:
  169690. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169691. break;
  169692. }
  169693. }
  169694. }
  169695. /*
  169696. * Initialize IDCT manager.
  169697. */
  169698. GLOBAL(void)
  169699. jinit_inverse_dct (j_decompress_ptr cinfo)
  169700. {
  169701. my_idct_ptr idct;
  169702. int ci;
  169703. jpeg_component_info *compptr;
  169704. idct = (my_idct_ptr)
  169705. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169706. SIZEOF(my_idct_controller));
  169707. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169708. idct->pub.start_pass = start_pass;
  169709. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169710. ci++, compptr++) {
  169711. /* Allocate and pre-zero a multiplier table for each component */
  169712. compptr->dct_table =
  169713. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169714. SIZEOF(multiplier_table));
  169715. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169716. /* Mark multiplier table not yet set up for any method */
  169717. idct->cur_method[ci] = -1;
  169718. }
  169719. }
  169720. /*** End of inlined file: jddctmgr.c ***/
  169721. #undef CONST_BITS
  169722. #undef ASSIGN_STATE
  169723. /*** Start of inlined file: jdhuff.c ***/
  169724. #define JPEG_INTERNALS
  169725. /*** Start of inlined file: jdhuff.h ***/
  169726. /* Short forms of external names for systems with brain-damaged linkers. */
  169727. #ifndef __jdhuff_h__
  169728. #define __jdhuff_h__
  169729. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169730. #define jpeg_make_d_derived_tbl jMkDDerived
  169731. #define jpeg_fill_bit_buffer jFilBitBuf
  169732. #define jpeg_huff_decode jHufDecode
  169733. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169734. /* Derived data constructed for each Huffman table */
  169735. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169736. typedef struct {
  169737. /* Basic tables: (element [0] of each array is unused) */
  169738. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169739. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169740. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169741. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169742. * the smallest code of length k; so given a code of length k, the
  169743. * corresponding symbol is huffval[code + valoffset[k]]
  169744. */
  169745. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169746. JHUFF_TBL *pub;
  169747. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169748. * the input data stream. If the next Huffman code is no more
  169749. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169750. * the corresponding symbol directly from these tables.
  169751. */
  169752. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169753. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169754. } d_derived_tbl;
  169755. /* Expand a Huffman table definition into the derived format */
  169756. EXTERN(void) jpeg_make_d_derived_tbl
  169757. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169758. d_derived_tbl ** pdtbl));
  169759. /*
  169760. * Fetching the next N bits from the input stream is a time-critical operation
  169761. * for the Huffman decoders. We implement it with a combination of inline
  169762. * macros and out-of-line subroutines. Note that N (the number of bits
  169763. * demanded at one time) never exceeds 15 for JPEG use.
  169764. *
  169765. * We read source bytes into get_buffer and dole out bits as needed.
  169766. * If get_buffer already contains enough bits, they are fetched in-line
  169767. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169768. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169769. * as full as possible (not just to the number of bits needed; this
  169770. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169771. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169772. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169773. * at least the requested number of bits --- dummy zeroes are inserted if
  169774. * necessary.
  169775. */
  169776. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169777. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169778. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169779. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169780. * appropriately should be a win. Unfortunately we can't define the size
  169781. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169782. * because not all machines measure sizeof in 8-bit bytes.
  169783. */
  169784. typedef struct { /* Bitreading state saved across MCUs */
  169785. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169786. int bits_left; /* # of unused bits in it */
  169787. } bitread_perm_state;
  169788. typedef struct { /* Bitreading working state within an MCU */
  169789. /* Current data source location */
  169790. /* We need a copy, rather than munging the original, in case of suspension */
  169791. const JOCTET * next_input_byte; /* => next byte to read from source */
  169792. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169793. /* Bit input buffer --- note these values are kept in register variables,
  169794. * not in this struct, inside the inner loops.
  169795. */
  169796. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169797. int bits_left; /* # of unused bits in it */
  169798. /* Pointer needed by jpeg_fill_bit_buffer. */
  169799. j_decompress_ptr cinfo; /* back link to decompress master record */
  169800. } bitread_working_state;
  169801. /* Macros to declare and load/save bitread local variables. */
  169802. #define BITREAD_STATE_VARS \
  169803. register bit_buf_type get_buffer; \
  169804. register int bits_left; \
  169805. bitread_working_state br_state
  169806. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169807. br_state.cinfo = cinfop; \
  169808. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169809. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169810. get_buffer = permstate.get_buffer; \
  169811. bits_left = permstate.bits_left;
  169812. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169813. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169814. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169815. permstate.get_buffer = get_buffer; \
  169816. permstate.bits_left = bits_left
  169817. /*
  169818. * These macros provide the in-line portion of bit fetching.
  169819. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169820. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169821. * The variables get_buffer and bits_left are assumed to be locals,
  169822. * but the state struct might not be (jpeg_huff_decode needs this).
  169823. * CHECK_BIT_BUFFER(state,n,action);
  169824. * Ensure there are N bits in get_buffer; if suspend, take action.
  169825. * val = GET_BITS(n);
  169826. * Fetch next N bits.
  169827. * val = PEEK_BITS(n);
  169828. * Fetch next N bits without removing them from the buffer.
  169829. * DROP_BITS(n);
  169830. * Discard next N bits.
  169831. * The value N should be a simple variable, not an expression, because it
  169832. * is evaluated multiple times.
  169833. */
  169834. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169835. { if (bits_left < (nbits)) { \
  169836. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169837. { action; } \
  169838. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169839. #define GET_BITS(nbits) \
  169840. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169841. #define PEEK_BITS(nbits) \
  169842. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169843. #define DROP_BITS(nbits) \
  169844. (bits_left -= (nbits))
  169845. /* Load up the bit buffer to a depth of at least nbits */
  169846. EXTERN(boolean) jpeg_fill_bit_buffer
  169847. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169848. register int bits_left, int nbits));
  169849. /*
  169850. * Code for extracting next Huffman-coded symbol from input bit stream.
  169851. * Again, this is time-critical and we make the main paths be macros.
  169852. *
  169853. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169854. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169855. * or fewer bits long. The few overlength codes are handled with a loop,
  169856. * which need not be inline code.
  169857. *
  169858. * Notes about the HUFF_DECODE macro:
  169859. * 1. Near the end of the data segment, we may fail to get enough bits
  169860. * for a lookahead. In that case, we do it the hard way.
  169861. * 2. If the lookahead table contains no entry, the next code must be
  169862. * more than HUFF_LOOKAHEAD bits long.
  169863. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169864. */
  169865. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169866. { register int nb, look; \
  169867. if (bits_left < HUFF_LOOKAHEAD) { \
  169868. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169869. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169870. if (bits_left < HUFF_LOOKAHEAD) { \
  169871. nb = 1; goto slowlabel; \
  169872. } \
  169873. } \
  169874. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169875. if ((nb = htbl->look_nbits[look]) != 0) { \
  169876. DROP_BITS(nb); \
  169877. result = htbl->look_sym[look]; \
  169878. } else { \
  169879. nb = HUFF_LOOKAHEAD+1; \
  169880. slowlabel: \
  169881. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169882. { failaction; } \
  169883. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169884. } \
  169885. }
  169886. /* Out-of-line case for Huffman code fetching */
  169887. EXTERN(int) jpeg_huff_decode
  169888. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169889. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169890. #endif
  169891. /*** End of inlined file: jdhuff.h ***/
  169892. /* Declarations shared with jdphuff.c */
  169893. /*
  169894. * Expanded entropy decoder object for Huffman decoding.
  169895. *
  169896. * The savable_state subrecord contains fields that change within an MCU,
  169897. * but must not be updated permanently until we complete the MCU.
  169898. */
  169899. typedef struct {
  169900. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169901. } savable_state2;
  169902. /* This macro is to work around compilers with missing or broken
  169903. * structure assignment. You'll need to fix this code if you have
  169904. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169905. */
  169906. #ifndef NO_STRUCT_ASSIGN
  169907. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169908. #else
  169909. #if MAX_COMPS_IN_SCAN == 4
  169910. #define ASSIGN_STATE(dest,src) \
  169911. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169912. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169913. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169914. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169915. #endif
  169916. #endif
  169917. typedef struct {
  169918. struct jpeg_entropy_decoder pub; /* public fields */
  169919. /* These fields are loaded into local variables at start of each MCU.
  169920. * In case of suspension, we exit WITHOUT updating them.
  169921. */
  169922. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169923. savable_state2 saved; /* Other state at start of MCU */
  169924. /* These fields are NOT loaded into local working state. */
  169925. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169926. /* Pointers to derived tables (these workspaces have image lifespan) */
  169927. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169928. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169929. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169930. /* Pointers to derived tables to be used for each block within an MCU */
  169931. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169932. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169933. /* Whether we care about the DC and AC coefficient values for each block */
  169934. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169935. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169936. } huff_entropy_decoder2;
  169937. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169938. /*
  169939. * Initialize for a Huffman-compressed scan.
  169940. */
  169941. METHODDEF(void)
  169942. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169943. {
  169944. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169945. int ci, blkn, dctbl, actbl;
  169946. jpeg_component_info * compptr;
  169947. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169948. * This ought to be an error condition, but we make it a warning because
  169949. * there are some baseline files out there with all zeroes in these bytes.
  169950. */
  169951. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169952. cinfo->Ah != 0 || cinfo->Al != 0)
  169953. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169954. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169955. compptr = cinfo->cur_comp_info[ci];
  169956. dctbl = compptr->dc_tbl_no;
  169957. actbl = compptr->ac_tbl_no;
  169958. /* Compute derived values for Huffman tables */
  169959. /* We may do this more than once for a table, but it's not expensive */
  169960. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169961. & entropy->dc_derived_tbls[dctbl]);
  169962. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169963. & entropy->ac_derived_tbls[actbl]);
  169964. /* Initialize DC predictions to 0 */
  169965. entropy->saved.last_dc_val[ci] = 0;
  169966. }
  169967. /* Precalculate decoding info for each block in an MCU of this scan */
  169968. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169969. ci = cinfo->MCU_membership[blkn];
  169970. compptr = cinfo->cur_comp_info[ci];
  169971. /* Precalculate which table to use for each block */
  169972. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169973. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169974. /* Decide whether we really care about the coefficient values */
  169975. if (compptr->component_needed) {
  169976. entropy->dc_needed[blkn] = TRUE;
  169977. /* we don't need the ACs if producing a 1/8th-size image */
  169978. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169979. } else {
  169980. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169981. }
  169982. }
  169983. /* Initialize bitread state variables */
  169984. entropy->bitstate.bits_left = 0;
  169985. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169986. entropy->pub.insufficient_data = FALSE;
  169987. /* Initialize restart counter */
  169988. entropy->restarts_to_go = cinfo->restart_interval;
  169989. }
  169990. /*
  169991. * Compute the derived values for a Huffman table.
  169992. * This routine also performs some validation checks on the table.
  169993. *
  169994. * Note this is also used by jdphuff.c.
  169995. */
  169996. GLOBAL(void)
  169997. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169998. d_derived_tbl ** pdtbl)
  169999. {
  170000. JHUFF_TBL *htbl;
  170001. d_derived_tbl *dtbl;
  170002. int p, i, l, si, numsymbols;
  170003. int lookbits, ctr;
  170004. char huffsize[257];
  170005. unsigned int huffcode[257];
  170006. unsigned int code;
  170007. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170008. * paralleling the order of the symbols themselves in htbl->huffval[].
  170009. */
  170010. /* Find the input Huffman table */
  170011. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170012. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170013. htbl =
  170014. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170015. if (htbl == NULL)
  170016. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170017. /* Allocate a workspace if we haven't already done so. */
  170018. if (*pdtbl == NULL)
  170019. *pdtbl = (d_derived_tbl *)
  170020. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170021. SIZEOF(d_derived_tbl));
  170022. dtbl = *pdtbl;
  170023. dtbl->pub = htbl; /* fill in back link */
  170024. /* Figure C.1: make table of Huffman code length for each symbol */
  170025. p = 0;
  170026. for (l = 1; l <= 16; l++) {
  170027. i = (int) htbl->bits[l];
  170028. if (i < 0 || p + i > 256) /* protect against table overrun */
  170029. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170030. while (i--)
  170031. huffsize[p++] = (char) l;
  170032. }
  170033. huffsize[p] = 0;
  170034. numsymbols = p;
  170035. /* Figure C.2: generate the codes themselves */
  170036. /* We also validate that the counts represent a legal Huffman code tree. */
  170037. code = 0;
  170038. si = huffsize[0];
  170039. p = 0;
  170040. while (huffsize[p]) {
  170041. while (((int) huffsize[p]) == si) {
  170042. huffcode[p++] = code;
  170043. code++;
  170044. }
  170045. /* code is now 1 more than the last code used for codelength si; but
  170046. * it must still fit in si bits, since no code is allowed to be all ones.
  170047. */
  170048. if (((INT32) code) >= (((INT32) 1) << si))
  170049. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170050. code <<= 1;
  170051. si++;
  170052. }
  170053. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170054. p = 0;
  170055. for (l = 1; l <= 16; l++) {
  170056. if (htbl->bits[l]) {
  170057. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170058. * minus the minimum code of length l
  170059. */
  170060. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170061. p += htbl->bits[l];
  170062. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170063. } else {
  170064. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170065. }
  170066. }
  170067. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170068. /* Compute lookahead tables to speed up decoding.
  170069. * First we set all the table entries to 0, indicating "too long";
  170070. * then we iterate through the Huffman codes that are short enough and
  170071. * fill in all the entries that correspond to bit sequences starting
  170072. * with that code.
  170073. */
  170074. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170075. p = 0;
  170076. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170077. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170078. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170079. /* Generate left-justified code followed by all possible bit sequences */
  170080. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170081. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170082. dtbl->look_nbits[lookbits] = l;
  170083. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170084. lookbits++;
  170085. }
  170086. }
  170087. }
  170088. /* Validate symbols as being reasonable.
  170089. * For AC tables, we make no check, but accept all byte values 0..255.
  170090. * For DC tables, we require the symbols to be in range 0..15.
  170091. * (Tighter bounds could be applied depending on the data depth and mode,
  170092. * but this is sufficient to ensure safe decoding.)
  170093. */
  170094. if (isDC) {
  170095. for (i = 0; i < numsymbols; i++) {
  170096. int sym = htbl->huffval[i];
  170097. if (sym < 0 || sym > 15)
  170098. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170099. }
  170100. }
  170101. }
  170102. /*
  170103. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170104. * See jdhuff.h for info about usage.
  170105. * Note: current values of get_buffer and bits_left are passed as parameters,
  170106. * but are returned in the corresponding fields of the state struct.
  170107. *
  170108. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170109. * of get_buffer to be used. (On machines with wider words, an even larger
  170110. * buffer could be used.) However, on some machines 32-bit shifts are
  170111. * quite slow and take time proportional to the number of places shifted.
  170112. * (This is true with most PC compilers, for instance.) In this case it may
  170113. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170114. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170115. */
  170116. #ifdef SLOW_SHIFT_32
  170117. #define MIN_GET_BITS 15 /* minimum allowable value */
  170118. #else
  170119. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170120. #endif
  170121. GLOBAL(boolean)
  170122. jpeg_fill_bit_buffer (bitread_working_state * state,
  170123. register bit_buf_type get_buffer, register int bits_left,
  170124. int nbits)
  170125. /* Load up the bit buffer to a depth of at least nbits */
  170126. {
  170127. /* Copy heavily used state fields into locals (hopefully registers) */
  170128. register const JOCTET * next_input_byte = state->next_input_byte;
  170129. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170130. j_decompress_ptr cinfo = state->cinfo;
  170131. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170132. /* (It is assumed that no request will be for more than that many bits.) */
  170133. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170134. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170135. while (bits_left < MIN_GET_BITS) {
  170136. register int c;
  170137. /* Attempt to read a byte */
  170138. if (bytes_in_buffer == 0) {
  170139. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170140. return FALSE;
  170141. next_input_byte = cinfo->src->next_input_byte;
  170142. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170143. }
  170144. bytes_in_buffer--;
  170145. c = GETJOCTET(*next_input_byte++);
  170146. /* If it's 0xFF, check and discard stuffed zero byte */
  170147. if (c == 0xFF) {
  170148. /* Loop here to discard any padding FF's on terminating marker,
  170149. * so that we can save a valid unread_marker value. NOTE: we will
  170150. * accept multiple FF's followed by a 0 as meaning a single FF data
  170151. * byte. This data pattern is not valid according to the standard.
  170152. */
  170153. do {
  170154. if (bytes_in_buffer == 0) {
  170155. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170156. return FALSE;
  170157. next_input_byte = cinfo->src->next_input_byte;
  170158. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170159. }
  170160. bytes_in_buffer--;
  170161. c = GETJOCTET(*next_input_byte++);
  170162. } while (c == 0xFF);
  170163. if (c == 0) {
  170164. /* Found FF/00, which represents an FF data byte */
  170165. c = 0xFF;
  170166. } else {
  170167. /* Oops, it's actually a marker indicating end of compressed data.
  170168. * Save the marker code for later use.
  170169. * Fine point: it might appear that we should save the marker into
  170170. * bitread working state, not straight into permanent state. But
  170171. * once we have hit a marker, we cannot need to suspend within the
  170172. * current MCU, because we will read no more bytes from the data
  170173. * source. So it is OK to update permanent state right away.
  170174. */
  170175. cinfo->unread_marker = c;
  170176. /* See if we need to insert some fake zero bits. */
  170177. goto no_more_bytes;
  170178. }
  170179. }
  170180. /* OK, load c into get_buffer */
  170181. get_buffer = (get_buffer << 8) | c;
  170182. bits_left += 8;
  170183. } /* end while */
  170184. } else {
  170185. no_more_bytes:
  170186. /* We get here if we've read the marker that terminates the compressed
  170187. * data segment. There should be enough bits in the buffer register
  170188. * to satisfy the request; if so, no problem.
  170189. */
  170190. if (nbits > bits_left) {
  170191. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170192. * the data stream, so that we can produce some kind of image.
  170193. * We use a nonvolatile flag to ensure that only one warning message
  170194. * appears per data segment.
  170195. */
  170196. if (! cinfo->entropy->insufficient_data) {
  170197. WARNMS(cinfo, JWRN_HIT_MARKER);
  170198. cinfo->entropy->insufficient_data = TRUE;
  170199. }
  170200. /* Fill the buffer with zero bits */
  170201. get_buffer <<= MIN_GET_BITS - bits_left;
  170202. bits_left = MIN_GET_BITS;
  170203. }
  170204. }
  170205. /* Unload the local registers */
  170206. state->next_input_byte = next_input_byte;
  170207. state->bytes_in_buffer = bytes_in_buffer;
  170208. state->get_buffer = get_buffer;
  170209. state->bits_left = bits_left;
  170210. return TRUE;
  170211. }
  170212. /*
  170213. * Out-of-line code for Huffman code decoding.
  170214. * See jdhuff.h for info about usage.
  170215. */
  170216. GLOBAL(int)
  170217. jpeg_huff_decode (bitread_working_state * state,
  170218. register bit_buf_type get_buffer, register int bits_left,
  170219. d_derived_tbl * htbl, int min_bits)
  170220. {
  170221. register int l = min_bits;
  170222. register INT32 code;
  170223. /* HUFF_DECODE has determined that the code is at least min_bits */
  170224. /* bits long, so fetch that many bits in one swoop. */
  170225. CHECK_BIT_BUFFER(*state, l, return -1);
  170226. code = GET_BITS(l);
  170227. /* Collect the rest of the Huffman code one bit at a time. */
  170228. /* This is per Figure F.16 in the JPEG spec. */
  170229. while (code > htbl->maxcode[l]) {
  170230. code <<= 1;
  170231. CHECK_BIT_BUFFER(*state, 1, return -1);
  170232. code |= GET_BITS(1);
  170233. l++;
  170234. }
  170235. /* Unload the local registers */
  170236. state->get_buffer = get_buffer;
  170237. state->bits_left = bits_left;
  170238. /* With garbage input we may reach the sentinel value l = 17. */
  170239. if (l > 16) {
  170240. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170241. return 0; /* fake a zero as the safest result */
  170242. }
  170243. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170244. }
  170245. /*
  170246. * Check for a restart marker & resynchronize decoder.
  170247. * Returns FALSE if must suspend.
  170248. */
  170249. LOCAL(boolean)
  170250. process_restart (j_decompress_ptr cinfo)
  170251. {
  170252. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170253. int ci;
  170254. /* Throw away any unused bits remaining in bit buffer; */
  170255. /* include any full bytes in next_marker's count of discarded bytes */
  170256. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170257. entropy->bitstate.bits_left = 0;
  170258. /* Advance past the RSTn marker */
  170259. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170260. return FALSE;
  170261. /* Re-initialize DC predictions to 0 */
  170262. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170263. entropy->saved.last_dc_val[ci] = 0;
  170264. /* Reset restart counter */
  170265. entropy->restarts_to_go = cinfo->restart_interval;
  170266. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170267. * against a marker. In that case we will end up treating the next data
  170268. * segment as empty, and we can avoid producing bogus output pixels by
  170269. * leaving the flag set.
  170270. */
  170271. if (cinfo->unread_marker == 0)
  170272. entropy->pub.insufficient_data = FALSE;
  170273. return TRUE;
  170274. }
  170275. /*
  170276. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170277. * The coefficients are reordered from zigzag order into natural array order,
  170278. * but are not dequantized.
  170279. *
  170280. * The i'th block of the MCU is stored into the block pointed to by
  170281. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170282. * (Wholesale zeroing is usually a little faster than retail...)
  170283. *
  170284. * Returns FALSE if data source requested suspension. In that case no
  170285. * changes have been made to permanent state. (Exception: some output
  170286. * coefficients may already have been assigned. This is harmless for
  170287. * this module, since we'll just re-assign them on the next call.)
  170288. */
  170289. METHODDEF(boolean)
  170290. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170291. {
  170292. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170293. int blkn;
  170294. BITREAD_STATE_VARS;
  170295. savable_state2 state;
  170296. /* Process restart marker if needed; may have to suspend */
  170297. if (cinfo->restart_interval) {
  170298. if (entropy->restarts_to_go == 0)
  170299. if (! process_restart(cinfo))
  170300. return FALSE;
  170301. }
  170302. /* If we've run out of data, just leave the MCU set to zeroes.
  170303. * This way, we return uniform gray for the remainder of the segment.
  170304. */
  170305. if (! entropy->pub.insufficient_data) {
  170306. /* Load up working state */
  170307. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170308. ASSIGN_STATE(state, entropy->saved);
  170309. /* Outer loop handles each block in the MCU */
  170310. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170311. JBLOCKROW block = MCU_data[blkn];
  170312. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170313. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170314. register int s, k, r;
  170315. /* Decode a single block's worth of coefficients */
  170316. /* Section F.2.2.1: decode the DC coefficient difference */
  170317. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170318. if (s) {
  170319. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170320. r = GET_BITS(s);
  170321. s = HUFF_EXTEND(r, s);
  170322. }
  170323. if (entropy->dc_needed[blkn]) {
  170324. /* Convert DC difference to actual value, update last_dc_val */
  170325. int ci = cinfo->MCU_membership[blkn];
  170326. s += state.last_dc_val[ci];
  170327. state.last_dc_val[ci] = s;
  170328. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170329. (*block)[0] = (JCOEF) s;
  170330. }
  170331. if (entropy->ac_needed[blkn]) {
  170332. /* Section F.2.2.2: decode the AC coefficients */
  170333. /* Since zeroes are skipped, output area must be cleared beforehand */
  170334. for (k = 1; k < DCTSIZE2; k++) {
  170335. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170336. r = s >> 4;
  170337. s &= 15;
  170338. if (s) {
  170339. k += r;
  170340. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170341. r = GET_BITS(s);
  170342. s = HUFF_EXTEND(r, s);
  170343. /* Output coefficient in natural (dezigzagged) order.
  170344. * Note: the extra entries in jpeg_natural_order[] will save us
  170345. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170346. */
  170347. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170348. } else {
  170349. if (r != 15)
  170350. break;
  170351. k += 15;
  170352. }
  170353. }
  170354. } else {
  170355. /* Section F.2.2.2: decode the AC coefficients */
  170356. /* In this path we just discard the values */
  170357. for (k = 1; k < DCTSIZE2; k++) {
  170358. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170359. r = s >> 4;
  170360. s &= 15;
  170361. if (s) {
  170362. k += r;
  170363. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170364. DROP_BITS(s);
  170365. } else {
  170366. if (r != 15)
  170367. break;
  170368. k += 15;
  170369. }
  170370. }
  170371. }
  170372. }
  170373. /* Completed MCU, so update state */
  170374. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170375. ASSIGN_STATE(entropy->saved, state);
  170376. }
  170377. /* Account for restart interval (no-op if not using restarts) */
  170378. entropy->restarts_to_go--;
  170379. return TRUE;
  170380. }
  170381. /*
  170382. * Module initialization routine for Huffman entropy decoding.
  170383. */
  170384. GLOBAL(void)
  170385. jinit_huff_decoder (j_decompress_ptr cinfo)
  170386. {
  170387. huff_entropy_ptr2 entropy;
  170388. int i;
  170389. entropy = (huff_entropy_ptr2)
  170390. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170391. SIZEOF(huff_entropy_decoder2));
  170392. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170393. entropy->pub.start_pass = start_pass_huff_decoder;
  170394. entropy->pub.decode_mcu = decode_mcu;
  170395. /* Mark tables unallocated */
  170396. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170397. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170398. }
  170399. }
  170400. /*** End of inlined file: jdhuff.c ***/
  170401. /*** Start of inlined file: jdinput.c ***/
  170402. #define JPEG_INTERNALS
  170403. /* Private state */
  170404. typedef struct {
  170405. struct jpeg_input_controller pub; /* public fields */
  170406. boolean inheaders; /* TRUE until first SOS is reached */
  170407. } my_input_controller;
  170408. typedef my_input_controller * my_inputctl_ptr;
  170409. /* Forward declarations */
  170410. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170411. /*
  170412. * Routines to calculate various quantities related to the size of the image.
  170413. */
  170414. LOCAL(void)
  170415. initial_setup2 (j_decompress_ptr cinfo)
  170416. /* Called once, when first SOS marker is reached */
  170417. {
  170418. int ci;
  170419. jpeg_component_info *compptr;
  170420. /* Make sure image isn't bigger than I can handle */
  170421. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170422. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170423. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170424. /* For now, precision must match compiled-in value... */
  170425. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170426. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170427. /* Check that number of components won't exceed internal array sizes */
  170428. if (cinfo->num_components > MAX_COMPONENTS)
  170429. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170430. MAX_COMPONENTS);
  170431. /* Compute maximum sampling factors; check factor validity */
  170432. cinfo->max_h_samp_factor = 1;
  170433. cinfo->max_v_samp_factor = 1;
  170434. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170435. ci++, compptr++) {
  170436. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170437. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170438. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170439. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170440. compptr->h_samp_factor);
  170441. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170442. compptr->v_samp_factor);
  170443. }
  170444. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170445. * In the full decompressor, this will be overridden by jdmaster.c;
  170446. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170447. */
  170448. cinfo->min_DCT_scaled_size = DCTSIZE;
  170449. /* Compute dimensions of components */
  170450. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170451. ci++, compptr++) {
  170452. compptr->DCT_scaled_size = DCTSIZE;
  170453. /* Size in DCT blocks */
  170454. compptr->width_in_blocks = (JDIMENSION)
  170455. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170456. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170457. compptr->height_in_blocks = (JDIMENSION)
  170458. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170459. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170460. /* downsampled_width and downsampled_height will also be overridden by
  170461. * jdmaster.c if we are doing full decompression. The transcoder library
  170462. * doesn't use these values, but the calling application might.
  170463. */
  170464. /* Size in samples */
  170465. compptr->downsampled_width = (JDIMENSION)
  170466. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170467. (long) cinfo->max_h_samp_factor);
  170468. compptr->downsampled_height = (JDIMENSION)
  170469. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170470. (long) cinfo->max_v_samp_factor);
  170471. /* Mark component needed, until color conversion says otherwise */
  170472. compptr->component_needed = TRUE;
  170473. /* Mark no quantization table yet saved for component */
  170474. compptr->quant_table = NULL;
  170475. }
  170476. /* Compute number of fully interleaved MCU rows. */
  170477. cinfo->total_iMCU_rows = (JDIMENSION)
  170478. jdiv_round_up((long) cinfo->image_height,
  170479. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170480. /* Decide whether file contains multiple scans */
  170481. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170482. cinfo->inputctl->has_multiple_scans = TRUE;
  170483. else
  170484. cinfo->inputctl->has_multiple_scans = FALSE;
  170485. }
  170486. LOCAL(void)
  170487. per_scan_setup2 (j_decompress_ptr cinfo)
  170488. /* Do computations that are needed before processing a JPEG scan */
  170489. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170490. {
  170491. int ci, mcublks, tmp;
  170492. jpeg_component_info *compptr;
  170493. if (cinfo->comps_in_scan == 1) {
  170494. /* Noninterleaved (single-component) scan */
  170495. compptr = cinfo->cur_comp_info[0];
  170496. /* Overall image size in MCUs */
  170497. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170498. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170499. /* For noninterleaved scan, always one block per MCU */
  170500. compptr->MCU_width = 1;
  170501. compptr->MCU_height = 1;
  170502. compptr->MCU_blocks = 1;
  170503. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170504. compptr->last_col_width = 1;
  170505. /* For noninterleaved scans, it is convenient to define last_row_height
  170506. * as the number of block rows present in the last iMCU row.
  170507. */
  170508. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170509. if (tmp == 0) tmp = compptr->v_samp_factor;
  170510. compptr->last_row_height = tmp;
  170511. /* Prepare array describing MCU composition */
  170512. cinfo->blocks_in_MCU = 1;
  170513. cinfo->MCU_membership[0] = 0;
  170514. } else {
  170515. /* Interleaved (multi-component) scan */
  170516. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170517. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170518. MAX_COMPS_IN_SCAN);
  170519. /* Overall image size in MCUs */
  170520. cinfo->MCUs_per_row = (JDIMENSION)
  170521. jdiv_round_up((long) cinfo->image_width,
  170522. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170523. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170524. jdiv_round_up((long) cinfo->image_height,
  170525. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170526. cinfo->blocks_in_MCU = 0;
  170527. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170528. compptr = cinfo->cur_comp_info[ci];
  170529. /* Sampling factors give # of blocks of component in each MCU */
  170530. compptr->MCU_width = compptr->h_samp_factor;
  170531. compptr->MCU_height = compptr->v_samp_factor;
  170532. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170533. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170534. /* Figure number of non-dummy blocks in last MCU column & row */
  170535. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170536. if (tmp == 0) tmp = compptr->MCU_width;
  170537. compptr->last_col_width = tmp;
  170538. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170539. if (tmp == 0) tmp = compptr->MCU_height;
  170540. compptr->last_row_height = tmp;
  170541. /* Prepare array describing MCU composition */
  170542. mcublks = compptr->MCU_blocks;
  170543. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170544. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170545. while (mcublks-- > 0) {
  170546. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170547. }
  170548. }
  170549. }
  170550. }
  170551. /*
  170552. * Save away a copy of the Q-table referenced by each component present
  170553. * in the current scan, unless already saved during a prior scan.
  170554. *
  170555. * In a multiple-scan JPEG file, the encoder could assign different components
  170556. * the same Q-table slot number, but change table definitions between scans
  170557. * so that each component uses a different Q-table. (The IJG encoder is not
  170558. * currently capable of doing this, but other encoders might.) Since we want
  170559. * to be able to dequantize all the components at the end of the file, this
  170560. * means that we have to save away the table actually used for each component.
  170561. * We do this by copying the table at the start of the first scan containing
  170562. * the component.
  170563. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170564. * slot between scans of a component using that slot. If the encoder does so
  170565. * anyway, this decoder will simply use the Q-table values that were current
  170566. * at the start of the first scan for the component.
  170567. *
  170568. * The decompressor output side looks only at the saved quant tables,
  170569. * not at the current Q-table slots.
  170570. */
  170571. LOCAL(void)
  170572. latch_quant_tables (j_decompress_ptr cinfo)
  170573. {
  170574. int ci, qtblno;
  170575. jpeg_component_info *compptr;
  170576. JQUANT_TBL * qtbl;
  170577. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170578. compptr = cinfo->cur_comp_info[ci];
  170579. /* No work if we already saved Q-table for this component */
  170580. if (compptr->quant_table != NULL)
  170581. continue;
  170582. /* Make sure specified quantization table is present */
  170583. qtblno = compptr->quant_tbl_no;
  170584. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170585. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170586. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170587. /* OK, save away the quantization table */
  170588. qtbl = (JQUANT_TBL *)
  170589. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170590. SIZEOF(JQUANT_TBL));
  170591. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170592. compptr->quant_table = qtbl;
  170593. }
  170594. }
  170595. /*
  170596. * Initialize the input modules to read a scan of compressed data.
  170597. * The first call to this is done by jdmaster.c after initializing
  170598. * the entire decompressor (during jpeg_start_decompress).
  170599. * Subsequent calls come from consume_markers, below.
  170600. */
  170601. METHODDEF(void)
  170602. start_input_pass2 (j_decompress_ptr cinfo)
  170603. {
  170604. per_scan_setup2(cinfo);
  170605. latch_quant_tables(cinfo);
  170606. (*cinfo->entropy->start_pass) (cinfo);
  170607. (*cinfo->coef->start_input_pass) (cinfo);
  170608. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170609. }
  170610. /*
  170611. * Finish up after inputting a compressed-data scan.
  170612. * This is called by the coefficient controller after it's read all
  170613. * the expected data of the scan.
  170614. */
  170615. METHODDEF(void)
  170616. finish_input_pass (j_decompress_ptr cinfo)
  170617. {
  170618. cinfo->inputctl->consume_input = consume_markers;
  170619. }
  170620. /*
  170621. * Read JPEG markers before, between, or after compressed-data scans.
  170622. * Change state as necessary when a new scan is reached.
  170623. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170624. *
  170625. * The consume_input method pointer points either here or to the
  170626. * coefficient controller's consume_data routine, depending on whether
  170627. * we are reading a compressed data segment or inter-segment markers.
  170628. */
  170629. METHODDEF(int)
  170630. consume_markers (j_decompress_ptr cinfo)
  170631. {
  170632. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170633. int val;
  170634. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170635. return JPEG_REACHED_EOI;
  170636. val = (*cinfo->marker->read_markers) (cinfo);
  170637. switch (val) {
  170638. case JPEG_REACHED_SOS: /* Found SOS */
  170639. if (inputctl->inheaders) { /* 1st SOS */
  170640. initial_setup2(cinfo);
  170641. inputctl->inheaders = FALSE;
  170642. /* Note: start_input_pass must be called by jdmaster.c
  170643. * before any more input can be consumed. jdapimin.c is
  170644. * responsible for enforcing this sequencing.
  170645. */
  170646. } else { /* 2nd or later SOS marker */
  170647. if (! inputctl->pub.has_multiple_scans)
  170648. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170649. start_input_pass2(cinfo);
  170650. }
  170651. break;
  170652. case JPEG_REACHED_EOI: /* Found EOI */
  170653. inputctl->pub.eoi_reached = TRUE;
  170654. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170655. if (cinfo->marker->saw_SOF)
  170656. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170657. } else {
  170658. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170659. * if user set output_scan_number larger than number of scans.
  170660. */
  170661. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170662. cinfo->output_scan_number = cinfo->input_scan_number;
  170663. }
  170664. break;
  170665. case JPEG_SUSPENDED:
  170666. break;
  170667. }
  170668. return val;
  170669. }
  170670. /*
  170671. * Reset state to begin a fresh datastream.
  170672. */
  170673. METHODDEF(void)
  170674. reset_input_controller (j_decompress_ptr cinfo)
  170675. {
  170676. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170677. inputctl->pub.consume_input = consume_markers;
  170678. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170679. inputctl->pub.eoi_reached = FALSE;
  170680. inputctl->inheaders = TRUE;
  170681. /* Reset other modules */
  170682. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170683. (*cinfo->marker->reset_marker_reader) (cinfo);
  170684. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170685. cinfo->coef_bits = NULL;
  170686. }
  170687. /*
  170688. * Initialize the input controller module.
  170689. * This is called only once, when the decompression object is created.
  170690. */
  170691. GLOBAL(void)
  170692. jinit_input_controller (j_decompress_ptr cinfo)
  170693. {
  170694. my_inputctl_ptr inputctl;
  170695. /* Create subobject in permanent pool */
  170696. inputctl = (my_inputctl_ptr)
  170697. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170698. SIZEOF(my_input_controller));
  170699. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170700. /* Initialize method pointers */
  170701. inputctl->pub.consume_input = consume_markers;
  170702. inputctl->pub.reset_input_controller = reset_input_controller;
  170703. inputctl->pub.start_input_pass = start_input_pass2;
  170704. inputctl->pub.finish_input_pass = finish_input_pass;
  170705. /* Initialize state: can't use reset_input_controller since we don't
  170706. * want to try to reset other modules yet.
  170707. */
  170708. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170709. inputctl->pub.eoi_reached = FALSE;
  170710. inputctl->inheaders = TRUE;
  170711. }
  170712. /*** End of inlined file: jdinput.c ***/
  170713. /*** Start of inlined file: jdmainct.c ***/
  170714. #define JPEG_INTERNALS
  170715. /*
  170716. * In the current system design, the main buffer need never be a full-image
  170717. * buffer; any full-height buffers will be found inside the coefficient or
  170718. * postprocessing controllers. Nonetheless, the main controller is not
  170719. * trivial. Its responsibility is to provide context rows for upsampling/
  170720. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170721. *
  170722. * Postprocessor input data is counted in "row groups". A row group
  170723. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170724. * sample rows of each component. (We require DCT_scaled_size values to be
  170725. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170726. * values will likely be powers of two, so we actually have the stronger
  170727. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170728. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170729. * row group (times any additional scale factor that the upsampler is
  170730. * applying).
  170731. *
  170732. * The coefficient controller will deliver data to us one iMCU row at a time;
  170733. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170734. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170735. * to one row of MCUs when the image is fully interleaved.) Note that the
  170736. * number of sample rows varies across components, but the number of row
  170737. * groups does not. Some garbage sample rows may be included in the last iMCU
  170738. * row at the bottom of the image.
  170739. *
  170740. * Depending on the vertical scaling algorithm used, the upsampler may need
  170741. * access to the sample row(s) above and below its current input row group.
  170742. * The upsampler is required to set need_context_rows TRUE at global selection
  170743. * time if so. When need_context_rows is FALSE, this controller can simply
  170744. * obtain one iMCU row at a time from the coefficient controller and dole it
  170745. * out as row groups to the postprocessor.
  170746. *
  170747. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170748. * passed to postprocessing contains at least one row group's worth of samples
  170749. * above and below the row group(s) being processed. Note that the context
  170750. * rows "above" the first passed row group appear at negative row offsets in
  170751. * the passed buffer. At the top and bottom of the image, the required
  170752. * context rows are manufactured by duplicating the first or last real sample
  170753. * row; this avoids having special cases in the upsampling inner loops.
  170754. *
  170755. * The amount of context is fixed at one row group just because that's a
  170756. * convenient number for this controller to work with. The existing
  170757. * upsamplers really only need one sample row of context. An upsampler
  170758. * supporting arbitrary output rescaling might wish for more than one row
  170759. * group of context when shrinking the image; tough, we don't handle that.
  170760. * (This is justified by the assumption that downsizing will be handled mostly
  170761. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170762. * the upsample step needn't be much less than one.)
  170763. *
  170764. * To provide the desired context, we have to retain the last two row groups
  170765. * of one iMCU row while reading in the next iMCU row. (The last row group
  170766. * can't be processed until we have another row group for its below-context,
  170767. * and so we have to save the next-to-last group too for its above-context.)
  170768. * We could do this most simply by copying data around in our buffer, but
  170769. * that'd be very slow. We can avoid copying any data by creating a rather
  170770. * strange pointer structure. Here's how it works. We allocate a workspace
  170771. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170772. * of row groups per iMCU row). We create two sets of redundant pointers to
  170773. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170774. * pointer lists look like this:
  170775. * M+1 M-1
  170776. * master pointer --> 0 master pointer --> 0
  170777. * 1 1
  170778. * ... ...
  170779. * M-3 M-3
  170780. * M-2 M
  170781. * M-1 M+1
  170782. * M M-2
  170783. * M+1 M-1
  170784. * 0 0
  170785. * We read alternate iMCU rows using each master pointer; thus the last two
  170786. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170787. * The pointer lists are set up so that the required context rows appear to
  170788. * be adjacent to the proper places when we pass the pointer lists to the
  170789. * upsampler.
  170790. *
  170791. * The above pictures describe the normal state of the pointer lists.
  170792. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170793. * the first or last sample row as necessary (this is cheaper than copying
  170794. * sample rows around).
  170795. *
  170796. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170797. * situation each iMCU row provides only one row group so the buffering logic
  170798. * must be different (eg, we must read two iMCU rows before we can emit the
  170799. * first row group). For now, we simply do not support providing context
  170800. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170801. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170802. * want it quick and dirty, so a context-free upsampler is sufficient.
  170803. */
  170804. /* Private buffer controller object */
  170805. typedef struct {
  170806. struct jpeg_d_main_controller pub; /* public fields */
  170807. /* Pointer to allocated workspace (M or M+2 row groups). */
  170808. JSAMPARRAY buffer[MAX_COMPONENTS];
  170809. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170810. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170811. /* Remaining fields are only used in the context case. */
  170812. /* These are the master pointers to the funny-order pointer lists. */
  170813. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170814. int whichptr; /* indicates which pointer set is now in use */
  170815. int context_state; /* process_data state machine status */
  170816. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170817. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170818. } my_main_controller4;
  170819. typedef my_main_controller4 * my_main_ptr4;
  170820. /* context_state values: */
  170821. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170822. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170823. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170824. /* Forward declarations */
  170825. METHODDEF(void) process_data_simple_main2
  170826. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170827. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170828. METHODDEF(void) process_data_context_main
  170829. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170830. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170831. #ifdef QUANT_2PASS_SUPPORTED
  170832. METHODDEF(void) process_data_crank_post
  170833. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170834. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170835. #endif
  170836. LOCAL(void)
  170837. alloc_funny_pointers (j_decompress_ptr cinfo)
  170838. /* Allocate space for the funny pointer lists.
  170839. * This is done only once, not once per pass.
  170840. */
  170841. {
  170842. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170843. int ci, rgroup;
  170844. int M = cinfo->min_DCT_scaled_size;
  170845. jpeg_component_info *compptr;
  170846. JSAMPARRAY xbuf;
  170847. /* Get top-level space for component array pointers.
  170848. * We alloc both arrays with one call to save a few cycles.
  170849. */
  170850. main_->xbuffer[0] = (JSAMPIMAGE)
  170851. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170852. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170853. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170854. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170855. ci++, compptr++) {
  170856. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170857. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170858. /* Get space for pointer lists --- M+4 row groups in each list.
  170859. * We alloc both pointer lists with one call to save a few cycles.
  170860. */
  170861. xbuf = (JSAMPARRAY)
  170862. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170863. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170864. xbuf += rgroup; /* want one row group at negative offsets */
  170865. main_->xbuffer[0][ci] = xbuf;
  170866. xbuf += rgroup * (M + 4);
  170867. main_->xbuffer[1][ci] = xbuf;
  170868. }
  170869. }
  170870. LOCAL(void)
  170871. make_funny_pointers (j_decompress_ptr cinfo)
  170872. /* Create the funny pointer lists discussed in the comments above.
  170873. * The actual workspace is already allocated (in main->buffer),
  170874. * and the space for the pointer lists is allocated too.
  170875. * This routine just fills in the curiously ordered lists.
  170876. * This will be repeated at the beginning of each pass.
  170877. */
  170878. {
  170879. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170880. int ci, i, rgroup;
  170881. int M = cinfo->min_DCT_scaled_size;
  170882. jpeg_component_info *compptr;
  170883. JSAMPARRAY buf, xbuf0, xbuf1;
  170884. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170885. ci++, compptr++) {
  170886. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170887. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170888. xbuf0 = main_->xbuffer[0][ci];
  170889. xbuf1 = main_->xbuffer[1][ci];
  170890. /* First copy the workspace pointers as-is */
  170891. buf = main_->buffer[ci];
  170892. for (i = 0; i < rgroup * (M + 2); i++) {
  170893. xbuf0[i] = xbuf1[i] = buf[i];
  170894. }
  170895. /* In the second list, put the last four row groups in swapped order */
  170896. for (i = 0; i < rgroup * 2; i++) {
  170897. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170898. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170899. }
  170900. /* The wraparound pointers at top and bottom will be filled later
  170901. * (see set_wraparound_pointers, below). Initially we want the "above"
  170902. * pointers to duplicate the first actual data line. This only needs
  170903. * to happen in xbuffer[0].
  170904. */
  170905. for (i = 0; i < rgroup; i++) {
  170906. xbuf0[i - rgroup] = xbuf0[0];
  170907. }
  170908. }
  170909. }
  170910. LOCAL(void)
  170911. set_wraparound_pointers (j_decompress_ptr cinfo)
  170912. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170913. * This changes the pointer list state from top-of-image to the normal state.
  170914. */
  170915. {
  170916. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170917. int ci, i, rgroup;
  170918. int M = cinfo->min_DCT_scaled_size;
  170919. jpeg_component_info *compptr;
  170920. JSAMPARRAY xbuf0, xbuf1;
  170921. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170922. ci++, compptr++) {
  170923. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170924. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170925. xbuf0 = main_->xbuffer[0][ci];
  170926. xbuf1 = main_->xbuffer[1][ci];
  170927. for (i = 0; i < rgroup; i++) {
  170928. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170929. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170930. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170931. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170932. }
  170933. }
  170934. }
  170935. LOCAL(void)
  170936. set_bottom_pointers (j_decompress_ptr cinfo)
  170937. /* Change the pointer lists to duplicate the last sample row at the bottom
  170938. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170939. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170940. */
  170941. {
  170942. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170943. int ci, i, rgroup, iMCUheight, rows_left;
  170944. jpeg_component_info *compptr;
  170945. JSAMPARRAY xbuf;
  170946. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170947. ci++, compptr++) {
  170948. /* Count sample rows in one iMCU row and in one row group */
  170949. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170950. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170951. /* Count nondummy sample rows remaining for this component */
  170952. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170953. if (rows_left == 0) rows_left = iMCUheight;
  170954. /* Count nondummy row groups. Should get same answer for each component,
  170955. * so we need only do it once.
  170956. */
  170957. if (ci == 0) {
  170958. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170959. }
  170960. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170961. * last partial rowgroup and ensures at least one full rowgroup of context.
  170962. */
  170963. xbuf = main_->xbuffer[main_->whichptr][ci];
  170964. for (i = 0; i < rgroup * 2; i++) {
  170965. xbuf[rows_left + i] = xbuf[rows_left-1];
  170966. }
  170967. }
  170968. }
  170969. /*
  170970. * Initialize for a processing pass.
  170971. */
  170972. METHODDEF(void)
  170973. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170974. {
  170975. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170976. switch (pass_mode) {
  170977. case JBUF_PASS_THRU:
  170978. if (cinfo->upsample->need_context_rows) {
  170979. main_->pub.process_data = process_data_context_main;
  170980. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170981. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170982. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170983. main_->iMCU_row_ctr = 0;
  170984. } else {
  170985. /* Simple case with no context needed */
  170986. main_->pub.process_data = process_data_simple_main2;
  170987. }
  170988. main_->buffer_full = FALSE; /* Mark buffer empty */
  170989. main_->rowgroup_ctr = 0;
  170990. break;
  170991. #ifdef QUANT_2PASS_SUPPORTED
  170992. case JBUF_CRANK_DEST:
  170993. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170994. main_->pub.process_data = process_data_crank_post;
  170995. break;
  170996. #endif
  170997. default:
  170998. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170999. break;
  171000. }
  171001. }
  171002. /*
  171003. * Process some data.
  171004. * This handles the simple case where no context is required.
  171005. */
  171006. METHODDEF(void)
  171007. process_data_simple_main2 (j_decompress_ptr cinfo,
  171008. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171009. JDIMENSION out_rows_avail)
  171010. {
  171011. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171012. JDIMENSION rowgroups_avail;
  171013. /* Read input data if we haven't filled the main buffer yet */
  171014. if (! main_->buffer_full) {
  171015. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171016. return; /* suspension forced, can do nothing more */
  171017. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171018. }
  171019. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171020. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171021. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171022. * to the postprocessor. The postprocessor has to check for bottom
  171023. * of image anyway (at row resolution), so no point in us doing it too.
  171024. */
  171025. /* Feed the postprocessor */
  171026. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171027. &main_->rowgroup_ctr, rowgroups_avail,
  171028. output_buf, out_row_ctr, out_rows_avail);
  171029. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171030. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171031. main_->buffer_full = FALSE;
  171032. main_->rowgroup_ctr = 0;
  171033. }
  171034. }
  171035. /*
  171036. * Process some data.
  171037. * This handles the case where context rows must be provided.
  171038. */
  171039. METHODDEF(void)
  171040. process_data_context_main (j_decompress_ptr cinfo,
  171041. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171042. JDIMENSION out_rows_avail)
  171043. {
  171044. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171045. /* Read input data if we haven't filled the main buffer yet */
  171046. if (! main_->buffer_full) {
  171047. if (! (*cinfo->coef->decompress_data) (cinfo,
  171048. main_->xbuffer[main_->whichptr]))
  171049. return; /* suspension forced, can do nothing more */
  171050. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171051. main_->iMCU_row_ctr++; /* count rows received */
  171052. }
  171053. /* Postprocessor typically will not swallow all the input data it is handed
  171054. * in one call (due to filling the output buffer first). Must be prepared
  171055. * to exit and restart. This switch lets us keep track of how far we got.
  171056. * Note that each case falls through to the next on successful completion.
  171057. */
  171058. switch (main_->context_state) {
  171059. case CTX_POSTPONED_ROW:
  171060. /* Call postprocessor using previously set pointers for postponed row */
  171061. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171062. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171063. output_buf, out_row_ctr, out_rows_avail);
  171064. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171065. return; /* Need to suspend */
  171066. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171067. if (*out_row_ctr >= out_rows_avail)
  171068. return; /* Postprocessor exactly filled output buf */
  171069. /*FALLTHROUGH*/
  171070. case CTX_PREPARE_FOR_IMCU:
  171071. /* Prepare to process first M-1 row groups of this iMCU row */
  171072. main_->rowgroup_ctr = 0;
  171073. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171074. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171075. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171076. */
  171077. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171078. set_bottom_pointers(cinfo);
  171079. main_->context_state = CTX_PROCESS_IMCU;
  171080. /*FALLTHROUGH*/
  171081. case CTX_PROCESS_IMCU:
  171082. /* Call postprocessor using previously set pointers */
  171083. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171084. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171085. output_buf, out_row_ctr, out_rows_avail);
  171086. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171087. return; /* Need to suspend */
  171088. /* After the first iMCU, change wraparound pointers to normal state */
  171089. if (main_->iMCU_row_ctr == 1)
  171090. set_wraparound_pointers(cinfo);
  171091. /* Prepare to load new iMCU row using other xbuffer list */
  171092. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171093. main_->buffer_full = FALSE;
  171094. /* Still need to process last row group of this iMCU row, */
  171095. /* which is saved at index M+1 of the other xbuffer */
  171096. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171097. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171098. main_->context_state = CTX_POSTPONED_ROW;
  171099. }
  171100. }
  171101. /*
  171102. * Process some data.
  171103. * Final pass of two-pass quantization: just call the postprocessor.
  171104. * Source data will be the postprocessor controller's internal buffer.
  171105. */
  171106. #ifdef QUANT_2PASS_SUPPORTED
  171107. METHODDEF(void)
  171108. process_data_crank_post (j_decompress_ptr cinfo,
  171109. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171110. JDIMENSION out_rows_avail)
  171111. {
  171112. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171113. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171114. output_buf, out_row_ctr, out_rows_avail);
  171115. }
  171116. #endif /* QUANT_2PASS_SUPPORTED */
  171117. /*
  171118. * Initialize main buffer controller.
  171119. */
  171120. GLOBAL(void)
  171121. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171122. {
  171123. my_main_ptr4 main_;
  171124. int ci, rgroup, ngroups;
  171125. jpeg_component_info *compptr;
  171126. main_ = (my_main_ptr4)
  171127. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171128. SIZEOF(my_main_controller4));
  171129. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171130. main_->pub.start_pass = start_pass_main2;
  171131. if (need_full_buffer) /* shouldn't happen */
  171132. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171133. /* Allocate the workspace.
  171134. * ngroups is the number of row groups we need.
  171135. */
  171136. if (cinfo->upsample->need_context_rows) {
  171137. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171138. ERREXIT(cinfo, JERR_NOTIMPL);
  171139. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171140. ngroups = cinfo->min_DCT_scaled_size + 2;
  171141. } else {
  171142. ngroups = cinfo->min_DCT_scaled_size;
  171143. }
  171144. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171145. ci++, compptr++) {
  171146. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171147. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171148. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171149. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171150. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171151. (JDIMENSION) (rgroup * ngroups));
  171152. }
  171153. }
  171154. /*** End of inlined file: jdmainct.c ***/
  171155. /*** Start of inlined file: jdmarker.c ***/
  171156. #define JPEG_INTERNALS
  171157. /* Private state */
  171158. typedef struct {
  171159. struct jpeg_marker_reader pub; /* public fields */
  171160. /* Application-overridable marker processing methods */
  171161. jpeg_marker_parser_method process_COM;
  171162. jpeg_marker_parser_method process_APPn[16];
  171163. /* Limit on marker data length to save for each marker type */
  171164. unsigned int length_limit_COM;
  171165. unsigned int length_limit_APPn[16];
  171166. /* Status of COM/APPn marker saving */
  171167. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171168. unsigned int bytes_read; /* data bytes read so far in marker */
  171169. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171170. } my_marker_reader;
  171171. typedef my_marker_reader * my_marker_ptr2;
  171172. /*
  171173. * Macros for fetching data from the data source module.
  171174. *
  171175. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171176. * the current restart point; we update them only when we have reached a
  171177. * suitable place to restart if a suspension occurs.
  171178. */
  171179. /* Declare and initialize local copies of input pointer/count */
  171180. #define INPUT_VARS(cinfo) \
  171181. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171182. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171183. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171184. /* Unload the local copies --- do this only at a restart boundary */
  171185. #define INPUT_SYNC(cinfo) \
  171186. ( datasrc->next_input_byte = next_input_byte, \
  171187. datasrc->bytes_in_buffer = bytes_in_buffer )
  171188. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171189. #define INPUT_RELOAD(cinfo) \
  171190. ( next_input_byte = datasrc->next_input_byte, \
  171191. bytes_in_buffer = datasrc->bytes_in_buffer )
  171192. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171193. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171194. * but we must reload the local copies after a successful fill.
  171195. */
  171196. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171197. if (bytes_in_buffer == 0) { \
  171198. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171199. { action; } \
  171200. INPUT_RELOAD(cinfo); \
  171201. }
  171202. /* Read a byte into variable V.
  171203. * If must suspend, take the specified action (typically "return FALSE").
  171204. */
  171205. #define INPUT_BYTE(cinfo,V,action) \
  171206. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171207. bytes_in_buffer--; \
  171208. V = GETJOCTET(*next_input_byte++); )
  171209. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171210. * V should be declared unsigned int or perhaps INT32.
  171211. */
  171212. #define INPUT_2BYTES(cinfo,V,action) \
  171213. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171214. bytes_in_buffer--; \
  171215. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171216. MAKE_BYTE_AVAIL(cinfo,action); \
  171217. bytes_in_buffer--; \
  171218. V += GETJOCTET(*next_input_byte++); )
  171219. /*
  171220. * Routines to process JPEG markers.
  171221. *
  171222. * Entry condition: JPEG marker itself has been read and its code saved
  171223. * in cinfo->unread_marker; input restart point is just after the marker.
  171224. *
  171225. * Exit: if return TRUE, have read and processed any parameters, and have
  171226. * updated the restart point to point after the parameters.
  171227. * If return FALSE, was forced to suspend before reaching end of
  171228. * marker parameters; restart point has not been moved. Same routine
  171229. * will be called again after application supplies more input data.
  171230. *
  171231. * This approach to suspension assumes that all of a marker's parameters
  171232. * can fit into a single input bufferload. This should hold for "normal"
  171233. * markers. Some COM/APPn markers might have large parameter segments
  171234. * that might not fit. If we are simply dropping such a marker, we use
  171235. * skip_input_data to get past it, and thereby put the problem on the
  171236. * source manager's shoulders. If we are saving the marker's contents
  171237. * into memory, we use a slightly different convention: when forced to
  171238. * suspend, the marker processor updates the restart point to the end of
  171239. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171240. * On resumption, cinfo->unread_marker still contains the marker code,
  171241. * but the data source will point to the next chunk of marker data.
  171242. * The marker processor must retain internal state to deal with this.
  171243. *
  171244. * Note that we don't bother to avoid duplicate trace messages if a
  171245. * suspension occurs within marker parameters. Other side effects
  171246. * require more care.
  171247. */
  171248. LOCAL(boolean)
  171249. get_soi (j_decompress_ptr cinfo)
  171250. /* Process an SOI marker */
  171251. {
  171252. int i;
  171253. TRACEMS(cinfo, 1, JTRC_SOI);
  171254. if (cinfo->marker->saw_SOI)
  171255. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171256. /* Reset all parameters that are defined to be reset by SOI */
  171257. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171258. cinfo->arith_dc_L[i] = 0;
  171259. cinfo->arith_dc_U[i] = 1;
  171260. cinfo->arith_ac_K[i] = 5;
  171261. }
  171262. cinfo->restart_interval = 0;
  171263. /* Set initial assumptions for colorspace etc */
  171264. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171265. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171266. cinfo->saw_JFIF_marker = FALSE;
  171267. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171268. cinfo->JFIF_minor_version = 1;
  171269. cinfo->density_unit = 0;
  171270. cinfo->X_density = 1;
  171271. cinfo->Y_density = 1;
  171272. cinfo->saw_Adobe_marker = FALSE;
  171273. cinfo->Adobe_transform = 0;
  171274. cinfo->marker->saw_SOI = TRUE;
  171275. return TRUE;
  171276. }
  171277. LOCAL(boolean)
  171278. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171279. /* Process a SOFn marker */
  171280. {
  171281. INT32 length;
  171282. int c, ci;
  171283. jpeg_component_info * compptr;
  171284. INPUT_VARS(cinfo);
  171285. cinfo->progressive_mode = is_prog;
  171286. cinfo->arith_code = is_arith;
  171287. INPUT_2BYTES(cinfo, length, return FALSE);
  171288. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171289. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171290. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171291. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171292. length -= 8;
  171293. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171294. (int) cinfo->image_width, (int) cinfo->image_height,
  171295. cinfo->num_components);
  171296. if (cinfo->marker->saw_SOF)
  171297. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171298. /* We don't support files in which the image height is initially specified */
  171299. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171300. /* might as well have a general sanity check. */
  171301. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171302. || cinfo->num_components <= 0)
  171303. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171304. if (length != (cinfo->num_components * 3))
  171305. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171306. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171307. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171308. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171309. cinfo->num_components * SIZEOF(jpeg_component_info));
  171310. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171311. ci++, compptr++) {
  171312. compptr->component_index = ci;
  171313. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171314. INPUT_BYTE(cinfo, c, return FALSE);
  171315. compptr->h_samp_factor = (c >> 4) & 15;
  171316. compptr->v_samp_factor = (c ) & 15;
  171317. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171318. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171319. compptr->component_id, compptr->h_samp_factor,
  171320. compptr->v_samp_factor, compptr->quant_tbl_no);
  171321. }
  171322. cinfo->marker->saw_SOF = TRUE;
  171323. INPUT_SYNC(cinfo);
  171324. return TRUE;
  171325. }
  171326. LOCAL(boolean)
  171327. get_sos (j_decompress_ptr cinfo)
  171328. /* Process a SOS marker */
  171329. {
  171330. INT32 length;
  171331. int i, ci, n, c, cc;
  171332. jpeg_component_info * compptr;
  171333. INPUT_VARS(cinfo);
  171334. if (! cinfo->marker->saw_SOF)
  171335. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171336. INPUT_2BYTES(cinfo, length, return FALSE);
  171337. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171338. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171339. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171340. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171341. cinfo->comps_in_scan = n;
  171342. /* Collect the component-spec parameters */
  171343. for (i = 0; i < n; i++) {
  171344. INPUT_BYTE(cinfo, cc, return FALSE);
  171345. INPUT_BYTE(cinfo, c, return FALSE);
  171346. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171347. ci++, compptr++) {
  171348. if (cc == compptr->component_id)
  171349. goto id_found;
  171350. }
  171351. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171352. id_found:
  171353. cinfo->cur_comp_info[i] = compptr;
  171354. compptr->dc_tbl_no = (c >> 4) & 15;
  171355. compptr->ac_tbl_no = (c ) & 15;
  171356. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171357. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171358. }
  171359. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171360. INPUT_BYTE(cinfo, c, return FALSE);
  171361. cinfo->Ss = c;
  171362. INPUT_BYTE(cinfo, c, return FALSE);
  171363. cinfo->Se = c;
  171364. INPUT_BYTE(cinfo, c, return FALSE);
  171365. cinfo->Ah = (c >> 4) & 15;
  171366. cinfo->Al = (c ) & 15;
  171367. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171368. cinfo->Ah, cinfo->Al);
  171369. /* Prepare to scan data & restart markers */
  171370. cinfo->marker->next_restart_num = 0;
  171371. /* Count another SOS marker */
  171372. cinfo->input_scan_number++;
  171373. INPUT_SYNC(cinfo);
  171374. return TRUE;
  171375. }
  171376. #ifdef D_ARITH_CODING_SUPPORTED
  171377. LOCAL(boolean)
  171378. get_dac (j_decompress_ptr cinfo)
  171379. /* Process a DAC marker */
  171380. {
  171381. INT32 length;
  171382. int index, val;
  171383. INPUT_VARS(cinfo);
  171384. INPUT_2BYTES(cinfo, length, return FALSE);
  171385. length -= 2;
  171386. while (length > 0) {
  171387. INPUT_BYTE(cinfo, index, return FALSE);
  171388. INPUT_BYTE(cinfo, val, return FALSE);
  171389. length -= 2;
  171390. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171391. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171392. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171393. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171394. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171395. } else { /* define DC table */
  171396. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171397. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171398. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171399. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171400. }
  171401. }
  171402. if (length != 0)
  171403. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171404. INPUT_SYNC(cinfo);
  171405. return TRUE;
  171406. }
  171407. #else /* ! D_ARITH_CODING_SUPPORTED */
  171408. #define get_dac(cinfo) skip_variable(cinfo)
  171409. #endif /* D_ARITH_CODING_SUPPORTED */
  171410. LOCAL(boolean)
  171411. get_dht (j_decompress_ptr cinfo)
  171412. /* Process a DHT marker */
  171413. {
  171414. INT32 length;
  171415. UINT8 bits[17];
  171416. UINT8 huffval[256];
  171417. int i, index, count;
  171418. JHUFF_TBL **htblptr;
  171419. INPUT_VARS(cinfo);
  171420. INPUT_2BYTES(cinfo, length, return FALSE);
  171421. length -= 2;
  171422. while (length > 16) {
  171423. INPUT_BYTE(cinfo, index, return FALSE);
  171424. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171425. bits[0] = 0;
  171426. count = 0;
  171427. for (i = 1; i <= 16; i++) {
  171428. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171429. count += bits[i];
  171430. }
  171431. length -= 1 + 16;
  171432. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171433. bits[1], bits[2], bits[3], bits[4],
  171434. bits[5], bits[6], bits[7], bits[8]);
  171435. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171436. bits[9], bits[10], bits[11], bits[12],
  171437. bits[13], bits[14], bits[15], bits[16]);
  171438. /* Here we just do minimal validation of the counts to avoid walking
  171439. * off the end of our table space. jdhuff.c will check more carefully.
  171440. */
  171441. if (count > 256 || ((INT32) count) > length)
  171442. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171443. for (i = 0; i < count; i++)
  171444. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171445. length -= count;
  171446. if (index & 0x10) { /* AC table definition */
  171447. index -= 0x10;
  171448. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171449. } else { /* DC table definition */
  171450. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171451. }
  171452. if (index < 0 || index >= NUM_HUFF_TBLS)
  171453. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171454. if (*htblptr == NULL)
  171455. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171456. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171457. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171458. }
  171459. if (length != 0)
  171460. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171461. INPUT_SYNC(cinfo);
  171462. return TRUE;
  171463. }
  171464. LOCAL(boolean)
  171465. get_dqt (j_decompress_ptr cinfo)
  171466. /* Process a DQT marker */
  171467. {
  171468. INT32 length;
  171469. int n, i, prec;
  171470. unsigned int tmp;
  171471. JQUANT_TBL *quant_ptr;
  171472. INPUT_VARS(cinfo);
  171473. INPUT_2BYTES(cinfo, length, return FALSE);
  171474. length -= 2;
  171475. while (length > 0) {
  171476. INPUT_BYTE(cinfo, n, return FALSE);
  171477. prec = n >> 4;
  171478. n &= 0x0F;
  171479. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171480. if (n >= NUM_QUANT_TBLS)
  171481. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171482. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171483. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171484. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171485. for (i = 0; i < DCTSIZE2; i++) {
  171486. if (prec)
  171487. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171488. else
  171489. INPUT_BYTE(cinfo, tmp, return FALSE);
  171490. /* We convert the zigzag-order table to natural array order. */
  171491. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171492. }
  171493. if (cinfo->err->trace_level >= 2) {
  171494. for (i = 0; i < DCTSIZE2; i += 8) {
  171495. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171496. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171497. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171498. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171499. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171500. }
  171501. }
  171502. length -= DCTSIZE2+1;
  171503. if (prec) length -= DCTSIZE2;
  171504. }
  171505. if (length != 0)
  171506. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171507. INPUT_SYNC(cinfo);
  171508. return TRUE;
  171509. }
  171510. LOCAL(boolean)
  171511. get_dri (j_decompress_ptr cinfo)
  171512. /* Process a DRI marker */
  171513. {
  171514. INT32 length;
  171515. unsigned int tmp;
  171516. INPUT_VARS(cinfo);
  171517. INPUT_2BYTES(cinfo, length, return FALSE);
  171518. if (length != 4)
  171519. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171520. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171521. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171522. cinfo->restart_interval = tmp;
  171523. INPUT_SYNC(cinfo);
  171524. return TRUE;
  171525. }
  171526. /*
  171527. * Routines for processing APPn and COM markers.
  171528. * These are either saved in memory or discarded, per application request.
  171529. * APP0 and APP14 are specially checked to see if they are
  171530. * JFIF and Adobe markers, respectively.
  171531. */
  171532. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171533. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171534. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171535. LOCAL(void)
  171536. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171537. unsigned int datalen, INT32 remaining)
  171538. /* Examine first few bytes from an APP0.
  171539. * Take appropriate action if it is a JFIF marker.
  171540. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171541. */
  171542. {
  171543. INT32 totallen = (INT32) datalen + remaining;
  171544. if (datalen >= APP0_DATA_LEN &&
  171545. GETJOCTET(data[0]) == 0x4A &&
  171546. GETJOCTET(data[1]) == 0x46 &&
  171547. GETJOCTET(data[2]) == 0x49 &&
  171548. GETJOCTET(data[3]) == 0x46 &&
  171549. GETJOCTET(data[4]) == 0) {
  171550. /* Found JFIF APP0 marker: save info */
  171551. cinfo->saw_JFIF_marker = TRUE;
  171552. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171553. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171554. cinfo->density_unit = GETJOCTET(data[7]);
  171555. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171556. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171557. /* Check version.
  171558. * Major version must be 1, anything else signals an incompatible change.
  171559. * (We used to treat this as an error, but now it's a nonfatal warning,
  171560. * because some bozo at Hijaak couldn't read the spec.)
  171561. * Minor version should be 0..2, but process anyway if newer.
  171562. */
  171563. if (cinfo->JFIF_major_version != 1)
  171564. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171565. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171566. /* Generate trace messages */
  171567. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171568. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171569. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171570. /* Validate thumbnail dimensions and issue appropriate messages */
  171571. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171572. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171573. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171574. totallen -= APP0_DATA_LEN;
  171575. if (totallen !=
  171576. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171577. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171578. } else if (datalen >= 6 &&
  171579. GETJOCTET(data[0]) == 0x4A &&
  171580. GETJOCTET(data[1]) == 0x46 &&
  171581. GETJOCTET(data[2]) == 0x58 &&
  171582. GETJOCTET(data[3]) == 0x58 &&
  171583. GETJOCTET(data[4]) == 0) {
  171584. /* Found JFIF "JFXX" extension APP0 marker */
  171585. /* The library doesn't actually do anything with these,
  171586. * but we try to produce a helpful trace message.
  171587. */
  171588. switch (GETJOCTET(data[5])) {
  171589. case 0x10:
  171590. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171591. break;
  171592. case 0x11:
  171593. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171594. break;
  171595. case 0x13:
  171596. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171597. break;
  171598. default:
  171599. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171600. GETJOCTET(data[5]), (int) totallen);
  171601. break;
  171602. }
  171603. } else {
  171604. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171605. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171606. }
  171607. }
  171608. LOCAL(void)
  171609. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171610. unsigned int datalen, INT32 remaining)
  171611. /* Examine first few bytes from an APP14.
  171612. * Take appropriate action if it is an Adobe marker.
  171613. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171614. */
  171615. {
  171616. unsigned int version, flags0, flags1, transform;
  171617. if (datalen >= APP14_DATA_LEN &&
  171618. GETJOCTET(data[0]) == 0x41 &&
  171619. GETJOCTET(data[1]) == 0x64 &&
  171620. GETJOCTET(data[2]) == 0x6F &&
  171621. GETJOCTET(data[3]) == 0x62 &&
  171622. GETJOCTET(data[4]) == 0x65) {
  171623. /* Found Adobe APP14 marker */
  171624. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171625. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171626. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171627. transform = GETJOCTET(data[11]);
  171628. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171629. cinfo->saw_Adobe_marker = TRUE;
  171630. cinfo->Adobe_transform = (UINT8) transform;
  171631. } else {
  171632. /* Start of APP14 does not match "Adobe", or too short */
  171633. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171634. }
  171635. }
  171636. METHODDEF(boolean)
  171637. get_interesting_appn (j_decompress_ptr cinfo)
  171638. /* Process an APP0 or APP14 marker without saving it */
  171639. {
  171640. INT32 length;
  171641. JOCTET b[APPN_DATA_LEN];
  171642. unsigned int i, numtoread;
  171643. INPUT_VARS(cinfo);
  171644. INPUT_2BYTES(cinfo, length, return FALSE);
  171645. length -= 2;
  171646. /* get the interesting part of the marker data */
  171647. if (length >= APPN_DATA_LEN)
  171648. numtoread = APPN_DATA_LEN;
  171649. else if (length > 0)
  171650. numtoread = (unsigned int) length;
  171651. else
  171652. numtoread = 0;
  171653. for (i = 0; i < numtoread; i++)
  171654. INPUT_BYTE(cinfo, b[i], return FALSE);
  171655. length -= numtoread;
  171656. /* process it */
  171657. switch (cinfo->unread_marker) {
  171658. case M_APP0:
  171659. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171660. break;
  171661. case M_APP14:
  171662. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171663. break;
  171664. default:
  171665. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171666. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171667. break;
  171668. }
  171669. /* skip any remaining data -- could be lots */
  171670. INPUT_SYNC(cinfo);
  171671. if (length > 0)
  171672. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171673. return TRUE;
  171674. }
  171675. #ifdef SAVE_MARKERS_SUPPORTED
  171676. METHODDEF(boolean)
  171677. save_marker (j_decompress_ptr cinfo)
  171678. /* Save an APPn or COM marker into the marker list */
  171679. {
  171680. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171681. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171682. unsigned int bytes_read, data_length;
  171683. JOCTET FAR * data;
  171684. INT32 length = 0;
  171685. INPUT_VARS(cinfo);
  171686. if (cur_marker == NULL) {
  171687. /* begin reading a marker */
  171688. INPUT_2BYTES(cinfo, length, return FALSE);
  171689. length -= 2;
  171690. if (length >= 0) { /* watch out for bogus length word */
  171691. /* figure out how much we want to save */
  171692. unsigned int limit;
  171693. if (cinfo->unread_marker == (int) M_COM)
  171694. limit = marker->length_limit_COM;
  171695. else
  171696. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171697. if ((unsigned int) length < limit)
  171698. limit = (unsigned int) length;
  171699. /* allocate and initialize the marker item */
  171700. cur_marker = (jpeg_saved_marker_ptr)
  171701. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171702. SIZEOF(struct jpeg_marker_struct) + limit);
  171703. cur_marker->next = NULL;
  171704. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171705. cur_marker->original_length = (unsigned int) length;
  171706. cur_marker->data_length = limit;
  171707. /* data area is just beyond the jpeg_marker_struct */
  171708. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171709. marker->cur_marker = cur_marker;
  171710. marker->bytes_read = 0;
  171711. bytes_read = 0;
  171712. data_length = limit;
  171713. } else {
  171714. /* deal with bogus length word */
  171715. bytes_read = data_length = 0;
  171716. data = NULL;
  171717. }
  171718. } else {
  171719. /* resume reading a marker */
  171720. bytes_read = marker->bytes_read;
  171721. data_length = cur_marker->data_length;
  171722. data = cur_marker->data + bytes_read;
  171723. }
  171724. while (bytes_read < data_length) {
  171725. INPUT_SYNC(cinfo); /* move the restart point to here */
  171726. marker->bytes_read = bytes_read;
  171727. /* If there's not at least one byte in buffer, suspend */
  171728. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171729. /* Copy bytes with reasonable rapidity */
  171730. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171731. *data++ = *next_input_byte++;
  171732. bytes_in_buffer--;
  171733. bytes_read++;
  171734. }
  171735. }
  171736. /* Done reading what we want to read */
  171737. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171738. /* Add new marker to end of list */
  171739. if (cinfo->marker_list == NULL) {
  171740. cinfo->marker_list = cur_marker;
  171741. } else {
  171742. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171743. while (prev->next != NULL)
  171744. prev = prev->next;
  171745. prev->next = cur_marker;
  171746. }
  171747. /* Reset pointer & calc remaining data length */
  171748. data = cur_marker->data;
  171749. length = cur_marker->original_length - data_length;
  171750. }
  171751. /* Reset to initial state for next marker */
  171752. marker->cur_marker = NULL;
  171753. /* Process the marker if interesting; else just make a generic trace msg */
  171754. switch (cinfo->unread_marker) {
  171755. case M_APP0:
  171756. examine_app0(cinfo, data, data_length, length);
  171757. break;
  171758. case M_APP14:
  171759. examine_app14(cinfo, data, data_length, length);
  171760. break;
  171761. default:
  171762. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171763. (int) (data_length + length));
  171764. break;
  171765. }
  171766. /* skip any remaining data -- could be lots */
  171767. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171768. if (length > 0)
  171769. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171770. return TRUE;
  171771. }
  171772. #endif /* SAVE_MARKERS_SUPPORTED */
  171773. METHODDEF(boolean)
  171774. skip_variable (j_decompress_ptr cinfo)
  171775. /* Skip over an unknown or uninteresting variable-length marker */
  171776. {
  171777. INT32 length;
  171778. INPUT_VARS(cinfo);
  171779. INPUT_2BYTES(cinfo, length, return FALSE);
  171780. length -= 2;
  171781. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171782. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171783. if (length > 0)
  171784. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171785. return TRUE;
  171786. }
  171787. /*
  171788. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171789. * Returns FALSE if had to suspend before reaching a marker;
  171790. * in that case cinfo->unread_marker is unchanged.
  171791. *
  171792. * Note that the result might not be a valid marker code,
  171793. * but it will never be 0 or FF.
  171794. */
  171795. LOCAL(boolean)
  171796. next_marker (j_decompress_ptr cinfo)
  171797. {
  171798. int c;
  171799. INPUT_VARS(cinfo);
  171800. for (;;) {
  171801. INPUT_BYTE(cinfo, c, return FALSE);
  171802. /* Skip any non-FF bytes.
  171803. * This may look a bit inefficient, but it will not occur in a valid file.
  171804. * We sync after each discarded byte so that a suspending data source
  171805. * can discard the byte from its buffer.
  171806. */
  171807. while (c != 0xFF) {
  171808. cinfo->marker->discarded_bytes++;
  171809. INPUT_SYNC(cinfo);
  171810. INPUT_BYTE(cinfo, c, return FALSE);
  171811. }
  171812. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171813. * pad bytes, so don't count them in discarded_bytes. We assume there
  171814. * will not be so many consecutive FF bytes as to overflow a suspending
  171815. * data source's input buffer.
  171816. */
  171817. do {
  171818. INPUT_BYTE(cinfo, c, return FALSE);
  171819. } while (c == 0xFF);
  171820. if (c != 0)
  171821. break; /* found a valid marker, exit loop */
  171822. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171823. * Discard it and loop back to try again.
  171824. */
  171825. cinfo->marker->discarded_bytes += 2;
  171826. INPUT_SYNC(cinfo);
  171827. }
  171828. if (cinfo->marker->discarded_bytes != 0) {
  171829. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171830. cinfo->marker->discarded_bytes = 0;
  171831. }
  171832. cinfo->unread_marker = c;
  171833. INPUT_SYNC(cinfo);
  171834. return TRUE;
  171835. }
  171836. LOCAL(boolean)
  171837. first_marker (j_decompress_ptr cinfo)
  171838. /* Like next_marker, but used to obtain the initial SOI marker. */
  171839. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171840. * we might well scan an entire input file before realizing it ain't JPEG.
  171841. * If an application wants to process non-JFIF files, it must seek to the
  171842. * SOI before calling the JPEG library.
  171843. */
  171844. {
  171845. int c, c2;
  171846. INPUT_VARS(cinfo);
  171847. INPUT_BYTE(cinfo, c, return FALSE);
  171848. INPUT_BYTE(cinfo, c2, return FALSE);
  171849. if (c != 0xFF || c2 != (int) M_SOI)
  171850. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171851. cinfo->unread_marker = c2;
  171852. INPUT_SYNC(cinfo);
  171853. return TRUE;
  171854. }
  171855. /*
  171856. * Read markers until SOS or EOI.
  171857. *
  171858. * Returns same codes as are defined for jpeg_consume_input:
  171859. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171860. */
  171861. METHODDEF(int)
  171862. read_markers (j_decompress_ptr cinfo)
  171863. {
  171864. /* Outer loop repeats once for each marker. */
  171865. for (;;) {
  171866. /* Collect the marker proper, unless we already did. */
  171867. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171868. if (cinfo->unread_marker == 0) {
  171869. if (! cinfo->marker->saw_SOI) {
  171870. if (! first_marker(cinfo))
  171871. return JPEG_SUSPENDED;
  171872. } else {
  171873. if (! next_marker(cinfo))
  171874. return JPEG_SUSPENDED;
  171875. }
  171876. }
  171877. /* At this point cinfo->unread_marker contains the marker code and the
  171878. * input point is just past the marker proper, but before any parameters.
  171879. * A suspension will cause us to return with this state still true.
  171880. */
  171881. switch (cinfo->unread_marker) {
  171882. case M_SOI:
  171883. if (! get_soi(cinfo))
  171884. return JPEG_SUSPENDED;
  171885. break;
  171886. case M_SOF0: /* Baseline */
  171887. case M_SOF1: /* Extended sequential, Huffman */
  171888. if (! get_sof(cinfo, FALSE, FALSE))
  171889. return JPEG_SUSPENDED;
  171890. break;
  171891. case M_SOF2: /* Progressive, Huffman */
  171892. if (! get_sof(cinfo, TRUE, FALSE))
  171893. return JPEG_SUSPENDED;
  171894. break;
  171895. case M_SOF9: /* Extended sequential, arithmetic */
  171896. if (! get_sof(cinfo, FALSE, TRUE))
  171897. return JPEG_SUSPENDED;
  171898. break;
  171899. case M_SOF10: /* Progressive, arithmetic */
  171900. if (! get_sof(cinfo, TRUE, TRUE))
  171901. return JPEG_SUSPENDED;
  171902. break;
  171903. /* Currently unsupported SOFn types */
  171904. case M_SOF3: /* Lossless, Huffman */
  171905. case M_SOF5: /* Differential sequential, Huffman */
  171906. case M_SOF6: /* Differential progressive, Huffman */
  171907. case M_SOF7: /* Differential lossless, Huffman */
  171908. case M_JPG: /* Reserved for JPEG extensions */
  171909. case M_SOF11: /* Lossless, arithmetic */
  171910. case M_SOF13: /* Differential sequential, arithmetic */
  171911. case M_SOF14: /* Differential progressive, arithmetic */
  171912. case M_SOF15: /* Differential lossless, arithmetic */
  171913. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171914. break;
  171915. case M_SOS:
  171916. if (! get_sos(cinfo))
  171917. return JPEG_SUSPENDED;
  171918. cinfo->unread_marker = 0; /* processed the marker */
  171919. return JPEG_REACHED_SOS;
  171920. case M_EOI:
  171921. TRACEMS(cinfo, 1, JTRC_EOI);
  171922. cinfo->unread_marker = 0; /* processed the marker */
  171923. return JPEG_REACHED_EOI;
  171924. case M_DAC:
  171925. if (! get_dac(cinfo))
  171926. return JPEG_SUSPENDED;
  171927. break;
  171928. case M_DHT:
  171929. if (! get_dht(cinfo))
  171930. return JPEG_SUSPENDED;
  171931. break;
  171932. case M_DQT:
  171933. if (! get_dqt(cinfo))
  171934. return JPEG_SUSPENDED;
  171935. break;
  171936. case M_DRI:
  171937. if (! get_dri(cinfo))
  171938. return JPEG_SUSPENDED;
  171939. break;
  171940. case M_APP0:
  171941. case M_APP1:
  171942. case M_APP2:
  171943. case M_APP3:
  171944. case M_APP4:
  171945. case M_APP5:
  171946. case M_APP6:
  171947. case M_APP7:
  171948. case M_APP8:
  171949. case M_APP9:
  171950. case M_APP10:
  171951. case M_APP11:
  171952. case M_APP12:
  171953. case M_APP13:
  171954. case M_APP14:
  171955. case M_APP15:
  171956. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171957. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171958. return JPEG_SUSPENDED;
  171959. break;
  171960. case M_COM:
  171961. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171962. return JPEG_SUSPENDED;
  171963. break;
  171964. case M_RST0: /* these are all parameterless */
  171965. case M_RST1:
  171966. case M_RST2:
  171967. case M_RST3:
  171968. case M_RST4:
  171969. case M_RST5:
  171970. case M_RST6:
  171971. case M_RST7:
  171972. case M_TEM:
  171973. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171974. break;
  171975. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171976. if (! skip_variable(cinfo))
  171977. return JPEG_SUSPENDED;
  171978. break;
  171979. default: /* must be DHP, EXP, JPGn, or RESn */
  171980. /* For now, we treat the reserved markers as fatal errors since they are
  171981. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171982. * Once the JPEG 3 version-number marker is well defined, this code
  171983. * ought to change!
  171984. */
  171985. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171986. break;
  171987. }
  171988. /* Successfully processed marker, so reset state variable */
  171989. cinfo->unread_marker = 0;
  171990. } /* end loop */
  171991. }
  171992. /*
  171993. * Read a restart marker, which is expected to appear next in the datastream;
  171994. * if the marker is not there, take appropriate recovery action.
  171995. * Returns FALSE if suspension is required.
  171996. *
  171997. * This is called by the entropy decoder after it has read an appropriate
  171998. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171999. * has already read a marker from the data source. Under normal conditions
  172000. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172001. * it holds a marker which the decoder will be unable to read past.
  172002. */
  172003. METHODDEF(boolean)
  172004. read_restart_marker (j_decompress_ptr cinfo)
  172005. {
  172006. /* Obtain a marker unless we already did. */
  172007. /* Note that next_marker will complain if it skips any data. */
  172008. if (cinfo->unread_marker == 0) {
  172009. if (! next_marker(cinfo))
  172010. return FALSE;
  172011. }
  172012. if (cinfo->unread_marker ==
  172013. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172014. /* Normal case --- swallow the marker and let entropy decoder continue */
  172015. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172016. cinfo->unread_marker = 0;
  172017. } else {
  172018. /* Uh-oh, the restart markers have been messed up. */
  172019. /* Let the data source manager determine how to resync. */
  172020. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172021. cinfo->marker->next_restart_num))
  172022. return FALSE;
  172023. }
  172024. /* Update next-restart state */
  172025. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172026. return TRUE;
  172027. }
  172028. /*
  172029. * This is the default resync_to_restart method for data source managers
  172030. * to use if they don't have any better approach. Some data source managers
  172031. * may be able to back up, or may have additional knowledge about the data
  172032. * which permits a more intelligent recovery strategy; such managers would
  172033. * presumably supply their own resync method.
  172034. *
  172035. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172036. * the restart marker it was expecting. (This code is *not* used unless
  172037. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172038. * the marker code actually found (might be anything, except 0 or FF).
  172039. * The desired restart marker number (0..7) is passed as a parameter.
  172040. * This routine is supposed to apply whatever error recovery strategy seems
  172041. * appropriate in order to position the input stream to the next data segment.
  172042. * Note that cinfo->unread_marker is treated as a marker appearing before
  172043. * the current data-source input point; usually it should be reset to zero
  172044. * before returning.
  172045. * Returns FALSE if suspension is required.
  172046. *
  172047. * This implementation is substantially constrained by wanting to treat the
  172048. * input as a data stream; this means we can't back up. Therefore, we have
  172049. * only the following actions to work with:
  172050. * 1. Simply discard the marker and let the entropy decoder resume at next
  172051. * byte of file.
  172052. * 2. Read forward until we find another marker, discarding intervening
  172053. * data. (In theory we could look ahead within the current bufferload,
  172054. * without having to discard data if we don't find the desired marker.
  172055. * This idea is not implemented here, in part because it makes behavior
  172056. * dependent on buffer size and chance buffer-boundary positions.)
  172057. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172058. * This will cause the entropy decoder to process an empty data segment,
  172059. * inserting dummy zeroes, and then we will reprocess the marker.
  172060. *
  172061. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172062. * appropriate if the found marker is a future restart marker (indicating
  172063. * that we have missed the desired restart marker, probably because it got
  172064. * corrupted).
  172065. * We apply #2 or #3 if the found marker is a restart marker no more than
  172066. * two counts behind or ahead of the expected one. We also apply #2 if the
  172067. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172068. * If the found marker is a restart marker more than 2 counts away, we do #1
  172069. * (too much risk that the marker is erroneous; with luck we will be able to
  172070. * resync at some future point).
  172071. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172072. * overrunning the end of a scan. An implementation limited to single-scan
  172073. * files might find it better to apply #2 for markers other than EOI, since
  172074. * any other marker would have to be bogus data in that case.
  172075. */
  172076. GLOBAL(boolean)
  172077. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172078. {
  172079. int marker = cinfo->unread_marker;
  172080. int action = 1;
  172081. /* Always put up a warning. */
  172082. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172083. /* Outer loop handles repeated decision after scanning forward. */
  172084. for (;;) {
  172085. if (marker < (int) M_SOF0)
  172086. action = 2; /* invalid marker */
  172087. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172088. action = 3; /* valid non-restart marker */
  172089. else {
  172090. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172091. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172092. action = 3; /* one of the next two expected restarts */
  172093. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172094. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172095. action = 2; /* a prior restart, so advance */
  172096. else
  172097. action = 1; /* desired restart or too far away */
  172098. }
  172099. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172100. switch (action) {
  172101. case 1:
  172102. /* Discard marker and let entropy decoder resume processing. */
  172103. cinfo->unread_marker = 0;
  172104. return TRUE;
  172105. case 2:
  172106. /* Scan to the next marker, and repeat the decision loop. */
  172107. if (! next_marker(cinfo))
  172108. return FALSE;
  172109. marker = cinfo->unread_marker;
  172110. break;
  172111. case 3:
  172112. /* Return without advancing past this marker. */
  172113. /* Entropy decoder will be forced to process an empty segment. */
  172114. return TRUE;
  172115. }
  172116. } /* end loop */
  172117. }
  172118. /*
  172119. * Reset marker processing state to begin a fresh datastream.
  172120. */
  172121. METHODDEF(void)
  172122. reset_marker_reader (j_decompress_ptr cinfo)
  172123. {
  172124. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172125. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172126. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172127. cinfo->unread_marker = 0; /* no pending marker */
  172128. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172129. marker->pub.saw_SOF = FALSE;
  172130. marker->pub.discarded_bytes = 0;
  172131. marker->cur_marker = NULL;
  172132. }
  172133. /*
  172134. * Initialize the marker reader module.
  172135. * This is called only once, when the decompression object is created.
  172136. */
  172137. GLOBAL(void)
  172138. jinit_marker_reader (j_decompress_ptr cinfo)
  172139. {
  172140. my_marker_ptr2 marker;
  172141. int i;
  172142. /* Create subobject in permanent pool */
  172143. marker = (my_marker_ptr2)
  172144. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172145. SIZEOF(my_marker_reader));
  172146. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172147. /* Initialize public method pointers */
  172148. marker->pub.reset_marker_reader = reset_marker_reader;
  172149. marker->pub.read_markers = read_markers;
  172150. marker->pub.read_restart_marker = read_restart_marker;
  172151. /* Initialize COM/APPn processing.
  172152. * By default, we examine and then discard APP0 and APP14,
  172153. * but simply discard COM and all other APPn.
  172154. */
  172155. marker->process_COM = skip_variable;
  172156. marker->length_limit_COM = 0;
  172157. for (i = 0; i < 16; i++) {
  172158. marker->process_APPn[i] = skip_variable;
  172159. marker->length_limit_APPn[i] = 0;
  172160. }
  172161. marker->process_APPn[0] = get_interesting_appn;
  172162. marker->process_APPn[14] = get_interesting_appn;
  172163. /* Reset marker processing state */
  172164. reset_marker_reader(cinfo);
  172165. }
  172166. /*
  172167. * Control saving of COM and APPn markers into marker_list.
  172168. */
  172169. #ifdef SAVE_MARKERS_SUPPORTED
  172170. GLOBAL(void)
  172171. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172172. unsigned int length_limit)
  172173. {
  172174. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172175. long maxlength;
  172176. jpeg_marker_parser_method processor;
  172177. /* Length limit mustn't be larger than what we can allocate
  172178. * (should only be a concern in a 16-bit environment).
  172179. */
  172180. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172181. if (((long) length_limit) > maxlength)
  172182. length_limit = (unsigned int) maxlength;
  172183. /* Choose processor routine to use.
  172184. * APP0/APP14 have special requirements.
  172185. */
  172186. if (length_limit) {
  172187. processor = save_marker;
  172188. /* If saving APP0/APP14, save at least enough for our internal use. */
  172189. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172190. length_limit = APP0_DATA_LEN;
  172191. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172192. length_limit = APP14_DATA_LEN;
  172193. } else {
  172194. processor = skip_variable;
  172195. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172196. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172197. processor = get_interesting_appn;
  172198. }
  172199. if (marker_code == (int) M_COM) {
  172200. marker->process_COM = processor;
  172201. marker->length_limit_COM = length_limit;
  172202. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172203. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172204. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172205. } else
  172206. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172207. }
  172208. #endif /* SAVE_MARKERS_SUPPORTED */
  172209. /*
  172210. * Install a special processing method for COM or APPn markers.
  172211. */
  172212. GLOBAL(void)
  172213. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172214. jpeg_marker_parser_method routine)
  172215. {
  172216. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172217. if (marker_code == (int) M_COM)
  172218. marker->process_COM = routine;
  172219. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172220. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172221. else
  172222. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172223. }
  172224. /*** End of inlined file: jdmarker.c ***/
  172225. /*** Start of inlined file: jdmaster.c ***/
  172226. #define JPEG_INTERNALS
  172227. /* Private state */
  172228. typedef struct {
  172229. struct jpeg_decomp_master pub; /* public fields */
  172230. int pass_number; /* # of passes completed */
  172231. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172232. /* Saved references to initialized quantizer modules,
  172233. * in case we need to switch modes.
  172234. */
  172235. struct jpeg_color_quantizer * quantizer_1pass;
  172236. struct jpeg_color_quantizer * quantizer_2pass;
  172237. } my_decomp_master;
  172238. typedef my_decomp_master * my_master_ptr6;
  172239. /*
  172240. * Determine whether merged upsample/color conversion should be used.
  172241. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172242. */
  172243. LOCAL(boolean)
  172244. use_merged_upsample (j_decompress_ptr cinfo)
  172245. {
  172246. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172247. /* Merging is the equivalent of plain box-filter upsampling */
  172248. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172249. return FALSE;
  172250. /* jdmerge.c only supports YCC=>RGB color conversion */
  172251. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172252. cinfo->out_color_space != JCS_RGB ||
  172253. cinfo->out_color_components != RGB_PIXELSIZE)
  172254. return FALSE;
  172255. /* and it only handles 2h1v or 2h2v sampling ratios */
  172256. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172257. cinfo->comp_info[1].h_samp_factor != 1 ||
  172258. cinfo->comp_info[2].h_samp_factor != 1 ||
  172259. cinfo->comp_info[0].v_samp_factor > 2 ||
  172260. cinfo->comp_info[1].v_samp_factor != 1 ||
  172261. cinfo->comp_info[2].v_samp_factor != 1)
  172262. return FALSE;
  172263. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172264. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172265. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172266. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172267. return FALSE;
  172268. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172269. return TRUE; /* by golly, it'll work... */
  172270. #else
  172271. return FALSE;
  172272. #endif
  172273. }
  172274. /*
  172275. * Compute output image dimensions and related values.
  172276. * NOTE: this is exported for possible use by application.
  172277. * Hence it mustn't do anything that can't be done twice.
  172278. * Also note that it may be called before the master module is initialized!
  172279. */
  172280. GLOBAL(void)
  172281. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172282. /* Do computations that are needed before master selection phase */
  172283. {
  172284. #ifdef IDCT_SCALING_SUPPORTED
  172285. int ci;
  172286. jpeg_component_info *compptr;
  172287. #endif
  172288. /* Prevent application from calling me at wrong times */
  172289. if (cinfo->global_state != DSTATE_READY)
  172290. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172291. #ifdef IDCT_SCALING_SUPPORTED
  172292. /* Compute actual output image dimensions and DCT scaling choices. */
  172293. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172294. /* Provide 1/8 scaling */
  172295. cinfo->output_width = (JDIMENSION)
  172296. jdiv_round_up((long) cinfo->image_width, 8L);
  172297. cinfo->output_height = (JDIMENSION)
  172298. jdiv_round_up((long) cinfo->image_height, 8L);
  172299. cinfo->min_DCT_scaled_size = 1;
  172300. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172301. /* Provide 1/4 scaling */
  172302. cinfo->output_width = (JDIMENSION)
  172303. jdiv_round_up((long) cinfo->image_width, 4L);
  172304. cinfo->output_height = (JDIMENSION)
  172305. jdiv_round_up((long) cinfo->image_height, 4L);
  172306. cinfo->min_DCT_scaled_size = 2;
  172307. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172308. /* Provide 1/2 scaling */
  172309. cinfo->output_width = (JDIMENSION)
  172310. jdiv_round_up((long) cinfo->image_width, 2L);
  172311. cinfo->output_height = (JDIMENSION)
  172312. jdiv_round_up((long) cinfo->image_height, 2L);
  172313. cinfo->min_DCT_scaled_size = 4;
  172314. } else {
  172315. /* Provide 1/1 scaling */
  172316. cinfo->output_width = cinfo->image_width;
  172317. cinfo->output_height = cinfo->image_height;
  172318. cinfo->min_DCT_scaled_size = DCTSIZE;
  172319. }
  172320. /* In selecting the actual DCT scaling for each component, we try to
  172321. * scale up the chroma components via IDCT scaling rather than upsampling.
  172322. * This saves time if the upsampler gets to use 1:1 scaling.
  172323. * Note this code assumes that the supported DCT scalings are powers of 2.
  172324. */
  172325. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172326. ci++, compptr++) {
  172327. int ssize = cinfo->min_DCT_scaled_size;
  172328. while (ssize < DCTSIZE &&
  172329. (compptr->h_samp_factor * ssize * 2 <=
  172330. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172331. (compptr->v_samp_factor * ssize * 2 <=
  172332. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172333. ssize = ssize * 2;
  172334. }
  172335. compptr->DCT_scaled_size = ssize;
  172336. }
  172337. /* Recompute downsampled dimensions of components;
  172338. * application needs to know these if using raw downsampled data.
  172339. */
  172340. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172341. ci++, compptr++) {
  172342. /* Size in samples, after IDCT scaling */
  172343. compptr->downsampled_width = (JDIMENSION)
  172344. jdiv_round_up((long) cinfo->image_width *
  172345. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172346. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172347. compptr->downsampled_height = (JDIMENSION)
  172348. jdiv_round_up((long) cinfo->image_height *
  172349. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172350. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172351. }
  172352. #else /* !IDCT_SCALING_SUPPORTED */
  172353. /* Hardwire it to "no scaling" */
  172354. cinfo->output_width = cinfo->image_width;
  172355. cinfo->output_height = cinfo->image_height;
  172356. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172357. * and has computed unscaled downsampled_width and downsampled_height.
  172358. */
  172359. #endif /* IDCT_SCALING_SUPPORTED */
  172360. /* Report number of components in selected colorspace. */
  172361. /* Probably this should be in the color conversion module... */
  172362. switch (cinfo->out_color_space) {
  172363. case JCS_GRAYSCALE:
  172364. cinfo->out_color_components = 1;
  172365. break;
  172366. case JCS_RGB:
  172367. #if RGB_PIXELSIZE != 3
  172368. cinfo->out_color_components = RGB_PIXELSIZE;
  172369. break;
  172370. #endif /* else share code with YCbCr */
  172371. case JCS_YCbCr:
  172372. cinfo->out_color_components = 3;
  172373. break;
  172374. case JCS_CMYK:
  172375. case JCS_YCCK:
  172376. cinfo->out_color_components = 4;
  172377. break;
  172378. default: /* else must be same colorspace as in file */
  172379. cinfo->out_color_components = cinfo->num_components;
  172380. break;
  172381. }
  172382. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172383. cinfo->out_color_components);
  172384. /* See if upsampler will want to emit more than one row at a time */
  172385. if (use_merged_upsample(cinfo))
  172386. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172387. else
  172388. cinfo->rec_outbuf_height = 1;
  172389. }
  172390. /*
  172391. * Several decompression processes need to range-limit values to the range
  172392. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172393. * due to noise introduced by quantization, roundoff error, etc. These
  172394. * processes are inner loops and need to be as fast as possible. On most
  172395. * machines, particularly CPUs with pipelines or instruction prefetch,
  172396. * a (subscript-check-less) C table lookup
  172397. * x = sample_range_limit[x];
  172398. * is faster than explicit tests
  172399. * if (x < 0) x = 0;
  172400. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172401. * These processes all use a common table prepared by the routine below.
  172402. *
  172403. * For most steps we can mathematically guarantee that the initial value
  172404. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172405. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172406. * limiting step (just after the IDCT), a wildly out-of-range value is
  172407. * possible if the input data is corrupt. To avoid any chance of indexing
  172408. * off the end of memory and getting a bad-pointer trap, we perform the
  172409. * post-IDCT limiting thus:
  172410. * x = range_limit[x & MASK];
  172411. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172412. * samples. Under normal circumstances this is more than enough range and
  172413. * a correct output will be generated; with bogus input data the mask will
  172414. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172415. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172416. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172417. * So the post-IDCT limiting table ends up looking like this:
  172418. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172419. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172420. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172421. * 0,1,...,CENTERJSAMPLE-1
  172422. * Negative inputs select values from the upper half of the table after
  172423. * masking.
  172424. *
  172425. * We can save some space by overlapping the start of the post-IDCT table
  172426. * with the simpler range limiting table. The post-IDCT table begins at
  172427. * sample_range_limit + CENTERJSAMPLE.
  172428. *
  172429. * Note that the table is allocated in near data space on PCs; it's small
  172430. * enough and used often enough to justify this.
  172431. */
  172432. LOCAL(void)
  172433. prepare_range_limit_table (j_decompress_ptr cinfo)
  172434. /* Allocate and fill in the sample_range_limit table */
  172435. {
  172436. JSAMPLE * table;
  172437. int i;
  172438. table = (JSAMPLE *)
  172439. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172440. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172441. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172442. cinfo->sample_range_limit = table;
  172443. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172444. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172445. /* Main part of "simple" table: limit[x] = x */
  172446. for (i = 0; i <= MAXJSAMPLE; i++)
  172447. table[i] = (JSAMPLE) i;
  172448. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172449. /* End of simple table, rest of first half of post-IDCT table */
  172450. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172451. table[i] = MAXJSAMPLE;
  172452. /* Second half of post-IDCT table */
  172453. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172454. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172455. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172456. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172457. }
  172458. /*
  172459. * Master selection of decompression modules.
  172460. * This is done once at jpeg_start_decompress time. We determine
  172461. * which modules will be used and give them appropriate initialization calls.
  172462. * We also initialize the decompressor input side to begin consuming data.
  172463. *
  172464. * Since jpeg_read_header has finished, we know what is in the SOF
  172465. * and (first) SOS markers. We also have all the application parameter
  172466. * settings.
  172467. */
  172468. LOCAL(void)
  172469. master_selection (j_decompress_ptr cinfo)
  172470. {
  172471. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172472. boolean use_c_buffer;
  172473. long samplesperrow;
  172474. JDIMENSION jd_samplesperrow;
  172475. /* Initialize dimensions and other stuff */
  172476. jpeg_calc_output_dimensions(cinfo);
  172477. prepare_range_limit_table(cinfo);
  172478. /* Width of an output scanline must be representable as JDIMENSION. */
  172479. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172480. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172481. if ((long) jd_samplesperrow != samplesperrow)
  172482. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172483. /* Initialize my private state */
  172484. master->pass_number = 0;
  172485. master->using_merged_upsample = use_merged_upsample(cinfo);
  172486. /* Color quantizer selection */
  172487. master->quantizer_1pass = NULL;
  172488. master->quantizer_2pass = NULL;
  172489. /* No mode changes if not using buffered-image mode. */
  172490. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172491. cinfo->enable_1pass_quant = FALSE;
  172492. cinfo->enable_external_quant = FALSE;
  172493. cinfo->enable_2pass_quant = FALSE;
  172494. }
  172495. if (cinfo->quantize_colors) {
  172496. if (cinfo->raw_data_out)
  172497. ERREXIT(cinfo, JERR_NOTIMPL);
  172498. /* 2-pass quantizer only works in 3-component color space. */
  172499. if (cinfo->out_color_components != 3) {
  172500. cinfo->enable_1pass_quant = TRUE;
  172501. cinfo->enable_external_quant = FALSE;
  172502. cinfo->enable_2pass_quant = FALSE;
  172503. cinfo->colormap = NULL;
  172504. } else if (cinfo->colormap != NULL) {
  172505. cinfo->enable_external_quant = TRUE;
  172506. } else if (cinfo->two_pass_quantize) {
  172507. cinfo->enable_2pass_quant = TRUE;
  172508. } else {
  172509. cinfo->enable_1pass_quant = TRUE;
  172510. }
  172511. if (cinfo->enable_1pass_quant) {
  172512. #ifdef QUANT_1PASS_SUPPORTED
  172513. jinit_1pass_quantizer(cinfo);
  172514. master->quantizer_1pass = cinfo->cquantize;
  172515. #else
  172516. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172517. #endif
  172518. }
  172519. /* We use the 2-pass code to map to external colormaps. */
  172520. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172521. #ifdef QUANT_2PASS_SUPPORTED
  172522. jinit_2pass_quantizer(cinfo);
  172523. master->quantizer_2pass = cinfo->cquantize;
  172524. #else
  172525. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172526. #endif
  172527. }
  172528. /* If both quantizers are initialized, the 2-pass one is left active;
  172529. * this is necessary for starting with quantization to an external map.
  172530. */
  172531. }
  172532. /* Post-processing: in particular, color conversion first */
  172533. if (! cinfo->raw_data_out) {
  172534. if (master->using_merged_upsample) {
  172535. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172536. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172537. #else
  172538. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172539. #endif
  172540. } else {
  172541. jinit_color_deconverter(cinfo);
  172542. jinit_upsampler(cinfo);
  172543. }
  172544. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172545. }
  172546. /* Inverse DCT */
  172547. jinit_inverse_dct(cinfo);
  172548. /* Entropy decoding: either Huffman or arithmetic coding. */
  172549. if (cinfo->arith_code) {
  172550. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172551. } else {
  172552. if (cinfo->progressive_mode) {
  172553. #ifdef D_PROGRESSIVE_SUPPORTED
  172554. jinit_phuff_decoder(cinfo);
  172555. #else
  172556. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172557. #endif
  172558. } else
  172559. jinit_huff_decoder(cinfo);
  172560. }
  172561. /* Initialize principal buffer controllers. */
  172562. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172563. jinit_d_coef_controller(cinfo, use_c_buffer);
  172564. if (! cinfo->raw_data_out)
  172565. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172566. /* We can now tell the memory manager to allocate virtual arrays. */
  172567. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172568. /* Initialize input side of decompressor to consume first scan. */
  172569. (*cinfo->inputctl->start_input_pass) (cinfo);
  172570. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172571. /* If jpeg_start_decompress will read the whole file, initialize
  172572. * progress monitoring appropriately. The input step is counted
  172573. * as one pass.
  172574. */
  172575. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172576. cinfo->inputctl->has_multiple_scans) {
  172577. int nscans;
  172578. /* Estimate number of scans to set pass_limit. */
  172579. if (cinfo->progressive_mode) {
  172580. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172581. nscans = 2 + 3 * cinfo->num_components;
  172582. } else {
  172583. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172584. nscans = cinfo->num_components;
  172585. }
  172586. cinfo->progress->pass_counter = 0L;
  172587. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172588. cinfo->progress->completed_passes = 0;
  172589. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172590. /* Count the input pass as done */
  172591. master->pass_number++;
  172592. }
  172593. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172594. }
  172595. /*
  172596. * Per-pass setup.
  172597. * This is called at the beginning of each output pass. We determine which
  172598. * modules will be active during this pass and give them appropriate
  172599. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172600. * is a "real" output pass or a dummy pass for color quantization.
  172601. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172602. */
  172603. METHODDEF(void)
  172604. prepare_for_output_pass (j_decompress_ptr cinfo)
  172605. {
  172606. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172607. if (master->pub.is_dummy_pass) {
  172608. #ifdef QUANT_2PASS_SUPPORTED
  172609. /* Final pass of 2-pass quantization */
  172610. master->pub.is_dummy_pass = FALSE;
  172611. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172612. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172613. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172614. #else
  172615. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172616. #endif /* QUANT_2PASS_SUPPORTED */
  172617. } else {
  172618. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172619. /* Select new quantization method */
  172620. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172621. cinfo->cquantize = master->quantizer_2pass;
  172622. master->pub.is_dummy_pass = TRUE;
  172623. } else if (cinfo->enable_1pass_quant) {
  172624. cinfo->cquantize = master->quantizer_1pass;
  172625. } else {
  172626. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172627. }
  172628. }
  172629. (*cinfo->idct->start_pass) (cinfo);
  172630. (*cinfo->coef->start_output_pass) (cinfo);
  172631. if (! cinfo->raw_data_out) {
  172632. if (! master->using_merged_upsample)
  172633. (*cinfo->cconvert->start_pass) (cinfo);
  172634. (*cinfo->upsample->start_pass) (cinfo);
  172635. if (cinfo->quantize_colors)
  172636. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172637. (*cinfo->post->start_pass) (cinfo,
  172638. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172639. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172640. }
  172641. }
  172642. /* Set up progress monitor's pass info if present */
  172643. if (cinfo->progress != NULL) {
  172644. cinfo->progress->completed_passes = master->pass_number;
  172645. cinfo->progress->total_passes = master->pass_number +
  172646. (master->pub.is_dummy_pass ? 2 : 1);
  172647. /* In buffered-image mode, we assume one more output pass if EOI not
  172648. * yet reached, but no more passes if EOI has been reached.
  172649. */
  172650. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172651. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172652. }
  172653. }
  172654. }
  172655. /*
  172656. * Finish up at end of an output pass.
  172657. */
  172658. METHODDEF(void)
  172659. finish_output_pass (j_decompress_ptr cinfo)
  172660. {
  172661. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172662. if (cinfo->quantize_colors)
  172663. (*cinfo->cquantize->finish_pass) (cinfo);
  172664. master->pass_number++;
  172665. }
  172666. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172667. /*
  172668. * Switch to a new external colormap between output passes.
  172669. */
  172670. GLOBAL(void)
  172671. jpeg_new_colormap (j_decompress_ptr cinfo)
  172672. {
  172673. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172674. /* Prevent application from calling me at wrong times */
  172675. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172676. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172677. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172678. cinfo->colormap != NULL) {
  172679. /* Select 2-pass quantizer for external colormap use */
  172680. cinfo->cquantize = master->quantizer_2pass;
  172681. /* Notify quantizer of colormap change */
  172682. (*cinfo->cquantize->new_color_map) (cinfo);
  172683. master->pub.is_dummy_pass = FALSE; /* just in case */
  172684. } else
  172685. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172686. }
  172687. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172688. /*
  172689. * Initialize master decompression control and select active modules.
  172690. * This is performed at the start of jpeg_start_decompress.
  172691. */
  172692. GLOBAL(void)
  172693. jinit_master_decompress (j_decompress_ptr cinfo)
  172694. {
  172695. my_master_ptr6 master;
  172696. master = (my_master_ptr6)
  172697. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172698. SIZEOF(my_decomp_master));
  172699. cinfo->master = (struct jpeg_decomp_master *) master;
  172700. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172701. master->pub.finish_output_pass = finish_output_pass;
  172702. master->pub.is_dummy_pass = FALSE;
  172703. master_selection(cinfo);
  172704. }
  172705. /*** End of inlined file: jdmaster.c ***/
  172706. #undef FIX
  172707. /*** Start of inlined file: jdmerge.c ***/
  172708. #define JPEG_INTERNALS
  172709. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172710. /* Private subobject */
  172711. typedef struct {
  172712. struct jpeg_upsampler pub; /* public fields */
  172713. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172714. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172715. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172716. JSAMPARRAY output_buf));
  172717. /* Private state for YCC->RGB conversion */
  172718. int * Cr_r_tab; /* => table for Cr to R conversion */
  172719. int * Cb_b_tab; /* => table for Cb to B conversion */
  172720. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172721. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172722. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172723. * We need a "spare" row buffer to hold the second output row if the
  172724. * application provides just a one-row buffer; we also use the spare
  172725. * to discard the dummy last row if the image height is odd.
  172726. */
  172727. JSAMPROW spare_row;
  172728. boolean spare_full; /* T if spare buffer is occupied */
  172729. JDIMENSION out_row_width; /* samples per output row */
  172730. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172731. } my_upsampler;
  172732. typedef my_upsampler * my_upsample_ptr;
  172733. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172734. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172735. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172736. /*
  172737. * Initialize tables for YCC->RGB colorspace conversion.
  172738. * This is taken directly from jdcolor.c; see that file for more info.
  172739. */
  172740. LOCAL(void)
  172741. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172742. {
  172743. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172744. int i;
  172745. INT32 x;
  172746. SHIFT_TEMPS
  172747. upsample->Cr_r_tab = (int *)
  172748. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172749. (MAXJSAMPLE+1) * SIZEOF(int));
  172750. upsample->Cb_b_tab = (int *)
  172751. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172752. (MAXJSAMPLE+1) * SIZEOF(int));
  172753. upsample->Cr_g_tab = (INT32 *)
  172754. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172755. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172756. upsample->Cb_g_tab = (INT32 *)
  172757. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172758. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172759. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172760. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172761. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172762. /* Cr=>R value is nearest int to 1.40200 * x */
  172763. upsample->Cr_r_tab[i] = (int)
  172764. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172765. /* Cb=>B value is nearest int to 1.77200 * x */
  172766. upsample->Cb_b_tab[i] = (int)
  172767. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172768. /* Cr=>G value is scaled-up -0.71414 * x */
  172769. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172770. /* Cb=>G value is scaled-up -0.34414 * x */
  172771. /* We also add in ONE_HALF so that need not do it in inner loop */
  172772. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172773. }
  172774. }
  172775. /*
  172776. * Initialize for an upsampling pass.
  172777. */
  172778. METHODDEF(void)
  172779. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172780. {
  172781. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172782. /* Mark the spare buffer empty */
  172783. upsample->spare_full = FALSE;
  172784. /* Initialize total-height counter for detecting bottom of image */
  172785. upsample->rows_to_go = cinfo->output_height;
  172786. }
  172787. /*
  172788. * Control routine to do upsampling (and color conversion).
  172789. *
  172790. * The control routine just handles the row buffering considerations.
  172791. */
  172792. METHODDEF(void)
  172793. merged_2v_upsample (j_decompress_ptr cinfo,
  172794. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172795. JDIMENSION,
  172796. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172797. JDIMENSION out_rows_avail)
  172798. /* 2:1 vertical sampling case: may need a spare row. */
  172799. {
  172800. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172801. JSAMPROW work_ptrs[2];
  172802. JDIMENSION num_rows; /* number of rows returned to caller */
  172803. if (upsample->spare_full) {
  172804. /* If we have a spare row saved from a previous cycle, just return it. */
  172805. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172806. 1, upsample->out_row_width);
  172807. num_rows = 1;
  172808. upsample->spare_full = FALSE;
  172809. } else {
  172810. /* Figure number of rows to return to caller. */
  172811. num_rows = 2;
  172812. /* Not more than the distance to the end of the image. */
  172813. if (num_rows > upsample->rows_to_go)
  172814. num_rows = upsample->rows_to_go;
  172815. /* And not more than what the client can accept: */
  172816. out_rows_avail -= *out_row_ctr;
  172817. if (num_rows > out_rows_avail)
  172818. num_rows = out_rows_avail;
  172819. /* Create output pointer array for upsampler. */
  172820. work_ptrs[0] = output_buf[*out_row_ctr];
  172821. if (num_rows > 1) {
  172822. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172823. } else {
  172824. work_ptrs[1] = upsample->spare_row;
  172825. upsample->spare_full = TRUE;
  172826. }
  172827. /* Now do the upsampling. */
  172828. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172829. }
  172830. /* Adjust counts */
  172831. *out_row_ctr += num_rows;
  172832. upsample->rows_to_go -= num_rows;
  172833. /* When the buffer is emptied, declare this input row group consumed */
  172834. if (! upsample->spare_full)
  172835. (*in_row_group_ctr)++;
  172836. }
  172837. METHODDEF(void)
  172838. merged_1v_upsample (j_decompress_ptr cinfo,
  172839. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172840. JDIMENSION,
  172841. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172842. JDIMENSION)
  172843. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172844. {
  172845. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172846. /* Just do the upsampling. */
  172847. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172848. output_buf + *out_row_ctr);
  172849. /* Adjust counts */
  172850. (*out_row_ctr)++;
  172851. (*in_row_group_ctr)++;
  172852. }
  172853. /*
  172854. * These are the routines invoked by the control routines to do
  172855. * the actual upsampling/conversion. One row group is processed per call.
  172856. *
  172857. * Note: since we may be writing directly into application-supplied buffers,
  172858. * we have to be honest about the output width; we can't assume the buffer
  172859. * has been rounded up to an even width.
  172860. */
  172861. /*
  172862. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172863. */
  172864. METHODDEF(void)
  172865. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172866. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172867. JSAMPARRAY output_buf)
  172868. {
  172869. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172870. register int y, cred, cgreen, cblue;
  172871. int cb, cr;
  172872. register JSAMPROW outptr;
  172873. JSAMPROW inptr0, inptr1, inptr2;
  172874. JDIMENSION col;
  172875. /* copy these pointers into registers if possible */
  172876. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172877. int * Crrtab = upsample->Cr_r_tab;
  172878. int * Cbbtab = upsample->Cb_b_tab;
  172879. INT32 * Crgtab = upsample->Cr_g_tab;
  172880. INT32 * Cbgtab = upsample->Cb_g_tab;
  172881. SHIFT_TEMPS
  172882. inptr0 = input_buf[0][in_row_group_ctr];
  172883. inptr1 = input_buf[1][in_row_group_ctr];
  172884. inptr2 = input_buf[2][in_row_group_ctr];
  172885. outptr = output_buf[0];
  172886. /* Loop for each pair of output pixels */
  172887. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172888. /* Do the chroma part of the calculation */
  172889. cb = GETJSAMPLE(*inptr1++);
  172890. cr = GETJSAMPLE(*inptr2++);
  172891. cred = Crrtab[cr];
  172892. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172893. cblue = Cbbtab[cb];
  172894. /* Fetch 2 Y values and emit 2 pixels */
  172895. y = GETJSAMPLE(*inptr0++);
  172896. outptr[RGB_RED] = range_limit[y + cred];
  172897. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172898. outptr[RGB_BLUE] = range_limit[y + cblue];
  172899. outptr += RGB_PIXELSIZE;
  172900. y = GETJSAMPLE(*inptr0++);
  172901. outptr[RGB_RED] = range_limit[y + cred];
  172902. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172903. outptr[RGB_BLUE] = range_limit[y + cblue];
  172904. outptr += RGB_PIXELSIZE;
  172905. }
  172906. /* If image width is odd, do the last output column separately */
  172907. if (cinfo->output_width & 1) {
  172908. cb = GETJSAMPLE(*inptr1);
  172909. cr = GETJSAMPLE(*inptr2);
  172910. cred = Crrtab[cr];
  172911. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172912. cblue = Cbbtab[cb];
  172913. y = GETJSAMPLE(*inptr0);
  172914. outptr[RGB_RED] = range_limit[y + cred];
  172915. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172916. outptr[RGB_BLUE] = range_limit[y + cblue];
  172917. }
  172918. }
  172919. /*
  172920. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172921. */
  172922. METHODDEF(void)
  172923. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172924. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172925. JSAMPARRAY output_buf)
  172926. {
  172927. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172928. register int y, cred, cgreen, cblue;
  172929. int cb, cr;
  172930. register JSAMPROW outptr0, outptr1;
  172931. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172932. JDIMENSION col;
  172933. /* copy these pointers into registers if possible */
  172934. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172935. int * Crrtab = upsample->Cr_r_tab;
  172936. int * Cbbtab = upsample->Cb_b_tab;
  172937. INT32 * Crgtab = upsample->Cr_g_tab;
  172938. INT32 * Cbgtab = upsample->Cb_g_tab;
  172939. SHIFT_TEMPS
  172940. inptr00 = input_buf[0][in_row_group_ctr*2];
  172941. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172942. inptr1 = input_buf[1][in_row_group_ctr];
  172943. inptr2 = input_buf[2][in_row_group_ctr];
  172944. outptr0 = output_buf[0];
  172945. outptr1 = output_buf[1];
  172946. /* Loop for each group of output pixels */
  172947. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172948. /* Do the chroma part of the calculation */
  172949. cb = GETJSAMPLE(*inptr1++);
  172950. cr = GETJSAMPLE(*inptr2++);
  172951. cred = Crrtab[cr];
  172952. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172953. cblue = Cbbtab[cb];
  172954. /* Fetch 4 Y values and emit 4 pixels */
  172955. y = GETJSAMPLE(*inptr00++);
  172956. outptr0[RGB_RED] = range_limit[y + cred];
  172957. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172958. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172959. outptr0 += RGB_PIXELSIZE;
  172960. y = GETJSAMPLE(*inptr00++);
  172961. outptr0[RGB_RED] = range_limit[y + cred];
  172962. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172963. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172964. outptr0 += RGB_PIXELSIZE;
  172965. y = GETJSAMPLE(*inptr01++);
  172966. outptr1[RGB_RED] = range_limit[y + cred];
  172967. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172968. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172969. outptr1 += RGB_PIXELSIZE;
  172970. y = GETJSAMPLE(*inptr01++);
  172971. outptr1[RGB_RED] = range_limit[y + cred];
  172972. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172973. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172974. outptr1 += RGB_PIXELSIZE;
  172975. }
  172976. /* If image width is odd, do the last output column separately */
  172977. if (cinfo->output_width & 1) {
  172978. cb = GETJSAMPLE(*inptr1);
  172979. cr = GETJSAMPLE(*inptr2);
  172980. cred = Crrtab[cr];
  172981. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172982. cblue = Cbbtab[cb];
  172983. y = GETJSAMPLE(*inptr00);
  172984. outptr0[RGB_RED] = range_limit[y + cred];
  172985. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172986. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172987. y = GETJSAMPLE(*inptr01);
  172988. outptr1[RGB_RED] = range_limit[y + cred];
  172989. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172990. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172991. }
  172992. }
  172993. /*
  172994. * Module initialization routine for merged upsampling/color conversion.
  172995. *
  172996. * NB: this is called under the conditions determined by use_merged_upsample()
  172997. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172998. * of this module; no safety checks are made here.
  172999. */
  173000. GLOBAL(void)
  173001. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173002. {
  173003. my_upsample_ptr upsample;
  173004. upsample = (my_upsample_ptr)
  173005. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173006. SIZEOF(my_upsampler));
  173007. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173008. upsample->pub.start_pass = start_pass_merged_upsample;
  173009. upsample->pub.need_context_rows = FALSE;
  173010. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173011. if (cinfo->max_v_samp_factor == 2) {
  173012. upsample->pub.upsample = merged_2v_upsample;
  173013. upsample->upmethod = h2v2_merged_upsample;
  173014. /* Allocate a spare row buffer */
  173015. upsample->spare_row = (JSAMPROW)
  173016. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173017. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173018. } else {
  173019. upsample->pub.upsample = merged_1v_upsample;
  173020. upsample->upmethod = h2v1_merged_upsample;
  173021. /* No spare row needed */
  173022. upsample->spare_row = NULL;
  173023. }
  173024. build_ycc_rgb_table2(cinfo);
  173025. }
  173026. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173027. /*** End of inlined file: jdmerge.c ***/
  173028. #undef ASSIGN_STATE
  173029. /*** Start of inlined file: jdphuff.c ***/
  173030. #define JPEG_INTERNALS
  173031. #ifdef D_PROGRESSIVE_SUPPORTED
  173032. /*
  173033. * Expanded entropy decoder object for progressive Huffman decoding.
  173034. *
  173035. * The savable_state subrecord contains fields that change within an MCU,
  173036. * but must not be updated permanently until we complete the MCU.
  173037. */
  173038. typedef struct {
  173039. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173040. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173041. } savable_state3;
  173042. /* This macro is to work around compilers with missing or broken
  173043. * structure assignment. You'll need to fix this code if you have
  173044. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173045. */
  173046. #ifndef NO_STRUCT_ASSIGN
  173047. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173048. #else
  173049. #if MAX_COMPS_IN_SCAN == 4
  173050. #define ASSIGN_STATE(dest,src) \
  173051. ((dest).EOBRUN = (src).EOBRUN, \
  173052. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173053. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173054. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173055. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173056. #endif
  173057. #endif
  173058. typedef struct {
  173059. struct jpeg_entropy_decoder pub; /* public fields */
  173060. /* These fields are loaded into local variables at start of each MCU.
  173061. * In case of suspension, we exit WITHOUT updating them.
  173062. */
  173063. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173064. savable_state3 saved; /* Other state at start of MCU */
  173065. /* These fields are NOT loaded into local working state. */
  173066. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173067. /* Pointers to derived tables (these workspaces have image lifespan) */
  173068. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173069. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173070. } phuff_entropy_decoder;
  173071. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173072. /* Forward declarations */
  173073. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173074. JBLOCKROW *MCU_data));
  173075. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173076. JBLOCKROW *MCU_data));
  173077. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173078. JBLOCKROW *MCU_data));
  173079. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173080. JBLOCKROW *MCU_data));
  173081. /*
  173082. * Initialize for a Huffman-compressed scan.
  173083. */
  173084. METHODDEF(void)
  173085. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173086. {
  173087. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173088. boolean is_DC_band, bad;
  173089. int ci, coefi, tbl;
  173090. int *coef_bit_ptr;
  173091. jpeg_component_info * compptr;
  173092. is_DC_band = (cinfo->Ss == 0);
  173093. /* Validate scan parameters */
  173094. bad = FALSE;
  173095. if (is_DC_band) {
  173096. if (cinfo->Se != 0)
  173097. bad = TRUE;
  173098. } else {
  173099. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173100. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173101. bad = TRUE;
  173102. /* AC scans may have only one component */
  173103. if (cinfo->comps_in_scan != 1)
  173104. bad = TRUE;
  173105. }
  173106. if (cinfo->Ah != 0) {
  173107. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173108. if (cinfo->Al != cinfo->Ah-1)
  173109. bad = TRUE;
  173110. }
  173111. if (cinfo->Al > 13) /* need not check for < 0 */
  173112. bad = TRUE;
  173113. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173114. * but the spec doesn't say so, and we try to be liberal about what we
  173115. * accept. Note: large Al values could result in out-of-range DC
  173116. * coefficients during early scans, leading to bizarre displays due to
  173117. * overflows in the IDCT math. But we won't crash.
  173118. */
  173119. if (bad)
  173120. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173121. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173122. /* Update progression status, and verify that scan order is legal.
  173123. * Note that inter-scan inconsistencies are treated as warnings
  173124. * not fatal errors ... not clear if this is right way to behave.
  173125. */
  173126. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173127. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173128. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173129. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173130. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173131. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173132. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173133. if (cinfo->Ah != expected)
  173134. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173135. coef_bit_ptr[coefi] = cinfo->Al;
  173136. }
  173137. }
  173138. /* Select MCU decoding routine */
  173139. if (cinfo->Ah == 0) {
  173140. if (is_DC_band)
  173141. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173142. else
  173143. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173144. } else {
  173145. if (is_DC_band)
  173146. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173147. else
  173148. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173149. }
  173150. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173151. compptr = cinfo->cur_comp_info[ci];
  173152. /* Make sure requested tables are present, and compute derived tables.
  173153. * We may build same derived table more than once, but it's not expensive.
  173154. */
  173155. if (is_DC_band) {
  173156. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173157. tbl = compptr->dc_tbl_no;
  173158. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173159. & entropy->derived_tbls[tbl]);
  173160. }
  173161. } else {
  173162. tbl = compptr->ac_tbl_no;
  173163. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173164. & entropy->derived_tbls[tbl]);
  173165. /* remember the single active table */
  173166. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173167. }
  173168. /* Initialize DC predictions to 0 */
  173169. entropy->saved.last_dc_val[ci] = 0;
  173170. }
  173171. /* Initialize bitread state variables */
  173172. entropy->bitstate.bits_left = 0;
  173173. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173174. entropy->pub.insufficient_data = FALSE;
  173175. /* Initialize private state variables */
  173176. entropy->saved.EOBRUN = 0;
  173177. /* Initialize restart counter */
  173178. entropy->restarts_to_go = cinfo->restart_interval;
  173179. }
  173180. /*
  173181. * Check for a restart marker & resynchronize decoder.
  173182. * Returns FALSE if must suspend.
  173183. */
  173184. LOCAL(boolean)
  173185. process_restartp (j_decompress_ptr cinfo)
  173186. {
  173187. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173188. int ci;
  173189. /* Throw away any unused bits remaining in bit buffer; */
  173190. /* include any full bytes in next_marker's count of discarded bytes */
  173191. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173192. entropy->bitstate.bits_left = 0;
  173193. /* Advance past the RSTn marker */
  173194. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173195. return FALSE;
  173196. /* Re-initialize DC predictions to 0 */
  173197. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173198. entropy->saved.last_dc_val[ci] = 0;
  173199. /* Re-init EOB run count, too */
  173200. entropy->saved.EOBRUN = 0;
  173201. /* Reset restart counter */
  173202. entropy->restarts_to_go = cinfo->restart_interval;
  173203. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173204. * against a marker. In that case we will end up treating the next data
  173205. * segment as empty, and we can avoid producing bogus output pixels by
  173206. * leaving the flag set.
  173207. */
  173208. if (cinfo->unread_marker == 0)
  173209. entropy->pub.insufficient_data = FALSE;
  173210. return TRUE;
  173211. }
  173212. /*
  173213. * Huffman MCU decoding.
  173214. * Each of these routines decodes and returns one MCU's worth of
  173215. * Huffman-compressed coefficients.
  173216. * The coefficients are reordered from zigzag order into natural array order,
  173217. * but are not dequantized.
  173218. *
  173219. * The i'th block of the MCU is stored into the block pointed to by
  173220. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173221. *
  173222. * We return FALSE if data source requested suspension. In that case no
  173223. * changes have been made to permanent state. (Exception: some output
  173224. * coefficients may already have been assigned. This is harmless for
  173225. * spectral selection, since we'll just re-assign them on the next call.
  173226. * Successive approximation AC refinement has to be more careful, however.)
  173227. */
  173228. /*
  173229. * MCU decoding for DC initial scan (either spectral selection,
  173230. * or first pass of successive approximation).
  173231. */
  173232. METHODDEF(boolean)
  173233. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173234. {
  173235. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173236. int Al = cinfo->Al;
  173237. register int s, r;
  173238. int blkn, ci;
  173239. JBLOCKROW block;
  173240. BITREAD_STATE_VARS;
  173241. savable_state3 state;
  173242. d_derived_tbl * tbl;
  173243. jpeg_component_info * compptr;
  173244. /* Process restart marker if needed; may have to suspend */
  173245. if (cinfo->restart_interval) {
  173246. if (entropy->restarts_to_go == 0)
  173247. if (! process_restartp(cinfo))
  173248. return FALSE;
  173249. }
  173250. /* If we've run out of data, just leave the MCU set to zeroes.
  173251. * This way, we return uniform gray for the remainder of the segment.
  173252. */
  173253. if (! entropy->pub.insufficient_data) {
  173254. /* Load up working state */
  173255. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173256. ASSIGN_STATE(state, entropy->saved);
  173257. /* Outer loop handles each block in the MCU */
  173258. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173259. block = MCU_data[blkn];
  173260. ci = cinfo->MCU_membership[blkn];
  173261. compptr = cinfo->cur_comp_info[ci];
  173262. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173263. /* Decode a single block's worth of coefficients */
  173264. /* Section F.2.2.1: decode the DC coefficient difference */
  173265. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173266. if (s) {
  173267. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173268. r = GET_BITS(s);
  173269. s = HUFF_EXTEND(r, s);
  173270. }
  173271. /* Convert DC difference to actual value, update last_dc_val */
  173272. s += state.last_dc_val[ci];
  173273. state.last_dc_val[ci] = s;
  173274. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173275. (*block)[0] = (JCOEF) (s << Al);
  173276. }
  173277. /* Completed MCU, so update state */
  173278. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173279. ASSIGN_STATE(entropy->saved, state);
  173280. }
  173281. /* Account for restart interval (no-op if not using restarts) */
  173282. entropy->restarts_to_go--;
  173283. return TRUE;
  173284. }
  173285. /*
  173286. * MCU decoding for AC initial scan (either spectral selection,
  173287. * or first pass of successive approximation).
  173288. */
  173289. METHODDEF(boolean)
  173290. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173291. {
  173292. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173293. int Se = cinfo->Se;
  173294. int Al = cinfo->Al;
  173295. register int s, k, r;
  173296. unsigned int EOBRUN;
  173297. JBLOCKROW block;
  173298. BITREAD_STATE_VARS;
  173299. d_derived_tbl * tbl;
  173300. /* Process restart marker if needed; may have to suspend */
  173301. if (cinfo->restart_interval) {
  173302. if (entropy->restarts_to_go == 0)
  173303. if (! process_restartp(cinfo))
  173304. return FALSE;
  173305. }
  173306. /* If we've run out of data, just leave the MCU set to zeroes.
  173307. * This way, we return uniform gray for the remainder of the segment.
  173308. */
  173309. if (! entropy->pub.insufficient_data) {
  173310. /* Load up working state.
  173311. * We can avoid loading/saving bitread state if in an EOB run.
  173312. */
  173313. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173314. /* There is always only one block per MCU */
  173315. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173316. EOBRUN--; /* ...process it now (we do nothing) */
  173317. else {
  173318. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173319. block = MCU_data[0];
  173320. tbl = entropy->ac_derived_tbl;
  173321. for (k = cinfo->Ss; k <= Se; k++) {
  173322. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173323. r = s >> 4;
  173324. s &= 15;
  173325. if (s) {
  173326. k += r;
  173327. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173328. r = GET_BITS(s);
  173329. s = HUFF_EXTEND(r, s);
  173330. /* Scale and output coefficient in natural (dezigzagged) order */
  173331. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173332. } else {
  173333. if (r == 15) { /* ZRL */
  173334. k += 15; /* skip 15 zeroes in band */
  173335. } else { /* EOBr, run length is 2^r + appended bits */
  173336. EOBRUN = 1 << r;
  173337. if (r) { /* EOBr, r > 0 */
  173338. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173339. r = GET_BITS(r);
  173340. EOBRUN += r;
  173341. }
  173342. EOBRUN--; /* this band is processed at this moment */
  173343. break; /* force end-of-band */
  173344. }
  173345. }
  173346. }
  173347. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173348. }
  173349. /* Completed MCU, so update state */
  173350. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173351. }
  173352. /* Account for restart interval (no-op if not using restarts) */
  173353. entropy->restarts_to_go--;
  173354. return TRUE;
  173355. }
  173356. /*
  173357. * MCU decoding for DC successive approximation refinement scan.
  173358. * Note: we assume such scans can be multi-component, although the spec
  173359. * is not very clear on the point.
  173360. */
  173361. METHODDEF(boolean)
  173362. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173363. {
  173364. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173365. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173366. int blkn;
  173367. JBLOCKROW block;
  173368. BITREAD_STATE_VARS;
  173369. /* Process restart marker if needed; may have to suspend */
  173370. if (cinfo->restart_interval) {
  173371. if (entropy->restarts_to_go == 0)
  173372. if (! process_restartp(cinfo))
  173373. return FALSE;
  173374. }
  173375. /* Not worth the cycles to check insufficient_data here,
  173376. * since we will not change the data anyway if we read zeroes.
  173377. */
  173378. /* Load up working state */
  173379. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173380. /* Outer loop handles each block in the MCU */
  173381. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173382. block = MCU_data[blkn];
  173383. /* Encoded data is simply the next bit of the two's-complement DC value */
  173384. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173385. if (GET_BITS(1))
  173386. (*block)[0] |= p1;
  173387. /* Note: since we use |=, repeating the assignment later is safe */
  173388. }
  173389. /* Completed MCU, so update state */
  173390. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173391. /* Account for restart interval (no-op if not using restarts) */
  173392. entropy->restarts_to_go--;
  173393. return TRUE;
  173394. }
  173395. /*
  173396. * MCU decoding for AC successive approximation refinement scan.
  173397. */
  173398. METHODDEF(boolean)
  173399. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173400. {
  173401. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173402. int Se = cinfo->Se;
  173403. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173404. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173405. register int s, k, r;
  173406. unsigned int EOBRUN;
  173407. JBLOCKROW block;
  173408. JCOEFPTR thiscoef;
  173409. BITREAD_STATE_VARS;
  173410. d_derived_tbl * tbl;
  173411. int num_newnz;
  173412. int newnz_pos[DCTSIZE2];
  173413. /* Process restart marker if needed; may have to suspend */
  173414. if (cinfo->restart_interval) {
  173415. if (entropy->restarts_to_go == 0)
  173416. if (! process_restartp(cinfo))
  173417. return FALSE;
  173418. }
  173419. /* If we've run out of data, don't modify the MCU.
  173420. */
  173421. if (! entropy->pub.insufficient_data) {
  173422. /* Load up working state */
  173423. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173424. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173425. /* There is always only one block per MCU */
  173426. block = MCU_data[0];
  173427. tbl = entropy->ac_derived_tbl;
  173428. /* If we are forced to suspend, we must undo the assignments to any newly
  173429. * nonzero coefficients in the block, because otherwise we'd get confused
  173430. * next time about which coefficients were already nonzero.
  173431. * But we need not undo addition of bits to already-nonzero coefficients;
  173432. * instead, we can test the current bit to see if we already did it.
  173433. */
  173434. num_newnz = 0;
  173435. /* initialize coefficient loop counter to start of band */
  173436. k = cinfo->Ss;
  173437. if (EOBRUN == 0) {
  173438. for (; k <= Se; k++) {
  173439. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173440. r = s >> 4;
  173441. s &= 15;
  173442. if (s) {
  173443. if (s != 1) /* size of new coef should always be 1 */
  173444. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173445. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173446. if (GET_BITS(1))
  173447. s = p1; /* newly nonzero coef is positive */
  173448. else
  173449. s = m1; /* newly nonzero coef is negative */
  173450. } else {
  173451. if (r != 15) {
  173452. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173453. if (r) {
  173454. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173455. r = GET_BITS(r);
  173456. EOBRUN += r;
  173457. }
  173458. break; /* rest of block is handled by EOB logic */
  173459. }
  173460. /* note s = 0 for processing ZRL */
  173461. }
  173462. /* Advance over already-nonzero coefs and r still-zero coefs,
  173463. * appending correction bits to the nonzeroes. A correction bit is 1
  173464. * if the absolute value of the coefficient must be increased.
  173465. */
  173466. do {
  173467. thiscoef = *block + jpeg_natural_order[k];
  173468. if (*thiscoef != 0) {
  173469. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173470. if (GET_BITS(1)) {
  173471. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173472. if (*thiscoef >= 0)
  173473. *thiscoef += p1;
  173474. else
  173475. *thiscoef += m1;
  173476. }
  173477. }
  173478. } else {
  173479. if (--r < 0)
  173480. break; /* reached target zero coefficient */
  173481. }
  173482. k++;
  173483. } while (k <= Se);
  173484. if (s) {
  173485. int pos = jpeg_natural_order[k];
  173486. /* Output newly nonzero coefficient */
  173487. (*block)[pos] = (JCOEF) s;
  173488. /* Remember its position in case we have to suspend */
  173489. newnz_pos[num_newnz++] = pos;
  173490. }
  173491. }
  173492. }
  173493. if (EOBRUN > 0) {
  173494. /* Scan any remaining coefficient positions after the end-of-band
  173495. * (the last newly nonzero coefficient, if any). Append a correction
  173496. * bit to each already-nonzero coefficient. A correction bit is 1
  173497. * if the absolute value of the coefficient must be increased.
  173498. */
  173499. for (; k <= Se; k++) {
  173500. thiscoef = *block + jpeg_natural_order[k];
  173501. if (*thiscoef != 0) {
  173502. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173503. if (GET_BITS(1)) {
  173504. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173505. if (*thiscoef >= 0)
  173506. *thiscoef += p1;
  173507. else
  173508. *thiscoef += m1;
  173509. }
  173510. }
  173511. }
  173512. }
  173513. /* Count one block completed in EOB run */
  173514. EOBRUN--;
  173515. }
  173516. /* Completed MCU, so update state */
  173517. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173518. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173519. }
  173520. /* Account for restart interval (no-op if not using restarts) */
  173521. entropy->restarts_to_go--;
  173522. return TRUE;
  173523. undoit:
  173524. /* Re-zero any output coefficients that we made newly nonzero */
  173525. while (num_newnz > 0)
  173526. (*block)[newnz_pos[--num_newnz]] = 0;
  173527. return FALSE;
  173528. }
  173529. /*
  173530. * Module initialization routine for progressive Huffman entropy decoding.
  173531. */
  173532. GLOBAL(void)
  173533. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173534. {
  173535. phuff_entropy_ptr2 entropy;
  173536. int *coef_bit_ptr;
  173537. int ci, i;
  173538. entropy = (phuff_entropy_ptr2)
  173539. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173540. SIZEOF(phuff_entropy_decoder));
  173541. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173542. entropy->pub.start_pass = start_pass_phuff_decoder;
  173543. /* Mark derived tables unallocated */
  173544. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173545. entropy->derived_tbls[i] = NULL;
  173546. }
  173547. /* Create progression status table */
  173548. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173549. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173550. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173551. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173552. for (ci = 0; ci < cinfo->num_components; ci++)
  173553. for (i = 0; i < DCTSIZE2; i++)
  173554. *coef_bit_ptr++ = -1;
  173555. }
  173556. #endif /* D_PROGRESSIVE_SUPPORTED */
  173557. /*** End of inlined file: jdphuff.c ***/
  173558. /*** Start of inlined file: jdpostct.c ***/
  173559. #define JPEG_INTERNALS
  173560. /* Private buffer controller object */
  173561. typedef struct {
  173562. struct jpeg_d_post_controller pub; /* public fields */
  173563. /* Color quantization source buffer: this holds output data from
  173564. * the upsample/color conversion step to be passed to the quantizer.
  173565. * For two-pass color quantization, we need a full-image buffer;
  173566. * for one-pass operation, a strip buffer is sufficient.
  173567. */
  173568. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173569. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173570. JDIMENSION strip_height; /* buffer size in rows */
  173571. /* for two-pass mode only: */
  173572. JDIMENSION starting_row; /* row # of first row in current strip */
  173573. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173574. } my_post_controller;
  173575. typedef my_post_controller * my_post_ptr;
  173576. /* Forward declarations */
  173577. METHODDEF(void) post_process_1pass
  173578. JPP((j_decompress_ptr cinfo,
  173579. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173580. JDIMENSION in_row_groups_avail,
  173581. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173582. JDIMENSION out_rows_avail));
  173583. #ifdef QUANT_2PASS_SUPPORTED
  173584. METHODDEF(void) post_process_prepass
  173585. JPP((j_decompress_ptr cinfo,
  173586. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173587. JDIMENSION in_row_groups_avail,
  173588. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173589. JDIMENSION out_rows_avail));
  173590. METHODDEF(void) post_process_2pass
  173591. JPP((j_decompress_ptr cinfo,
  173592. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173593. JDIMENSION in_row_groups_avail,
  173594. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173595. JDIMENSION out_rows_avail));
  173596. #endif
  173597. /*
  173598. * Initialize for a processing pass.
  173599. */
  173600. METHODDEF(void)
  173601. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173602. {
  173603. my_post_ptr post = (my_post_ptr) cinfo->post;
  173604. switch (pass_mode) {
  173605. case JBUF_PASS_THRU:
  173606. if (cinfo->quantize_colors) {
  173607. /* Single-pass processing with color quantization. */
  173608. post->pub.post_process_data = post_process_1pass;
  173609. /* We could be doing buffered-image output before starting a 2-pass
  173610. * color quantization; in that case, jinit_d_post_controller did not
  173611. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173612. */
  173613. if (post->buffer == NULL) {
  173614. post->buffer = (*cinfo->mem->access_virt_sarray)
  173615. ((j_common_ptr) cinfo, post->whole_image,
  173616. (JDIMENSION) 0, post->strip_height, TRUE);
  173617. }
  173618. } else {
  173619. /* For single-pass processing without color quantization,
  173620. * I have no work to do; just call the upsampler directly.
  173621. */
  173622. post->pub.post_process_data = cinfo->upsample->upsample;
  173623. }
  173624. break;
  173625. #ifdef QUANT_2PASS_SUPPORTED
  173626. case JBUF_SAVE_AND_PASS:
  173627. /* First pass of 2-pass quantization */
  173628. if (post->whole_image == NULL)
  173629. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173630. post->pub.post_process_data = post_process_prepass;
  173631. break;
  173632. case JBUF_CRANK_DEST:
  173633. /* Second pass of 2-pass quantization */
  173634. if (post->whole_image == NULL)
  173635. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173636. post->pub.post_process_data = post_process_2pass;
  173637. break;
  173638. #endif /* QUANT_2PASS_SUPPORTED */
  173639. default:
  173640. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173641. break;
  173642. }
  173643. post->starting_row = post->next_row = 0;
  173644. }
  173645. /*
  173646. * Process some data in the one-pass (strip buffer) case.
  173647. * This is used for color precision reduction as well as one-pass quantization.
  173648. */
  173649. METHODDEF(void)
  173650. post_process_1pass (j_decompress_ptr cinfo,
  173651. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173652. JDIMENSION in_row_groups_avail,
  173653. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173654. JDIMENSION out_rows_avail)
  173655. {
  173656. my_post_ptr post = (my_post_ptr) cinfo->post;
  173657. JDIMENSION num_rows, max_rows;
  173658. /* Fill the buffer, but not more than what we can dump out in one go. */
  173659. /* Note we rely on the upsampler to detect bottom of image. */
  173660. max_rows = out_rows_avail - *out_row_ctr;
  173661. if (max_rows > post->strip_height)
  173662. max_rows = post->strip_height;
  173663. num_rows = 0;
  173664. (*cinfo->upsample->upsample) (cinfo,
  173665. input_buf, in_row_group_ctr, in_row_groups_avail,
  173666. post->buffer, &num_rows, max_rows);
  173667. /* Quantize and emit data. */
  173668. (*cinfo->cquantize->color_quantize) (cinfo,
  173669. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173670. *out_row_ctr += num_rows;
  173671. }
  173672. #ifdef QUANT_2PASS_SUPPORTED
  173673. /*
  173674. * Process some data in the first pass of 2-pass quantization.
  173675. */
  173676. METHODDEF(void)
  173677. post_process_prepass (j_decompress_ptr cinfo,
  173678. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173679. JDIMENSION in_row_groups_avail,
  173680. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173681. JDIMENSION)
  173682. {
  173683. my_post_ptr post = (my_post_ptr) cinfo->post;
  173684. JDIMENSION old_next_row, num_rows;
  173685. /* Reposition virtual buffer if at start of strip. */
  173686. if (post->next_row == 0) {
  173687. post->buffer = (*cinfo->mem->access_virt_sarray)
  173688. ((j_common_ptr) cinfo, post->whole_image,
  173689. post->starting_row, post->strip_height, TRUE);
  173690. }
  173691. /* Upsample some data (up to a strip height's worth). */
  173692. old_next_row = post->next_row;
  173693. (*cinfo->upsample->upsample) (cinfo,
  173694. input_buf, in_row_group_ctr, in_row_groups_avail,
  173695. post->buffer, &post->next_row, post->strip_height);
  173696. /* Allow quantizer to scan new data. No data is emitted, */
  173697. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173698. if (post->next_row > old_next_row) {
  173699. num_rows = post->next_row - old_next_row;
  173700. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173701. (JSAMPARRAY) NULL, (int) num_rows);
  173702. *out_row_ctr += num_rows;
  173703. }
  173704. /* Advance if we filled the strip. */
  173705. if (post->next_row >= post->strip_height) {
  173706. post->starting_row += post->strip_height;
  173707. post->next_row = 0;
  173708. }
  173709. }
  173710. /*
  173711. * Process some data in the second pass of 2-pass quantization.
  173712. */
  173713. METHODDEF(void)
  173714. post_process_2pass (j_decompress_ptr cinfo,
  173715. JSAMPIMAGE, JDIMENSION *,
  173716. JDIMENSION,
  173717. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173718. JDIMENSION out_rows_avail)
  173719. {
  173720. my_post_ptr post = (my_post_ptr) cinfo->post;
  173721. JDIMENSION num_rows, max_rows;
  173722. /* Reposition virtual buffer if at start of strip. */
  173723. if (post->next_row == 0) {
  173724. post->buffer = (*cinfo->mem->access_virt_sarray)
  173725. ((j_common_ptr) cinfo, post->whole_image,
  173726. post->starting_row, post->strip_height, FALSE);
  173727. }
  173728. /* Determine number of rows to emit. */
  173729. num_rows = post->strip_height - post->next_row; /* available in strip */
  173730. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173731. if (num_rows > max_rows)
  173732. num_rows = max_rows;
  173733. /* We have to check bottom of image here, can't depend on upsampler. */
  173734. max_rows = cinfo->output_height - post->starting_row;
  173735. if (num_rows > max_rows)
  173736. num_rows = max_rows;
  173737. /* Quantize and emit data. */
  173738. (*cinfo->cquantize->color_quantize) (cinfo,
  173739. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173740. (int) num_rows);
  173741. *out_row_ctr += num_rows;
  173742. /* Advance if we filled the strip. */
  173743. post->next_row += num_rows;
  173744. if (post->next_row >= post->strip_height) {
  173745. post->starting_row += post->strip_height;
  173746. post->next_row = 0;
  173747. }
  173748. }
  173749. #endif /* QUANT_2PASS_SUPPORTED */
  173750. /*
  173751. * Initialize postprocessing controller.
  173752. */
  173753. GLOBAL(void)
  173754. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173755. {
  173756. my_post_ptr post;
  173757. post = (my_post_ptr)
  173758. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173759. SIZEOF(my_post_controller));
  173760. cinfo->post = (struct jpeg_d_post_controller *) post;
  173761. post->pub.start_pass = start_pass_dpost;
  173762. post->whole_image = NULL; /* flag for no virtual arrays */
  173763. post->buffer = NULL; /* flag for no strip buffer */
  173764. /* Create the quantization buffer, if needed */
  173765. if (cinfo->quantize_colors) {
  173766. /* The buffer strip height is max_v_samp_factor, which is typically
  173767. * an efficient number of rows for upsampling to return.
  173768. * (In the presence of output rescaling, we might want to be smarter?)
  173769. */
  173770. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173771. if (need_full_buffer) {
  173772. /* Two-pass color quantization: need full-image storage. */
  173773. /* We round up the number of rows to a multiple of the strip height. */
  173774. #ifdef QUANT_2PASS_SUPPORTED
  173775. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173776. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173777. cinfo->output_width * cinfo->out_color_components,
  173778. (JDIMENSION) jround_up((long) cinfo->output_height,
  173779. (long) post->strip_height),
  173780. post->strip_height);
  173781. #else
  173782. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173783. #endif /* QUANT_2PASS_SUPPORTED */
  173784. } else {
  173785. /* One-pass color quantization: just make a strip buffer. */
  173786. post->buffer = (*cinfo->mem->alloc_sarray)
  173787. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173788. cinfo->output_width * cinfo->out_color_components,
  173789. post->strip_height);
  173790. }
  173791. }
  173792. }
  173793. /*** End of inlined file: jdpostct.c ***/
  173794. #undef FIX
  173795. /*** Start of inlined file: jdsample.c ***/
  173796. #define JPEG_INTERNALS
  173797. /* Pointer to routine to upsample a single component */
  173798. typedef JMETHOD(void, upsample1_ptr,
  173799. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173800. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173801. /* Private subobject */
  173802. typedef struct {
  173803. struct jpeg_upsampler pub; /* public fields */
  173804. /* Color conversion buffer. When using separate upsampling and color
  173805. * conversion steps, this buffer holds one upsampled row group until it
  173806. * has been color converted and output.
  173807. * Note: we do not allocate any storage for component(s) which are full-size,
  173808. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173809. * simply set to point to the input data array, thereby avoiding copying.
  173810. */
  173811. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173812. /* Per-component upsampling method pointers */
  173813. upsample1_ptr methods[MAX_COMPONENTS];
  173814. int next_row_out; /* counts rows emitted from color_buf */
  173815. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173816. /* Height of an input row group for each component. */
  173817. int rowgroup_height[MAX_COMPONENTS];
  173818. /* These arrays save pixel expansion factors so that int_expand need not
  173819. * recompute them each time. They are unused for other upsampling methods.
  173820. */
  173821. UINT8 h_expand[MAX_COMPONENTS];
  173822. UINT8 v_expand[MAX_COMPONENTS];
  173823. } my_upsampler2;
  173824. typedef my_upsampler2 * my_upsample_ptr2;
  173825. /*
  173826. * Initialize for an upsampling pass.
  173827. */
  173828. METHODDEF(void)
  173829. start_pass_upsample (j_decompress_ptr cinfo)
  173830. {
  173831. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173832. /* Mark the conversion buffer empty */
  173833. upsample->next_row_out = cinfo->max_v_samp_factor;
  173834. /* Initialize total-height counter for detecting bottom of image */
  173835. upsample->rows_to_go = cinfo->output_height;
  173836. }
  173837. /*
  173838. * Control routine to do upsampling (and color conversion).
  173839. *
  173840. * In this version we upsample each component independently.
  173841. * We upsample one row group into the conversion buffer, then apply
  173842. * color conversion a row at a time.
  173843. */
  173844. METHODDEF(void)
  173845. sep_upsample (j_decompress_ptr cinfo,
  173846. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173847. JDIMENSION,
  173848. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173849. JDIMENSION out_rows_avail)
  173850. {
  173851. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173852. int ci;
  173853. jpeg_component_info * compptr;
  173854. JDIMENSION num_rows;
  173855. /* Fill the conversion buffer, if it's empty */
  173856. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173857. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173858. ci++, compptr++) {
  173859. /* Invoke per-component upsample method. Notice we pass a POINTER
  173860. * to color_buf[ci], so that fullsize_upsample can change it.
  173861. */
  173862. (*upsample->methods[ci]) (cinfo, compptr,
  173863. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173864. upsample->color_buf + ci);
  173865. }
  173866. upsample->next_row_out = 0;
  173867. }
  173868. /* Color-convert and emit rows */
  173869. /* How many we have in the buffer: */
  173870. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173871. /* Not more than the distance to the end of the image. Need this test
  173872. * in case the image height is not a multiple of max_v_samp_factor:
  173873. */
  173874. if (num_rows > upsample->rows_to_go)
  173875. num_rows = upsample->rows_to_go;
  173876. /* And not more than what the client can accept: */
  173877. out_rows_avail -= *out_row_ctr;
  173878. if (num_rows > out_rows_avail)
  173879. num_rows = out_rows_avail;
  173880. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173881. (JDIMENSION) upsample->next_row_out,
  173882. output_buf + *out_row_ctr,
  173883. (int) num_rows);
  173884. /* Adjust counts */
  173885. *out_row_ctr += num_rows;
  173886. upsample->rows_to_go -= num_rows;
  173887. upsample->next_row_out += num_rows;
  173888. /* When the buffer is emptied, declare this input row group consumed */
  173889. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173890. (*in_row_group_ctr)++;
  173891. }
  173892. /*
  173893. * These are the routines invoked by sep_upsample to upsample pixel values
  173894. * of a single component. One row group is processed per call.
  173895. */
  173896. /*
  173897. * For full-size components, we just make color_buf[ci] point at the
  173898. * input buffer, and thus avoid copying any data. Note that this is
  173899. * safe only because sep_upsample doesn't declare the input row group
  173900. * "consumed" until we are done color converting and emitting it.
  173901. */
  173902. METHODDEF(void)
  173903. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173904. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173905. {
  173906. *output_data_ptr = input_data;
  173907. }
  173908. /*
  173909. * This is a no-op version used for "uninteresting" components.
  173910. * These components will not be referenced by color conversion.
  173911. */
  173912. METHODDEF(void)
  173913. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173914. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173915. {
  173916. *output_data_ptr = NULL; /* safety check */
  173917. }
  173918. /*
  173919. * This version handles any integral sampling ratios.
  173920. * This is not used for typical JPEG files, so it need not be fast.
  173921. * Nor, for that matter, is it particularly accurate: the algorithm is
  173922. * simple replication of the input pixel onto the corresponding output
  173923. * pixels. The hi-falutin sampling literature refers to this as a
  173924. * "box filter". A box filter tends to introduce visible artifacts,
  173925. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173926. * you would be well advised to improve this code.
  173927. */
  173928. METHODDEF(void)
  173929. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173930. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173931. {
  173932. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173933. JSAMPARRAY output_data = *output_data_ptr;
  173934. register JSAMPROW inptr, outptr;
  173935. register JSAMPLE invalue;
  173936. register int h;
  173937. JSAMPROW outend;
  173938. int h_expand, v_expand;
  173939. int inrow, outrow;
  173940. h_expand = upsample->h_expand[compptr->component_index];
  173941. v_expand = upsample->v_expand[compptr->component_index];
  173942. inrow = outrow = 0;
  173943. while (outrow < cinfo->max_v_samp_factor) {
  173944. /* Generate one output row with proper horizontal expansion */
  173945. inptr = input_data[inrow];
  173946. outptr = output_data[outrow];
  173947. outend = outptr + cinfo->output_width;
  173948. while (outptr < outend) {
  173949. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173950. for (h = h_expand; h > 0; h--) {
  173951. *outptr++ = invalue;
  173952. }
  173953. }
  173954. /* Generate any additional output rows by duplicating the first one */
  173955. if (v_expand > 1) {
  173956. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173957. v_expand-1, cinfo->output_width);
  173958. }
  173959. inrow++;
  173960. outrow += v_expand;
  173961. }
  173962. }
  173963. /*
  173964. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173965. * It's still a box filter.
  173966. */
  173967. METHODDEF(void)
  173968. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173969. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173970. {
  173971. JSAMPARRAY output_data = *output_data_ptr;
  173972. register JSAMPROW inptr, outptr;
  173973. register JSAMPLE invalue;
  173974. JSAMPROW outend;
  173975. int inrow;
  173976. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173977. inptr = input_data[inrow];
  173978. outptr = output_data[inrow];
  173979. outend = outptr + cinfo->output_width;
  173980. while (outptr < outend) {
  173981. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173982. *outptr++ = invalue;
  173983. *outptr++ = invalue;
  173984. }
  173985. }
  173986. }
  173987. /*
  173988. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173989. * It's still a box filter.
  173990. */
  173991. METHODDEF(void)
  173992. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173993. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173994. {
  173995. JSAMPARRAY output_data = *output_data_ptr;
  173996. register JSAMPROW inptr, outptr;
  173997. register JSAMPLE invalue;
  173998. JSAMPROW outend;
  173999. int inrow, outrow;
  174000. inrow = outrow = 0;
  174001. while (outrow < cinfo->max_v_samp_factor) {
  174002. inptr = input_data[inrow];
  174003. outptr = output_data[outrow];
  174004. outend = outptr + cinfo->output_width;
  174005. while (outptr < outend) {
  174006. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174007. *outptr++ = invalue;
  174008. *outptr++ = invalue;
  174009. }
  174010. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174011. 1, cinfo->output_width);
  174012. inrow++;
  174013. outrow += 2;
  174014. }
  174015. }
  174016. /*
  174017. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174018. *
  174019. * The upsampling algorithm is linear interpolation between pixel centers,
  174020. * also known as a "triangle filter". This is a good compromise between
  174021. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174022. * of the way between input pixel centers.
  174023. *
  174024. * A note about the "bias" calculations: when rounding fractional values to
  174025. * integer, we do not want to always round 0.5 up to the next integer.
  174026. * If we did that, we'd introduce a noticeable bias towards larger values.
  174027. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174028. * alternate pixel locations (a simple ordered dither pattern).
  174029. */
  174030. METHODDEF(void)
  174031. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174032. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174033. {
  174034. JSAMPARRAY output_data = *output_data_ptr;
  174035. register JSAMPROW inptr, outptr;
  174036. register int invalue;
  174037. register JDIMENSION colctr;
  174038. int inrow;
  174039. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174040. inptr = input_data[inrow];
  174041. outptr = output_data[inrow];
  174042. /* Special case for first column */
  174043. invalue = GETJSAMPLE(*inptr++);
  174044. *outptr++ = (JSAMPLE) invalue;
  174045. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174046. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174047. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174048. invalue = GETJSAMPLE(*inptr++) * 3;
  174049. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174050. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174051. }
  174052. /* Special case for last column */
  174053. invalue = GETJSAMPLE(*inptr);
  174054. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174055. *outptr++ = (JSAMPLE) invalue;
  174056. }
  174057. }
  174058. /*
  174059. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174060. * Again a triangle filter; see comments for h2v1 case, above.
  174061. *
  174062. * It is OK for us to reference the adjacent input rows because we demanded
  174063. * context from the main buffer controller (see initialization code).
  174064. */
  174065. METHODDEF(void)
  174066. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174067. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174068. {
  174069. JSAMPARRAY output_data = *output_data_ptr;
  174070. register JSAMPROW inptr0, inptr1, outptr;
  174071. #if BITS_IN_JSAMPLE == 8
  174072. register int thiscolsum, lastcolsum, nextcolsum;
  174073. #else
  174074. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174075. #endif
  174076. register JDIMENSION colctr;
  174077. int inrow, outrow, v;
  174078. inrow = outrow = 0;
  174079. while (outrow < cinfo->max_v_samp_factor) {
  174080. for (v = 0; v < 2; v++) {
  174081. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174082. inptr0 = input_data[inrow];
  174083. if (v == 0) /* next nearest is row above */
  174084. inptr1 = input_data[inrow-1];
  174085. else /* next nearest is row below */
  174086. inptr1 = input_data[inrow+1];
  174087. outptr = output_data[outrow++];
  174088. /* Special case for first column */
  174089. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174090. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174091. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174092. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174093. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174094. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174095. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174096. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174097. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174098. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174099. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174100. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174101. }
  174102. /* Special case for last column */
  174103. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174104. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174105. }
  174106. inrow++;
  174107. }
  174108. }
  174109. /*
  174110. * Module initialization routine for upsampling.
  174111. */
  174112. GLOBAL(void)
  174113. jinit_upsampler (j_decompress_ptr cinfo)
  174114. {
  174115. my_upsample_ptr2 upsample;
  174116. int ci;
  174117. jpeg_component_info * compptr;
  174118. boolean need_buffer, do_fancy;
  174119. int h_in_group, v_in_group, h_out_group, v_out_group;
  174120. upsample = (my_upsample_ptr2)
  174121. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174122. SIZEOF(my_upsampler2));
  174123. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174124. upsample->pub.start_pass = start_pass_upsample;
  174125. upsample->pub.upsample = sep_upsample;
  174126. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174127. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174128. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174129. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174130. * so don't ask for it.
  174131. */
  174132. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174133. /* Verify we can handle the sampling factors, select per-component methods,
  174134. * and create storage as needed.
  174135. */
  174136. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174137. ci++, compptr++) {
  174138. /* Compute size of an "input group" after IDCT scaling. This many samples
  174139. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174140. */
  174141. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174142. cinfo->min_DCT_scaled_size;
  174143. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174144. cinfo->min_DCT_scaled_size;
  174145. h_out_group = cinfo->max_h_samp_factor;
  174146. v_out_group = cinfo->max_v_samp_factor;
  174147. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174148. need_buffer = TRUE;
  174149. if (! compptr->component_needed) {
  174150. /* Don't bother to upsample an uninteresting component. */
  174151. upsample->methods[ci] = noop_upsample;
  174152. need_buffer = FALSE;
  174153. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174154. /* Fullsize components can be processed without any work. */
  174155. upsample->methods[ci] = fullsize_upsample;
  174156. need_buffer = FALSE;
  174157. } else if (h_in_group * 2 == h_out_group &&
  174158. v_in_group == v_out_group) {
  174159. /* Special cases for 2h1v upsampling */
  174160. if (do_fancy && compptr->downsampled_width > 2)
  174161. upsample->methods[ci] = h2v1_fancy_upsample;
  174162. else
  174163. upsample->methods[ci] = h2v1_upsample;
  174164. } else if (h_in_group * 2 == h_out_group &&
  174165. v_in_group * 2 == v_out_group) {
  174166. /* Special cases for 2h2v upsampling */
  174167. if (do_fancy && compptr->downsampled_width > 2) {
  174168. upsample->methods[ci] = h2v2_fancy_upsample;
  174169. upsample->pub.need_context_rows = TRUE;
  174170. } else
  174171. upsample->methods[ci] = h2v2_upsample;
  174172. } else if ((h_out_group % h_in_group) == 0 &&
  174173. (v_out_group % v_in_group) == 0) {
  174174. /* Generic integral-factors upsampling method */
  174175. upsample->methods[ci] = int_upsample;
  174176. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174177. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174178. } else
  174179. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174180. if (need_buffer) {
  174181. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174182. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174183. (JDIMENSION) jround_up((long) cinfo->output_width,
  174184. (long) cinfo->max_h_samp_factor),
  174185. (JDIMENSION) cinfo->max_v_samp_factor);
  174186. }
  174187. }
  174188. }
  174189. /*** End of inlined file: jdsample.c ***/
  174190. /*** Start of inlined file: jdtrans.c ***/
  174191. #define JPEG_INTERNALS
  174192. /* Forward declarations */
  174193. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174194. /*
  174195. * Read the coefficient arrays from a JPEG file.
  174196. * jpeg_read_header must be completed before calling this.
  174197. *
  174198. * The entire image is read into a set of virtual coefficient-block arrays,
  174199. * one per component. The return value is a pointer to the array of
  174200. * virtual-array descriptors. These can be manipulated directly via the
  174201. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174202. * To release the memory occupied by the virtual arrays, call
  174203. * jpeg_finish_decompress() when done with the data.
  174204. *
  174205. * An alternative usage is to simply obtain access to the coefficient arrays
  174206. * during a buffered-image-mode decompression operation. This is allowed
  174207. * after any jpeg_finish_output() call. The arrays can be accessed until
  174208. * jpeg_finish_decompress() is called. (Note that any call to the library
  174209. * may reposition the arrays, so don't rely on access_virt_barray() results
  174210. * to stay valid across library calls.)
  174211. *
  174212. * Returns NULL if suspended. This case need be checked only if
  174213. * a suspending data source is used.
  174214. */
  174215. GLOBAL(jvirt_barray_ptr *)
  174216. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174217. {
  174218. if (cinfo->global_state == DSTATE_READY) {
  174219. /* First call: initialize active modules */
  174220. transdecode_master_selection(cinfo);
  174221. cinfo->global_state = DSTATE_RDCOEFS;
  174222. }
  174223. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174224. /* Absorb whole file into the coef buffer */
  174225. for (;;) {
  174226. int retcode;
  174227. /* Call progress monitor hook if present */
  174228. if (cinfo->progress != NULL)
  174229. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174230. /* Absorb some more input */
  174231. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174232. if (retcode == JPEG_SUSPENDED)
  174233. return NULL;
  174234. if (retcode == JPEG_REACHED_EOI)
  174235. break;
  174236. /* Advance progress counter if appropriate */
  174237. if (cinfo->progress != NULL &&
  174238. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174239. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174240. /* startup underestimated number of scans; ratchet up one scan */
  174241. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174242. }
  174243. }
  174244. }
  174245. /* Set state so that jpeg_finish_decompress does the right thing */
  174246. cinfo->global_state = DSTATE_STOPPING;
  174247. }
  174248. /* At this point we should be in state DSTATE_STOPPING if being used
  174249. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174250. * to the coefficients during a full buffered-image-mode decompression.
  174251. */
  174252. if ((cinfo->global_state == DSTATE_STOPPING ||
  174253. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174254. return cinfo->coef->coef_arrays;
  174255. }
  174256. /* Oops, improper usage */
  174257. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174258. return NULL; /* keep compiler happy */
  174259. }
  174260. /*
  174261. * Master selection of decompression modules for transcoding.
  174262. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174263. */
  174264. LOCAL(void)
  174265. transdecode_master_selection (j_decompress_ptr cinfo)
  174266. {
  174267. /* This is effectively a buffered-image operation. */
  174268. cinfo->buffered_image = TRUE;
  174269. /* Entropy decoding: either Huffman or arithmetic coding. */
  174270. if (cinfo->arith_code) {
  174271. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174272. } else {
  174273. if (cinfo->progressive_mode) {
  174274. #ifdef D_PROGRESSIVE_SUPPORTED
  174275. jinit_phuff_decoder(cinfo);
  174276. #else
  174277. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174278. #endif
  174279. } else
  174280. jinit_huff_decoder(cinfo);
  174281. }
  174282. /* Always get a full-image coefficient buffer. */
  174283. jinit_d_coef_controller(cinfo, TRUE);
  174284. /* We can now tell the memory manager to allocate virtual arrays. */
  174285. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174286. /* Initialize input side of decompressor to consume first scan. */
  174287. (*cinfo->inputctl->start_input_pass) (cinfo);
  174288. /* Initialize progress monitoring. */
  174289. if (cinfo->progress != NULL) {
  174290. int nscans;
  174291. /* Estimate number of scans to set pass_limit. */
  174292. if (cinfo->progressive_mode) {
  174293. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174294. nscans = 2 + 3 * cinfo->num_components;
  174295. } else if (cinfo->inputctl->has_multiple_scans) {
  174296. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174297. nscans = cinfo->num_components;
  174298. } else {
  174299. nscans = 1;
  174300. }
  174301. cinfo->progress->pass_counter = 0L;
  174302. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174303. cinfo->progress->completed_passes = 0;
  174304. cinfo->progress->total_passes = 1;
  174305. }
  174306. }
  174307. /*** End of inlined file: jdtrans.c ***/
  174308. /*** Start of inlined file: jfdctflt.c ***/
  174309. #define JPEG_INTERNALS
  174310. #ifdef DCT_FLOAT_SUPPORTED
  174311. /*
  174312. * This module is specialized to the case DCTSIZE = 8.
  174313. */
  174314. #if DCTSIZE != 8
  174315. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174316. #endif
  174317. /*
  174318. * Perform the forward DCT on one block of samples.
  174319. */
  174320. GLOBAL(void)
  174321. jpeg_fdct_float (FAST_FLOAT * data)
  174322. {
  174323. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174324. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174325. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174326. FAST_FLOAT *dataptr;
  174327. int ctr;
  174328. /* Pass 1: process rows. */
  174329. dataptr = data;
  174330. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174331. tmp0 = dataptr[0] + dataptr[7];
  174332. tmp7 = dataptr[0] - dataptr[7];
  174333. tmp1 = dataptr[1] + dataptr[6];
  174334. tmp6 = dataptr[1] - dataptr[6];
  174335. tmp2 = dataptr[2] + dataptr[5];
  174336. tmp5 = dataptr[2] - dataptr[5];
  174337. tmp3 = dataptr[3] + dataptr[4];
  174338. tmp4 = dataptr[3] - dataptr[4];
  174339. /* Even part */
  174340. tmp10 = tmp0 + tmp3; /* phase 2 */
  174341. tmp13 = tmp0 - tmp3;
  174342. tmp11 = tmp1 + tmp2;
  174343. tmp12 = tmp1 - tmp2;
  174344. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174345. dataptr[4] = tmp10 - tmp11;
  174346. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174347. dataptr[2] = tmp13 + z1; /* phase 5 */
  174348. dataptr[6] = tmp13 - z1;
  174349. /* Odd part */
  174350. tmp10 = tmp4 + tmp5; /* phase 2 */
  174351. tmp11 = tmp5 + tmp6;
  174352. tmp12 = tmp6 + tmp7;
  174353. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174354. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174355. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174356. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174357. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174358. z11 = tmp7 + z3; /* phase 5 */
  174359. z13 = tmp7 - z3;
  174360. dataptr[5] = z13 + z2; /* phase 6 */
  174361. dataptr[3] = z13 - z2;
  174362. dataptr[1] = z11 + z4;
  174363. dataptr[7] = z11 - z4;
  174364. dataptr += DCTSIZE; /* advance pointer to next row */
  174365. }
  174366. /* Pass 2: process columns. */
  174367. dataptr = data;
  174368. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174369. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174370. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174371. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174372. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174373. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174374. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174375. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174376. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174377. /* Even part */
  174378. tmp10 = tmp0 + tmp3; /* phase 2 */
  174379. tmp13 = tmp0 - tmp3;
  174380. tmp11 = tmp1 + tmp2;
  174381. tmp12 = tmp1 - tmp2;
  174382. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174383. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174384. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174385. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174386. dataptr[DCTSIZE*6] = tmp13 - z1;
  174387. /* Odd part */
  174388. tmp10 = tmp4 + tmp5; /* phase 2 */
  174389. tmp11 = tmp5 + tmp6;
  174390. tmp12 = tmp6 + tmp7;
  174391. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174392. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174393. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174394. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174395. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174396. z11 = tmp7 + z3; /* phase 5 */
  174397. z13 = tmp7 - z3;
  174398. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174399. dataptr[DCTSIZE*3] = z13 - z2;
  174400. dataptr[DCTSIZE*1] = z11 + z4;
  174401. dataptr[DCTSIZE*7] = z11 - z4;
  174402. dataptr++; /* advance pointer to next column */
  174403. }
  174404. }
  174405. #endif /* DCT_FLOAT_SUPPORTED */
  174406. /*** End of inlined file: jfdctflt.c ***/
  174407. /*** Start of inlined file: jfdctint.c ***/
  174408. #define JPEG_INTERNALS
  174409. #ifdef DCT_ISLOW_SUPPORTED
  174410. /*
  174411. * This module is specialized to the case DCTSIZE = 8.
  174412. */
  174413. #if DCTSIZE != 8
  174414. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174415. #endif
  174416. /*
  174417. * The poop on this scaling stuff is as follows:
  174418. *
  174419. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174420. * larger than the true DCT outputs. The final outputs are therefore
  174421. * a factor of N larger than desired; since N=8 this can be cured by
  174422. * a simple right shift at the end of the algorithm. The advantage of
  174423. * this arrangement is that we save two multiplications per 1-D DCT,
  174424. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174425. * In the IJG code, this factor of 8 is removed by the quantization step
  174426. * (in jcdctmgr.c), NOT in this module.
  174427. *
  174428. * We have to do addition and subtraction of the integer inputs, which
  174429. * is no problem, and multiplication by fractional constants, which is
  174430. * a problem to do in integer arithmetic. We multiply all the constants
  174431. * by CONST_SCALE and convert them to integer constants (thus retaining
  174432. * CONST_BITS bits of precision in the constants). After doing a
  174433. * multiplication we have to divide the product by CONST_SCALE, with proper
  174434. * rounding, to produce the correct output. This division can be done
  174435. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174436. * as long as possible so that partial sums can be added together with
  174437. * full fractional precision.
  174438. *
  174439. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174440. * they are represented to better-than-integral precision. These outputs
  174441. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174442. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174443. * array is INT32 anyway.)
  174444. *
  174445. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174446. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174447. * shows that the values given below are the most effective.
  174448. */
  174449. #if BITS_IN_JSAMPLE == 8
  174450. #define CONST_BITS 13
  174451. #define PASS1_BITS 2
  174452. #else
  174453. #define CONST_BITS 13
  174454. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174455. #endif
  174456. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174457. * causing a lot of useless floating-point operations at run time.
  174458. * To get around this we use the following pre-calculated constants.
  174459. * If you change CONST_BITS you may want to add appropriate values.
  174460. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174461. */
  174462. #if CONST_BITS == 13
  174463. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174464. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174465. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174466. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174467. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174468. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174469. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174470. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174471. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174472. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174473. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174474. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174475. #else
  174476. #define FIX_0_298631336 FIX(0.298631336)
  174477. #define FIX_0_390180644 FIX(0.390180644)
  174478. #define FIX_0_541196100 FIX(0.541196100)
  174479. #define FIX_0_765366865 FIX(0.765366865)
  174480. #define FIX_0_899976223 FIX(0.899976223)
  174481. #define FIX_1_175875602 FIX(1.175875602)
  174482. #define FIX_1_501321110 FIX(1.501321110)
  174483. #define FIX_1_847759065 FIX(1.847759065)
  174484. #define FIX_1_961570560 FIX(1.961570560)
  174485. #define FIX_2_053119869 FIX(2.053119869)
  174486. #define FIX_2_562915447 FIX(2.562915447)
  174487. #define FIX_3_072711026 FIX(3.072711026)
  174488. #endif
  174489. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174490. * For 8-bit samples with the recommended scaling, all the variable
  174491. * and constant values involved are no more than 16 bits wide, so a
  174492. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174493. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174494. */
  174495. #if BITS_IN_JSAMPLE == 8
  174496. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174497. #else
  174498. #define MULTIPLY(var,const) ((var) * (const))
  174499. #endif
  174500. /*
  174501. * Perform the forward DCT on one block of samples.
  174502. */
  174503. GLOBAL(void)
  174504. jpeg_fdct_islow (DCTELEM * data)
  174505. {
  174506. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174507. INT32 tmp10, tmp11, tmp12, tmp13;
  174508. INT32 z1, z2, z3, z4, z5;
  174509. DCTELEM *dataptr;
  174510. int ctr;
  174511. SHIFT_TEMPS
  174512. /* Pass 1: process rows. */
  174513. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174514. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174515. dataptr = data;
  174516. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174517. tmp0 = dataptr[0] + dataptr[7];
  174518. tmp7 = dataptr[0] - dataptr[7];
  174519. tmp1 = dataptr[1] + dataptr[6];
  174520. tmp6 = dataptr[1] - dataptr[6];
  174521. tmp2 = dataptr[2] + dataptr[5];
  174522. tmp5 = dataptr[2] - dataptr[5];
  174523. tmp3 = dataptr[3] + dataptr[4];
  174524. tmp4 = dataptr[3] - dataptr[4];
  174525. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174526. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174527. */
  174528. tmp10 = tmp0 + tmp3;
  174529. tmp13 = tmp0 - tmp3;
  174530. tmp11 = tmp1 + tmp2;
  174531. tmp12 = tmp1 - tmp2;
  174532. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174533. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174534. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174535. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174536. CONST_BITS-PASS1_BITS);
  174537. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174538. CONST_BITS-PASS1_BITS);
  174539. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174540. * cK represents cos(K*pi/16).
  174541. * i0..i3 in the paper are tmp4..tmp7 here.
  174542. */
  174543. z1 = tmp4 + tmp7;
  174544. z2 = tmp5 + tmp6;
  174545. z3 = tmp4 + tmp6;
  174546. z4 = tmp5 + tmp7;
  174547. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174548. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174549. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174550. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174551. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174552. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174553. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174554. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174555. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174556. z3 += z5;
  174557. z4 += z5;
  174558. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174559. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174560. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174561. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174562. dataptr += DCTSIZE; /* advance pointer to next row */
  174563. }
  174564. /* Pass 2: process columns.
  174565. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174566. * by an overall factor of 8.
  174567. */
  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 per LL&M figure 1 --- note that published figure is faulty;
  174579. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174580. */
  174581. tmp10 = tmp0 + tmp3;
  174582. tmp13 = tmp0 - tmp3;
  174583. tmp11 = tmp1 + tmp2;
  174584. tmp12 = tmp1 - tmp2;
  174585. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174586. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174587. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174588. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174589. CONST_BITS+PASS1_BITS);
  174590. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174591. CONST_BITS+PASS1_BITS);
  174592. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174593. * cK represents cos(K*pi/16).
  174594. * i0..i3 in the paper are tmp4..tmp7 here.
  174595. */
  174596. z1 = tmp4 + tmp7;
  174597. z2 = tmp5 + tmp6;
  174598. z3 = tmp4 + tmp6;
  174599. z4 = tmp5 + tmp7;
  174600. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174601. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174602. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174603. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174604. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174605. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174606. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174607. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174608. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174609. z3 += z5;
  174610. z4 += z5;
  174611. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174612. CONST_BITS+PASS1_BITS);
  174613. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174614. CONST_BITS+PASS1_BITS);
  174615. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174616. CONST_BITS+PASS1_BITS);
  174617. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174618. CONST_BITS+PASS1_BITS);
  174619. dataptr++; /* advance pointer to next column */
  174620. }
  174621. }
  174622. #endif /* DCT_ISLOW_SUPPORTED */
  174623. /*** End of inlined file: jfdctint.c ***/
  174624. #undef CONST_BITS
  174625. #undef MULTIPLY
  174626. #undef FIX_0_541196100
  174627. /*** Start of inlined file: jfdctfst.c ***/
  174628. #define JPEG_INTERNALS
  174629. #ifdef DCT_IFAST_SUPPORTED
  174630. /*
  174631. * This module is specialized to the case DCTSIZE = 8.
  174632. */
  174633. #if DCTSIZE != 8
  174634. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174635. #endif
  174636. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174637. * see jfdctint.c for more details. However, we choose to descale
  174638. * (right shift) multiplication products as soon as they are formed,
  174639. * rather than carrying additional fractional bits into subsequent additions.
  174640. * This compromises accuracy slightly, but it lets us save a few shifts.
  174641. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174642. * everywhere except in the multiplications proper; this saves a good deal
  174643. * of work on 16-bit-int machines.
  174644. *
  174645. * Again to save a few shifts, the intermediate results between pass 1 and
  174646. * pass 2 are not upscaled, but are represented only to integral precision.
  174647. *
  174648. * A final compromise is to represent the multiplicative constants to only
  174649. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174650. * machines, and may also reduce the cost of multiplication (since there
  174651. * are fewer one-bits in the constants).
  174652. */
  174653. #define CONST_BITS 8
  174654. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174655. * causing a lot of useless floating-point operations at run time.
  174656. * To get around this we use the following pre-calculated constants.
  174657. * If you change CONST_BITS you may want to add appropriate values.
  174658. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174659. */
  174660. #if CONST_BITS == 8
  174661. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174662. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174663. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174664. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174665. #else
  174666. #define FIX_0_382683433 FIX(0.382683433)
  174667. #define FIX_0_541196100 FIX(0.541196100)
  174668. #define FIX_0_707106781 FIX(0.707106781)
  174669. #define FIX_1_306562965 FIX(1.306562965)
  174670. #endif
  174671. /* We can gain a little more speed, with a further compromise in accuracy,
  174672. * by omitting the addition in a descaling shift. This yields an incorrectly
  174673. * rounded result half the time...
  174674. */
  174675. #ifndef USE_ACCURATE_ROUNDING
  174676. #undef DESCALE
  174677. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174678. #endif
  174679. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174680. * descale to yield a DCTELEM result.
  174681. */
  174682. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174683. /*
  174684. * Perform the forward DCT on one block of samples.
  174685. */
  174686. GLOBAL(void)
  174687. jpeg_fdct_ifast (DCTELEM * data)
  174688. {
  174689. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174690. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174691. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174692. DCTELEM *dataptr;
  174693. int ctr;
  174694. SHIFT_TEMPS
  174695. /* Pass 1: process rows. */
  174696. dataptr = data;
  174697. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174698. tmp0 = dataptr[0] + dataptr[7];
  174699. tmp7 = dataptr[0] - dataptr[7];
  174700. tmp1 = dataptr[1] + dataptr[6];
  174701. tmp6 = dataptr[1] - dataptr[6];
  174702. tmp2 = dataptr[2] + dataptr[5];
  174703. tmp5 = dataptr[2] - dataptr[5];
  174704. tmp3 = dataptr[3] + dataptr[4];
  174705. tmp4 = dataptr[3] - dataptr[4];
  174706. /* Even part */
  174707. tmp10 = tmp0 + tmp3; /* phase 2 */
  174708. tmp13 = tmp0 - tmp3;
  174709. tmp11 = tmp1 + tmp2;
  174710. tmp12 = tmp1 - tmp2;
  174711. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174712. dataptr[4] = tmp10 - tmp11;
  174713. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174714. dataptr[2] = tmp13 + z1; /* phase 5 */
  174715. dataptr[6] = tmp13 - z1;
  174716. /* Odd part */
  174717. tmp10 = tmp4 + tmp5; /* phase 2 */
  174718. tmp11 = tmp5 + tmp6;
  174719. tmp12 = tmp6 + tmp7;
  174720. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174721. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174722. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174723. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174724. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174725. z11 = tmp7 + z3; /* phase 5 */
  174726. z13 = tmp7 - z3;
  174727. dataptr[5] = z13 + z2; /* phase 6 */
  174728. dataptr[3] = z13 - z2;
  174729. dataptr[1] = z11 + z4;
  174730. dataptr[7] = z11 - z4;
  174731. dataptr += DCTSIZE; /* advance pointer to next row */
  174732. }
  174733. /* Pass 2: process columns. */
  174734. dataptr = data;
  174735. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174736. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174737. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174738. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174739. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174740. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174741. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174742. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174743. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174744. /* Even part */
  174745. tmp10 = tmp0 + tmp3; /* phase 2 */
  174746. tmp13 = tmp0 - tmp3;
  174747. tmp11 = tmp1 + tmp2;
  174748. tmp12 = tmp1 - tmp2;
  174749. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174750. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174751. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174752. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174753. dataptr[DCTSIZE*6] = tmp13 - z1;
  174754. /* Odd part */
  174755. tmp10 = tmp4 + tmp5; /* phase 2 */
  174756. tmp11 = tmp5 + tmp6;
  174757. tmp12 = tmp6 + tmp7;
  174758. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174759. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174760. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174761. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174762. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174763. z11 = tmp7 + z3; /* phase 5 */
  174764. z13 = tmp7 - z3;
  174765. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174766. dataptr[DCTSIZE*3] = z13 - z2;
  174767. dataptr[DCTSIZE*1] = z11 + z4;
  174768. dataptr[DCTSIZE*7] = z11 - z4;
  174769. dataptr++; /* advance pointer to next column */
  174770. }
  174771. }
  174772. #endif /* DCT_IFAST_SUPPORTED */
  174773. /*** End of inlined file: jfdctfst.c ***/
  174774. #undef FIX_0_541196100
  174775. /*** Start of inlined file: jidctflt.c ***/
  174776. #define JPEG_INTERNALS
  174777. #ifdef DCT_FLOAT_SUPPORTED
  174778. /*
  174779. * This module is specialized to the case DCTSIZE = 8.
  174780. */
  174781. #if DCTSIZE != 8
  174782. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174783. #endif
  174784. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174785. * entry; produce a float result.
  174786. */
  174787. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174788. /*
  174789. * Perform dequantization and inverse DCT on one block of coefficients.
  174790. */
  174791. GLOBAL(void)
  174792. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174793. JCOEFPTR coef_block,
  174794. JSAMPARRAY output_buf, JDIMENSION output_col)
  174795. {
  174796. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174797. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174798. FAST_FLOAT z5, z10, z11, z12, z13;
  174799. JCOEFPTR inptr;
  174800. FLOAT_MULT_TYPE * quantptr;
  174801. FAST_FLOAT * wsptr;
  174802. JSAMPROW outptr;
  174803. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174804. int ctr;
  174805. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174806. SHIFT_TEMPS
  174807. /* Pass 1: process columns from input, store into work array. */
  174808. inptr = coef_block;
  174809. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174810. wsptr = workspace;
  174811. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174812. /* Due to quantization, we will usually find that many of the input
  174813. * coefficients are zero, especially the AC terms. We can exploit this
  174814. * by short-circuiting the IDCT calculation for any column in which all
  174815. * the AC terms are zero. In that case each output is equal to the
  174816. * DC coefficient (with scale factor as needed).
  174817. * With typical images and quantization tables, half or more of the
  174818. * column DCT calculations can be simplified this way.
  174819. */
  174820. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174821. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174822. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174823. inptr[DCTSIZE*7] == 0) {
  174824. /* AC terms all zero */
  174825. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174826. wsptr[DCTSIZE*0] = dcval;
  174827. wsptr[DCTSIZE*1] = dcval;
  174828. wsptr[DCTSIZE*2] = dcval;
  174829. wsptr[DCTSIZE*3] = dcval;
  174830. wsptr[DCTSIZE*4] = dcval;
  174831. wsptr[DCTSIZE*5] = dcval;
  174832. wsptr[DCTSIZE*6] = dcval;
  174833. wsptr[DCTSIZE*7] = dcval;
  174834. inptr++; /* advance pointers to next column */
  174835. quantptr++;
  174836. wsptr++;
  174837. continue;
  174838. }
  174839. /* Even part */
  174840. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174841. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174842. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174843. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174844. tmp10 = tmp0 + tmp2; /* phase 3 */
  174845. tmp11 = tmp0 - tmp2;
  174846. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174847. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174848. tmp0 = tmp10 + tmp13; /* phase 2 */
  174849. tmp3 = tmp10 - tmp13;
  174850. tmp1 = tmp11 + tmp12;
  174851. tmp2 = tmp11 - tmp12;
  174852. /* Odd part */
  174853. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174854. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174855. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174856. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174857. z13 = tmp6 + tmp5; /* phase 6 */
  174858. z10 = tmp6 - tmp5;
  174859. z11 = tmp4 + tmp7;
  174860. z12 = tmp4 - tmp7;
  174861. tmp7 = z11 + z13; /* phase 5 */
  174862. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174863. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174864. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174865. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174866. tmp6 = tmp12 - tmp7; /* phase 2 */
  174867. tmp5 = tmp11 - tmp6;
  174868. tmp4 = tmp10 + tmp5;
  174869. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174870. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174871. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174872. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174873. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174874. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174875. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174876. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174877. inptr++; /* advance pointers to next column */
  174878. quantptr++;
  174879. wsptr++;
  174880. }
  174881. /* Pass 2: process rows from work array, store into output array. */
  174882. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174883. wsptr = workspace;
  174884. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174885. outptr = output_buf[ctr] + output_col;
  174886. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174887. * However, the column calculation has created many nonzero AC terms, so
  174888. * the simplification applies less often (typically 5% to 10% of the time).
  174889. * And testing floats for zero is relatively expensive, so we don't bother.
  174890. */
  174891. /* Even part */
  174892. tmp10 = wsptr[0] + wsptr[4];
  174893. tmp11 = wsptr[0] - wsptr[4];
  174894. tmp13 = wsptr[2] + wsptr[6];
  174895. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174896. tmp0 = tmp10 + tmp13;
  174897. tmp3 = tmp10 - tmp13;
  174898. tmp1 = tmp11 + tmp12;
  174899. tmp2 = tmp11 - tmp12;
  174900. /* Odd part */
  174901. z13 = wsptr[5] + wsptr[3];
  174902. z10 = wsptr[5] - wsptr[3];
  174903. z11 = wsptr[1] + wsptr[7];
  174904. z12 = wsptr[1] - wsptr[7];
  174905. tmp7 = z11 + z13;
  174906. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174907. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174908. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174909. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174910. tmp6 = tmp12 - tmp7;
  174911. tmp5 = tmp11 - tmp6;
  174912. tmp4 = tmp10 + tmp5;
  174913. /* Final output stage: scale down by a factor of 8 and range-limit */
  174914. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174915. & RANGE_MASK];
  174916. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174917. & RANGE_MASK];
  174918. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174919. & RANGE_MASK];
  174920. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174921. & RANGE_MASK];
  174922. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174923. & RANGE_MASK];
  174924. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174925. & RANGE_MASK];
  174926. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174927. & RANGE_MASK];
  174928. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174929. & RANGE_MASK];
  174930. wsptr += DCTSIZE; /* advance pointer to next row */
  174931. }
  174932. }
  174933. #endif /* DCT_FLOAT_SUPPORTED */
  174934. /*** End of inlined file: jidctflt.c ***/
  174935. #undef CONST_BITS
  174936. #undef FIX_1_847759065
  174937. #undef MULTIPLY
  174938. #undef DEQUANTIZE
  174939. #undef DESCALE
  174940. /*** Start of inlined file: jidctfst.c ***/
  174941. #define JPEG_INTERNALS
  174942. #ifdef DCT_IFAST_SUPPORTED
  174943. /*
  174944. * This module is specialized to the case DCTSIZE = 8.
  174945. */
  174946. #if DCTSIZE != 8
  174947. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174948. #endif
  174949. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174950. * see jidctint.c for more details. However, we choose to descale
  174951. * (right shift) multiplication products as soon as they are formed,
  174952. * rather than carrying additional fractional bits into subsequent additions.
  174953. * This compromises accuracy slightly, but it lets us save a few shifts.
  174954. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174955. * everywhere except in the multiplications proper; this saves a good deal
  174956. * of work on 16-bit-int machines.
  174957. *
  174958. * The dequantized coefficients are not integers because the AA&N scaling
  174959. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174960. * so that the first and second IDCT rounds have the same input scaling.
  174961. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174962. * avoid a descaling shift; this compromises accuracy rather drastically
  174963. * for small quantization table entries, but it saves a lot of shifts.
  174964. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174965. * so we use a much larger scaling factor to preserve accuracy.
  174966. *
  174967. * A final compromise is to represent the multiplicative constants to only
  174968. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174969. * machines, and may also reduce the cost of multiplication (since there
  174970. * are fewer one-bits in the constants).
  174971. */
  174972. #if BITS_IN_JSAMPLE == 8
  174973. #define CONST_BITS 8
  174974. #define PASS1_BITS 2
  174975. #else
  174976. #define CONST_BITS 8
  174977. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174978. #endif
  174979. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174980. * causing a lot of useless floating-point operations at run time.
  174981. * To get around this we use the following pre-calculated constants.
  174982. * If you change CONST_BITS you may want to add appropriate values.
  174983. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174984. */
  174985. #if CONST_BITS == 8
  174986. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174987. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174988. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174989. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174990. #else
  174991. #define FIX_1_082392200 FIX(1.082392200)
  174992. #define FIX_1_414213562 FIX(1.414213562)
  174993. #define FIX_1_847759065 FIX(1.847759065)
  174994. #define FIX_2_613125930 FIX(2.613125930)
  174995. #endif
  174996. /* We can gain a little more speed, with a further compromise in accuracy,
  174997. * by omitting the addition in a descaling shift. This yields an incorrectly
  174998. * rounded result half the time...
  174999. */
  175000. #ifndef USE_ACCURATE_ROUNDING
  175001. #undef DESCALE
  175002. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175003. #endif
  175004. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175005. * descale to yield a DCTELEM result.
  175006. */
  175007. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175008. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175009. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175010. * multiplication will do. For 12-bit data, the multiplier table is
  175011. * declared INT32, so a 32-bit multiply will be used.
  175012. */
  175013. #if BITS_IN_JSAMPLE == 8
  175014. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175015. #else
  175016. #define DEQUANTIZE(coef,quantval) \
  175017. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175018. #endif
  175019. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175020. * We assume that int right shift is unsigned if INT32 right shift is.
  175021. */
  175022. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175023. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175024. #if BITS_IN_JSAMPLE == 8
  175025. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175026. #else
  175027. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175028. #endif
  175029. #define IRIGHT_SHIFT(x,shft) \
  175030. ((ishift_temp = (x)) < 0 ? \
  175031. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175032. (ishift_temp >> (shft)))
  175033. #else
  175034. #define ISHIFT_TEMPS
  175035. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175036. #endif
  175037. #ifdef USE_ACCURATE_ROUNDING
  175038. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175039. #else
  175040. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175041. #endif
  175042. /*
  175043. * Perform dequantization and inverse DCT on one block of coefficients.
  175044. */
  175045. GLOBAL(void)
  175046. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175047. JCOEFPTR coef_block,
  175048. JSAMPARRAY output_buf, JDIMENSION output_col)
  175049. {
  175050. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175051. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175052. DCTELEM z5, z10, z11, z12, z13;
  175053. JCOEFPTR inptr;
  175054. IFAST_MULT_TYPE * quantptr;
  175055. int * wsptr;
  175056. JSAMPROW outptr;
  175057. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175058. int ctr;
  175059. int workspace[DCTSIZE2]; /* buffers data between passes */
  175060. SHIFT_TEMPS /* for DESCALE */
  175061. ISHIFT_TEMPS /* for IDESCALE */
  175062. /* Pass 1: process columns from input, store into work array. */
  175063. inptr = coef_block;
  175064. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175065. wsptr = workspace;
  175066. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175067. /* Due to quantization, we will usually find that many of the input
  175068. * coefficients are zero, especially the AC terms. We can exploit this
  175069. * by short-circuiting the IDCT calculation for any column in which all
  175070. * the AC terms are zero. In that case each output is equal to the
  175071. * DC coefficient (with scale factor as needed).
  175072. * With typical images and quantization tables, half or more of the
  175073. * column DCT calculations can be simplified this way.
  175074. */
  175075. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175076. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175077. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175078. inptr[DCTSIZE*7] == 0) {
  175079. /* AC terms all zero */
  175080. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175081. wsptr[DCTSIZE*0] = dcval;
  175082. wsptr[DCTSIZE*1] = dcval;
  175083. wsptr[DCTSIZE*2] = dcval;
  175084. wsptr[DCTSIZE*3] = dcval;
  175085. wsptr[DCTSIZE*4] = dcval;
  175086. wsptr[DCTSIZE*5] = dcval;
  175087. wsptr[DCTSIZE*6] = dcval;
  175088. wsptr[DCTSIZE*7] = dcval;
  175089. inptr++; /* advance pointers to next column */
  175090. quantptr++;
  175091. wsptr++;
  175092. continue;
  175093. }
  175094. /* Even part */
  175095. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175096. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175097. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175098. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175099. tmp10 = tmp0 + tmp2; /* phase 3 */
  175100. tmp11 = tmp0 - tmp2;
  175101. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175102. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175103. tmp0 = tmp10 + tmp13; /* phase 2 */
  175104. tmp3 = tmp10 - tmp13;
  175105. tmp1 = tmp11 + tmp12;
  175106. tmp2 = tmp11 - tmp12;
  175107. /* Odd part */
  175108. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175109. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175110. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175111. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175112. z13 = tmp6 + tmp5; /* phase 6 */
  175113. z10 = tmp6 - tmp5;
  175114. z11 = tmp4 + tmp7;
  175115. z12 = tmp4 - tmp7;
  175116. tmp7 = z11 + z13; /* phase 5 */
  175117. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175118. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175119. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175120. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175121. tmp6 = tmp12 - tmp7; /* phase 2 */
  175122. tmp5 = tmp11 - tmp6;
  175123. tmp4 = tmp10 + tmp5;
  175124. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175125. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175126. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175127. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175128. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175129. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175130. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175131. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175132. inptr++; /* advance pointers to next column */
  175133. quantptr++;
  175134. wsptr++;
  175135. }
  175136. /* Pass 2: process rows from work array, store into output array. */
  175137. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175138. /* and also undo the PASS1_BITS scaling. */
  175139. wsptr = workspace;
  175140. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175141. outptr = output_buf[ctr] + output_col;
  175142. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175143. * However, the column calculation has created many nonzero AC terms, so
  175144. * the simplification applies less often (typically 5% to 10% of the time).
  175145. * On machines with very fast multiplication, it's possible that the
  175146. * test takes more time than it's worth. In that case this section
  175147. * may be commented out.
  175148. */
  175149. #ifndef NO_ZERO_ROW_TEST
  175150. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175151. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175152. /* AC terms all zero */
  175153. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175154. & RANGE_MASK];
  175155. outptr[0] = dcval;
  175156. outptr[1] = dcval;
  175157. outptr[2] = dcval;
  175158. outptr[3] = dcval;
  175159. outptr[4] = dcval;
  175160. outptr[5] = dcval;
  175161. outptr[6] = dcval;
  175162. outptr[7] = dcval;
  175163. wsptr += DCTSIZE; /* advance pointer to next row */
  175164. continue;
  175165. }
  175166. #endif
  175167. /* Even part */
  175168. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175169. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175170. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175171. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175172. - tmp13;
  175173. tmp0 = tmp10 + tmp13;
  175174. tmp3 = tmp10 - tmp13;
  175175. tmp1 = tmp11 + tmp12;
  175176. tmp2 = tmp11 - tmp12;
  175177. /* Odd part */
  175178. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175179. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175180. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175181. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175182. tmp7 = z11 + z13; /* phase 5 */
  175183. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175184. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175185. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175186. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175187. tmp6 = tmp12 - tmp7; /* phase 2 */
  175188. tmp5 = tmp11 - tmp6;
  175189. tmp4 = tmp10 + tmp5;
  175190. /* Final output stage: scale down by a factor of 8 and range-limit */
  175191. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175192. & RANGE_MASK];
  175193. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175194. & RANGE_MASK];
  175195. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175196. & RANGE_MASK];
  175197. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175198. & RANGE_MASK];
  175199. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175200. & RANGE_MASK];
  175201. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175202. & RANGE_MASK];
  175203. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175204. & RANGE_MASK];
  175205. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175206. & RANGE_MASK];
  175207. wsptr += DCTSIZE; /* advance pointer to next row */
  175208. }
  175209. }
  175210. #endif /* DCT_IFAST_SUPPORTED */
  175211. /*** End of inlined file: jidctfst.c ***/
  175212. #undef CONST_BITS
  175213. #undef FIX_1_847759065
  175214. #undef MULTIPLY
  175215. #undef DEQUANTIZE
  175216. /*** Start of inlined file: jidctint.c ***/
  175217. #define JPEG_INTERNALS
  175218. #ifdef DCT_ISLOW_SUPPORTED
  175219. /*
  175220. * This module is specialized to the case DCTSIZE = 8.
  175221. */
  175222. #if DCTSIZE != 8
  175223. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175224. #endif
  175225. /*
  175226. * The poop on this scaling stuff is as follows:
  175227. *
  175228. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175229. * larger than the true IDCT outputs. The final outputs are therefore
  175230. * a factor of N larger than desired; since N=8 this can be cured by
  175231. * a simple right shift at the end of the algorithm. The advantage of
  175232. * this arrangement is that we save two multiplications per 1-D IDCT,
  175233. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175234. *
  175235. * We have to do addition and subtraction of the integer inputs, which
  175236. * is no problem, and multiplication by fractional constants, which is
  175237. * a problem to do in integer arithmetic. We multiply all the constants
  175238. * by CONST_SCALE and convert them to integer constants (thus retaining
  175239. * CONST_BITS bits of precision in the constants). After doing a
  175240. * multiplication we have to divide the product by CONST_SCALE, with proper
  175241. * rounding, to produce the correct output. This division can be done
  175242. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175243. * as long as possible so that partial sums can be added together with
  175244. * full fractional precision.
  175245. *
  175246. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175247. * they are represented to better-than-integral precision. These outputs
  175248. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175249. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175250. * intermediate INT32 array would be needed.)
  175251. *
  175252. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175253. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175254. * shows that the values given below are the most effective.
  175255. */
  175256. #if BITS_IN_JSAMPLE == 8
  175257. #define CONST_BITS 13
  175258. #define PASS1_BITS 2
  175259. #else
  175260. #define CONST_BITS 13
  175261. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175262. #endif
  175263. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175264. * causing a lot of useless floating-point operations at run time.
  175265. * To get around this we use the following pre-calculated constants.
  175266. * If you change CONST_BITS you may want to add appropriate values.
  175267. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175268. */
  175269. #if CONST_BITS == 13
  175270. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175271. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175272. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175273. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175274. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175275. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175276. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175277. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175278. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175279. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175280. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175281. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175282. #else
  175283. #define FIX_0_298631336 FIX(0.298631336)
  175284. #define FIX_0_390180644 FIX(0.390180644)
  175285. #define FIX_0_541196100 FIX(0.541196100)
  175286. #define FIX_0_765366865 FIX(0.765366865)
  175287. #define FIX_0_899976223 FIX(0.899976223)
  175288. #define FIX_1_175875602 FIX(1.175875602)
  175289. #define FIX_1_501321110 FIX(1.501321110)
  175290. #define FIX_1_847759065 FIX(1.847759065)
  175291. #define FIX_1_961570560 FIX(1.961570560)
  175292. #define FIX_2_053119869 FIX(2.053119869)
  175293. #define FIX_2_562915447 FIX(2.562915447)
  175294. #define FIX_3_072711026 FIX(3.072711026)
  175295. #endif
  175296. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175297. * For 8-bit samples with the recommended scaling, all the variable
  175298. * and constant values involved are no more than 16 bits wide, so a
  175299. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175300. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175301. */
  175302. #if BITS_IN_JSAMPLE == 8
  175303. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175304. #else
  175305. #define MULTIPLY(var,const) ((var) * (const))
  175306. #endif
  175307. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175308. * entry; produce an int result. In this module, both inputs and result
  175309. * are 16 bits or less, so either int or short multiply will work.
  175310. */
  175311. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175312. /*
  175313. * Perform dequantization and inverse DCT on one block of coefficients.
  175314. */
  175315. GLOBAL(void)
  175316. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175317. JCOEFPTR coef_block,
  175318. JSAMPARRAY output_buf, JDIMENSION output_col)
  175319. {
  175320. INT32 tmp0, tmp1, tmp2, tmp3;
  175321. INT32 tmp10, tmp11, tmp12, tmp13;
  175322. INT32 z1, z2, z3, z4, z5;
  175323. JCOEFPTR inptr;
  175324. ISLOW_MULT_TYPE * quantptr;
  175325. int * wsptr;
  175326. JSAMPROW outptr;
  175327. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175328. int ctr;
  175329. int workspace[DCTSIZE2]; /* buffers data between passes */
  175330. SHIFT_TEMPS
  175331. /* Pass 1: process columns from input, store into work array. */
  175332. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175333. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175334. inptr = coef_block;
  175335. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175336. wsptr = workspace;
  175337. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175338. /* Due to quantization, we will usually find that many of the input
  175339. * coefficients are zero, especially the AC terms. We can exploit this
  175340. * by short-circuiting the IDCT calculation for any column in which all
  175341. * the AC terms are zero. In that case each output is equal to the
  175342. * DC coefficient (with scale factor as needed).
  175343. * With typical images and quantization tables, half or more of the
  175344. * column DCT calculations can be simplified this way.
  175345. */
  175346. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175347. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175348. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175349. inptr[DCTSIZE*7] == 0) {
  175350. /* AC terms all zero */
  175351. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175352. wsptr[DCTSIZE*0] = dcval;
  175353. wsptr[DCTSIZE*1] = dcval;
  175354. wsptr[DCTSIZE*2] = dcval;
  175355. wsptr[DCTSIZE*3] = dcval;
  175356. wsptr[DCTSIZE*4] = dcval;
  175357. wsptr[DCTSIZE*5] = dcval;
  175358. wsptr[DCTSIZE*6] = dcval;
  175359. wsptr[DCTSIZE*7] = dcval;
  175360. inptr++; /* advance pointers to next column */
  175361. quantptr++;
  175362. wsptr++;
  175363. continue;
  175364. }
  175365. /* Even part: reverse the even part of the forward DCT. */
  175366. /* The rotator is sqrt(2)*c(-6). */
  175367. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175368. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175369. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175370. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175371. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175372. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175373. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175374. tmp0 = (z2 + z3) << CONST_BITS;
  175375. tmp1 = (z2 - z3) << CONST_BITS;
  175376. tmp10 = tmp0 + tmp3;
  175377. tmp13 = tmp0 - tmp3;
  175378. tmp11 = tmp1 + tmp2;
  175379. tmp12 = tmp1 - tmp2;
  175380. /* Odd part per figure 8; the matrix is unitary and hence its
  175381. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175382. */
  175383. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175384. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175385. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175386. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175387. z1 = tmp0 + tmp3;
  175388. z2 = tmp1 + tmp2;
  175389. z3 = tmp0 + tmp2;
  175390. z4 = tmp1 + tmp3;
  175391. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175392. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175393. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175394. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175395. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175396. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175397. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175398. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175399. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175400. z3 += z5;
  175401. z4 += z5;
  175402. tmp0 += z1 + z3;
  175403. tmp1 += z2 + z4;
  175404. tmp2 += z2 + z3;
  175405. tmp3 += z1 + z4;
  175406. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175407. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175408. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175409. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175410. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175411. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175412. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175413. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175414. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175415. inptr++; /* advance pointers to next column */
  175416. quantptr++;
  175417. wsptr++;
  175418. }
  175419. /* Pass 2: process rows from work array, store into output array. */
  175420. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175421. /* and also undo the PASS1_BITS scaling. */
  175422. wsptr = workspace;
  175423. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175424. outptr = output_buf[ctr] + output_col;
  175425. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175426. * However, the column calculation has created many nonzero AC terms, so
  175427. * the simplification applies less often (typically 5% to 10% of the time).
  175428. * On machines with very fast multiplication, it's possible that the
  175429. * test takes more time than it's worth. In that case this section
  175430. * may be commented out.
  175431. */
  175432. #ifndef NO_ZERO_ROW_TEST
  175433. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175434. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175435. /* AC terms all zero */
  175436. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175437. & RANGE_MASK];
  175438. outptr[0] = dcval;
  175439. outptr[1] = dcval;
  175440. outptr[2] = dcval;
  175441. outptr[3] = dcval;
  175442. outptr[4] = dcval;
  175443. outptr[5] = dcval;
  175444. outptr[6] = dcval;
  175445. outptr[7] = dcval;
  175446. wsptr += DCTSIZE; /* advance pointer to next row */
  175447. continue;
  175448. }
  175449. #endif
  175450. /* Even part: reverse the even part of the forward DCT. */
  175451. /* The rotator is sqrt(2)*c(-6). */
  175452. z2 = (INT32) wsptr[2];
  175453. z3 = (INT32) wsptr[6];
  175454. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175455. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175456. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175457. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175458. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175459. tmp10 = tmp0 + tmp3;
  175460. tmp13 = tmp0 - tmp3;
  175461. tmp11 = tmp1 + tmp2;
  175462. tmp12 = tmp1 - tmp2;
  175463. /* Odd part per figure 8; the matrix is unitary and hence its
  175464. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175465. */
  175466. tmp0 = (INT32) wsptr[7];
  175467. tmp1 = (INT32) wsptr[5];
  175468. tmp2 = (INT32) wsptr[3];
  175469. tmp3 = (INT32) wsptr[1];
  175470. z1 = tmp0 + tmp3;
  175471. z2 = tmp1 + tmp2;
  175472. z3 = tmp0 + tmp2;
  175473. z4 = tmp1 + tmp3;
  175474. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175475. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175476. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175477. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175478. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175479. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175480. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175481. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175482. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175483. z3 += z5;
  175484. z4 += z5;
  175485. tmp0 += z1 + z3;
  175486. tmp1 += z2 + z4;
  175487. tmp2 += z2 + z3;
  175488. tmp3 += z1 + z4;
  175489. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175490. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175491. CONST_BITS+PASS1_BITS+3)
  175492. & RANGE_MASK];
  175493. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175494. CONST_BITS+PASS1_BITS+3)
  175495. & RANGE_MASK];
  175496. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175497. CONST_BITS+PASS1_BITS+3)
  175498. & RANGE_MASK];
  175499. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175500. CONST_BITS+PASS1_BITS+3)
  175501. & RANGE_MASK];
  175502. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175503. CONST_BITS+PASS1_BITS+3)
  175504. & RANGE_MASK];
  175505. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175506. CONST_BITS+PASS1_BITS+3)
  175507. & RANGE_MASK];
  175508. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175509. CONST_BITS+PASS1_BITS+3)
  175510. & RANGE_MASK];
  175511. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175512. CONST_BITS+PASS1_BITS+3)
  175513. & RANGE_MASK];
  175514. wsptr += DCTSIZE; /* advance pointer to next row */
  175515. }
  175516. }
  175517. #endif /* DCT_ISLOW_SUPPORTED */
  175518. /*** End of inlined file: jidctint.c ***/
  175519. /*** Start of inlined file: jidctred.c ***/
  175520. #define JPEG_INTERNALS
  175521. #ifdef IDCT_SCALING_SUPPORTED
  175522. /*
  175523. * This module is specialized to the case DCTSIZE = 8.
  175524. */
  175525. #if DCTSIZE != 8
  175526. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175527. #endif
  175528. /* Scaling is the same as in jidctint.c. */
  175529. #if BITS_IN_JSAMPLE == 8
  175530. #define CONST_BITS 13
  175531. #define PASS1_BITS 2
  175532. #else
  175533. #define CONST_BITS 13
  175534. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175535. #endif
  175536. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175537. * causing a lot of useless floating-point operations at run time.
  175538. * To get around this we use the following pre-calculated constants.
  175539. * If you change CONST_BITS you may want to add appropriate values.
  175540. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175541. */
  175542. #if CONST_BITS == 13
  175543. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175544. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175545. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175546. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175547. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175548. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175549. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175550. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175551. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175552. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175553. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175554. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175555. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175556. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175557. #else
  175558. #define FIX_0_211164243 FIX(0.211164243)
  175559. #define FIX_0_509795579 FIX(0.509795579)
  175560. #define FIX_0_601344887 FIX(0.601344887)
  175561. #define FIX_0_720959822 FIX(0.720959822)
  175562. #define FIX_0_765366865 FIX(0.765366865)
  175563. #define FIX_0_850430095 FIX(0.850430095)
  175564. #define FIX_0_899976223 FIX(0.899976223)
  175565. #define FIX_1_061594337 FIX(1.061594337)
  175566. #define FIX_1_272758580 FIX(1.272758580)
  175567. #define FIX_1_451774981 FIX(1.451774981)
  175568. #define FIX_1_847759065 FIX(1.847759065)
  175569. #define FIX_2_172734803 FIX(2.172734803)
  175570. #define FIX_2_562915447 FIX(2.562915447)
  175571. #define FIX_3_624509785 FIX(3.624509785)
  175572. #endif
  175573. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175574. * For 8-bit samples with the recommended scaling, all the variable
  175575. * and constant values involved are no more than 16 bits wide, so a
  175576. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175577. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175578. */
  175579. #if BITS_IN_JSAMPLE == 8
  175580. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175581. #else
  175582. #define MULTIPLY(var,const) ((var) * (const))
  175583. #endif
  175584. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175585. * entry; produce an int result. In this module, both inputs and result
  175586. * are 16 bits or less, so either int or short multiply will work.
  175587. */
  175588. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175589. /*
  175590. * Perform dequantization and inverse DCT on one block of coefficients,
  175591. * producing a reduced-size 4x4 output block.
  175592. */
  175593. GLOBAL(void)
  175594. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175595. JCOEFPTR coef_block,
  175596. JSAMPARRAY output_buf, JDIMENSION output_col)
  175597. {
  175598. INT32 tmp0, tmp2, tmp10, tmp12;
  175599. INT32 z1, z2, z3, z4;
  175600. JCOEFPTR inptr;
  175601. ISLOW_MULT_TYPE * quantptr;
  175602. int * wsptr;
  175603. JSAMPROW outptr;
  175604. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175605. int ctr;
  175606. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175607. SHIFT_TEMPS
  175608. /* Pass 1: process columns from input, store into work array. */
  175609. inptr = coef_block;
  175610. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175611. wsptr = workspace;
  175612. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175613. /* Don't bother to process column 4, because second pass won't use it */
  175614. if (ctr == DCTSIZE-4)
  175615. continue;
  175616. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175617. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175618. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175619. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175620. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175621. wsptr[DCTSIZE*0] = dcval;
  175622. wsptr[DCTSIZE*1] = dcval;
  175623. wsptr[DCTSIZE*2] = dcval;
  175624. wsptr[DCTSIZE*3] = dcval;
  175625. continue;
  175626. }
  175627. /* Even part */
  175628. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175629. tmp0 <<= (CONST_BITS+1);
  175630. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175631. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175632. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175633. tmp10 = tmp0 + tmp2;
  175634. tmp12 = tmp0 - tmp2;
  175635. /* Odd part */
  175636. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175637. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175638. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175639. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175640. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175641. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175642. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175643. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175644. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175645. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175646. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175647. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175648. /* Final output stage */
  175649. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175650. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175651. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175652. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175653. }
  175654. /* Pass 2: process 4 rows from work array, store into output array. */
  175655. wsptr = workspace;
  175656. for (ctr = 0; ctr < 4; ctr++) {
  175657. outptr = output_buf[ctr] + output_col;
  175658. /* It's not clear whether a zero row test is worthwhile here ... */
  175659. #ifndef NO_ZERO_ROW_TEST
  175660. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175661. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175662. /* AC terms all zero */
  175663. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175664. & RANGE_MASK];
  175665. outptr[0] = dcval;
  175666. outptr[1] = dcval;
  175667. outptr[2] = dcval;
  175668. outptr[3] = dcval;
  175669. wsptr += DCTSIZE; /* advance pointer to next row */
  175670. continue;
  175671. }
  175672. #endif
  175673. /* Even part */
  175674. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175675. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175676. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175677. tmp10 = tmp0 + tmp2;
  175678. tmp12 = tmp0 - tmp2;
  175679. /* Odd part */
  175680. z1 = (INT32) wsptr[7];
  175681. z2 = (INT32) wsptr[5];
  175682. z3 = (INT32) wsptr[3];
  175683. z4 = (INT32) wsptr[1];
  175684. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175685. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175686. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175687. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175688. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175689. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175690. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175691. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175692. /* Final output stage */
  175693. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175694. CONST_BITS+PASS1_BITS+3+1)
  175695. & RANGE_MASK];
  175696. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175697. CONST_BITS+PASS1_BITS+3+1)
  175698. & RANGE_MASK];
  175699. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175700. CONST_BITS+PASS1_BITS+3+1)
  175701. & RANGE_MASK];
  175702. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175703. CONST_BITS+PASS1_BITS+3+1)
  175704. & RANGE_MASK];
  175705. wsptr += DCTSIZE; /* advance pointer to next row */
  175706. }
  175707. }
  175708. /*
  175709. * Perform dequantization and inverse DCT on one block of coefficients,
  175710. * producing a reduced-size 2x2 output block.
  175711. */
  175712. GLOBAL(void)
  175713. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175714. JCOEFPTR coef_block,
  175715. JSAMPARRAY output_buf, JDIMENSION output_col)
  175716. {
  175717. INT32 tmp0, tmp10, z1;
  175718. JCOEFPTR inptr;
  175719. ISLOW_MULT_TYPE * quantptr;
  175720. int * wsptr;
  175721. JSAMPROW outptr;
  175722. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175723. int ctr;
  175724. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175725. SHIFT_TEMPS
  175726. /* Pass 1: process columns from input, store into work array. */
  175727. inptr = coef_block;
  175728. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175729. wsptr = workspace;
  175730. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175731. /* Don't bother to process columns 2,4,6 */
  175732. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175733. continue;
  175734. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175735. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175736. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175737. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175738. wsptr[DCTSIZE*0] = dcval;
  175739. wsptr[DCTSIZE*1] = dcval;
  175740. continue;
  175741. }
  175742. /* Even part */
  175743. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175744. tmp10 = z1 << (CONST_BITS+2);
  175745. /* Odd part */
  175746. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175747. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175748. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175749. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175750. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175751. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175752. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175753. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175754. /* Final output stage */
  175755. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175756. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175757. }
  175758. /* Pass 2: process 2 rows from work array, store into output array. */
  175759. wsptr = workspace;
  175760. for (ctr = 0; ctr < 2; ctr++) {
  175761. outptr = output_buf[ctr] + output_col;
  175762. /* It's not clear whether a zero row test is worthwhile here ... */
  175763. #ifndef NO_ZERO_ROW_TEST
  175764. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175765. /* AC terms all zero */
  175766. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175767. & RANGE_MASK];
  175768. outptr[0] = dcval;
  175769. outptr[1] = dcval;
  175770. wsptr += DCTSIZE; /* advance pointer to next row */
  175771. continue;
  175772. }
  175773. #endif
  175774. /* Even part */
  175775. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175776. /* Odd part */
  175777. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175778. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175779. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175780. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175781. /* Final output stage */
  175782. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175783. CONST_BITS+PASS1_BITS+3+2)
  175784. & RANGE_MASK];
  175785. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175786. CONST_BITS+PASS1_BITS+3+2)
  175787. & RANGE_MASK];
  175788. wsptr += DCTSIZE; /* advance pointer to next row */
  175789. }
  175790. }
  175791. /*
  175792. * Perform dequantization and inverse DCT on one block of coefficients,
  175793. * producing a reduced-size 1x1 output block.
  175794. */
  175795. GLOBAL(void)
  175796. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175797. JCOEFPTR coef_block,
  175798. JSAMPARRAY output_buf, JDIMENSION output_col)
  175799. {
  175800. int dcval;
  175801. ISLOW_MULT_TYPE * quantptr;
  175802. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175803. SHIFT_TEMPS
  175804. /* We hardly need an inverse DCT routine for this: just take the
  175805. * average pixel value, which is one-eighth of the DC coefficient.
  175806. */
  175807. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175808. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175809. dcval = (int) DESCALE((INT32) dcval, 3);
  175810. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175811. }
  175812. #endif /* IDCT_SCALING_SUPPORTED */
  175813. /*** End of inlined file: jidctred.c ***/
  175814. /*** Start of inlined file: jmemmgr.c ***/
  175815. #define JPEG_INTERNALS
  175816. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175817. /*** Start of inlined file: jmemsys.h ***/
  175818. #ifndef __jmemsys_h__
  175819. #define __jmemsys_h__
  175820. /* Short forms of external names for systems with brain-damaged linkers. */
  175821. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175822. #define jpeg_get_small jGetSmall
  175823. #define jpeg_free_small jFreeSmall
  175824. #define jpeg_get_large jGetLarge
  175825. #define jpeg_free_large jFreeLarge
  175826. #define jpeg_mem_available jMemAvail
  175827. #define jpeg_open_backing_store jOpenBackStore
  175828. #define jpeg_mem_init jMemInit
  175829. #define jpeg_mem_term jMemTerm
  175830. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175831. /*
  175832. * These two functions are used to allocate and release small chunks of
  175833. * memory. (Typically the total amount requested through jpeg_get_small is
  175834. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175835. * Behavior should be the same as for the standard library functions malloc
  175836. * and free; in particular, jpeg_get_small must return NULL on failure.
  175837. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175838. * size of the object being freed, just in case it's needed.
  175839. * On an 80x86 machine using small-data memory model, these manage near heap.
  175840. */
  175841. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175842. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175843. size_t sizeofobject));
  175844. /*
  175845. * These two functions are used to allocate and release large chunks of
  175846. * memory (up to the total free space designated by jpeg_mem_available).
  175847. * The interface is the same as above, except that on an 80x86 machine,
  175848. * far pointers are used. On most other machines these are identical to
  175849. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175850. * in case a different allocation strategy is desirable for large chunks.
  175851. */
  175852. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175853. size_t sizeofobject));
  175854. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175855. size_t sizeofobject));
  175856. /*
  175857. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175858. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175859. * matter, but that case should never come into play). This macro is needed
  175860. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175861. * On those machines, we expect that jconfig.h will provide a proper value.
  175862. * On machines with 32-bit flat address spaces, any large constant may be used.
  175863. *
  175864. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175865. * size_t and will be a multiple of sizeof(align_type).
  175866. */
  175867. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175868. #define MAX_ALLOC_CHUNK 1000000000L
  175869. #endif
  175870. /*
  175871. * This routine computes the total space still available for allocation by
  175872. * jpeg_get_large. If more space than this is needed, backing store will be
  175873. * used. NOTE: any memory already allocated must not be counted.
  175874. *
  175875. * There is a minimum space requirement, corresponding to the minimum
  175876. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175877. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175878. * all working storage in memory, is also passed in case it is useful.
  175879. * Finally, the total space already allocated is passed. If no better
  175880. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175881. * is often a suitable calculation.
  175882. *
  175883. * It is OK for jpeg_mem_available to underestimate the space available
  175884. * (that'll just lead to more backing-store access than is really necessary).
  175885. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175886. * a slop factor from the true available space. 5% should be enough.
  175887. *
  175888. * On machines with lots of virtual memory, any large constant may be returned.
  175889. * Conversely, zero may be returned to always use the minimum amount of memory.
  175890. */
  175891. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175892. long min_bytes_needed,
  175893. long max_bytes_needed,
  175894. long already_allocated));
  175895. /*
  175896. * This structure holds whatever state is needed to access a single
  175897. * backing-store object. The read/write/close method pointers are called
  175898. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175899. * are private to the system-dependent backing store routines.
  175900. */
  175901. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175902. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175903. typedef unsigned short XMSH; /* type of extended-memory handles */
  175904. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175905. typedef union {
  175906. short file_handle; /* DOS file handle if it's a temp file */
  175907. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175908. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175909. } handle_union;
  175910. #endif /* USE_MSDOS_MEMMGR */
  175911. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175912. #include <Files.h>
  175913. #endif /* USE_MAC_MEMMGR */
  175914. //typedef struct backing_store_struct * backing_store_ptr;
  175915. typedef struct backing_store_struct {
  175916. /* Methods for reading/writing/closing this backing-store object */
  175917. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175918. struct backing_store_struct *info,
  175919. void FAR * buffer_address,
  175920. long file_offset, long byte_count));
  175921. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175922. struct backing_store_struct *info,
  175923. void FAR * buffer_address,
  175924. long file_offset, long byte_count));
  175925. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175926. struct backing_store_struct *info));
  175927. /* Private fields for system-dependent backing-store management */
  175928. #ifdef USE_MSDOS_MEMMGR
  175929. /* For the MS-DOS manager (jmemdos.c), we need: */
  175930. handle_union handle; /* reference to backing-store storage object */
  175931. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175932. #else
  175933. #ifdef USE_MAC_MEMMGR
  175934. /* For the Mac manager (jmemmac.c), we need: */
  175935. short temp_file; /* file reference number to temp file */
  175936. FSSpec tempSpec; /* the FSSpec for the temp file */
  175937. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175938. #else
  175939. /* For a typical implementation with temp files, we need: */
  175940. FILE * temp_file; /* stdio reference to temp file */
  175941. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175942. #endif
  175943. #endif
  175944. } backing_store_info;
  175945. /*
  175946. * Initial opening of a backing-store object. This must fill in the
  175947. * read/write/close pointers in the object. The read/write routines
  175948. * may take an error exit if the specified maximum file size is exceeded.
  175949. * (If jpeg_mem_available always returns a large value, this routine can
  175950. * just take an error exit.)
  175951. */
  175952. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175953. struct backing_store_struct *info,
  175954. long total_bytes_needed));
  175955. /*
  175956. * These routines take care of any system-dependent initialization and
  175957. * cleanup required. jpeg_mem_init will be called before anything is
  175958. * allocated (and, therefore, nothing in cinfo is of use except the error
  175959. * manager pointer). It should return a suitable default value for
  175960. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175961. * application. (Note that max_memory_to_use is only important if
  175962. * jpeg_mem_available chooses to consult it ... no one else will.)
  175963. * jpeg_mem_term may assume that all requested memory has been freed and that
  175964. * all opened backing-store objects have been closed.
  175965. */
  175966. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175967. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175968. #endif
  175969. /*** End of inlined file: jmemsys.h ***/
  175970. /* import the system-dependent declarations */
  175971. #ifndef NO_GETENV
  175972. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175973. extern char * getenv JPP((const char * name));
  175974. #endif
  175975. #endif
  175976. /*
  175977. * Some important notes:
  175978. * The allocation routines provided here must never return NULL.
  175979. * They should exit to error_exit if unsuccessful.
  175980. *
  175981. * It's not a good idea to try to merge the sarray and barray routines,
  175982. * even though they are textually almost the same, because samples are
  175983. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175984. * in machines where byte pointers have a different representation from
  175985. * word pointers, the resulting machine code could not be the same.
  175986. */
  175987. /*
  175988. * Many machines require storage alignment: longs must start on 4-byte
  175989. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175990. * always returns pointers that are multiples of the worst-case alignment
  175991. * requirement, and we had better do so too.
  175992. * There isn't any really portable way to determine the worst-case alignment
  175993. * requirement. This module assumes that the alignment requirement is
  175994. * multiples of sizeof(ALIGN_TYPE).
  175995. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175996. * workstations (where doubles really do need 8-byte alignment) and will work
  175997. * fine on nearly everything. If your machine has lesser alignment needs,
  175998. * you can save a few bytes by making ALIGN_TYPE smaller.
  175999. * The only place I know of where this will NOT work is certain Macintosh
  176000. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176001. * Doing 10-byte alignment is counterproductive because longwords won't be
  176002. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176003. * such a compiler.
  176004. */
  176005. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176006. #define ALIGN_TYPE double
  176007. #endif
  176008. /*
  176009. * We allocate objects from "pools", where each pool is gotten with a single
  176010. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176011. * overhead within a pool, except for alignment padding. Each pool has a
  176012. * header with a link to the next pool of the same class.
  176013. * Small and large pool headers are identical except that the latter's
  176014. * link pointer must be FAR on 80x86 machines.
  176015. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176016. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176017. * of the alignment requirement of ALIGN_TYPE.
  176018. */
  176019. typedef union small_pool_struct * small_pool_ptr;
  176020. typedef union small_pool_struct {
  176021. struct {
  176022. small_pool_ptr next; /* next in list of pools */
  176023. size_t bytes_used; /* how many bytes already used within pool */
  176024. size_t bytes_left; /* bytes still available in this pool */
  176025. } hdr;
  176026. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176027. } small_pool_hdr;
  176028. typedef union large_pool_struct FAR * large_pool_ptr;
  176029. typedef union large_pool_struct {
  176030. struct {
  176031. large_pool_ptr next; /* next in list of pools */
  176032. size_t bytes_used; /* how many bytes already used within pool */
  176033. size_t bytes_left; /* bytes still available in this pool */
  176034. } hdr;
  176035. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176036. } large_pool_hdr;
  176037. /*
  176038. * Here is the full definition of a memory manager object.
  176039. */
  176040. typedef struct {
  176041. struct jpeg_memory_mgr pub; /* public fields */
  176042. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176043. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176044. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176045. /* Since we only have one lifetime class of virtual arrays, only one
  176046. * linked list is necessary (for each datatype). Note that the virtual
  176047. * array control blocks being linked together are actually stored somewhere
  176048. * in the small-pool list.
  176049. */
  176050. jvirt_sarray_ptr virt_sarray_list;
  176051. jvirt_barray_ptr virt_barray_list;
  176052. /* This counts total space obtained from jpeg_get_small/large */
  176053. long total_space_allocated;
  176054. /* alloc_sarray and alloc_barray set this value for use by virtual
  176055. * array routines.
  176056. */
  176057. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176058. } my_memory_mgr;
  176059. typedef my_memory_mgr * my_mem_ptr;
  176060. /*
  176061. * The control blocks for virtual arrays.
  176062. * Note that these blocks are allocated in the "small" pool area.
  176063. * System-dependent info for the associated backing store (if any) is hidden
  176064. * inside the backing_store_info struct.
  176065. */
  176066. struct jvirt_sarray_control {
  176067. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176068. JDIMENSION rows_in_array; /* total virtual array height */
  176069. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176070. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176071. JDIMENSION rows_in_mem; /* height of memory buffer */
  176072. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176073. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176074. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176075. boolean pre_zero; /* pre-zero mode requested? */
  176076. boolean dirty; /* do current buffer contents need written? */
  176077. boolean b_s_open; /* is backing-store data valid? */
  176078. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176079. backing_store_info b_s_info; /* System-dependent control info */
  176080. };
  176081. struct jvirt_barray_control {
  176082. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176083. JDIMENSION rows_in_array; /* total virtual array height */
  176084. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176085. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176086. JDIMENSION rows_in_mem; /* height of memory buffer */
  176087. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176088. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176089. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176090. boolean pre_zero; /* pre-zero mode requested? */
  176091. boolean dirty; /* do current buffer contents need written? */
  176092. boolean b_s_open; /* is backing-store data valid? */
  176093. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176094. backing_store_info b_s_info; /* System-dependent control info */
  176095. };
  176096. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176097. LOCAL(void)
  176098. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176099. {
  176100. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176101. small_pool_ptr shdr_ptr;
  176102. large_pool_ptr lhdr_ptr;
  176103. /* Since this is only a debugging stub, we can cheat a little by using
  176104. * fprintf directly rather than going through the trace message code.
  176105. * This is helpful because message parm array can't handle longs.
  176106. */
  176107. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176108. pool_id, mem->total_space_allocated);
  176109. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176110. lhdr_ptr = lhdr_ptr->hdr.next) {
  176111. fprintf(stderr, " Large chunk used %ld\n",
  176112. (long) lhdr_ptr->hdr.bytes_used);
  176113. }
  176114. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176115. shdr_ptr = shdr_ptr->hdr.next) {
  176116. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176117. (long) shdr_ptr->hdr.bytes_used,
  176118. (long) shdr_ptr->hdr.bytes_left);
  176119. }
  176120. }
  176121. #endif /* MEM_STATS */
  176122. LOCAL(void)
  176123. out_of_memory (j_common_ptr cinfo, int which)
  176124. /* Report an out-of-memory error and stop execution */
  176125. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176126. {
  176127. #ifdef MEM_STATS
  176128. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176129. #endif
  176130. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176131. }
  176132. /*
  176133. * Allocation of "small" objects.
  176134. *
  176135. * For these, we use pooled storage. When a new pool must be created,
  176136. * we try to get enough space for the current request plus a "slop" factor,
  176137. * where the slop will be the amount of leftover space in the new pool.
  176138. * The speed vs. space tradeoff is largely determined by the slop values.
  176139. * A different slop value is provided for each pool class (lifetime),
  176140. * and we also distinguish the first pool of a class from later ones.
  176141. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176142. * machines, but may be too small if longs are 64 bits or more.
  176143. */
  176144. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176145. {
  176146. 1600, /* first PERMANENT pool */
  176147. 16000 /* first IMAGE pool */
  176148. };
  176149. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176150. {
  176151. 0, /* additional PERMANENT pools */
  176152. 5000 /* additional IMAGE pools */
  176153. };
  176154. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176155. METHODDEF(void *)
  176156. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176157. /* Allocate a "small" object */
  176158. {
  176159. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176160. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176161. char * data_ptr;
  176162. size_t odd_bytes, min_request, slop;
  176163. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176164. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176165. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176166. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176167. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176168. if (odd_bytes > 0)
  176169. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176170. /* See if space is available in any existing pool */
  176171. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176172. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176173. prev_hdr_ptr = NULL;
  176174. hdr_ptr = mem->small_list[pool_id];
  176175. while (hdr_ptr != NULL) {
  176176. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176177. break; /* found pool with enough space */
  176178. prev_hdr_ptr = hdr_ptr;
  176179. hdr_ptr = hdr_ptr->hdr.next;
  176180. }
  176181. /* Time to make a new pool? */
  176182. if (hdr_ptr == NULL) {
  176183. /* min_request is what we need now, slop is what will be leftover */
  176184. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176185. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176186. slop = first_pool_slop[pool_id];
  176187. else
  176188. slop = extra_pool_slop[pool_id];
  176189. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176190. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176191. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176192. /* Try to get space, if fail reduce slop and try again */
  176193. for (;;) {
  176194. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176195. if (hdr_ptr != NULL)
  176196. break;
  176197. slop /= 2;
  176198. if (slop < MIN_SLOP) /* give up when it gets real small */
  176199. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176200. }
  176201. mem->total_space_allocated += min_request + slop;
  176202. /* Success, initialize the new pool header and add to end of list */
  176203. hdr_ptr->hdr.next = NULL;
  176204. hdr_ptr->hdr.bytes_used = 0;
  176205. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176206. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176207. mem->small_list[pool_id] = hdr_ptr;
  176208. else
  176209. prev_hdr_ptr->hdr.next = hdr_ptr;
  176210. }
  176211. /* OK, allocate the object from the current pool */
  176212. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176213. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176214. hdr_ptr->hdr.bytes_used += sizeofobject;
  176215. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176216. return (void *) data_ptr;
  176217. }
  176218. /*
  176219. * Allocation of "large" objects.
  176220. *
  176221. * The external semantics of these are the same as "small" objects,
  176222. * except that FAR pointers are used on 80x86. However the pool
  176223. * management heuristics are quite different. We assume that each
  176224. * request is large enough that it may as well be passed directly to
  176225. * jpeg_get_large; the pool management just links everything together
  176226. * so that we can free it all on demand.
  176227. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176228. * structures. The routines that create these structures (see below)
  176229. * deliberately bunch rows together to ensure a large request size.
  176230. */
  176231. METHODDEF(void FAR *)
  176232. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176233. /* Allocate a "large" object */
  176234. {
  176235. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176236. large_pool_ptr hdr_ptr;
  176237. size_t odd_bytes;
  176238. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176239. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176240. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176241. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176242. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176243. if (odd_bytes > 0)
  176244. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176245. /* Always make a new pool */
  176246. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176247. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176248. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176249. SIZEOF(large_pool_hdr));
  176250. if (hdr_ptr == NULL)
  176251. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176252. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176253. /* Success, initialize the new pool header and add to list */
  176254. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176255. /* We maintain space counts in each pool header for statistical purposes,
  176256. * even though they are not needed for allocation.
  176257. */
  176258. hdr_ptr->hdr.bytes_used = sizeofobject;
  176259. hdr_ptr->hdr.bytes_left = 0;
  176260. mem->large_list[pool_id] = hdr_ptr;
  176261. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176262. }
  176263. /*
  176264. * Creation of 2-D sample arrays.
  176265. * The pointers are in near heap, the samples themselves in FAR heap.
  176266. *
  176267. * To minimize allocation overhead and to allow I/O of large contiguous
  176268. * blocks, we allocate the sample rows in groups of as many rows as possible
  176269. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176270. * NB: the virtual array control routines, later in this file, know about
  176271. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176272. * object so that it can be saved away if this sarray is the workspace for
  176273. * a virtual array.
  176274. */
  176275. METHODDEF(JSAMPARRAY)
  176276. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176277. JDIMENSION samplesperrow, JDIMENSION numrows)
  176278. /* Allocate a 2-D sample array */
  176279. {
  176280. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176281. JSAMPARRAY result;
  176282. JSAMPROW workspace;
  176283. JDIMENSION rowsperchunk, currow, i;
  176284. long ltemp;
  176285. /* Calculate max # of rows allowed in one allocation chunk */
  176286. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176287. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176288. if (ltemp <= 0)
  176289. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176290. if (ltemp < (long) numrows)
  176291. rowsperchunk = (JDIMENSION) ltemp;
  176292. else
  176293. rowsperchunk = numrows;
  176294. mem->last_rowsperchunk = rowsperchunk;
  176295. /* Get space for row pointers (small object) */
  176296. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176297. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176298. /* Get the rows themselves (large objects) */
  176299. currow = 0;
  176300. while (currow < numrows) {
  176301. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176302. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176303. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176304. * SIZEOF(JSAMPLE)));
  176305. for (i = rowsperchunk; i > 0; i--) {
  176306. result[currow++] = workspace;
  176307. workspace += samplesperrow;
  176308. }
  176309. }
  176310. return result;
  176311. }
  176312. /*
  176313. * Creation of 2-D coefficient-block arrays.
  176314. * This is essentially the same as the code for sample arrays, above.
  176315. */
  176316. METHODDEF(JBLOCKARRAY)
  176317. alloc_barray (j_common_ptr cinfo, int pool_id,
  176318. JDIMENSION blocksperrow, JDIMENSION numrows)
  176319. /* Allocate a 2-D coefficient-block array */
  176320. {
  176321. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176322. JBLOCKARRAY result;
  176323. JBLOCKROW workspace;
  176324. JDIMENSION rowsperchunk, currow, i;
  176325. long ltemp;
  176326. /* Calculate max # of rows allowed in one allocation chunk */
  176327. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176328. ((long) blocksperrow * SIZEOF(JBLOCK));
  176329. if (ltemp <= 0)
  176330. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176331. if (ltemp < (long) numrows)
  176332. rowsperchunk = (JDIMENSION) ltemp;
  176333. else
  176334. rowsperchunk = numrows;
  176335. mem->last_rowsperchunk = rowsperchunk;
  176336. /* Get space for row pointers (small object) */
  176337. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176338. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176339. /* Get the rows themselves (large objects) */
  176340. currow = 0;
  176341. while (currow < numrows) {
  176342. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176343. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176344. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176345. * SIZEOF(JBLOCK)));
  176346. for (i = rowsperchunk; i > 0; i--) {
  176347. result[currow++] = workspace;
  176348. workspace += blocksperrow;
  176349. }
  176350. }
  176351. return result;
  176352. }
  176353. /*
  176354. * About virtual array management:
  176355. *
  176356. * The above "normal" array routines are only used to allocate strip buffers
  176357. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176358. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176359. * time, but the memory manager must save the whole array for repeated
  176360. * accesses. The intended implementation is that there is a strip buffer in
  176361. * memory (as high as is possible given the desired memory limit), plus a
  176362. * backing file that holds the rest of the array.
  176363. *
  176364. * The request_virt_array routines are told the total size of the image and
  176365. * the maximum number of rows that will be accessed at once. The in-memory
  176366. * buffer must be at least as large as the maxaccess value.
  176367. *
  176368. * The request routines create control blocks but not the in-memory buffers.
  176369. * That is postponed until realize_virt_arrays is called. At that time the
  176370. * total amount of space needed is known (approximately, anyway), so free
  176371. * memory can be divided up fairly.
  176372. *
  176373. * The access_virt_array routines are responsible for making a specific strip
  176374. * area accessible (after reading or writing the backing file, if necessary).
  176375. * Note that the access routines are told whether the caller intends to modify
  176376. * the accessed strip; during a read-only pass this saves having to rewrite
  176377. * data to disk. The access routines are also responsible for pre-zeroing
  176378. * any newly accessed rows, if pre-zeroing was requested.
  176379. *
  176380. * In current usage, the access requests are usually for nonoverlapping
  176381. * strips; that is, successive access start_row numbers differ by exactly
  176382. * num_rows = maxaccess. This means we can get good performance with simple
  176383. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176384. * of the access height; then there will never be accesses across bufferload
  176385. * boundaries. The code will still work with overlapping access requests,
  176386. * but it doesn't handle bufferload overlaps very efficiently.
  176387. */
  176388. METHODDEF(jvirt_sarray_ptr)
  176389. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176390. JDIMENSION samplesperrow, JDIMENSION numrows,
  176391. JDIMENSION maxaccess)
  176392. /* Request a virtual 2-D sample array */
  176393. {
  176394. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176395. jvirt_sarray_ptr result;
  176396. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176397. if (pool_id != JPOOL_IMAGE)
  176398. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176399. /* get control block */
  176400. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176401. SIZEOF(struct jvirt_sarray_control));
  176402. result->mem_buffer = NULL; /* marks array not yet realized */
  176403. result->rows_in_array = numrows;
  176404. result->samplesperrow = samplesperrow;
  176405. result->maxaccess = maxaccess;
  176406. result->pre_zero = pre_zero;
  176407. result->b_s_open = FALSE; /* no associated backing-store object */
  176408. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176409. mem->virt_sarray_list = result;
  176410. return result;
  176411. }
  176412. METHODDEF(jvirt_barray_ptr)
  176413. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176414. JDIMENSION blocksperrow, JDIMENSION numrows,
  176415. JDIMENSION maxaccess)
  176416. /* Request a virtual 2-D coefficient-block array */
  176417. {
  176418. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176419. jvirt_barray_ptr result;
  176420. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176421. if (pool_id != JPOOL_IMAGE)
  176422. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176423. /* get control block */
  176424. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176425. SIZEOF(struct jvirt_barray_control));
  176426. result->mem_buffer = NULL; /* marks array not yet realized */
  176427. result->rows_in_array = numrows;
  176428. result->blocksperrow = blocksperrow;
  176429. result->maxaccess = maxaccess;
  176430. result->pre_zero = pre_zero;
  176431. result->b_s_open = FALSE; /* no associated backing-store object */
  176432. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176433. mem->virt_barray_list = result;
  176434. return result;
  176435. }
  176436. METHODDEF(void)
  176437. realize_virt_arrays (j_common_ptr cinfo)
  176438. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176439. {
  176440. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176441. long space_per_minheight, maximum_space, avail_mem;
  176442. long minheights, max_minheights;
  176443. jvirt_sarray_ptr sptr;
  176444. jvirt_barray_ptr bptr;
  176445. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176446. * and the maximum space needed (full image height in each buffer).
  176447. * These may be of use to the system-dependent jpeg_mem_available routine.
  176448. */
  176449. space_per_minheight = 0;
  176450. maximum_space = 0;
  176451. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176452. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176453. space_per_minheight += (long) sptr->maxaccess *
  176454. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176455. maximum_space += (long) sptr->rows_in_array *
  176456. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176457. }
  176458. }
  176459. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176460. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176461. space_per_minheight += (long) bptr->maxaccess *
  176462. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176463. maximum_space += (long) bptr->rows_in_array *
  176464. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176465. }
  176466. }
  176467. if (space_per_minheight <= 0)
  176468. return; /* no unrealized arrays, no work */
  176469. /* Determine amount of memory to actually use; this is system-dependent. */
  176470. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176471. mem->total_space_allocated);
  176472. /* If the maximum space needed is available, make all the buffers full
  176473. * height; otherwise parcel it out with the same number of minheights
  176474. * in each buffer.
  176475. */
  176476. if (avail_mem >= maximum_space)
  176477. max_minheights = 1000000000L;
  176478. else {
  176479. max_minheights = avail_mem / space_per_minheight;
  176480. /* If there doesn't seem to be enough space, try to get the minimum
  176481. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176482. */
  176483. if (max_minheights <= 0)
  176484. max_minheights = 1;
  176485. }
  176486. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176487. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176488. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176489. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176490. if (minheights <= max_minheights) {
  176491. /* This buffer fits in memory */
  176492. sptr->rows_in_mem = sptr->rows_in_array;
  176493. } else {
  176494. /* It doesn't fit in memory, create backing store. */
  176495. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176496. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176497. (long) sptr->rows_in_array *
  176498. (long) sptr->samplesperrow *
  176499. (long) SIZEOF(JSAMPLE));
  176500. sptr->b_s_open = TRUE;
  176501. }
  176502. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176503. sptr->samplesperrow, sptr->rows_in_mem);
  176504. sptr->rowsperchunk = mem->last_rowsperchunk;
  176505. sptr->cur_start_row = 0;
  176506. sptr->first_undef_row = 0;
  176507. sptr->dirty = FALSE;
  176508. }
  176509. }
  176510. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176511. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176512. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176513. if (minheights <= max_minheights) {
  176514. /* This buffer fits in memory */
  176515. bptr->rows_in_mem = bptr->rows_in_array;
  176516. } else {
  176517. /* It doesn't fit in memory, create backing store. */
  176518. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176519. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176520. (long) bptr->rows_in_array *
  176521. (long) bptr->blocksperrow *
  176522. (long) SIZEOF(JBLOCK));
  176523. bptr->b_s_open = TRUE;
  176524. }
  176525. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176526. bptr->blocksperrow, bptr->rows_in_mem);
  176527. bptr->rowsperchunk = mem->last_rowsperchunk;
  176528. bptr->cur_start_row = 0;
  176529. bptr->first_undef_row = 0;
  176530. bptr->dirty = FALSE;
  176531. }
  176532. }
  176533. }
  176534. LOCAL(void)
  176535. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176536. /* Do backing store read or write of a virtual sample array */
  176537. {
  176538. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176539. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176540. file_offset = ptr->cur_start_row * bytesperrow;
  176541. /* Loop to read or write each allocation chunk in mem_buffer */
  176542. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176543. /* One chunk, but check for short chunk at end of buffer */
  176544. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176545. /* Transfer no more than is currently defined */
  176546. thisrow = (long) ptr->cur_start_row + i;
  176547. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176548. /* Transfer no more than fits in file */
  176549. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176550. if (rows <= 0) /* this chunk might be past end of file! */
  176551. break;
  176552. byte_count = rows * bytesperrow;
  176553. if (writing)
  176554. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176555. (void FAR *) ptr->mem_buffer[i],
  176556. file_offset, byte_count);
  176557. else
  176558. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176559. (void FAR *) ptr->mem_buffer[i],
  176560. file_offset, byte_count);
  176561. file_offset += byte_count;
  176562. }
  176563. }
  176564. LOCAL(void)
  176565. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176566. /* Do backing store read or write of a virtual coefficient-block array */
  176567. {
  176568. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176569. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176570. file_offset = ptr->cur_start_row * bytesperrow;
  176571. /* Loop to read or write each allocation chunk in mem_buffer */
  176572. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176573. /* One chunk, but check for short chunk at end of buffer */
  176574. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176575. /* Transfer no more than is currently defined */
  176576. thisrow = (long) ptr->cur_start_row + i;
  176577. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176578. /* Transfer no more than fits in file */
  176579. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176580. if (rows <= 0) /* this chunk might be past end of file! */
  176581. break;
  176582. byte_count = rows * bytesperrow;
  176583. if (writing)
  176584. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176585. (void FAR *) ptr->mem_buffer[i],
  176586. file_offset, byte_count);
  176587. else
  176588. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176589. (void FAR *) ptr->mem_buffer[i],
  176590. file_offset, byte_count);
  176591. file_offset += byte_count;
  176592. }
  176593. }
  176594. METHODDEF(JSAMPARRAY)
  176595. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176596. JDIMENSION start_row, JDIMENSION num_rows,
  176597. boolean writable)
  176598. /* Access the part of a virtual sample array starting at start_row */
  176599. /* and extending for num_rows rows. writable is true if */
  176600. /* caller intends to modify the accessed area. */
  176601. {
  176602. JDIMENSION end_row = start_row + num_rows;
  176603. JDIMENSION undef_row;
  176604. /* debugging check */
  176605. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176606. ptr->mem_buffer == NULL)
  176607. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176608. /* Make the desired part of the virtual array accessible */
  176609. if (start_row < ptr->cur_start_row ||
  176610. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176611. if (! ptr->b_s_open)
  176612. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176613. /* Flush old buffer contents if necessary */
  176614. if (ptr->dirty) {
  176615. do_sarray_io(cinfo, ptr, TRUE);
  176616. ptr->dirty = FALSE;
  176617. }
  176618. /* Decide what part of virtual array to access.
  176619. * Algorithm: if target address > current window, assume forward scan,
  176620. * load starting at target address. If target address < current window,
  176621. * assume backward scan, load so that target area is top of window.
  176622. * Note that when switching from forward write to forward read, will have
  176623. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176624. */
  176625. if (start_row > ptr->cur_start_row) {
  176626. ptr->cur_start_row = start_row;
  176627. } else {
  176628. /* use long arithmetic here to avoid overflow & unsigned problems */
  176629. long ltemp;
  176630. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176631. if (ltemp < 0)
  176632. ltemp = 0; /* don't fall off front end of file */
  176633. ptr->cur_start_row = (JDIMENSION) ltemp;
  176634. }
  176635. /* Read in the selected part of the array.
  176636. * During the initial write pass, we will do no actual read
  176637. * because the selected part is all undefined.
  176638. */
  176639. do_sarray_io(cinfo, ptr, FALSE);
  176640. }
  176641. /* Ensure the accessed part of the array is defined; prezero if needed.
  176642. * To improve locality of access, we only prezero the part of the array
  176643. * that the caller is about to access, not the entire in-memory array.
  176644. */
  176645. if (ptr->first_undef_row < end_row) {
  176646. if (ptr->first_undef_row < start_row) {
  176647. if (writable) /* writer skipped over a section of array */
  176648. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176649. undef_row = start_row; /* but reader is allowed to read ahead */
  176650. } else {
  176651. undef_row = ptr->first_undef_row;
  176652. }
  176653. if (writable)
  176654. ptr->first_undef_row = end_row;
  176655. if (ptr->pre_zero) {
  176656. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176657. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176658. end_row -= ptr->cur_start_row;
  176659. while (undef_row < end_row) {
  176660. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176661. undef_row++;
  176662. }
  176663. } else {
  176664. if (! writable) /* reader looking at undefined data */
  176665. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176666. }
  176667. }
  176668. /* Flag the buffer dirty if caller will write in it */
  176669. if (writable)
  176670. ptr->dirty = TRUE;
  176671. /* Return address of proper part of the buffer */
  176672. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176673. }
  176674. METHODDEF(JBLOCKARRAY)
  176675. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176676. JDIMENSION start_row, JDIMENSION num_rows,
  176677. boolean writable)
  176678. /* Access the part of a virtual block array starting at start_row */
  176679. /* and extending for num_rows rows. writable is true if */
  176680. /* caller intends to modify the accessed area. */
  176681. {
  176682. JDIMENSION end_row = start_row + num_rows;
  176683. JDIMENSION undef_row;
  176684. /* debugging check */
  176685. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176686. ptr->mem_buffer == NULL)
  176687. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176688. /* Make the desired part of the virtual array accessible */
  176689. if (start_row < ptr->cur_start_row ||
  176690. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176691. if (! ptr->b_s_open)
  176692. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176693. /* Flush old buffer contents if necessary */
  176694. if (ptr->dirty) {
  176695. do_barray_io(cinfo, ptr, TRUE);
  176696. ptr->dirty = FALSE;
  176697. }
  176698. /* Decide what part of virtual array to access.
  176699. * Algorithm: if target address > current window, assume forward scan,
  176700. * load starting at target address. If target address < current window,
  176701. * assume backward scan, load so that target area is top of window.
  176702. * Note that when switching from forward write to forward read, will have
  176703. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176704. */
  176705. if (start_row > ptr->cur_start_row) {
  176706. ptr->cur_start_row = start_row;
  176707. } else {
  176708. /* use long arithmetic here to avoid overflow & unsigned problems */
  176709. long ltemp;
  176710. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176711. if (ltemp < 0)
  176712. ltemp = 0; /* don't fall off front end of file */
  176713. ptr->cur_start_row = (JDIMENSION) ltemp;
  176714. }
  176715. /* Read in the selected part of the array.
  176716. * During the initial write pass, we will do no actual read
  176717. * because the selected part is all undefined.
  176718. */
  176719. do_barray_io(cinfo, ptr, FALSE);
  176720. }
  176721. /* Ensure the accessed part of the array is defined; prezero if needed.
  176722. * To improve locality of access, we only prezero the part of the array
  176723. * that the caller is about to access, not the entire in-memory array.
  176724. */
  176725. if (ptr->first_undef_row < end_row) {
  176726. if (ptr->first_undef_row < start_row) {
  176727. if (writable) /* writer skipped over a section of array */
  176728. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176729. undef_row = start_row; /* but reader is allowed to read ahead */
  176730. } else {
  176731. undef_row = ptr->first_undef_row;
  176732. }
  176733. if (writable)
  176734. ptr->first_undef_row = end_row;
  176735. if (ptr->pre_zero) {
  176736. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176737. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176738. end_row -= ptr->cur_start_row;
  176739. while (undef_row < end_row) {
  176740. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176741. undef_row++;
  176742. }
  176743. } else {
  176744. if (! writable) /* reader looking at undefined data */
  176745. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176746. }
  176747. }
  176748. /* Flag the buffer dirty if caller will write in it */
  176749. if (writable)
  176750. ptr->dirty = TRUE;
  176751. /* Return address of proper part of the buffer */
  176752. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176753. }
  176754. /*
  176755. * Release all objects belonging to a specified pool.
  176756. */
  176757. METHODDEF(void)
  176758. free_pool (j_common_ptr cinfo, int pool_id)
  176759. {
  176760. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176761. small_pool_ptr shdr_ptr;
  176762. large_pool_ptr lhdr_ptr;
  176763. size_t space_freed;
  176764. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176765. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176766. #ifdef MEM_STATS
  176767. if (cinfo->err->trace_level > 1)
  176768. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176769. #endif
  176770. /* If freeing IMAGE pool, close any virtual arrays first */
  176771. if (pool_id == JPOOL_IMAGE) {
  176772. jvirt_sarray_ptr sptr;
  176773. jvirt_barray_ptr bptr;
  176774. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176775. if (sptr->b_s_open) { /* there may be no backing store */
  176776. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176777. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176778. }
  176779. }
  176780. mem->virt_sarray_list = NULL;
  176781. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176782. if (bptr->b_s_open) { /* there may be no backing store */
  176783. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176784. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176785. }
  176786. }
  176787. mem->virt_barray_list = NULL;
  176788. }
  176789. /* Release large objects */
  176790. lhdr_ptr = mem->large_list[pool_id];
  176791. mem->large_list[pool_id] = NULL;
  176792. while (lhdr_ptr != NULL) {
  176793. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176794. space_freed = lhdr_ptr->hdr.bytes_used +
  176795. lhdr_ptr->hdr.bytes_left +
  176796. SIZEOF(large_pool_hdr);
  176797. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176798. mem->total_space_allocated -= space_freed;
  176799. lhdr_ptr = next_lhdr_ptr;
  176800. }
  176801. /* Release small objects */
  176802. shdr_ptr = mem->small_list[pool_id];
  176803. mem->small_list[pool_id] = NULL;
  176804. while (shdr_ptr != NULL) {
  176805. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176806. space_freed = shdr_ptr->hdr.bytes_used +
  176807. shdr_ptr->hdr.bytes_left +
  176808. SIZEOF(small_pool_hdr);
  176809. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176810. mem->total_space_allocated -= space_freed;
  176811. shdr_ptr = next_shdr_ptr;
  176812. }
  176813. }
  176814. /*
  176815. * Close up shop entirely.
  176816. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176817. */
  176818. METHODDEF(void)
  176819. self_destruct (j_common_ptr cinfo)
  176820. {
  176821. int pool;
  176822. /* Close all backing store, release all memory.
  176823. * Releasing pools in reverse order might help avoid fragmentation
  176824. * with some (brain-damaged) malloc libraries.
  176825. */
  176826. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176827. free_pool(cinfo, pool);
  176828. }
  176829. /* Release the memory manager control block too. */
  176830. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176831. cinfo->mem = NULL; /* ensures I will be called only once */
  176832. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176833. }
  176834. /*
  176835. * Memory manager initialization.
  176836. * When this is called, only the error manager pointer is valid in cinfo!
  176837. */
  176838. GLOBAL(void)
  176839. jinit_memory_mgr (j_common_ptr cinfo)
  176840. {
  176841. my_mem_ptr mem;
  176842. long max_to_use;
  176843. int pool;
  176844. size_t test_mac;
  176845. cinfo->mem = NULL; /* for safety if init fails */
  176846. /* Check for configuration errors.
  176847. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176848. * doesn't reflect any real hardware alignment requirement.
  176849. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176850. * in common if and only if X is a power of 2, ie has only one one-bit.
  176851. * Some compilers may give an "unreachable code" warning here; ignore it.
  176852. */
  176853. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176854. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176855. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176856. * a multiple of SIZEOF(ALIGN_TYPE).
  176857. * Again, an "unreachable code" warning may be ignored here.
  176858. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176859. */
  176860. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176861. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176862. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176863. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176864. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176865. /* Attempt to allocate memory manager's control block */
  176866. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176867. if (mem == NULL) {
  176868. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176869. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176870. }
  176871. /* OK, fill in the method pointers */
  176872. mem->pub.alloc_small = alloc_small;
  176873. mem->pub.alloc_large = alloc_large;
  176874. mem->pub.alloc_sarray = alloc_sarray;
  176875. mem->pub.alloc_barray = alloc_barray;
  176876. mem->pub.request_virt_sarray = request_virt_sarray;
  176877. mem->pub.request_virt_barray = request_virt_barray;
  176878. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176879. mem->pub.access_virt_sarray = access_virt_sarray;
  176880. mem->pub.access_virt_barray = access_virt_barray;
  176881. mem->pub.free_pool = free_pool;
  176882. mem->pub.self_destruct = self_destruct;
  176883. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176884. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176885. /* Initialize working state */
  176886. mem->pub.max_memory_to_use = max_to_use;
  176887. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176888. mem->small_list[pool] = NULL;
  176889. mem->large_list[pool] = NULL;
  176890. }
  176891. mem->virt_sarray_list = NULL;
  176892. mem->virt_barray_list = NULL;
  176893. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176894. /* Declare ourselves open for business */
  176895. cinfo->mem = & mem->pub;
  176896. /* Check for an environment variable JPEGMEM; if found, override the
  176897. * default max_memory setting from jpeg_mem_init. Note that the
  176898. * surrounding application may again override this value.
  176899. * If your system doesn't support getenv(), define NO_GETENV to disable
  176900. * this feature.
  176901. */
  176902. #ifndef NO_GETENV
  176903. { char * memenv;
  176904. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176905. char ch = 'x';
  176906. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176907. if (ch == 'm' || ch == 'M')
  176908. max_to_use *= 1000L;
  176909. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176910. }
  176911. }
  176912. }
  176913. #endif
  176914. }
  176915. /*** End of inlined file: jmemmgr.c ***/
  176916. /*** Start of inlined file: jmemnobs.c ***/
  176917. #define JPEG_INTERNALS
  176918. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176919. extern void * malloc JPP((size_t size));
  176920. extern void free JPP((void *ptr));
  176921. #endif
  176922. /*
  176923. * Memory allocation and freeing are controlled by the regular library
  176924. * routines malloc() and free().
  176925. */
  176926. GLOBAL(void *)
  176927. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176928. {
  176929. return (void *) malloc(sizeofobject);
  176930. }
  176931. GLOBAL(void)
  176932. jpeg_free_small (j_common_ptr , void * object, size_t)
  176933. {
  176934. free(object);
  176935. }
  176936. /*
  176937. * "Large" objects are treated the same as "small" ones.
  176938. * NB: although we include FAR keywords in the routine declarations,
  176939. * this file won't actually work in 80x86 small/medium model; at least,
  176940. * you probably won't be able to process useful-size images in only 64KB.
  176941. */
  176942. GLOBAL(void FAR *)
  176943. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176944. {
  176945. return (void FAR *) malloc(sizeofobject);
  176946. }
  176947. GLOBAL(void)
  176948. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176949. {
  176950. free(object);
  176951. }
  176952. /*
  176953. * This routine computes the total memory space available for allocation.
  176954. * Here we always say, "we got all you want bud!"
  176955. */
  176956. GLOBAL(long)
  176957. jpeg_mem_available (j_common_ptr, long,
  176958. long max_bytes_needed, long)
  176959. {
  176960. return max_bytes_needed;
  176961. }
  176962. /*
  176963. * Backing store (temporary file) management.
  176964. * Since jpeg_mem_available always promised the moon,
  176965. * this should never be called and we can just error out.
  176966. */
  176967. GLOBAL(void)
  176968. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176969. long )
  176970. {
  176971. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176972. }
  176973. /*
  176974. * These routines take care of any system-dependent initialization and
  176975. * cleanup required. Here, there isn't any.
  176976. */
  176977. GLOBAL(long)
  176978. jpeg_mem_init (j_common_ptr)
  176979. {
  176980. return 0; /* just set max_memory_to_use to 0 */
  176981. }
  176982. GLOBAL(void)
  176983. jpeg_mem_term (j_common_ptr)
  176984. {
  176985. /* no work */
  176986. }
  176987. /*** End of inlined file: jmemnobs.c ***/
  176988. /*** Start of inlined file: jquant1.c ***/
  176989. #define JPEG_INTERNALS
  176990. #ifdef QUANT_1PASS_SUPPORTED
  176991. /*
  176992. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176993. * high quality, colormapped output capability. A 2-pass quantizer usually
  176994. * gives better visual quality; however, for quantized grayscale output this
  176995. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176996. * quantizer, though you can turn it off if you really want to.
  176997. *
  176998. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176999. * image. We use a map consisting of all combinations of Ncolors[i] color
  177000. * values for the i'th component. The Ncolors[] values are chosen so that
  177001. * their product, the total number of colors, is no more than that requested.
  177002. * (In most cases, the product will be somewhat less.)
  177003. *
  177004. * Since the colormap is orthogonal, the representative value for each color
  177005. * component can be determined without considering the other components;
  177006. * then these indexes can be combined into a colormap index by a standard
  177007. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177008. * can be precalculated and stored in the lookup table colorindex[].
  177009. * colorindex[i][j] maps pixel value j in component i to the nearest
  177010. * representative value (grid plane) for that component; this index is
  177011. * multiplied by the array stride for component i, so that the
  177012. * index of the colormap entry closest to a given pixel value is just
  177013. * sum( colorindex[component-number][pixel-component-value] )
  177014. * Aside from being fast, this scheme allows for variable spacing between
  177015. * representative values with no additional lookup cost.
  177016. *
  177017. * If gamma correction has been applied in color conversion, it might be wise
  177018. * to adjust the color grid spacing so that the representative colors are
  177019. * equidistant in linear space. At this writing, gamma correction is not
  177020. * implemented by jdcolor, so nothing is done here.
  177021. */
  177022. /* Declarations for ordered dithering.
  177023. *
  177024. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177025. * dithering is described in many references, for instance Dale Schumacher's
  177026. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177027. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177028. * "dither" value to the input pixel and then round the result to the nearest
  177029. * output value. The dither value is equivalent to (0.5 - threshold) times
  177030. * the distance between output values. For ordered dithering, we assume that
  177031. * the output colors are equally spaced; if not, results will probably be
  177032. * worse, since the dither may be too much or too little at a given point.
  177033. *
  177034. * The normal calculation would be to form pixel value + dither, range-limit
  177035. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177036. * We can skip the separate range-limiting step by extending the colorindex
  177037. * table in both directions.
  177038. */
  177039. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177040. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177041. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177042. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177043. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177044. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177045. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177046. /* Bayer's order-4 dither array. Generated by the code given in
  177047. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177048. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177049. */
  177050. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177051. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177052. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177053. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177054. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177055. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177056. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177057. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177058. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177059. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177060. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177061. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177062. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177063. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177064. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177065. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177066. };
  177067. /* Declarations for Floyd-Steinberg dithering.
  177068. *
  177069. * Errors are accumulated into the array fserrors[], at a resolution of
  177070. * 1/16th of a pixel count. The error at a given pixel is propagated
  177071. * to its not-yet-processed neighbors using the standard F-S fractions,
  177072. * ... (here) 7/16
  177073. * 3/16 5/16 1/16
  177074. * We work left-to-right on even rows, right-to-left on odd rows.
  177075. *
  177076. * We can get away with a single array (holding one row's worth of errors)
  177077. * by using it to store the current row's errors at pixel columns not yet
  177078. * processed, but the next row's errors at columns already processed. We
  177079. * need only a few extra variables to hold the errors immediately around the
  177080. * current column. (If we are lucky, those variables are in registers, but
  177081. * even if not, they're probably cheaper to access than array elements are.)
  177082. *
  177083. * The fserrors[] array is indexed [component#][position].
  177084. * We provide (#columns + 2) entries per component; the extra entry at each
  177085. * end saves us from special-casing the first and last pixels.
  177086. *
  177087. * Note: on a wide image, we might not have enough room in a PC's near data
  177088. * segment to hold the error array; so it is allocated with alloc_large.
  177089. */
  177090. #if BITS_IN_JSAMPLE == 8
  177091. typedef INT16 FSERROR; /* 16 bits should be enough */
  177092. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177093. #else
  177094. typedef INT32 FSERROR; /* may need more than 16 bits */
  177095. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177096. #endif
  177097. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177098. /* Private subobject */
  177099. #define MAX_Q_COMPS 4 /* max components I can handle */
  177100. typedef struct {
  177101. struct jpeg_color_quantizer pub; /* public fields */
  177102. /* Initially allocated colormap is saved here */
  177103. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177104. int sv_actual; /* number of entries in use */
  177105. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177106. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177107. * premultiplied as described above. Since colormap indexes must fit into
  177108. * JSAMPLEs, the entries of this array will too.
  177109. */
  177110. boolean is_padded; /* is the colorindex padded for odither? */
  177111. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177112. /* Variables for ordered dithering */
  177113. int row_index; /* cur row's vertical index in dither matrix */
  177114. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177115. /* Variables for Floyd-Steinberg dithering */
  177116. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177117. boolean on_odd_row; /* flag to remember which row we are on */
  177118. } my_cquantizer;
  177119. typedef my_cquantizer * my_cquantize_ptr;
  177120. /*
  177121. * Policy-making subroutines for create_colormap and create_colorindex.
  177122. * These routines determine the colormap to be used. The rest of the module
  177123. * only assumes that the colormap is orthogonal.
  177124. *
  177125. * * select_ncolors decides how to divvy up the available colors
  177126. * among the components.
  177127. * * output_value defines the set of representative values for a component.
  177128. * * largest_input_value defines the mapping from input values to
  177129. * representative values for a component.
  177130. * Note that the latter two routines may impose different policies for
  177131. * different components, though this is not currently done.
  177132. */
  177133. LOCAL(int)
  177134. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177135. /* Determine allocation of desired colors to components, */
  177136. /* and fill in Ncolors[] array to indicate choice. */
  177137. /* Return value is total number of colors (product of Ncolors[] values). */
  177138. {
  177139. int nc = cinfo->out_color_components; /* number of color components */
  177140. int max_colors = cinfo->desired_number_of_colors;
  177141. int total_colors, iroot, i, j;
  177142. boolean changed;
  177143. long temp;
  177144. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177145. /* We can allocate at least the nc'th root of max_colors per component. */
  177146. /* Compute floor(nc'th root of max_colors). */
  177147. iroot = 1;
  177148. do {
  177149. iroot++;
  177150. temp = iroot; /* set temp = iroot ** nc */
  177151. for (i = 1; i < nc; i++)
  177152. temp *= iroot;
  177153. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177154. iroot--; /* now iroot = floor(root) */
  177155. /* Must have at least 2 color values per component */
  177156. if (iroot < 2)
  177157. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177158. /* Initialize to iroot color values for each component */
  177159. total_colors = 1;
  177160. for (i = 0; i < nc; i++) {
  177161. Ncolors[i] = iroot;
  177162. total_colors *= iroot;
  177163. }
  177164. /* We may be able to increment the count for one or more components without
  177165. * exceeding max_colors, though we know not all can be incremented.
  177166. * Sometimes, the first component can be incremented more than once!
  177167. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177168. * In RGB colorspace, try to increment G first, then R, then B.
  177169. */
  177170. do {
  177171. changed = FALSE;
  177172. for (i = 0; i < nc; i++) {
  177173. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177174. /* calculate new total_colors if Ncolors[j] is incremented */
  177175. temp = total_colors / Ncolors[j];
  177176. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177177. if (temp > (long) max_colors)
  177178. break; /* won't fit, done with this pass */
  177179. Ncolors[j]++; /* OK, apply the increment */
  177180. total_colors = (int) temp;
  177181. changed = TRUE;
  177182. }
  177183. } while (changed);
  177184. return total_colors;
  177185. }
  177186. LOCAL(int)
  177187. output_value (j_decompress_ptr, int, int j, int maxj)
  177188. /* Return j'th output value, where j will range from 0 to maxj */
  177189. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177190. {
  177191. /* We always provide values 0 and MAXJSAMPLE for each component;
  177192. * any additional values are equally spaced between these limits.
  177193. * (Forcing the upper and lower values to the limits ensures that
  177194. * dithering can't produce a color outside the selected gamut.)
  177195. */
  177196. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177197. }
  177198. LOCAL(int)
  177199. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177200. /* Return largest input value that should map to j'th output value */
  177201. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177202. {
  177203. /* Breakpoints are halfway between values returned by output_value */
  177204. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177205. }
  177206. /*
  177207. * Create the colormap.
  177208. */
  177209. LOCAL(void)
  177210. create_colormap (j_decompress_ptr cinfo)
  177211. {
  177212. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177213. JSAMPARRAY colormap; /* Created colormap */
  177214. int total_colors; /* Number of distinct output colors */
  177215. int i,j,k, nci, blksize, blkdist, ptr, val;
  177216. /* Select number of colors for each component */
  177217. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177218. /* Report selected color counts */
  177219. if (cinfo->out_color_components == 3)
  177220. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177221. total_colors, cquantize->Ncolors[0],
  177222. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177223. else
  177224. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177225. /* Allocate and fill in the colormap. */
  177226. /* The colors are ordered in the map in standard row-major order, */
  177227. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177228. colormap = (*cinfo->mem->alloc_sarray)
  177229. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177230. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177231. /* blksize is number of adjacent repeated entries for a component */
  177232. /* blkdist is distance between groups of identical entries for a component */
  177233. blkdist = total_colors;
  177234. for (i = 0; i < cinfo->out_color_components; i++) {
  177235. /* fill in colormap entries for i'th color component */
  177236. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177237. blksize = blkdist / nci;
  177238. for (j = 0; j < nci; j++) {
  177239. /* Compute j'th output value (out of nci) for component */
  177240. val = output_value(cinfo, i, j, nci-1);
  177241. /* Fill in all colormap entries that have this value of this component */
  177242. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177243. /* fill in blksize entries beginning at ptr */
  177244. for (k = 0; k < blksize; k++)
  177245. colormap[i][ptr+k] = (JSAMPLE) val;
  177246. }
  177247. }
  177248. blkdist = blksize; /* blksize of this color is blkdist of next */
  177249. }
  177250. /* Save the colormap in private storage,
  177251. * where it will survive color quantization mode changes.
  177252. */
  177253. cquantize->sv_colormap = colormap;
  177254. cquantize->sv_actual = total_colors;
  177255. }
  177256. /*
  177257. * Create the color index table.
  177258. */
  177259. LOCAL(void)
  177260. create_colorindex (j_decompress_ptr cinfo)
  177261. {
  177262. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177263. JSAMPROW indexptr;
  177264. int i,j,k, nci, blksize, val, pad;
  177265. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177266. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177267. * This is not necessary in the other dithering modes. However, we
  177268. * flag whether it was done in case user changes dithering mode.
  177269. */
  177270. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177271. pad = MAXJSAMPLE*2;
  177272. cquantize->is_padded = TRUE;
  177273. } else {
  177274. pad = 0;
  177275. cquantize->is_padded = FALSE;
  177276. }
  177277. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177278. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177279. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177280. (JDIMENSION) cinfo->out_color_components);
  177281. /* blksize is number of adjacent repeated entries for a component */
  177282. blksize = cquantize->sv_actual;
  177283. for (i = 0; i < cinfo->out_color_components; i++) {
  177284. /* fill in colorindex entries for i'th color component */
  177285. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177286. blksize = blksize / nci;
  177287. /* adjust colorindex pointers to provide padding at negative indexes. */
  177288. if (pad)
  177289. cquantize->colorindex[i] += MAXJSAMPLE;
  177290. /* in loop, val = index of current output value, */
  177291. /* and k = largest j that maps to current val */
  177292. indexptr = cquantize->colorindex[i];
  177293. val = 0;
  177294. k = largest_input_value(cinfo, i, 0, nci-1);
  177295. for (j = 0; j <= MAXJSAMPLE; j++) {
  177296. while (j > k) /* advance val if past boundary */
  177297. k = largest_input_value(cinfo, i, ++val, nci-1);
  177298. /* premultiply so that no multiplication needed in main processing */
  177299. indexptr[j] = (JSAMPLE) (val * blksize);
  177300. }
  177301. /* Pad at both ends if necessary */
  177302. if (pad)
  177303. for (j = 1; j <= MAXJSAMPLE; j++) {
  177304. indexptr[-j] = indexptr[0];
  177305. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177306. }
  177307. }
  177308. }
  177309. /*
  177310. * Create an ordered-dither array for a component having ncolors
  177311. * distinct output values.
  177312. */
  177313. LOCAL(ODITHER_MATRIX_PTR)
  177314. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177315. {
  177316. ODITHER_MATRIX_PTR odither;
  177317. int j,k;
  177318. INT32 num,den;
  177319. odither = (ODITHER_MATRIX_PTR)
  177320. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177321. SIZEOF(ODITHER_MATRIX));
  177322. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177323. * Hence the dither value for the matrix cell with fill order f
  177324. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177325. * On 16-bit-int machine, be careful to avoid overflow.
  177326. */
  177327. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177328. for (j = 0; j < ODITHER_SIZE; j++) {
  177329. for (k = 0; k < ODITHER_SIZE; k++) {
  177330. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177331. * MAXJSAMPLE;
  177332. /* Ensure round towards zero despite C's lack of consistency
  177333. * about rounding negative values in integer division...
  177334. */
  177335. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177336. }
  177337. }
  177338. return odither;
  177339. }
  177340. /*
  177341. * Create the ordered-dither tables.
  177342. * Components having the same number of representative colors may
  177343. * share a dither table.
  177344. */
  177345. LOCAL(void)
  177346. create_odither_tables (j_decompress_ptr cinfo)
  177347. {
  177348. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177349. ODITHER_MATRIX_PTR odither;
  177350. int i, j, nci;
  177351. for (i = 0; i < cinfo->out_color_components; i++) {
  177352. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177353. odither = NULL; /* search for matching prior component */
  177354. for (j = 0; j < i; j++) {
  177355. if (nci == cquantize->Ncolors[j]) {
  177356. odither = cquantize->odither[j];
  177357. break;
  177358. }
  177359. }
  177360. if (odither == NULL) /* need a new table? */
  177361. odither = make_odither_array(cinfo, nci);
  177362. cquantize->odither[i] = odither;
  177363. }
  177364. }
  177365. /*
  177366. * Map some rows of pixels to the output colormapped representation.
  177367. */
  177368. METHODDEF(void)
  177369. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177370. JSAMPARRAY output_buf, int num_rows)
  177371. /* General case, no dithering */
  177372. {
  177373. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177374. JSAMPARRAY colorindex = cquantize->colorindex;
  177375. register int pixcode, ci;
  177376. register JSAMPROW ptrin, ptrout;
  177377. int row;
  177378. JDIMENSION col;
  177379. JDIMENSION width = cinfo->output_width;
  177380. register int nc = cinfo->out_color_components;
  177381. for (row = 0; row < num_rows; row++) {
  177382. ptrin = input_buf[row];
  177383. ptrout = output_buf[row];
  177384. for (col = width; col > 0; col--) {
  177385. pixcode = 0;
  177386. for (ci = 0; ci < nc; ci++) {
  177387. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177388. }
  177389. *ptrout++ = (JSAMPLE) pixcode;
  177390. }
  177391. }
  177392. }
  177393. METHODDEF(void)
  177394. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177395. JSAMPARRAY output_buf, int num_rows)
  177396. /* Fast path for out_color_components==3, no dithering */
  177397. {
  177398. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177399. register int pixcode;
  177400. register JSAMPROW ptrin, ptrout;
  177401. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177402. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177403. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177404. int row;
  177405. JDIMENSION col;
  177406. JDIMENSION width = cinfo->output_width;
  177407. for (row = 0; row < num_rows; row++) {
  177408. ptrin = input_buf[row];
  177409. ptrout = output_buf[row];
  177410. for (col = width; col > 0; col--) {
  177411. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177412. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177413. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177414. *ptrout++ = (JSAMPLE) pixcode;
  177415. }
  177416. }
  177417. }
  177418. METHODDEF(void)
  177419. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177420. JSAMPARRAY output_buf, int num_rows)
  177421. /* General case, with ordered dithering */
  177422. {
  177423. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177424. register JSAMPROW input_ptr;
  177425. register JSAMPROW output_ptr;
  177426. JSAMPROW colorindex_ci;
  177427. int * dither; /* points to active row of dither matrix */
  177428. int row_index, col_index; /* current indexes into dither matrix */
  177429. int nc = cinfo->out_color_components;
  177430. int ci;
  177431. int row;
  177432. JDIMENSION col;
  177433. JDIMENSION width = cinfo->output_width;
  177434. for (row = 0; row < num_rows; row++) {
  177435. /* Initialize output values to 0 so can process components separately */
  177436. jzero_far((void FAR *) output_buf[row],
  177437. (size_t) (width * SIZEOF(JSAMPLE)));
  177438. row_index = cquantize->row_index;
  177439. for (ci = 0; ci < nc; ci++) {
  177440. input_ptr = input_buf[row] + ci;
  177441. output_ptr = output_buf[row];
  177442. colorindex_ci = cquantize->colorindex[ci];
  177443. dither = cquantize->odither[ci][row_index];
  177444. col_index = 0;
  177445. for (col = width; col > 0; col--) {
  177446. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177447. * select output value, accumulate into output code for this pixel.
  177448. * Range-limiting need not be done explicitly, as we have extended
  177449. * the colorindex table to produce the right answers for out-of-range
  177450. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177451. * required amount of padding.
  177452. */
  177453. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177454. input_ptr += nc;
  177455. output_ptr++;
  177456. col_index = (col_index + 1) & ODITHER_MASK;
  177457. }
  177458. }
  177459. /* Advance row index for next row */
  177460. row_index = (row_index + 1) & ODITHER_MASK;
  177461. cquantize->row_index = row_index;
  177462. }
  177463. }
  177464. METHODDEF(void)
  177465. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177466. JSAMPARRAY output_buf, int num_rows)
  177467. /* Fast path for out_color_components==3, with ordered dithering */
  177468. {
  177469. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177470. register int pixcode;
  177471. register JSAMPROW input_ptr;
  177472. register JSAMPROW output_ptr;
  177473. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177474. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177475. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177476. int * dither0; /* points to active row of dither matrix */
  177477. int * dither1;
  177478. int * dither2;
  177479. int row_index, col_index; /* current indexes into dither matrix */
  177480. int row;
  177481. JDIMENSION col;
  177482. JDIMENSION width = cinfo->output_width;
  177483. for (row = 0; row < num_rows; row++) {
  177484. row_index = cquantize->row_index;
  177485. input_ptr = input_buf[row];
  177486. output_ptr = output_buf[row];
  177487. dither0 = cquantize->odither[0][row_index];
  177488. dither1 = cquantize->odither[1][row_index];
  177489. dither2 = cquantize->odither[2][row_index];
  177490. col_index = 0;
  177491. for (col = width; col > 0; col--) {
  177492. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177493. dither0[col_index]]);
  177494. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177495. dither1[col_index]]);
  177496. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177497. dither2[col_index]]);
  177498. *output_ptr++ = (JSAMPLE) pixcode;
  177499. col_index = (col_index + 1) & ODITHER_MASK;
  177500. }
  177501. row_index = (row_index + 1) & ODITHER_MASK;
  177502. cquantize->row_index = row_index;
  177503. }
  177504. }
  177505. METHODDEF(void)
  177506. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177507. JSAMPARRAY output_buf, int num_rows)
  177508. /* General case, with Floyd-Steinberg dithering */
  177509. {
  177510. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177511. register LOCFSERROR cur; /* current error or pixel value */
  177512. LOCFSERROR belowerr; /* error for pixel below cur */
  177513. LOCFSERROR bpreverr; /* error for below/prev col */
  177514. LOCFSERROR bnexterr; /* error for below/next col */
  177515. LOCFSERROR delta;
  177516. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177517. register JSAMPROW input_ptr;
  177518. register JSAMPROW output_ptr;
  177519. JSAMPROW colorindex_ci;
  177520. JSAMPROW colormap_ci;
  177521. int pixcode;
  177522. int nc = cinfo->out_color_components;
  177523. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177524. int dirnc; /* dir * nc */
  177525. int ci;
  177526. int row;
  177527. JDIMENSION col;
  177528. JDIMENSION width = cinfo->output_width;
  177529. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177530. SHIFT_TEMPS
  177531. for (row = 0; row < num_rows; row++) {
  177532. /* Initialize output values to 0 so can process components separately */
  177533. jzero_far((void FAR *) output_buf[row],
  177534. (size_t) (width * SIZEOF(JSAMPLE)));
  177535. for (ci = 0; ci < nc; ci++) {
  177536. input_ptr = input_buf[row] + ci;
  177537. output_ptr = output_buf[row];
  177538. if (cquantize->on_odd_row) {
  177539. /* work right to left in this row */
  177540. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177541. output_ptr += width-1;
  177542. dir = -1;
  177543. dirnc = -nc;
  177544. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177545. } else {
  177546. /* work left to right in this row */
  177547. dir = 1;
  177548. dirnc = nc;
  177549. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177550. }
  177551. colorindex_ci = cquantize->colorindex[ci];
  177552. colormap_ci = cquantize->sv_colormap[ci];
  177553. /* Preset error values: no error propagated to first pixel from left */
  177554. cur = 0;
  177555. /* and no error propagated to row below yet */
  177556. belowerr = bpreverr = 0;
  177557. for (col = width; col > 0; col--) {
  177558. /* cur holds the error propagated from the previous pixel on the
  177559. * current line. Add the error propagated from the previous line
  177560. * to form the complete error correction term for this pixel, and
  177561. * round the error term (which is expressed * 16) to an integer.
  177562. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177563. * for either sign of the error value.
  177564. * Note: errorptr points to *previous* column's array entry.
  177565. */
  177566. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177567. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177568. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177569. * of the range_limit array.
  177570. */
  177571. cur += GETJSAMPLE(*input_ptr);
  177572. cur = GETJSAMPLE(range_limit[cur]);
  177573. /* Select output value, accumulate into output code for this pixel */
  177574. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177575. *output_ptr += (JSAMPLE) pixcode;
  177576. /* Compute actual representation error at this pixel */
  177577. /* Note: we can do this even though we don't have the final */
  177578. /* pixel code, because the colormap is orthogonal. */
  177579. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177580. /* Compute error fractions to be propagated to adjacent pixels.
  177581. * Add these into the running sums, and simultaneously shift the
  177582. * next-line error sums left by 1 column.
  177583. */
  177584. bnexterr = cur;
  177585. delta = cur * 2;
  177586. cur += delta; /* form error * 3 */
  177587. errorptr[0] = (FSERROR) (bpreverr + cur);
  177588. cur += delta; /* form error * 5 */
  177589. bpreverr = belowerr + cur;
  177590. belowerr = bnexterr;
  177591. cur += delta; /* form error * 7 */
  177592. /* At this point cur contains the 7/16 error value to be propagated
  177593. * to the next pixel on the current line, and all the errors for the
  177594. * next line have been shifted over. We are therefore ready to move on.
  177595. */
  177596. input_ptr += dirnc; /* advance input ptr to next column */
  177597. output_ptr += dir; /* advance output ptr to next column */
  177598. errorptr += dir; /* advance errorptr to current column */
  177599. }
  177600. /* Post-loop cleanup: we must unload the final error value into the
  177601. * final fserrors[] entry. Note we need not unload belowerr because
  177602. * it is for the dummy column before or after the actual array.
  177603. */
  177604. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177605. }
  177606. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177607. }
  177608. }
  177609. /*
  177610. * Allocate workspace for Floyd-Steinberg errors.
  177611. */
  177612. LOCAL(void)
  177613. alloc_fs_workspace (j_decompress_ptr cinfo)
  177614. {
  177615. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177616. size_t arraysize;
  177617. int i;
  177618. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177619. for (i = 0; i < cinfo->out_color_components; i++) {
  177620. cquantize->fserrors[i] = (FSERRPTR)
  177621. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177622. }
  177623. }
  177624. /*
  177625. * Initialize for one-pass color quantization.
  177626. */
  177627. METHODDEF(void)
  177628. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177629. {
  177630. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177631. size_t arraysize;
  177632. int i;
  177633. /* Install my colormap. */
  177634. cinfo->colormap = cquantize->sv_colormap;
  177635. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177636. /* Initialize for desired dithering mode. */
  177637. switch (cinfo->dither_mode) {
  177638. case JDITHER_NONE:
  177639. if (cinfo->out_color_components == 3)
  177640. cquantize->pub.color_quantize = color_quantize3;
  177641. else
  177642. cquantize->pub.color_quantize = color_quantize;
  177643. break;
  177644. case JDITHER_ORDERED:
  177645. if (cinfo->out_color_components == 3)
  177646. cquantize->pub.color_quantize = quantize3_ord_dither;
  177647. else
  177648. cquantize->pub.color_quantize = quantize_ord_dither;
  177649. cquantize->row_index = 0; /* initialize state for ordered dither */
  177650. /* If user changed to ordered dither from another mode,
  177651. * we must recreate the color index table with padding.
  177652. * This will cost extra space, but probably isn't very likely.
  177653. */
  177654. if (! cquantize->is_padded)
  177655. create_colorindex(cinfo);
  177656. /* Create ordered-dither tables if we didn't already. */
  177657. if (cquantize->odither[0] == NULL)
  177658. create_odither_tables(cinfo);
  177659. break;
  177660. case JDITHER_FS:
  177661. cquantize->pub.color_quantize = quantize_fs_dither;
  177662. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177663. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177664. if (cquantize->fserrors[0] == NULL)
  177665. alloc_fs_workspace(cinfo);
  177666. /* Initialize the propagated errors to zero. */
  177667. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177668. for (i = 0; i < cinfo->out_color_components; i++)
  177669. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177670. break;
  177671. default:
  177672. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177673. break;
  177674. }
  177675. }
  177676. /*
  177677. * Finish up at the end of the pass.
  177678. */
  177679. METHODDEF(void)
  177680. finish_pass_1_quant (j_decompress_ptr)
  177681. {
  177682. /* no work in 1-pass case */
  177683. }
  177684. /*
  177685. * Switch to a new external colormap between output passes.
  177686. * Shouldn't get to this module!
  177687. */
  177688. METHODDEF(void)
  177689. new_color_map_1_quant (j_decompress_ptr cinfo)
  177690. {
  177691. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177692. }
  177693. /*
  177694. * Module initialization routine for 1-pass color quantization.
  177695. */
  177696. GLOBAL(void)
  177697. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177698. {
  177699. my_cquantize_ptr cquantize;
  177700. cquantize = (my_cquantize_ptr)
  177701. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177702. SIZEOF(my_cquantizer));
  177703. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177704. cquantize->pub.start_pass = start_pass_1_quant;
  177705. cquantize->pub.finish_pass = finish_pass_1_quant;
  177706. cquantize->pub.new_color_map = new_color_map_1_quant;
  177707. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177708. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177709. /* Make sure my internal arrays won't overflow */
  177710. if (cinfo->out_color_components > MAX_Q_COMPS)
  177711. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177712. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177713. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177714. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177715. /* Create the colormap and color index table. */
  177716. create_colormap(cinfo);
  177717. create_colorindex(cinfo);
  177718. /* Allocate Floyd-Steinberg workspace now if requested.
  177719. * We do this now since it is FAR storage and may affect the memory
  177720. * manager's space calculations. If the user changes to FS dither
  177721. * mode in a later pass, we will allocate the space then, and will
  177722. * possibly overrun the max_memory_to_use setting.
  177723. */
  177724. if (cinfo->dither_mode == JDITHER_FS)
  177725. alloc_fs_workspace(cinfo);
  177726. }
  177727. #endif /* QUANT_1PASS_SUPPORTED */
  177728. /*** End of inlined file: jquant1.c ***/
  177729. /*** Start of inlined file: jquant2.c ***/
  177730. #define JPEG_INTERNALS
  177731. #ifdef QUANT_2PASS_SUPPORTED
  177732. /*
  177733. * This module implements the well-known Heckbert paradigm for color
  177734. * quantization. Most of the ideas used here can be traced back to
  177735. * Heckbert's seminal paper
  177736. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177737. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177738. *
  177739. * In the first pass over the image, we accumulate a histogram showing the
  177740. * usage count of each possible color. To keep the histogram to a reasonable
  177741. * size, we reduce the precision of the input; typical practice is to retain
  177742. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177743. * in the same histogram cell.
  177744. *
  177745. * Next, the color-selection step begins with a box representing the whole
  177746. * color space, and repeatedly splits the "largest" remaining box until we
  177747. * have as many boxes as desired colors. Then the mean color in each
  177748. * remaining box becomes one of the possible output colors.
  177749. *
  177750. * The second pass over the image maps each input pixel to the closest output
  177751. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177752. * This mapping is logically trivial, but making it go fast enough requires
  177753. * considerable care.
  177754. *
  177755. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177756. * the "largest" box and deciding where to cut it. The particular policies
  177757. * used here have proved out well in experimental comparisons, but better ones
  177758. * may yet be found.
  177759. *
  177760. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177761. * space, processing the raw upsampled data without a color conversion step.
  177762. * This allowed the color conversion math to be done only once per colormap
  177763. * entry, not once per pixel. However, that optimization precluded other
  177764. * useful optimizations (such as merging color conversion with upsampling)
  177765. * and it also interfered with desired capabilities such as quantizing to an
  177766. * externally-supplied colormap. We have therefore abandoned that approach.
  177767. * The present code works in the post-conversion color space, typically RGB.
  177768. *
  177769. * To improve the visual quality of the results, we actually work in scaled
  177770. * RGB space, giving G distances more weight than R, and R in turn more than
  177771. * B. To do everything in integer math, we must use integer scale factors.
  177772. * The 2/3/1 scale factors used here correspond loosely to the relative
  177773. * weights of the colors in the NTSC grayscale equation.
  177774. * If you want to use this code to quantize a non-RGB color space, you'll
  177775. * probably need to change these scale factors.
  177776. */
  177777. #define R_SCALE 2 /* scale R distances by this much */
  177778. #define G_SCALE 3 /* scale G distances by this much */
  177779. #define B_SCALE 1 /* and B by this much */
  177780. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177781. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177782. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177783. * you'll get compile errors until you extend this logic. In that case
  177784. * you'll probably want to tweak the histogram sizes too.
  177785. */
  177786. #if RGB_RED == 0
  177787. #define C0_SCALE R_SCALE
  177788. #endif
  177789. #if RGB_BLUE == 0
  177790. #define C0_SCALE B_SCALE
  177791. #endif
  177792. #if RGB_GREEN == 1
  177793. #define C1_SCALE G_SCALE
  177794. #endif
  177795. #if RGB_RED == 2
  177796. #define C2_SCALE R_SCALE
  177797. #endif
  177798. #if RGB_BLUE == 2
  177799. #define C2_SCALE B_SCALE
  177800. #endif
  177801. /*
  177802. * First we have the histogram data structure and routines for creating it.
  177803. *
  177804. * The number of bits of precision can be adjusted by changing these symbols.
  177805. * We recommend keeping 6 bits for G and 5 each for R and B.
  177806. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177807. * better results; if you are short of memory, 5 bits all around will save
  177808. * some space but degrade the results.
  177809. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177810. * (preferably unsigned long) for each cell. In practice this is overkill;
  177811. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177812. * and clamping those that do overflow to the maximum value will give close-
  177813. * enough results. This reduces the recommended histogram size from 256Kb
  177814. * to 128Kb, which is a useful savings on PC-class machines.
  177815. * (In the second pass the histogram space is re-used for pixel mapping data;
  177816. * in that capacity, each cell must be able to store zero to the number of
  177817. * desired colors. 16 bits/cell is plenty for that too.)
  177818. * Since the JPEG code is intended to run in small memory model on 80x86
  177819. * machines, we can't just allocate the histogram in one chunk. Instead
  177820. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177821. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177822. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177823. * on 80x86 machines, the pointer row is in near memory but the actual
  177824. * arrays are in far memory (same arrangement as we use for image arrays).
  177825. */
  177826. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177827. /* These will do the right thing for either R,G,B or B,G,R color order,
  177828. * but you may not like the results for other color orders.
  177829. */
  177830. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177831. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177832. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177833. /* Number of elements along histogram axes. */
  177834. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177835. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177836. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177837. /* These are the amounts to shift an input value to get a histogram index. */
  177838. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177839. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177840. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177841. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177842. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177843. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177844. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177845. typedef hist2d * hist3d; /* type for top-level pointer */
  177846. /* Declarations for Floyd-Steinberg dithering.
  177847. *
  177848. * Errors are accumulated into the array fserrors[], at a resolution of
  177849. * 1/16th of a pixel count. The error at a given pixel is propagated
  177850. * to its not-yet-processed neighbors using the standard F-S fractions,
  177851. * ... (here) 7/16
  177852. * 3/16 5/16 1/16
  177853. * We work left-to-right on even rows, right-to-left on odd rows.
  177854. *
  177855. * We can get away with a single array (holding one row's worth of errors)
  177856. * by using it to store the current row's errors at pixel columns not yet
  177857. * processed, but the next row's errors at columns already processed. We
  177858. * need only a few extra variables to hold the errors immediately around the
  177859. * current column. (If we are lucky, those variables are in registers, but
  177860. * even if not, they're probably cheaper to access than array elements are.)
  177861. *
  177862. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177863. * each end saves us from special-casing the first and last pixels.
  177864. * Each entry is three values long, one value for each color component.
  177865. *
  177866. * Note: on a wide image, we might not have enough room in a PC's near data
  177867. * segment to hold the error array; so it is allocated with alloc_large.
  177868. */
  177869. #if BITS_IN_JSAMPLE == 8
  177870. typedef INT16 FSERROR; /* 16 bits should be enough */
  177871. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177872. #else
  177873. typedef INT32 FSERROR; /* may need more than 16 bits */
  177874. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177875. #endif
  177876. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177877. /* Private subobject */
  177878. typedef struct {
  177879. struct jpeg_color_quantizer pub; /* public fields */
  177880. /* Space for the eventually created colormap is stashed here */
  177881. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177882. int desired; /* desired # of colors = size of colormap */
  177883. /* Variables for accumulating image statistics */
  177884. hist3d histogram; /* pointer to the histogram */
  177885. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177886. /* Variables for Floyd-Steinberg dithering */
  177887. FSERRPTR fserrors; /* accumulated errors */
  177888. boolean on_odd_row; /* flag to remember which row we are on */
  177889. int * error_limiter; /* table for clamping the applied error */
  177890. } my_cquantizer2;
  177891. typedef my_cquantizer2 * my_cquantize_ptr2;
  177892. /*
  177893. * Prescan some rows of pixels.
  177894. * In this module the prescan simply updates the histogram, which has been
  177895. * initialized to zeroes by start_pass.
  177896. * An output_buf parameter is required by the method signature, but no data
  177897. * is actually output (in fact the buffer controller is probably passing a
  177898. * NULL pointer).
  177899. */
  177900. METHODDEF(void)
  177901. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177902. JSAMPARRAY, int num_rows)
  177903. {
  177904. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177905. register JSAMPROW ptr;
  177906. register histptr histp;
  177907. register hist3d histogram = cquantize->histogram;
  177908. int row;
  177909. JDIMENSION col;
  177910. JDIMENSION width = cinfo->output_width;
  177911. for (row = 0; row < num_rows; row++) {
  177912. ptr = input_buf[row];
  177913. for (col = width; col > 0; col--) {
  177914. /* get pixel value and index into the histogram */
  177915. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177916. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177917. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177918. /* increment, check for overflow and undo increment if so. */
  177919. if (++(*histp) <= 0)
  177920. (*histp)--;
  177921. ptr += 3;
  177922. }
  177923. }
  177924. }
  177925. /*
  177926. * Next we have the really interesting routines: selection of a colormap
  177927. * given the completed histogram.
  177928. * These routines work with a list of "boxes", each representing a rectangular
  177929. * subset of the input color space (to histogram precision).
  177930. */
  177931. typedef struct {
  177932. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177933. int c0min, c0max;
  177934. int c1min, c1max;
  177935. int c2min, c2max;
  177936. /* The volume (actually 2-norm) of the box */
  177937. INT32 volume;
  177938. /* The number of nonzero histogram cells within this box */
  177939. long colorcount;
  177940. } box;
  177941. typedef box * boxptr;
  177942. LOCAL(boxptr)
  177943. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177944. /* Find the splittable box with the largest color population */
  177945. /* Returns NULL if no splittable boxes remain */
  177946. {
  177947. register boxptr boxp;
  177948. register int i;
  177949. register long maxc = 0;
  177950. boxptr which = NULL;
  177951. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177952. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177953. which = boxp;
  177954. maxc = boxp->colorcount;
  177955. }
  177956. }
  177957. return which;
  177958. }
  177959. LOCAL(boxptr)
  177960. find_biggest_volume (boxptr boxlist, int numboxes)
  177961. /* Find the splittable box with the largest (scaled) volume */
  177962. /* Returns NULL if no splittable boxes remain */
  177963. {
  177964. register boxptr boxp;
  177965. register int i;
  177966. register INT32 maxv = 0;
  177967. boxptr which = NULL;
  177968. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177969. if (boxp->volume > maxv) {
  177970. which = boxp;
  177971. maxv = boxp->volume;
  177972. }
  177973. }
  177974. return which;
  177975. }
  177976. LOCAL(void)
  177977. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177978. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177979. /* and recompute its volume and population */
  177980. {
  177981. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177982. hist3d histogram = cquantize->histogram;
  177983. histptr histp;
  177984. int c0,c1,c2;
  177985. int c0min,c0max,c1min,c1max,c2min,c2max;
  177986. INT32 dist0,dist1,dist2;
  177987. long ccount;
  177988. c0min = boxp->c0min; c0max = boxp->c0max;
  177989. c1min = boxp->c1min; c1max = boxp->c1max;
  177990. c2min = boxp->c2min; c2max = boxp->c2max;
  177991. if (c0max > c0min)
  177992. for (c0 = c0min; c0 <= c0max; c0++)
  177993. for (c1 = c1min; c1 <= c1max; c1++) {
  177994. histp = & histogram[c0][c1][c2min];
  177995. for (c2 = c2min; c2 <= c2max; c2++)
  177996. if (*histp++ != 0) {
  177997. boxp->c0min = c0min = c0;
  177998. goto have_c0min;
  177999. }
  178000. }
  178001. have_c0min:
  178002. if (c0max > c0min)
  178003. for (c0 = c0max; c0 >= c0min; c0--)
  178004. for (c1 = c1min; c1 <= c1max; c1++) {
  178005. histp = & histogram[c0][c1][c2min];
  178006. for (c2 = c2min; c2 <= c2max; c2++)
  178007. if (*histp++ != 0) {
  178008. boxp->c0max = c0max = c0;
  178009. goto have_c0max;
  178010. }
  178011. }
  178012. have_c0max:
  178013. if (c1max > c1min)
  178014. for (c1 = c1min; c1 <= c1max; c1++)
  178015. for (c0 = c0min; c0 <= c0max; c0++) {
  178016. histp = & histogram[c0][c1][c2min];
  178017. for (c2 = c2min; c2 <= c2max; c2++)
  178018. if (*histp++ != 0) {
  178019. boxp->c1min = c1min = c1;
  178020. goto have_c1min;
  178021. }
  178022. }
  178023. have_c1min:
  178024. if (c1max > c1min)
  178025. for (c1 = c1max; c1 >= c1min; c1--)
  178026. for (c0 = c0min; c0 <= c0max; c0++) {
  178027. histp = & histogram[c0][c1][c2min];
  178028. for (c2 = c2min; c2 <= c2max; c2++)
  178029. if (*histp++ != 0) {
  178030. boxp->c1max = c1max = c1;
  178031. goto have_c1max;
  178032. }
  178033. }
  178034. have_c1max:
  178035. if (c2max > c2min)
  178036. for (c2 = c2min; c2 <= c2max; c2++)
  178037. for (c0 = c0min; c0 <= c0max; c0++) {
  178038. histp = & histogram[c0][c1min][c2];
  178039. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178040. if (*histp != 0) {
  178041. boxp->c2min = c2min = c2;
  178042. goto have_c2min;
  178043. }
  178044. }
  178045. have_c2min:
  178046. if (c2max > c2min)
  178047. for (c2 = c2max; c2 >= c2min; c2--)
  178048. for (c0 = c0min; c0 <= c0max; c0++) {
  178049. histp = & histogram[c0][c1min][c2];
  178050. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178051. if (*histp != 0) {
  178052. boxp->c2max = c2max = c2;
  178053. goto have_c2max;
  178054. }
  178055. }
  178056. have_c2max:
  178057. /* Update box volume.
  178058. * We use 2-norm rather than real volume here; this biases the method
  178059. * against making long narrow boxes, and it has the side benefit that
  178060. * a box is splittable iff norm > 0.
  178061. * Since the differences are expressed in histogram-cell units,
  178062. * we have to shift back to JSAMPLE units to get consistent distances;
  178063. * after which, we scale according to the selected distance scale factors.
  178064. */
  178065. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178066. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178067. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178068. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178069. /* Now scan remaining volume of box and compute population */
  178070. ccount = 0;
  178071. for (c0 = c0min; c0 <= c0max; c0++)
  178072. for (c1 = c1min; c1 <= c1max; c1++) {
  178073. histp = & histogram[c0][c1][c2min];
  178074. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178075. if (*histp != 0) {
  178076. ccount++;
  178077. }
  178078. }
  178079. boxp->colorcount = ccount;
  178080. }
  178081. LOCAL(int)
  178082. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178083. int desired_colors)
  178084. /* Repeatedly select and split the largest box until we have enough boxes */
  178085. {
  178086. int n,lb;
  178087. int c0,c1,c2,cmax;
  178088. register boxptr b1,b2;
  178089. while (numboxes < desired_colors) {
  178090. /* Select box to split.
  178091. * Current algorithm: by population for first half, then by volume.
  178092. */
  178093. if (numboxes*2 <= desired_colors) {
  178094. b1 = find_biggest_color_pop(boxlist, numboxes);
  178095. } else {
  178096. b1 = find_biggest_volume(boxlist, numboxes);
  178097. }
  178098. if (b1 == NULL) /* no splittable boxes left! */
  178099. break;
  178100. b2 = &boxlist[numboxes]; /* where new box will go */
  178101. /* Copy the color bounds to the new box. */
  178102. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178103. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178104. /* Choose which axis to split the box on.
  178105. * Current algorithm: longest scaled axis.
  178106. * See notes in update_box about scaling distances.
  178107. */
  178108. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178109. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178110. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178111. /* We want to break any ties in favor of green, then red, blue last.
  178112. * This code does the right thing for R,G,B or B,G,R color orders only.
  178113. */
  178114. #if RGB_RED == 0
  178115. cmax = c1; n = 1;
  178116. if (c0 > cmax) { cmax = c0; n = 0; }
  178117. if (c2 > cmax) { n = 2; }
  178118. #else
  178119. cmax = c1; n = 1;
  178120. if (c2 > cmax) { cmax = c2; n = 2; }
  178121. if (c0 > cmax) { n = 0; }
  178122. #endif
  178123. /* Choose split point along selected axis, and update box bounds.
  178124. * Current algorithm: split at halfway point.
  178125. * (Since the box has been shrunk to minimum volume,
  178126. * any split will produce two nonempty subboxes.)
  178127. * Note that lb value is max for lower box, so must be < old max.
  178128. */
  178129. switch (n) {
  178130. case 0:
  178131. lb = (b1->c0max + b1->c0min) / 2;
  178132. b1->c0max = lb;
  178133. b2->c0min = lb+1;
  178134. break;
  178135. case 1:
  178136. lb = (b1->c1max + b1->c1min) / 2;
  178137. b1->c1max = lb;
  178138. b2->c1min = lb+1;
  178139. break;
  178140. case 2:
  178141. lb = (b1->c2max + b1->c2min) / 2;
  178142. b1->c2max = lb;
  178143. b2->c2min = lb+1;
  178144. break;
  178145. }
  178146. /* Update stats for boxes */
  178147. update_box(cinfo, b1);
  178148. update_box(cinfo, b2);
  178149. numboxes++;
  178150. }
  178151. return numboxes;
  178152. }
  178153. LOCAL(void)
  178154. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178155. /* Compute representative color for a box, put it in colormap[icolor] */
  178156. {
  178157. /* Current algorithm: mean weighted by pixels (not colors) */
  178158. /* Note it is important to get the rounding correct! */
  178159. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178160. hist3d histogram = cquantize->histogram;
  178161. histptr histp;
  178162. int c0,c1,c2;
  178163. int c0min,c0max,c1min,c1max,c2min,c2max;
  178164. long count;
  178165. long total = 0;
  178166. long c0total = 0;
  178167. long c1total = 0;
  178168. long c2total = 0;
  178169. c0min = boxp->c0min; c0max = boxp->c0max;
  178170. c1min = boxp->c1min; c1max = boxp->c1max;
  178171. c2min = boxp->c2min; c2max = boxp->c2max;
  178172. for (c0 = c0min; c0 <= c0max; c0++)
  178173. for (c1 = c1min; c1 <= c1max; c1++) {
  178174. histp = & histogram[c0][c1][c2min];
  178175. for (c2 = c2min; c2 <= c2max; c2++) {
  178176. if ((count = *histp++) != 0) {
  178177. total += count;
  178178. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178179. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178180. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178181. }
  178182. }
  178183. }
  178184. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178185. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178186. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178187. }
  178188. LOCAL(void)
  178189. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178190. /* Master routine for color selection */
  178191. {
  178192. boxptr boxlist;
  178193. int numboxes;
  178194. int i;
  178195. /* Allocate workspace for box list */
  178196. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178197. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178198. /* Initialize one box containing whole space */
  178199. numboxes = 1;
  178200. boxlist[0].c0min = 0;
  178201. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178202. boxlist[0].c1min = 0;
  178203. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178204. boxlist[0].c2min = 0;
  178205. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178206. /* Shrink it to actually-used volume and set its statistics */
  178207. update_box(cinfo, & boxlist[0]);
  178208. /* Perform median-cut to produce final box list */
  178209. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178210. /* Compute the representative color for each box, fill colormap */
  178211. for (i = 0; i < numboxes; i++)
  178212. compute_color(cinfo, & boxlist[i], i);
  178213. cinfo->actual_number_of_colors = numboxes;
  178214. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178215. }
  178216. /*
  178217. * These routines are concerned with the time-critical task of mapping input
  178218. * colors to the nearest color in the selected colormap.
  178219. *
  178220. * We re-use the histogram space as an "inverse color map", essentially a
  178221. * cache for the results of nearest-color searches. All colors within a
  178222. * histogram cell will be mapped to the same colormap entry, namely the one
  178223. * closest to the cell's center. This may not be quite the closest entry to
  178224. * the actual input color, but it's almost as good. A zero in the cache
  178225. * indicates we haven't found the nearest color for that cell yet; the array
  178226. * is cleared to zeroes before starting the mapping pass. When we find the
  178227. * nearest color for a cell, its colormap index plus one is recorded in the
  178228. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178229. * when they need to use an unfilled entry in the cache.
  178230. *
  178231. * Our method of efficiently finding nearest colors is based on the "locally
  178232. * sorted search" idea described by Heckbert and on the incremental distance
  178233. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178234. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178235. * the distances from a given colormap entry to each cell of the histogram can
  178236. * be computed quickly using an incremental method: the differences between
  178237. * distances to adjacent cells themselves differ by a constant. This allows a
  178238. * fairly fast implementation of the "brute force" approach of computing the
  178239. * distance from every colormap entry to every histogram cell. Unfortunately,
  178240. * it needs a work array to hold the best-distance-so-far for each histogram
  178241. * cell (because the inner loop has to be over cells, not colormap entries).
  178242. * The work array elements have to be INT32s, so the work array would need
  178243. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178244. *
  178245. * To get around these problems, we apply Thomas' method to compute the
  178246. * nearest colors for only the cells within a small subbox of the histogram.
  178247. * The work array need be only as big as the subbox, so the memory usage
  178248. * problem is solved. Furthermore, we need not fill subboxes that are never
  178249. * referenced in pass2; many images use only part of the color gamut, so a
  178250. * fair amount of work is saved. An additional advantage of this
  178251. * approach is that we can apply Heckbert's locality criterion to quickly
  178252. * eliminate colormap entries that are far away from the subbox; typically
  178253. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178254. * and we need not compute their distances to individual cells in the subbox.
  178255. * The speed of this approach is heavily influenced by the subbox size: too
  178256. * small means too much overhead, too big loses because Heckbert's criterion
  178257. * can't eliminate as many colormap entries. Empirically the best subbox
  178258. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178259. *
  178260. * Thomas' article also describes a refined method which is asymptotically
  178261. * faster than the brute-force method, but it is also far more complex and
  178262. * cannot efficiently be applied to small subboxes. It is therefore not
  178263. * useful for programs intended to be portable to DOS machines. On machines
  178264. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178265. * refined method might be faster than the present code --- but then again,
  178266. * it might not be any faster, and it's certainly more complicated.
  178267. */
  178268. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178269. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178270. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178271. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178272. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178273. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178274. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178275. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178276. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178277. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178278. /*
  178279. * The next three routines implement inverse colormap filling. They could
  178280. * all be folded into one big routine, but splitting them up this way saves
  178281. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178282. * and may allow some compilers to produce better code by registerizing more
  178283. * inner-loop variables.
  178284. */
  178285. LOCAL(int)
  178286. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178287. JSAMPLE colorlist[])
  178288. /* Locate the colormap entries close enough to an update box to be candidates
  178289. * for the nearest entry to some cell(s) in the update box. The update box
  178290. * is specified by the center coordinates of its first cell. The number of
  178291. * candidate colormap entries is returned, and their colormap indexes are
  178292. * placed in colorlist[].
  178293. * This routine uses Heckbert's "locally sorted search" criterion to select
  178294. * the colors that need further consideration.
  178295. */
  178296. {
  178297. int numcolors = cinfo->actual_number_of_colors;
  178298. int maxc0, maxc1, maxc2;
  178299. int centerc0, centerc1, centerc2;
  178300. int i, x, ncolors;
  178301. INT32 minmaxdist, min_dist, max_dist, tdist;
  178302. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178303. /* Compute true coordinates of update box's upper corner and center.
  178304. * Actually we compute the coordinates of the center of the upper-corner
  178305. * histogram cell, which are the upper bounds of the volume we care about.
  178306. * Note that since ">>" rounds down, the "center" values may be closer to
  178307. * min than to max; hence comparisons to them must be "<=", not "<".
  178308. */
  178309. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178310. centerc0 = (minc0 + maxc0) >> 1;
  178311. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178312. centerc1 = (minc1 + maxc1) >> 1;
  178313. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178314. centerc2 = (minc2 + maxc2) >> 1;
  178315. /* For each color in colormap, find:
  178316. * 1. its minimum squared-distance to any point in the update box
  178317. * (zero if color is within update box);
  178318. * 2. its maximum squared-distance to any point in the update box.
  178319. * Both of these can be found by considering only the corners of the box.
  178320. * We save the minimum distance for each color in mindist[];
  178321. * only the smallest maximum distance is of interest.
  178322. */
  178323. minmaxdist = 0x7FFFFFFFL;
  178324. for (i = 0; i < numcolors; i++) {
  178325. /* We compute the squared-c0-distance term, then add in the other two. */
  178326. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178327. if (x < minc0) {
  178328. tdist = (x - minc0) * C0_SCALE;
  178329. min_dist = tdist*tdist;
  178330. tdist = (x - maxc0) * C0_SCALE;
  178331. max_dist = tdist*tdist;
  178332. } else if (x > maxc0) {
  178333. tdist = (x - maxc0) * C0_SCALE;
  178334. min_dist = tdist*tdist;
  178335. tdist = (x - minc0) * C0_SCALE;
  178336. max_dist = tdist*tdist;
  178337. } else {
  178338. /* within cell range so no contribution to min_dist */
  178339. min_dist = 0;
  178340. if (x <= centerc0) {
  178341. tdist = (x - maxc0) * C0_SCALE;
  178342. max_dist = tdist*tdist;
  178343. } else {
  178344. tdist = (x - minc0) * C0_SCALE;
  178345. max_dist = tdist*tdist;
  178346. }
  178347. }
  178348. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178349. if (x < minc1) {
  178350. tdist = (x - minc1) * C1_SCALE;
  178351. min_dist += tdist*tdist;
  178352. tdist = (x - maxc1) * C1_SCALE;
  178353. max_dist += tdist*tdist;
  178354. } else if (x > maxc1) {
  178355. tdist = (x - maxc1) * C1_SCALE;
  178356. min_dist += tdist*tdist;
  178357. tdist = (x - minc1) * C1_SCALE;
  178358. max_dist += tdist*tdist;
  178359. } else {
  178360. /* within cell range so no contribution to min_dist */
  178361. if (x <= centerc1) {
  178362. tdist = (x - maxc1) * C1_SCALE;
  178363. max_dist += tdist*tdist;
  178364. } else {
  178365. tdist = (x - minc1) * C1_SCALE;
  178366. max_dist += tdist*tdist;
  178367. }
  178368. }
  178369. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178370. if (x < minc2) {
  178371. tdist = (x - minc2) * C2_SCALE;
  178372. min_dist += tdist*tdist;
  178373. tdist = (x - maxc2) * C2_SCALE;
  178374. max_dist += tdist*tdist;
  178375. } else if (x > maxc2) {
  178376. tdist = (x - maxc2) * C2_SCALE;
  178377. min_dist += tdist*tdist;
  178378. tdist = (x - minc2) * C2_SCALE;
  178379. max_dist += tdist*tdist;
  178380. } else {
  178381. /* within cell range so no contribution to min_dist */
  178382. if (x <= centerc2) {
  178383. tdist = (x - maxc2) * C2_SCALE;
  178384. max_dist += tdist*tdist;
  178385. } else {
  178386. tdist = (x - minc2) * C2_SCALE;
  178387. max_dist += tdist*tdist;
  178388. }
  178389. }
  178390. mindist[i] = min_dist; /* save away the results */
  178391. if (max_dist < minmaxdist)
  178392. minmaxdist = max_dist;
  178393. }
  178394. /* Now we know that no cell in the update box is more than minmaxdist
  178395. * away from some colormap entry. Therefore, only colors that are
  178396. * within minmaxdist of some part of the box need be considered.
  178397. */
  178398. ncolors = 0;
  178399. for (i = 0; i < numcolors; i++) {
  178400. if (mindist[i] <= minmaxdist)
  178401. colorlist[ncolors++] = (JSAMPLE) i;
  178402. }
  178403. return ncolors;
  178404. }
  178405. LOCAL(void)
  178406. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178407. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178408. /* Find the closest colormap entry for each cell in the update box,
  178409. * given the list of candidate colors prepared by find_nearby_colors.
  178410. * Return the indexes of the closest entries in the bestcolor[] array.
  178411. * This routine uses Thomas' incremental distance calculation method to
  178412. * find the distance from a colormap entry to successive cells in the box.
  178413. */
  178414. {
  178415. int ic0, ic1, ic2;
  178416. int i, icolor;
  178417. register INT32 * bptr; /* pointer into bestdist[] array */
  178418. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178419. INT32 dist0, dist1; /* initial distance values */
  178420. register INT32 dist2; /* current distance in inner loop */
  178421. INT32 xx0, xx1; /* distance increments */
  178422. register INT32 xx2;
  178423. INT32 inc0, inc1, inc2; /* initial values for increments */
  178424. /* This array holds the distance to the nearest-so-far color for each cell */
  178425. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178426. /* Initialize best-distance for each cell of the update box */
  178427. bptr = bestdist;
  178428. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178429. *bptr++ = 0x7FFFFFFFL;
  178430. /* For each color selected by find_nearby_colors,
  178431. * compute its distance to the center of each cell in the box.
  178432. * If that's less than best-so-far, update best distance and color number.
  178433. */
  178434. /* Nominal steps between cell centers ("x" in Thomas article) */
  178435. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178436. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178437. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178438. for (i = 0; i < numcolors; i++) {
  178439. icolor = GETJSAMPLE(colorlist[i]);
  178440. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178441. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178442. dist0 = inc0*inc0;
  178443. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178444. dist0 += inc1*inc1;
  178445. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178446. dist0 += inc2*inc2;
  178447. /* Form the initial difference increments */
  178448. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178449. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178450. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178451. /* Now loop over all cells in box, updating distance per Thomas method */
  178452. bptr = bestdist;
  178453. cptr = bestcolor;
  178454. xx0 = inc0;
  178455. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178456. dist1 = dist0;
  178457. xx1 = inc1;
  178458. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178459. dist2 = dist1;
  178460. xx2 = inc2;
  178461. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178462. if (dist2 < *bptr) {
  178463. *bptr = dist2;
  178464. *cptr = (JSAMPLE) icolor;
  178465. }
  178466. dist2 += xx2;
  178467. xx2 += 2 * STEP_C2 * STEP_C2;
  178468. bptr++;
  178469. cptr++;
  178470. }
  178471. dist1 += xx1;
  178472. xx1 += 2 * STEP_C1 * STEP_C1;
  178473. }
  178474. dist0 += xx0;
  178475. xx0 += 2 * STEP_C0 * STEP_C0;
  178476. }
  178477. }
  178478. }
  178479. LOCAL(void)
  178480. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178481. /* Fill the inverse-colormap entries in the update box that contains */
  178482. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178483. /* we can fill as many others as we wish.) */
  178484. {
  178485. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178486. hist3d histogram = cquantize->histogram;
  178487. int minc0, minc1, minc2; /* lower left corner of update box */
  178488. int ic0, ic1, ic2;
  178489. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178490. register histptr cachep; /* pointer into main cache array */
  178491. /* This array lists the candidate colormap indexes. */
  178492. JSAMPLE colorlist[MAXNUMCOLORS];
  178493. int numcolors; /* number of candidate colors */
  178494. /* This array holds the actually closest colormap index for each cell. */
  178495. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178496. /* Convert cell coordinates to update box ID */
  178497. c0 >>= BOX_C0_LOG;
  178498. c1 >>= BOX_C1_LOG;
  178499. c2 >>= BOX_C2_LOG;
  178500. /* Compute true coordinates of update box's origin corner.
  178501. * Actually we compute the coordinates of the center of the corner
  178502. * histogram cell, which are the lower bounds of the volume we care about.
  178503. */
  178504. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178505. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178506. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178507. /* Determine which colormap entries are close enough to be candidates
  178508. * for the nearest entry to some cell in the update box.
  178509. */
  178510. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178511. /* Determine the actually nearest colors. */
  178512. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178513. bestcolor);
  178514. /* Save the best color numbers (plus 1) in the main cache array */
  178515. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178516. c1 <<= BOX_C1_LOG;
  178517. c2 <<= BOX_C2_LOG;
  178518. cptr = bestcolor;
  178519. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178520. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178521. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178522. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178523. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178524. }
  178525. }
  178526. }
  178527. }
  178528. /*
  178529. * Map some rows of pixels to the output colormapped representation.
  178530. */
  178531. METHODDEF(void)
  178532. pass2_no_dither (j_decompress_ptr cinfo,
  178533. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178534. /* This version performs no dithering */
  178535. {
  178536. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178537. hist3d histogram = cquantize->histogram;
  178538. register JSAMPROW inptr, outptr;
  178539. register histptr cachep;
  178540. register int c0, c1, c2;
  178541. int row;
  178542. JDIMENSION col;
  178543. JDIMENSION width = cinfo->output_width;
  178544. for (row = 0; row < num_rows; row++) {
  178545. inptr = input_buf[row];
  178546. outptr = output_buf[row];
  178547. for (col = width; col > 0; col--) {
  178548. /* get pixel value and index into the cache */
  178549. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178550. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178551. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178552. cachep = & histogram[c0][c1][c2];
  178553. /* If we have not seen this color before, find nearest colormap entry */
  178554. /* and update the cache */
  178555. if (*cachep == 0)
  178556. fill_inverse_cmap(cinfo, c0,c1,c2);
  178557. /* Now emit the colormap index for this cell */
  178558. *outptr++ = (JSAMPLE) (*cachep - 1);
  178559. }
  178560. }
  178561. }
  178562. METHODDEF(void)
  178563. pass2_fs_dither (j_decompress_ptr cinfo,
  178564. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178565. /* This version performs Floyd-Steinberg dithering */
  178566. {
  178567. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178568. hist3d histogram = cquantize->histogram;
  178569. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178570. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178571. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178572. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178573. JSAMPROW inptr; /* => current input pixel */
  178574. JSAMPROW outptr; /* => current output pixel */
  178575. histptr cachep;
  178576. int dir; /* +1 or -1 depending on direction */
  178577. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178578. int row;
  178579. JDIMENSION col;
  178580. JDIMENSION width = cinfo->output_width;
  178581. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178582. int *error_limit = cquantize->error_limiter;
  178583. JSAMPROW colormap0 = cinfo->colormap[0];
  178584. JSAMPROW colormap1 = cinfo->colormap[1];
  178585. JSAMPROW colormap2 = cinfo->colormap[2];
  178586. SHIFT_TEMPS
  178587. for (row = 0; row < num_rows; row++) {
  178588. inptr = input_buf[row];
  178589. outptr = output_buf[row];
  178590. if (cquantize->on_odd_row) {
  178591. /* work right to left in this row */
  178592. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178593. outptr += width-1;
  178594. dir = -1;
  178595. dir3 = -3;
  178596. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178597. cquantize->on_odd_row = FALSE; /* flip for next time */
  178598. } else {
  178599. /* work left to right in this row */
  178600. dir = 1;
  178601. dir3 = 3;
  178602. errorptr = cquantize->fserrors; /* => entry before first real column */
  178603. cquantize->on_odd_row = TRUE; /* flip for next time */
  178604. }
  178605. /* Preset error values: no error propagated to first pixel from left */
  178606. cur0 = cur1 = cur2 = 0;
  178607. /* and no error propagated to row below yet */
  178608. belowerr0 = belowerr1 = belowerr2 = 0;
  178609. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178610. for (col = width; col > 0; col--) {
  178611. /* curN holds the error propagated from the previous pixel on the
  178612. * current line. Add the error propagated from the previous line
  178613. * to form the complete error correction term for this pixel, and
  178614. * round the error term (which is expressed * 16) to an integer.
  178615. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178616. * for either sign of the error value.
  178617. * Note: errorptr points to *previous* column's array entry.
  178618. */
  178619. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178620. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178621. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178622. /* Limit the error using transfer function set by init_error_limit.
  178623. * See comments with init_error_limit for rationale.
  178624. */
  178625. cur0 = error_limit[cur0];
  178626. cur1 = error_limit[cur1];
  178627. cur2 = error_limit[cur2];
  178628. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178629. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178630. * this sets the required size of the range_limit array.
  178631. */
  178632. cur0 += GETJSAMPLE(inptr[0]);
  178633. cur1 += GETJSAMPLE(inptr[1]);
  178634. cur2 += GETJSAMPLE(inptr[2]);
  178635. cur0 = GETJSAMPLE(range_limit[cur0]);
  178636. cur1 = GETJSAMPLE(range_limit[cur1]);
  178637. cur2 = GETJSAMPLE(range_limit[cur2]);
  178638. /* Index into the cache with adjusted pixel value */
  178639. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178640. /* If we have not seen this color before, find nearest colormap */
  178641. /* entry and update the cache */
  178642. if (*cachep == 0)
  178643. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178644. /* Now emit the colormap index for this cell */
  178645. { register int pixcode = *cachep - 1;
  178646. *outptr = (JSAMPLE) pixcode;
  178647. /* Compute representation error for this pixel */
  178648. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178649. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178650. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178651. }
  178652. /* Compute error fractions to be propagated to adjacent pixels.
  178653. * Add these into the running sums, and simultaneously shift the
  178654. * next-line error sums left by 1 column.
  178655. */
  178656. { register LOCFSERROR bnexterr, delta;
  178657. bnexterr = cur0; /* Process component 0 */
  178658. delta = cur0 * 2;
  178659. cur0 += delta; /* form error * 3 */
  178660. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178661. cur0 += delta; /* form error * 5 */
  178662. bpreverr0 = belowerr0 + cur0;
  178663. belowerr0 = bnexterr;
  178664. cur0 += delta; /* form error * 7 */
  178665. bnexterr = cur1; /* Process component 1 */
  178666. delta = cur1 * 2;
  178667. cur1 += delta; /* form error * 3 */
  178668. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178669. cur1 += delta; /* form error * 5 */
  178670. bpreverr1 = belowerr1 + cur1;
  178671. belowerr1 = bnexterr;
  178672. cur1 += delta; /* form error * 7 */
  178673. bnexterr = cur2; /* Process component 2 */
  178674. delta = cur2 * 2;
  178675. cur2 += delta; /* form error * 3 */
  178676. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178677. cur2 += delta; /* form error * 5 */
  178678. bpreverr2 = belowerr2 + cur2;
  178679. belowerr2 = bnexterr;
  178680. cur2 += delta; /* form error * 7 */
  178681. }
  178682. /* At this point curN contains the 7/16 error value to be propagated
  178683. * to the next pixel on the current line, and all the errors for the
  178684. * next line have been shifted over. We are therefore ready to move on.
  178685. */
  178686. inptr += dir3; /* Advance pixel pointers to next column */
  178687. outptr += dir;
  178688. errorptr += dir3; /* advance errorptr to current column */
  178689. }
  178690. /* Post-loop cleanup: we must unload the final error values into the
  178691. * final fserrors[] entry. Note we need not unload belowerrN because
  178692. * it is for the dummy column before or after the actual array.
  178693. */
  178694. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178695. errorptr[1] = (FSERROR) bpreverr1;
  178696. errorptr[2] = (FSERROR) bpreverr2;
  178697. }
  178698. }
  178699. /*
  178700. * Initialize the error-limiting transfer function (lookup table).
  178701. * The raw F-S error computation can potentially compute error values of up to
  178702. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178703. * much less, otherwise obviously wrong pixels will be created. (Typical
  178704. * effects include weird fringes at color-area boundaries, isolated bright
  178705. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178706. * is to ensure that the "corners" of the color cube are allocated as output
  178707. * colors; then repeated errors in the same direction cannot cause cascading
  178708. * error buildup. However, that only prevents the error from getting
  178709. * completely out of hand; Aaron Giles reports that error limiting improves
  178710. * the results even with corner colors allocated.
  178711. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178712. * well, but the smoother transfer function used below is even better. Thanks
  178713. * to Aaron Giles for this idea.
  178714. */
  178715. LOCAL(void)
  178716. init_error_limit (j_decompress_ptr cinfo)
  178717. /* Allocate and fill in the error_limiter table */
  178718. {
  178719. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178720. int * table;
  178721. int in, out;
  178722. table = (int *) (*cinfo->mem->alloc_small)
  178723. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178724. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178725. cquantize->error_limiter = table;
  178726. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178727. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178728. out = 0;
  178729. for (in = 0; in < STEPSIZE; in++, out++) {
  178730. table[in] = out; table[-in] = -out;
  178731. }
  178732. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178733. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178734. table[in] = out; table[-in] = -out;
  178735. }
  178736. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178737. for (; in <= MAXJSAMPLE; in++) {
  178738. table[in] = out; table[-in] = -out;
  178739. }
  178740. #undef STEPSIZE
  178741. }
  178742. /*
  178743. * Finish up at the end of each pass.
  178744. */
  178745. METHODDEF(void)
  178746. finish_pass1 (j_decompress_ptr cinfo)
  178747. {
  178748. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178749. /* Select the representative colors and fill in cinfo->colormap */
  178750. cinfo->colormap = cquantize->sv_colormap;
  178751. select_colors(cinfo, cquantize->desired);
  178752. /* Force next pass to zero the color index table */
  178753. cquantize->needs_zeroed = TRUE;
  178754. }
  178755. METHODDEF(void)
  178756. finish_pass2 (j_decompress_ptr)
  178757. {
  178758. /* no work */
  178759. }
  178760. /*
  178761. * Initialize for each processing pass.
  178762. */
  178763. METHODDEF(void)
  178764. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178765. {
  178766. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178767. hist3d histogram = cquantize->histogram;
  178768. int i;
  178769. /* Only F-S dithering or no dithering is supported. */
  178770. /* If user asks for ordered dither, give him F-S. */
  178771. if (cinfo->dither_mode != JDITHER_NONE)
  178772. cinfo->dither_mode = JDITHER_FS;
  178773. if (is_pre_scan) {
  178774. /* Set up method pointers */
  178775. cquantize->pub.color_quantize = prescan_quantize;
  178776. cquantize->pub.finish_pass = finish_pass1;
  178777. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178778. } else {
  178779. /* Set up method pointers */
  178780. if (cinfo->dither_mode == JDITHER_FS)
  178781. cquantize->pub.color_quantize = pass2_fs_dither;
  178782. else
  178783. cquantize->pub.color_quantize = pass2_no_dither;
  178784. cquantize->pub.finish_pass = finish_pass2;
  178785. /* Make sure color count is acceptable */
  178786. i = cinfo->actual_number_of_colors;
  178787. if (i < 1)
  178788. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178789. if (i > MAXNUMCOLORS)
  178790. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178791. if (cinfo->dither_mode == JDITHER_FS) {
  178792. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178793. (3 * SIZEOF(FSERROR)));
  178794. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178795. if (cquantize->fserrors == NULL)
  178796. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178797. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178798. /* Initialize the propagated errors to zero. */
  178799. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178800. /* Make the error-limit table if we didn't already. */
  178801. if (cquantize->error_limiter == NULL)
  178802. init_error_limit(cinfo);
  178803. cquantize->on_odd_row = FALSE;
  178804. }
  178805. }
  178806. /* Zero the histogram or inverse color map, if necessary */
  178807. if (cquantize->needs_zeroed) {
  178808. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178809. jzero_far((void FAR *) histogram[i],
  178810. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178811. }
  178812. cquantize->needs_zeroed = FALSE;
  178813. }
  178814. }
  178815. /*
  178816. * Switch to a new external colormap between output passes.
  178817. */
  178818. METHODDEF(void)
  178819. new_color_map_2_quant (j_decompress_ptr cinfo)
  178820. {
  178821. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178822. /* Reset the inverse color map */
  178823. cquantize->needs_zeroed = TRUE;
  178824. }
  178825. /*
  178826. * Module initialization routine for 2-pass color quantization.
  178827. */
  178828. GLOBAL(void)
  178829. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178830. {
  178831. my_cquantize_ptr2 cquantize;
  178832. int i;
  178833. cquantize = (my_cquantize_ptr2)
  178834. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178835. SIZEOF(my_cquantizer2));
  178836. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178837. cquantize->pub.start_pass = start_pass_2_quant;
  178838. cquantize->pub.new_color_map = new_color_map_2_quant;
  178839. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178840. cquantize->error_limiter = NULL;
  178841. /* Make sure jdmaster didn't give me a case I can't handle */
  178842. if (cinfo->out_color_components != 3)
  178843. ERREXIT(cinfo, JERR_NOTIMPL);
  178844. /* Allocate the histogram/inverse colormap storage */
  178845. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178846. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178847. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178848. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178849. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178850. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178851. }
  178852. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178853. /* Allocate storage for the completed colormap, if required.
  178854. * We do this now since it is FAR storage and may affect
  178855. * the memory manager's space calculations.
  178856. */
  178857. if (cinfo->enable_2pass_quant) {
  178858. /* Make sure color count is acceptable */
  178859. int desired = cinfo->desired_number_of_colors;
  178860. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178861. if (desired < 8)
  178862. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178863. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178864. if (desired > MAXNUMCOLORS)
  178865. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178866. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178867. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178868. cquantize->desired = desired;
  178869. } else
  178870. cquantize->sv_colormap = NULL;
  178871. /* Only F-S dithering or no dithering is supported. */
  178872. /* If user asks for ordered dither, give him F-S. */
  178873. if (cinfo->dither_mode != JDITHER_NONE)
  178874. cinfo->dither_mode = JDITHER_FS;
  178875. /* Allocate Floyd-Steinberg workspace if necessary.
  178876. * This isn't really needed until pass 2, but again it is FAR storage.
  178877. * Although we will cope with a later change in dither_mode,
  178878. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178879. */
  178880. if (cinfo->dither_mode == JDITHER_FS) {
  178881. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178882. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178883. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178884. /* Might as well create the error-limiting table too. */
  178885. init_error_limit(cinfo);
  178886. }
  178887. }
  178888. #endif /* QUANT_2PASS_SUPPORTED */
  178889. /*** End of inlined file: jquant2.c ***/
  178890. /*** Start of inlined file: jutils.c ***/
  178891. #define JPEG_INTERNALS
  178892. /*
  178893. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178894. * of a DCT block read in natural order (left to right, top to bottom).
  178895. */
  178896. #if 0 /* This table is not actually needed in v6a */
  178897. const int jpeg_zigzag_order[DCTSIZE2] = {
  178898. 0, 1, 5, 6, 14, 15, 27, 28,
  178899. 2, 4, 7, 13, 16, 26, 29, 42,
  178900. 3, 8, 12, 17, 25, 30, 41, 43,
  178901. 9, 11, 18, 24, 31, 40, 44, 53,
  178902. 10, 19, 23, 32, 39, 45, 52, 54,
  178903. 20, 22, 33, 38, 46, 51, 55, 60,
  178904. 21, 34, 37, 47, 50, 56, 59, 61,
  178905. 35, 36, 48, 49, 57, 58, 62, 63
  178906. };
  178907. #endif
  178908. /*
  178909. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178910. * of zigzag order.
  178911. *
  178912. * When reading corrupted data, the Huffman decoders could attempt
  178913. * to reference an entry beyond the end of this array (if the decoded
  178914. * zero run length reaches past the end of the block). To prevent
  178915. * wild stores without adding an inner-loop test, we put some extra
  178916. * "63"s after the real entries. This will cause the extra coefficient
  178917. * to be stored in location 63 of the block, not somewhere random.
  178918. * The worst case would be a run-length of 15, which means we need 16
  178919. * fake entries.
  178920. */
  178921. const int jpeg_natural_order[DCTSIZE2+16] = {
  178922. 0, 1, 8, 16, 9, 2, 3, 10,
  178923. 17, 24, 32, 25, 18, 11, 4, 5,
  178924. 12, 19, 26, 33, 40, 48, 41, 34,
  178925. 27, 20, 13, 6, 7, 14, 21, 28,
  178926. 35, 42, 49, 56, 57, 50, 43, 36,
  178927. 29, 22, 15, 23, 30, 37, 44, 51,
  178928. 58, 59, 52, 45, 38, 31, 39, 46,
  178929. 53, 60, 61, 54, 47, 55, 62, 63,
  178930. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178931. 63, 63, 63, 63, 63, 63, 63, 63
  178932. };
  178933. /*
  178934. * Arithmetic utilities
  178935. */
  178936. GLOBAL(long)
  178937. jdiv_round_up (long a, long b)
  178938. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178939. /* Assumes a >= 0, b > 0 */
  178940. {
  178941. return (a + b - 1L) / b;
  178942. }
  178943. GLOBAL(long)
  178944. jround_up (long a, long b)
  178945. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178946. /* Assumes a >= 0, b > 0 */
  178947. {
  178948. a += b - 1L;
  178949. return a - (a % b);
  178950. }
  178951. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178952. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178953. * are FAR and we're assuming a small-pointer memory model. However, some
  178954. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178955. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178956. * Otherwise, the routines below do it the hard way. (The performance cost
  178957. * is not all that great, because these routines aren't very heavily used.)
  178958. */
  178959. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178960. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178961. #define FMEMZERO(target,size) MEMZERO(target,size)
  178962. #else /* 80x86 case, define if we can */
  178963. #ifdef USE_FMEM
  178964. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178965. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178966. #endif
  178967. #endif
  178968. GLOBAL(void)
  178969. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178970. JSAMPARRAY output_array, int dest_row,
  178971. int num_rows, JDIMENSION num_cols)
  178972. /* Copy some rows of samples from one place to another.
  178973. * num_rows rows are copied from input_array[source_row++]
  178974. * to output_array[dest_row++]; these areas may overlap for duplication.
  178975. * The source and destination arrays must be at least as wide as num_cols.
  178976. */
  178977. {
  178978. register JSAMPROW inptr, outptr;
  178979. #ifdef FMEMCOPY
  178980. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178981. #else
  178982. register JDIMENSION count;
  178983. #endif
  178984. register int row;
  178985. input_array += source_row;
  178986. output_array += dest_row;
  178987. for (row = num_rows; row > 0; row--) {
  178988. inptr = *input_array++;
  178989. outptr = *output_array++;
  178990. #ifdef FMEMCOPY
  178991. FMEMCOPY(outptr, inptr, count);
  178992. #else
  178993. for (count = num_cols; count > 0; count--)
  178994. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178995. #endif
  178996. }
  178997. }
  178998. GLOBAL(void)
  178999. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179000. JDIMENSION num_blocks)
  179001. /* Copy a row of coefficient blocks from one place to another. */
  179002. {
  179003. #ifdef FMEMCOPY
  179004. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179005. #else
  179006. register JCOEFPTR inptr, outptr;
  179007. register long count;
  179008. inptr = (JCOEFPTR) input_row;
  179009. outptr = (JCOEFPTR) output_row;
  179010. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179011. *outptr++ = *inptr++;
  179012. }
  179013. #endif
  179014. }
  179015. GLOBAL(void)
  179016. jzero_far (void FAR * target, size_t bytestozero)
  179017. /* Zero out a chunk of FAR memory. */
  179018. /* This might be sample-array data, block-array data, or alloc_large data. */
  179019. {
  179020. #ifdef FMEMZERO
  179021. FMEMZERO(target, bytestozero);
  179022. #else
  179023. register char FAR * ptr = (char FAR *) target;
  179024. register size_t count;
  179025. for (count = bytestozero; count > 0; count--) {
  179026. *ptr++ = 0;
  179027. }
  179028. #endif
  179029. }
  179030. /*** End of inlined file: jutils.c ***/
  179031. /*** Start of inlined file: transupp.c ***/
  179032. /* Although this file really shouldn't have access to the library internals,
  179033. * it's helpful to let it call jround_up() and jcopy_block_row().
  179034. */
  179035. #define JPEG_INTERNALS
  179036. /*** Start of inlined file: transupp.h ***/
  179037. /* If you happen not to want the image transform support, disable it here */
  179038. #ifndef TRANSFORMS_SUPPORTED
  179039. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179040. #endif
  179041. /* Short forms of external names for systems with brain-damaged linkers. */
  179042. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179043. #define jtransform_request_workspace jTrRequest
  179044. #define jtransform_adjust_parameters jTrAdjust
  179045. #define jtransform_execute_transformation jTrExec
  179046. #define jcopy_markers_setup jCMrkSetup
  179047. #define jcopy_markers_execute jCMrkExec
  179048. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179049. /*
  179050. * Codes for supported types of image transformations.
  179051. */
  179052. typedef enum {
  179053. JXFORM_NONE, /* no transformation */
  179054. JXFORM_FLIP_H, /* horizontal flip */
  179055. JXFORM_FLIP_V, /* vertical flip */
  179056. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179057. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179058. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179059. JXFORM_ROT_180, /* 180-degree rotation */
  179060. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179061. } JXFORM_CODE;
  179062. /*
  179063. * Although rotating and flipping data expressed as DCT coefficients is not
  179064. * hard, there is an asymmetry in the JPEG format specification for images
  179065. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179066. * image edges are padded out to the next iMCU boundary with junk data; but
  179067. * no padding is possible at the top and left edges. If we were to flip
  179068. * the whole image including the pad data, then pad garbage would become
  179069. * visible at the top and/or left, and real pixels would disappear into the
  179070. * pad margins --- perhaps permanently, since encoders & decoders may not
  179071. * bother to preserve DCT blocks that appear to be completely outside the
  179072. * nominal image area. So, we have to exclude any partial iMCUs from the
  179073. * basic transformation.
  179074. *
  179075. * Transpose is the only transformation that can handle partial iMCUs at the
  179076. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179077. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179078. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179079. * The other transforms are defined as combinations of these basic transforms
  179080. * and process edge blocks in a way that preserves the equivalence.
  179081. *
  179082. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179083. * this is not strictly lossless, but it usually gives the best-looking
  179084. * result for odd-size images. Note that when this option is active,
  179085. * the expected mathematical equivalences between the transforms may not hold.
  179086. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179087. * followed by -rot 180 -trim trims both edges.)
  179088. *
  179089. * We also offer a "force to grayscale" option, which simply discards the
  179090. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179091. * the luminance channel is preserved exactly. It's not the same kind of
  179092. * thing as the rotate/flip transformations, but it's convenient to handle it
  179093. * as part of this package, mainly because the transformation routines have to
  179094. * be aware of the option to know how many components to work on.
  179095. */
  179096. typedef struct {
  179097. /* Options: set by caller */
  179098. JXFORM_CODE transform; /* image transform operator */
  179099. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179100. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179101. /* Internal workspace: caller should not touch these */
  179102. int num_components; /* # of components in workspace */
  179103. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179104. } jpeg_transform_info;
  179105. #if TRANSFORMS_SUPPORTED
  179106. /* Request any required workspace */
  179107. EXTERN(void) jtransform_request_workspace
  179108. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179109. /* Adjust output image parameters */
  179110. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179111. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179112. jvirt_barray_ptr *src_coef_arrays,
  179113. jpeg_transform_info *info));
  179114. /* Execute the actual transformation, if any */
  179115. EXTERN(void) jtransform_execute_transformation
  179116. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179117. jvirt_barray_ptr *src_coef_arrays,
  179118. jpeg_transform_info *info));
  179119. #endif /* TRANSFORMS_SUPPORTED */
  179120. /*
  179121. * Support for copying optional markers from source to destination file.
  179122. */
  179123. typedef enum {
  179124. JCOPYOPT_NONE, /* copy no optional markers */
  179125. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179126. JCOPYOPT_ALL /* copy all optional markers */
  179127. } JCOPY_OPTION;
  179128. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179129. /* Setup decompression object to save desired markers in memory */
  179130. EXTERN(void) jcopy_markers_setup
  179131. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179132. /* Copy markers saved in the given source object to the destination object */
  179133. EXTERN(void) jcopy_markers_execute
  179134. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179135. JCOPY_OPTION option));
  179136. /*** End of inlined file: transupp.h ***/
  179137. /* My own external interface */
  179138. #if TRANSFORMS_SUPPORTED
  179139. /*
  179140. * Lossless image transformation routines. These routines work on DCT
  179141. * coefficient arrays and thus do not require any lossy decompression
  179142. * or recompression of the image.
  179143. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179144. *
  179145. * Horizontal flipping is done in-place, using a single top-to-bottom
  179146. * pass through the virtual source array. It will thus be much the
  179147. * fastest option for images larger than main memory.
  179148. *
  179149. * The other routines require a set of destination virtual arrays, so they
  179150. * need twice as much memory as jpegtran normally does. The destination
  179151. * arrays are always written in normal scan order (top to bottom) because
  179152. * the virtual array manager expects this. The source arrays will be scanned
  179153. * in the corresponding order, which means multiple passes through the source
  179154. * arrays for most of the transforms. That could result in much thrashing
  179155. * if the image is larger than main memory.
  179156. *
  179157. * Some notes about the operating environment of the individual transform
  179158. * routines:
  179159. * 1. Both the source and destination virtual arrays are allocated from the
  179160. * source JPEG object, and therefore should be manipulated by calling the
  179161. * source's memory manager.
  179162. * 2. The destination's component count should be used. It may be smaller
  179163. * than the source's when forcing to grayscale.
  179164. * 3. Likewise the destination's sampling factors should be used. When
  179165. * forcing to grayscale the destination's sampling factors will be all 1,
  179166. * and we may as well take that as the effective iMCU size.
  179167. * 4. When "trim" is in effect, the destination's dimensions will be the
  179168. * trimmed values but the source's will be untrimmed.
  179169. * 5. All the routines assume that the source and destination buffers are
  179170. * padded out to a full iMCU boundary. This is true, although for the
  179171. * source buffer it is an undocumented property of jdcoefct.c.
  179172. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179173. * dimensions and ignore the source's.
  179174. */
  179175. LOCAL(void)
  179176. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179177. jvirt_barray_ptr *src_coef_arrays)
  179178. /* Horizontal flip; done in-place, so no separate dest array is required */
  179179. {
  179180. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179181. int ci, k, offset_y;
  179182. JBLOCKARRAY buffer;
  179183. JCOEFPTR ptr1, ptr2;
  179184. JCOEF temp1, temp2;
  179185. jpeg_component_info *compptr;
  179186. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179187. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179188. * mirroring by changing the signs of odd-numbered columns.
  179189. * Partial iMCUs at the right edge are left untouched.
  179190. */
  179191. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179192. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179193. compptr = dstinfo->comp_info + ci;
  179194. comp_width = MCU_cols * compptr->h_samp_factor;
  179195. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179196. blk_y += compptr->v_samp_factor) {
  179197. buffer = (*srcinfo->mem->access_virt_barray)
  179198. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179199. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179200. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179201. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179202. ptr1 = buffer[offset_y][blk_x];
  179203. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179204. /* this unrolled loop doesn't need to know which row it's on... */
  179205. for (k = 0; k < DCTSIZE2; k += 2) {
  179206. temp1 = *ptr1; /* swap even column */
  179207. temp2 = *ptr2;
  179208. *ptr1++ = temp2;
  179209. *ptr2++ = temp1;
  179210. temp1 = *ptr1; /* swap odd column with sign change */
  179211. temp2 = *ptr2;
  179212. *ptr1++ = -temp2;
  179213. *ptr2++ = -temp1;
  179214. }
  179215. }
  179216. }
  179217. }
  179218. }
  179219. }
  179220. LOCAL(void)
  179221. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179222. jvirt_barray_ptr *src_coef_arrays,
  179223. jvirt_barray_ptr *dst_coef_arrays)
  179224. /* Vertical flip */
  179225. {
  179226. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179227. int ci, i, j, offset_y;
  179228. JBLOCKARRAY src_buffer, dst_buffer;
  179229. JBLOCKROW src_row_ptr, dst_row_ptr;
  179230. JCOEFPTR src_ptr, dst_ptr;
  179231. jpeg_component_info *compptr;
  179232. /* We output into a separate array because we can't touch different
  179233. * rows of the source virtual array simultaneously. Otherwise, this
  179234. * is a pretty straightforward analog of horizontal flip.
  179235. * Within a DCT block, vertical mirroring is done by changing the signs
  179236. * of odd-numbered rows.
  179237. * Partial iMCUs at the bottom edge are copied verbatim.
  179238. */
  179239. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179240. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179241. compptr = dstinfo->comp_info + ci;
  179242. comp_height = MCU_rows * compptr->v_samp_factor;
  179243. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179244. dst_blk_y += compptr->v_samp_factor) {
  179245. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179246. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179247. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179248. if (dst_blk_y < comp_height) {
  179249. /* Row is within the mirrorable area. */
  179250. src_buffer = (*srcinfo->mem->access_virt_barray)
  179251. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179252. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179253. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179254. } else {
  179255. /* Bottom-edge blocks will be copied verbatim. */
  179256. src_buffer = (*srcinfo->mem->access_virt_barray)
  179257. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179258. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179259. }
  179260. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179261. if (dst_blk_y < comp_height) {
  179262. /* Row is within the mirrorable area. */
  179263. dst_row_ptr = dst_buffer[offset_y];
  179264. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179265. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179266. dst_blk_x++) {
  179267. dst_ptr = dst_row_ptr[dst_blk_x];
  179268. src_ptr = src_row_ptr[dst_blk_x];
  179269. for (i = 0; i < DCTSIZE; i += 2) {
  179270. /* copy even row */
  179271. for (j = 0; j < DCTSIZE; j++)
  179272. *dst_ptr++ = *src_ptr++;
  179273. /* copy odd row with sign change */
  179274. for (j = 0; j < DCTSIZE; j++)
  179275. *dst_ptr++ = - *src_ptr++;
  179276. }
  179277. }
  179278. } else {
  179279. /* Just copy row verbatim. */
  179280. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179281. compptr->width_in_blocks);
  179282. }
  179283. }
  179284. }
  179285. }
  179286. }
  179287. LOCAL(void)
  179288. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179289. jvirt_barray_ptr *src_coef_arrays,
  179290. jvirt_barray_ptr *dst_coef_arrays)
  179291. /* Transpose source into destination */
  179292. {
  179293. JDIMENSION dst_blk_x, dst_blk_y;
  179294. int ci, i, j, offset_x, offset_y;
  179295. JBLOCKARRAY src_buffer, dst_buffer;
  179296. JCOEFPTR src_ptr, dst_ptr;
  179297. jpeg_component_info *compptr;
  179298. /* Transposing pixels within a block just requires transposing the
  179299. * DCT coefficients.
  179300. * Partial iMCUs at the edges require no special treatment; we simply
  179301. * process all the available DCT blocks for every component.
  179302. */
  179303. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179304. compptr = dstinfo->comp_info + ci;
  179305. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179306. dst_blk_y += compptr->v_samp_factor) {
  179307. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179308. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179309. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179310. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179311. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179312. dst_blk_x += compptr->h_samp_factor) {
  179313. src_buffer = (*srcinfo->mem->access_virt_barray)
  179314. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179315. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179316. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179317. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179318. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179319. for (i = 0; i < DCTSIZE; i++)
  179320. for (j = 0; j < DCTSIZE; j++)
  179321. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179322. }
  179323. }
  179324. }
  179325. }
  179326. }
  179327. }
  179328. LOCAL(void)
  179329. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179330. jvirt_barray_ptr *src_coef_arrays,
  179331. jvirt_barray_ptr *dst_coef_arrays)
  179332. /* 90 degree rotation is equivalent to
  179333. * 1. Transposing the image;
  179334. * 2. Horizontal mirroring.
  179335. * These two steps are merged into a single processing routine.
  179336. */
  179337. {
  179338. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179339. int ci, i, j, offset_x, offset_y;
  179340. JBLOCKARRAY src_buffer, dst_buffer;
  179341. JCOEFPTR src_ptr, dst_ptr;
  179342. jpeg_component_info *compptr;
  179343. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179344. * at the (output) right edge properly. They just get transposed and
  179345. * not mirrored.
  179346. */
  179347. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179348. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179349. compptr = dstinfo->comp_info + ci;
  179350. comp_width = MCU_cols * compptr->h_samp_factor;
  179351. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179352. dst_blk_y += compptr->v_samp_factor) {
  179353. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179354. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179355. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179356. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179357. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179358. dst_blk_x += compptr->h_samp_factor) {
  179359. src_buffer = (*srcinfo->mem->access_virt_barray)
  179360. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179361. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179362. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179363. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179364. if (dst_blk_x < comp_width) {
  179365. /* Block is within the mirrorable area. */
  179366. dst_ptr = dst_buffer[offset_y]
  179367. [comp_width - dst_blk_x - offset_x - 1];
  179368. for (i = 0; i < DCTSIZE; i++) {
  179369. for (j = 0; j < DCTSIZE; j++)
  179370. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179371. i++;
  179372. for (j = 0; j < DCTSIZE; j++)
  179373. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179374. }
  179375. } else {
  179376. /* Edge blocks are transposed but not mirrored. */
  179377. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179378. for (i = 0; i < DCTSIZE; i++)
  179379. for (j = 0; j < DCTSIZE; j++)
  179380. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179381. }
  179382. }
  179383. }
  179384. }
  179385. }
  179386. }
  179387. }
  179388. LOCAL(void)
  179389. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179390. jvirt_barray_ptr *src_coef_arrays,
  179391. jvirt_barray_ptr *dst_coef_arrays)
  179392. /* 270 degree rotation is equivalent to
  179393. * 1. Horizontal mirroring;
  179394. * 2. Transposing the image.
  179395. * These two steps are merged into a single processing routine.
  179396. */
  179397. {
  179398. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179399. int ci, i, j, offset_x, offset_y;
  179400. JBLOCKARRAY src_buffer, dst_buffer;
  179401. JCOEFPTR src_ptr, dst_ptr;
  179402. jpeg_component_info *compptr;
  179403. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179404. * at the (output) bottom edge properly. They just get transposed and
  179405. * not mirrored.
  179406. */
  179407. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179408. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179409. compptr = dstinfo->comp_info + ci;
  179410. comp_height = MCU_rows * compptr->v_samp_factor;
  179411. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179412. dst_blk_y += compptr->v_samp_factor) {
  179413. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179414. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179415. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179416. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179417. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179418. dst_blk_x += compptr->h_samp_factor) {
  179419. src_buffer = (*srcinfo->mem->access_virt_barray)
  179420. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179421. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179422. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179423. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179424. if (dst_blk_y < comp_height) {
  179425. /* Block is within the mirrorable area. */
  179426. src_ptr = src_buffer[offset_x]
  179427. [comp_height - dst_blk_y - offset_y - 1];
  179428. for (i = 0; i < DCTSIZE; i++) {
  179429. for (j = 0; j < DCTSIZE; j++) {
  179430. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179431. j++;
  179432. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179433. }
  179434. }
  179435. } else {
  179436. /* Edge blocks are transposed but not mirrored. */
  179437. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179438. for (i = 0; i < DCTSIZE; i++)
  179439. for (j = 0; j < DCTSIZE; j++)
  179440. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179441. }
  179442. }
  179443. }
  179444. }
  179445. }
  179446. }
  179447. }
  179448. LOCAL(void)
  179449. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179450. jvirt_barray_ptr *src_coef_arrays,
  179451. jvirt_barray_ptr *dst_coef_arrays)
  179452. /* 180 degree rotation is equivalent to
  179453. * 1. Vertical mirroring;
  179454. * 2. Horizontal mirroring.
  179455. * These two steps are merged into a single processing routine.
  179456. */
  179457. {
  179458. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179459. int ci, i, j, offset_y;
  179460. JBLOCKARRAY src_buffer, dst_buffer;
  179461. JBLOCKROW src_row_ptr, dst_row_ptr;
  179462. JCOEFPTR src_ptr, dst_ptr;
  179463. jpeg_component_info *compptr;
  179464. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179465. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179466. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179467. compptr = dstinfo->comp_info + ci;
  179468. comp_width = MCU_cols * compptr->h_samp_factor;
  179469. comp_height = MCU_rows * compptr->v_samp_factor;
  179470. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179471. dst_blk_y += compptr->v_samp_factor) {
  179472. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179473. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179474. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179475. if (dst_blk_y < comp_height) {
  179476. /* Row is within the vertically mirrorable area. */
  179477. src_buffer = (*srcinfo->mem->access_virt_barray)
  179478. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179479. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179480. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179481. } else {
  179482. /* Bottom-edge rows are only mirrored horizontally. */
  179483. src_buffer = (*srcinfo->mem->access_virt_barray)
  179484. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179485. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179486. }
  179487. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179488. if (dst_blk_y < comp_height) {
  179489. /* Row is within the mirrorable area. */
  179490. dst_row_ptr = dst_buffer[offset_y];
  179491. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179492. /* Process the blocks that can be mirrored both ways. */
  179493. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179494. dst_ptr = dst_row_ptr[dst_blk_x];
  179495. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179496. for (i = 0; i < DCTSIZE; i += 2) {
  179497. /* For even row, negate every odd column. */
  179498. for (j = 0; j < DCTSIZE; j += 2) {
  179499. *dst_ptr++ = *src_ptr++;
  179500. *dst_ptr++ = - *src_ptr++;
  179501. }
  179502. /* For odd row, negate every even column. */
  179503. for (j = 0; j < DCTSIZE; j += 2) {
  179504. *dst_ptr++ = - *src_ptr++;
  179505. *dst_ptr++ = *src_ptr++;
  179506. }
  179507. }
  179508. }
  179509. /* Any remaining right-edge blocks are only mirrored vertically. */
  179510. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179511. dst_ptr = dst_row_ptr[dst_blk_x];
  179512. src_ptr = src_row_ptr[dst_blk_x];
  179513. for (i = 0; i < DCTSIZE; i += 2) {
  179514. for (j = 0; j < DCTSIZE; j++)
  179515. *dst_ptr++ = *src_ptr++;
  179516. for (j = 0; j < DCTSIZE; j++)
  179517. *dst_ptr++ = - *src_ptr++;
  179518. }
  179519. }
  179520. } else {
  179521. /* Remaining rows are just mirrored horizontally. */
  179522. dst_row_ptr = dst_buffer[offset_y];
  179523. src_row_ptr = src_buffer[offset_y];
  179524. /* Process the blocks that can be mirrored. */
  179525. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179526. dst_ptr = dst_row_ptr[dst_blk_x];
  179527. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179528. for (i = 0; i < DCTSIZE2; i += 2) {
  179529. *dst_ptr++ = *src_ptr++;
  179530. *dst_ptr++ = - *src_ptr++;
  179531. }
  179532. }
  179533. /* Any remaining right-edge blocks are only copied. */
  179534. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179535. dst_ptr = dst_row_ptr[dst_blk_x];
  179536. src_ptr = src_row_ptr[dst_blk_x];
  179537. for (i = 0; i < DCTSIZE2; i++)
  179538. *dst_ptr++ = *src_ptr++;
  179539. }
  179540. }
  179541. }
  179542. }
  179543. }
  179544. }
  179545. LOCAL(void)
  179546. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179547. jvirt_barray_ptr *src_coef_arrays,
  179548. jvirt_barray_ptr *dst_coef_arrays)
  179549. /* Transverse transpose is equivalent to
  179550. * 1. 180 degree rotation;
  179551. * 2. Transposition;
  179552. * or
  179553. * 1. Horizontal mirroring;
  179554. * 2. Transposition;
  179555. * 3. Horizontal mirroring.
  179556. * These steps are merged into a single processing routine.
  179557. */
  179558. {
  179559. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179560. int ci, i, j, offset_x, offset_y;
  179561. JBLOCKARRAY src_buffer, dst_buffer;
  179562. JCOEFPTR src_ptr, dst_ptr;
  179563. jpeg_component_info *compptr;
  179564. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179565. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179566. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179567. compptr = dstinfo->comp_info + ci;
  179568. comp_width = MCU_cols * compptr->h_samp_factor;
  179569. comp_height = MCU_rows * compptr->v_samp_factor;
  179570. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179571. dst_blk_y += compptr->v_samp_factor) {
  179572. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179573. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179574. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179575. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179576. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179577. dst_blk_x += compptr->h_samp_factor) {
  179578. src_buffer = (*srcinfo->mem->access_virt_barray)
  179579. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179580. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179581. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179582. if (dst_blk_y < comp_height) {
  179583. src_ptr = src_buffer[offset_x]
  179584. [comp_height - dst_blk_y - offset_y - 1];
  179585. if (dst_blk_x < comp_width) {
  179586. /* Block is within the mirrorable area. */
  179587. dst_ptr = dst_buffer[offset_y]
  179588. [comp_width - dst_blk_x - offset_x - 1];
  179589. for (i = 0; i < DCTSIZE; i++) {
  179590. for (j = 0; j < DCTSIZE; j++) {
  179591. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179592. j++;
  179593. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179594. }
  179595. i++;
  179596. for (j = 0; j < DCTSIZE; j++) {
  179597. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179598. j++;
  179599. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179600. }
  179601. }
  179602. } else {
  179603. /* Right-edge blocks are mirrored in y only */
  179604. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179605. for (i = 0; i < DCTSIZE; i++) {
  179606. for (j = 0; j < DCTSIZE; j++) {
  179607. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179608. j++;
  179609. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179610. }
  179611. }
  179612. }
  179613. } else {
  179614. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179615. if (dst_blk_x < comp_width) {
  179616. /* Bottom-edge blocks are mirrored in x only */
  179617. dst_ptr = dst_buffer[offset_y]
  179618. [comp_width - dst_blk_x - offset_x - 1];
  179619. for (i = 0; i < DCTSIZE; i++) {
  179620. for (j = 0; j < DCTSIZE; j++)
  179621. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179622. i++;
  179623. for (j = 0; j < DCTSIZE; j++)
  179624. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179625. }
  179626. } else {
  179627. /* At lower right corner, just transpose, no mirroring */
  179628. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  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. }
  179633. }
  179634. }
  179635. }
  179636. }
  179637. }
  179638. }
  179639. }
  179640. /* Request any required workspace.
  179641. *
  179642. * We allocate the workspace virtual arrays from the source decompression
  179643. * object, so that all the arrays (both the original data and the workspace)
  179644. * will be taken into account while making memory management decisions.
  179645. * Hence, this routine must be called after jpeg_read_header (which reads
  179646. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179647. * the source's virtual arrays).
  179648. */
  179649. GLOBAL(void)
  179650. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179651. jpeg_transform_info *info)
  179652. {
  179653. jvirt_barray_ptr *coef_arrays = NULL;
  179654. jpeg_component_info *compptr;
  179655. int ci;
  179656. if (info->force_grayscale &&
  179657. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179658. srcinfo->num_components == 3) {
  179659. /* We'll only process the first component */
  179660. info->num_components = 1;
  179661. } else {
  179662. /* Process all the components */
  179663. info->num_components = srcinfo->num_components;
  179664. }
  179665. switch (info->transform) {
  179666. case JXFORM_NONE:
  179667. case JXFORM_FLIP_H:
  179668. /* Don't need a workspace array */
  179669. break;
  179670. case JXFORM_FLIP_V:
  179671. case JXFORM_ROT_180:
  179672. /* Need workspace arrays having same dimensions as source image.
  179673. * Note that we allocate arrays padded out to the next iMCU boundary,
  179674. * so that transform routines need not worry about missing edge blocks.
  179675. */
  179676. coef_arrays = (jvirt_barray_ptr *)
  179677. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179678. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179679. for (ci = 0; ci < info->num_components; ci++) {
  179680. compptr = srcinfo->comp_info + ci;
  179681. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179682. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179683. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179684. (long) compptr->h_samp_factor),
  179685. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179686. (long) compptr->v_samp_factor),
  179687. (JDIMENSION) compptr->v_samp_factor);
  179688. }
  179689. break;
  179690. case JXFORM_TRANSPOSE:
  179691. case JXFORM_TRANSVERSE:
  179692. case JXFORM_ROT_90:
  179693. case JXFORM_ROT_270:
  179694. /* Need workspace arrays having transposed dimensions.
  179695. * Note that we allocate arrays padded out to the next iMCU boundary,
  179696. * so that transform routines need not worry about missing edge blocks.
  179697. */
  179698. coef_arrays = (jvirt_barray_ptr *)
  179699. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179700. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179701. for (ci = 0; ci < info->num_components; ci++) {
  179702. compptr = srcinfo->comp_info + ci;
  179703. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179704. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179705. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179706. (long) compptr->v_samp_factor),
  179707. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179708. (long) compptr->h_samp_factor),
  179709. (JDIMENSION) compptr->h_samp_factor);
  179710. }
  179711. break;
  179712. }
  179713. info->workspace_coef_arrays = coef_arrays;
  179714. }
  179715. /* Transpose destination image parameters */
  179716. LOCAL(void)
  179717. transpose_critical_parameters (j_compress_ptr dstinfo)
  179718. {
  179719. int tblno, i, j, ci, itemp;
  179720. jpeg_component_info *compptr;
  179721. JQUANT_TBL *qtblptr;
  179722. JDIMENSION dtemp;
  179723. UINT16 qtemp;
  179724. /* Transpose basic image dimensions */
  179725. dtemp = dstinfo->image_width;
  179726. dstinfo->image_width = dstinfo->image_height;
  179727. dstinfo->image_height = dtemp;
  179728. /* Transpose sampling factors */
  179729. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179730. compptr = dstinfo->comp_info + ci;
  179731. itemp = compptr->h_samp_factor;
  179732. compptr->h_samp_factor = compptr->v_samp_factor;
  179733. compptr->v_samp_factor = itemp;
  179734. }
  179735. /* Transpose quantization tables */
  179736. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179737. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179738. if (qtblptr != NULL) {
  179739. for (i = 0; i < DCTSIZE; i++) {
  179740. for (j = 0; j < i; j++) {
  179741. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179742. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179743. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179744. }
  179745. }
  179746. }
  179747. }
  179748. }
  179749. /* Trim off any partial iMCUs on the indicated destination edge */
  179750. LOCAL(void)
  179751. trim_right_edge (j_compress_ptr dstinfo)
  179752. {
  179753. int ci, max_h_samp_factor;
  179754. JDIMENSION MCU_cols;
  179755. /* We have to compute max_h_samp_factor ourselves,
  179756. * because it hasn't been set yet in the destination
  179757. * (and we don't want to use the source's value).
  179758. */
  179759. max_h_samp_factor = 1;
  179760. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179761. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179762. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179763. }
  179764. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179765. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179766. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179767. }
  179768. LOCAL(void)
  179769. trim_bottom_edge (j_compress_ptr dstinfo)
  179770. {
  179771. int ci, max_v_samp_factor;
  179772. JDIMENSION MCU_rows;
  179773. /* We have to compute max_v_samp_factor ourselves,
  179774. * because it hasn't been set yet in the destination
  179775. * (and we don't want to use the source's value).
  179776. */
  179777. max_v_samp_factor = 1;
  179778. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179779. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179780. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179781. }
  179782. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179783. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179784. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179785. }
  179786. /* Adjust output image parameters as needed.
  179787. *
  179788. * This must be called after jpeg_copy_critical_parameters()
  179789. * and before jpeg_write_coefficients().
  179790. *
  179791. * The return value is the set of virtual coefficient arrays to be written
  179792. * (either the ones allocated by jtransform_request_workspace, or the
  179793. * original source data arrays). The caller will need to pass this value
  179794. * to jpeg_write_coefficients().
  179795. */
  179796. GLOBAL(jvirt_barray_ptr *)
  179797. jtransform_adjust_parameters (j_decompress_ptr,
  179798. j_compress_ptr dstinfo,
  179799. jvirt_barray_ptr *src_coef_arrays,
  179800. jpeg_transform_info *info)
  179801. {
  179802. /* If force-to-grayscale is requested, adjust destination parameters */
  179803. if (info->force_grayscale) {
  179804. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179805. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179806. * will get set to 1, which typically won't match the source.
  179807. * In fact we do this even if the source is already grayscale; that
  179808. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179809. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179810. */
  179811. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179812. dstinfo->num_components == 3) ||
  179813. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179814. dstinfo->num_components == 1)) {
  179815. /* We have to preserve the source's quantization table number. */
  179816. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179817. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179818. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179819. } else {
  179820. /* Sorry, can't do it */
  179821. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179822. }
  179823. }
  179824. /* Correct the destination's image dimensions etc if necessary */
  179825. switch (info->transform) {
  179826. case JXFORM_NONE:
  179827. /* Nothing to do */
  179828. break;
  179829. case JXFORM_FLIP_H:
  179830. if (info->trim)
  179831. trim_right_edge(dstinfo);
  179832. break;
  179833. case JXFORM_FLIP_V:
  179834. if (info->trim)
  179835. trim_bottom_edge(dstinfo);
  179836. break;
  179837. case JXFORM_TRANSPOSE:
  179838. transpose_critical_parameters(dstinfo);
  179839. /* transpose does NOT have to trim anything */
  179840. break;
  179841. case JXFORM_TRANSVERSE:
  179842. transpose_critical_parameters(dstinfo);
  179843. if (info->trim) {
  179844. trim_right_edge(dstinfo);
  179845. trim_bottom_edge(dstinfo);
  179846. }
  179847. break;
  179848. case JXFORM_ROT_90:
  179849. transpose_critical_parameters(dstinfo);
  179850. if (info->trim)
  179851. trim_right_edge(dstinfo);
  179852. break;
  179853. case JXFORM_ROT_180:
  179854. if (info->trim) {
  179855. trim_right_edge(dstinfo);
  179856. trim_bottom_edge(dstinfo);
  179857. }
  179858. break;
  179859. case JXFORM_ROT_270:
  179860. transpose_critical_parameters(dstinfo);
  179861. if (info->trim)
  179862. trim_bottom_edge(dstinfo);
  179863. break;
  179864. }
  179865. /* Return the appropriate output data set */
  179866. if (info->workspace_coef_arrays != NULL)
  179867. return info->workspace_coef_arrays;
  179868. return src_coef_arrays;
  179869. }
  179870. /* Execute the actual transformation, if any.
  179871. *
  179872. * This must be called *after* jpeg_write_coefficients, because it depends
  179873. * on jpeg_write_coefficients to have computed subsidiary values such as
  179874. * the per-component width and height fields in the destination object.
  179875. *
  179876. * Note that some transformations will modify the source data arrays!
  179877. */
  179878. GLOBAL(void)
  179879. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179880. j_compress_ptr dstinfo,
  179881. jvirt_barray_ptr *src_coef_arrays,
  179882. jpeg_transform_info *info)
  179883. {
  179884. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179885. switch (info->transform) {
  179886. case JXFORM_NONE:
  179887. break;
  179888. case JXFORM_FLIP_H:
  179889. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179890. break;
  179891. case JXFORM_FLIP_V:
  179892. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179893. break;
  179894. case JXFORM_TRANSPOSE:
  179895. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179896. break;
  179897. case JXFORM_TRANSVERSE:
  179898. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179899. break;
  179900. case JXFORM_ROT_90:
  179901. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179902. break;
  179903. case JXFORM_ROT_180:
  179904. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179905. break;
  179906. case JXFORM_ROT_270:
  179907. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179908. break;
  179909. }
  179910. }
  179911. #endif /* TRANSFORMS_SUPPORTED */
  179912. /* Setup decompression object to save desired markers in memory.
  179913. * This must be called before jpeg_read_header() to have the desired effect.
  179914. */
  179915. GLOBAL(void)
  179916. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179917. {
  179918. #ifdef SAVE_MARKERS_SUPPORTED
  179919. int m;
  179920. /* Save comments except under NONE option */
  179921. if (option != JCOPYOPT_NONE) {
  179922. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179923. }
  179924. /* Save all types of APPn markers iff ALL option */
  179925. if (option == JCOPYOPT_ALL) {
  179926. for (m = 0; m < 16; m++)
  179927. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179928. }
  179929. #endif /* SAVE_MARKERS_SUPPORTED */
  179930. }
  179931. /* Copy markers saved in the given source object to the destination object.
  179932. * This should be called just after jpeg_start_compress() or
  179933. * jpeg_write_coefficients().
  179934. * Note that those routines will have written the SOI, and also the
  179935. * JFIF APP0 or Adobe APP14 markers if selected.
  179936. */
  179937. GLOBAL(void)
  179938. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179939. JCOPY_OPTION)
  179940. {
  179941. jpeg_saved_marker_ptr marker;
  179942. /* In the current implementation, we don't actually need to examine the
  179943. * option flag here; we just copy everything that got saved.
  179944. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179945. * if the encoder library already wrote one.
  179946. */
  179947. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179948. if (dstinfo->write_JFIF_header &&
  179949. marker->marker == JPEG_APP0 &&
  179950. marker->data_length >= 5 &&
  179951. GETJOCTET(marker->data[0]) == 0x4A &&
  179952. GETJOCTET(marker->data[1]) == 0x46 &&
  179953. GETJOCTET(marker->data[2]) == 0x49 &&
  179954. GETJOCTET(marker->data[3]) == 0x46 &&
  179955. GETJOCTET(marker->data[4]) == 0)
  179956. continue; /* reject duplicate JFIF */
  179957. if (dstinfo->write_Adobe_marker &&
  179958. marker->marker == JPEG_APP0+14 &&
  179959. marker->data_length >= 5 &&
  179960. GETJOCTET(marker->data[0]) == 0x41 &&
  179961. GETJOCTET(marker->data[1]) == 0x64 &&
  179962. GETJOCTET(marker->data[2]) == 0x6F &&
  179963. GETJOCTET(marker->data[3]) == 0x62 &&
  179964. GETJOCTET(marker->data[4]) == 0x65)
  179965. continue; /* reject duplicate Adobe */
  179966. #ifdef NEED_FAR_POINTERS
  179967. /* We could use jpeg_write_marker if the data weren't FAR... */
  179968. {
  179969. unsigned int i;
  179970. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179971. for (i = 0; i < marker->data_length; i++)
  179972. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179973. }
  179974. #else
  179975. jpeg_write_marker(dstinfo, marker->marker,
  179976. marker->data, marker->data_length);
  179977. #endif
  179978. }
  179979. }
  179980. /*** End of inlined file: transupp.c ***/
  179981. #else
  179982. #define JPEG_INTERNALS
  179983. #undef FAR
  179984. #include <jpeglib.h>
  179985. #endif
  179986. }
  179987. #undef max
  179988. #undef min
  179989. #if JUCE_MSVC
  179990. #pragma warning (pop)
  179991. #endif
  179992. BEGIN_JUCE_NAMESPACE
  179993. namespace JPEGHelpers
  179994. {
  179995. using namespace jpeglibNamespace;
  179996. #if ! JUCE_MSVC
  179997. using jpeglibNamespace::boolean;
  179998. #endif
  179999. struct JPEGDecodingFailure {};
  180000. void fatalErrorHandler (j_common_ptr)
  180001. {
  180002. throw JPEGDecodingFailure();
  180003. }
  180004. void silentErrorCallback1 (j_common_ptr) {}
  180005. void silentErrorCallback2 (j_common_ptr, int) {}
  180006. void silentErrorCallback3 (j_common_ptr, char*) {}
  180007. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180008. {
  180009. zerostruct (err);
  180010. err.error_exit = fatalErrorHandler;
  180011. err.emit_message = silentErrorCallback2;
  180012. err.output_message = silentErrorCallback1;
  180013. err.format_message = silentErrorCallback3;
  180014. err.reset_error_mgr = silentErrorCallback1;
  180015. }
  180016. void dummyCallback1 (j_decompress_ptr)
  180017. {
  180018. }
  180019. void jpegSkip (j_decompress_ptr decompStruct, long num)
  180020. {
  180021. decompStruct->src->next_input_byte += num;
  180022. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  180023. decompStruct->src->bytes_in_buffer -= num;
  180024. }
  180025. boolean jpegFill (j_decompress_ptr)
  180026. {
  180027. return 0;
  180028. }
  180029. const int jpegBufferSize = 512;
  180030. struct JuceJpegDest : public jpeg_destination_mgr
  180031. {
  180032. OutputStream* output;
  180033. char* buffer;
  180034. };
  180035. void jpegWriteInit (j_compress_ptr)
  180036. {
  180037. }
  180038. void jpegWriteTerminate (j_compress_ptr cinfo)
  180039. {
  180040. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180041. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180042. dest->output->write (dest->buffer, (int) numToWrite);
  180043. }
  180044. boolean jpegWriteFlush (j_compress_ptr cinfo)
  180045. {
  180046. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180047. const int numToWrite = jpegBufferSize;
  180048. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180049. dest->free_in_buffer = jpegBufferSize;
  180050. return dest->output->write (dest->buffer, numToWrite);
  180051. }
  180052. }
  180053. JPEGImageFormat::JPEGImageFormat()
  180054. : quality (-1.0f)
  180055. {
  180056. }
  180057. JPEGImageFormat::~JPEGImageFormat() {}
  180058. void JPEGImageFormat::setQuality (const float newQuality)
  180059. {
  180060. quality = newQuality;
  180061. }
  180062. const String JPEGImageFormat::getFormatName()
  180063. {
  180064. return "JPEG";
  180065. }
  180066. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180067. {
  180068. const int bytesNeeded = 10;
  180069. uint8 header [bytesNeeded];
  180070. if (in.read (header, bytesNeeded) == bytesNeeded)
  180071. {
  180072. return header[0] == 0xff
  180073. && header[1] == 0xd8
  180074. && header[2] == 0xff
  180075. && (header[3] == 0xe0 || header[3] == 0xe1);
  180076. }
  180077. return false;
  180078. }
  180079. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180080. const Image juce_loadWithCoreImage (InputStream& input);
  180081. #endif
  180082. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180083. {
  180084. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180085. return juce_loadWithCoreImage (in);
  180086. #else
  180087. using namespace jpeglibNamespace;
  180088. using namespace JPEGHelpers;
  180089. MemoryOutputStream mb;
  180090. mb.writeFromInputStream (in, -1);
  180091. Image image;
  180092. if (mb.getDataSize() > 16)
  180093. {
  180094. struct jpeg_decompress_struct jpegDecompStruct;
  180095. struct jpeg_error_mgr jerr;
  180096. setupSilentErrorHandler (jerr);
  180097. jpegDecompStruct.err = &jerr;
  180098. jpeg_create_decompress (&jpegDecompStruct);
  180099. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180100. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180101. jpegDecompStruct.src->init_source = dummyCallback1;
  180102. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180103. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180104. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180105. jpegDecompStruct.src->term_source = dummyCallback1;
  180106. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180107. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180108. try
  180109. {
  180110. jpeg_read_header (&jpegDecompStruct, TRUE);
  180111. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180112. const int width = jpegDecompStruct.output_width;
  180113. const int height = jpegDecompStruct.output_height;
  180114. jpegDecompStruct.out_color_space = JCS_RGB;
  180115. JSAMPARRAY buffer
  180116. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180117. JPOOL_IMAGE,
  180118. width * 3, 1);
  180119. if (jpeg_start_decompress (&jpegDecompStruct))
  180120. {
  180121. image = Image (Image::RGB, width, height, false);
  180122. image.getProperties()->set ("originalImageHadAlpha", false);
  180123. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180124. const Image::BitmapData destData (image, true);
  180125. for (int y = 0; y < height; ++y)
  180126. {
  180127. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180128. const uint8* src = *buffer;
  180129. uint8* dest = destData.getLinePointer (y);
  180130. if (hasAlphaChan)
  180131. {
  180132. for (int i = width; --i >= 0;)
  180133. {
  180134. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180135. ((PixelARGB*) dest)->premultiply();
  180136. dest += destData.pixelStride;
  180137. src += 3;
  180138. }
  180139. }
  180140. else
  180141. {
  180142. for (int i = width; --i >= 0;)
  180143. {
  180144. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180145. dest += destData.pixelStride;
  180146. src += 3;
  180147. }
  180148. }
  180149. }
  180150. jpeg_finish_decompress (&jpegDecompStruct);
  180151. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180152. }
  180153. jpeg_destroy_decompress (&jpegDecompStruct);
  180154. }
  180155. catch (...)
  180156. {}
  180157. }
  180158. return image;
  180159. #endif
  180160. }
  180161. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180162. {
  180163. using namespace jpeglibNamespace;
  180164. using namespace JPEGHelpers;
  180165. if (image.hasAlphaChannel())
  180166. {
  180167. // this method could fill the background in white and still save the image..
  180168. jassertfalse;
  180169. return true;
  180170. }
  180171. struct jpeg_compress_struct jpegCompStruct;
  180172. struct jpeg_error_mgr jerr;
  180173. setupSilentErrorHandler (jerr);
  180174. jpegCompStruct.err = &jerr;
  180175. jpeg_create_compress (&jpegCompStruct);
  180176. JuceJpegDest dest;
  180177. jpegCompStruct.dest = &dest;
  180178. dest.output = &out;
  180179. HeapBlock <char> tempBuffer (jpegBufferSize);
  180180. dest.buffer = tempBuffer;
  180181. dest.next_output_byte = (JOCTET*) dest.buffer;
  180182. dest.free_in_buffer = jpegBufferSize;
  180183. dest.init_destination = jpegWriteInit;
  180184. dest.empty_output_buffer = jpegWriteFlush;
  180185. dest.term_destination = jpegWriteTerminate;
  180186. jpegCompStruct.image_width = image.getWidth();
  180187. jpegCompStruct.image_height = image.getHeight();
  180188. jpegCompStruct.input_components = 3;
  180189. jpegCompStruct.in_color_space = JCS_RGB;
  180190. jpegCompStruct.write_JFIF_header = 1;
  180191. jpegCompStruct.X_density = 72;
  180192. jpegCompStruct.Y_density = 72;
  180193. jpeg_set_defaults (&jpegCompStruct);
  180194. jpegCompStruct.dct_method = JDCT_FLOAT;
  180195. jpegCompStruct.optimize_coding = 1;
  180196. //jpegCompStruct.smoothing_factor = 10;
  180197. if (quality < 0.0f)
  180198. quality = 0.85f;
  180199. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180200. jpeg_start_compress (&jpegCompStruct, TRUE);
  180201. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180202. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180203. JPOOL_IMAGE, strideBytes, 1);
  180204. const Image::BitmapData srcData (image, false);
  180205. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180206. {
  180207. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180208. uint8* dst = *buffer;
  180209. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180210. {
  180211. *dst++ = ((const PixelRGB*) src)->getRed();
  180212. *dst++ = ((const PixelRGB*) src)->getGreen();
  180213. *dst++ = ((const PixelRGB*) src)->getBlue();
  180214. src += srcData.pixelStride;
  180215. }
  180216. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180217. }
  180218. jpeg_finish_compress (&jpegCompStruct);
  180219. jpeg_destroy_compress (&jpegCompStruct);
  180220. out.flush();
  180221. return true;
  180222. }
  180223. END_JUCE_NAMESPACE
  180224. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180225. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180226. #if JUCE_MSVC
  180227. #pragma warning (push)
  180228. #pragma warning (disable: 4390 4611)
  180229. #endif
  180230. namespace zlibNamespace
  180231. {
  180232. #if JUCE_INCLUDE_ZLIB_CODE
  180233. #undef OS_CODE
  180234. #undef fdopen
  180235. #undef OS_CODE
  180236. #else
  180237. #include <zlib.h>
  180238. #endif
  180239. }
  180240. namespace pnglibNamespace
  180241. {
  180242. using namespace zlibNamespace;
  180243. #if JUCE_INCLUDE_PNGLIB_CODE
  180244. #if _MSC_VER != 1310
  180245. using ::calloc; // (causes conflict in VS.NET 2003)
  180246. using ::malloc;
  180247. using ::free;
  180248. #endif
  180249. using ::abs;
  180250. #define PNG_INTERNAL
  180251. #define NO_DUMMY_DECL
  180252. #define PNG_SETJMP_NOT_SUPPORTED
  180253. /*** Start of inlined file: png.h ***/
  180254. /* png.h - header file for PNG reference library
  180255. *
  180256. * libpng version 1.2.21 - October 4, 2007
  180257. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180258. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180259. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180260. *
  180261. * Authors and maintainers:
  180262. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180263. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180264. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180265. * See also "Contributing Authors", below.
  180266. *
  180267. * Note about libpng version numbers:
  180268. *
  180269. * Due to various miscommunications, unforeseen code incompatibilities
  180270. * and occasional factors outside the authors' control, version numbering
  180271. * on the library has not always been consistent and straightforward.
  180272. * The following table summarizes matters since version 0.89c, which was
  180273. * the first widely used release:
  180274. *
  180275. * source png.h png.h shared-lib
  180276. * version string int version
  180277. * ------- ------ ----- ----------
  180278. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180279. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180280. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180281. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180282. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180283. * 0.97c 0.97 97 2.0.97
  180284. * 0.98 0.98 98 2.0.98
  180285. * 0.99 0.99 98 2.0.99
  180286. * 0.99a-m 0.99 99 2.0.99
  180287. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180288. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180289. * 1.0.1 png.h string is 10001 2.1.0
  180290. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180291. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180292. * 1.0.2a-b 10003 version, except as noted.
  180293. * 1.0.3 10003
  180294. * 1.0.3a-d 10004
  180295. * 1.0.4 10004
  180296. * 1.0.4a-f 10005
  180297. * 1.0.5 (+ 2 patches) 10005
  180298. * 1.0.5a-d 10006
  180299. * 1.0.5e-r 10100 (not source compatible)
  180300. * 1.0.5s-v 10006 (not binary compatible)
  180301. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180302. * 1.0.6d-f 10007 (still binary incompatible)
  180303. * 1.0.6g 10007
  180304. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180305. * 1.0.6i 10007 10.6i
  180306. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180307. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180308. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180309. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180310. * 1.0.7 1 10007 (still compatible)
  180311. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180312. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180313. * 1.0.8 1 10008 2.1.0.8
  180314. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180315. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180316. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180317. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180318. * 1.0.9 1 10009 2.1.0.9
  180319. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180320. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180321. * 1.0.10 1 10010 2.1.0.10
  180322. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180323. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180324. * 1.0.11 1 10011 2.1.0.11
  180325. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180326. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180327. * 1.0.12 2 10012 2.1.0.12
  180328. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180329. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180330. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180331. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180332. * 1.2.0 3 10200 3.1.2.0
  180333. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180334. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180335. * 1.2.1 3 10201 3.1.2.1
  180336. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180337. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180338. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180339. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180340. * 1.0.13 10 10013 10.so.0.1.0.13
  180341. * 1.2.2 12 10202 12.so.0.1.2.2
  180342. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180343. * 1.2.3 12 10203 12.so.0.1.2.3
  180344. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180345. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180346. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180347. * 1.0.14 10 10014 10.so.0.1.0.14
  180348. * 1.2.4 13 10204 12.so.0.1.2.4
  180349. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180350. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180351. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180352. * 1.0.15 10 10015 10.so.0.1.0.15
  180353. * 1.2.5 13 10205 12.so.0.1.2.5
  180354. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180355. * 1.0.16 10 10016 10.so.0.1.0.16
  180356. * 1.2.6 13 10206 12.so.0.1.2.6
  180357. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180358. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180359. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180360. * 1.0.17 10 10017 10.so.0.1.0.17
  180361. * 1.2.7 13 10207 12.so.0.1.2.7
  180362. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180363. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180364. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180365. * 1.0.18 10 10018 10.so.0.1.0.18
  180366. * 1.2.8 13 10208 12.so.0.1.2.8
  180367. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180368. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180369. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180370. * 1.2.9 13 10209 12.so.0.9[.0]
  180371. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180372. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180373. * 1.2.10 13 10210 12.so.0.10[.0]
  180374. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180375. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180376. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180377. * 1.0.19 10 10019 10.so.0.19[.0]
  180378. * 1.2.11 13 10211 12.so.0.11[.0]
  180379. * 1.0.20 10 10020 10.so.0.20[.0]
  180380. * 1.2.12 13 10212 12.so.0.12[.0]
  180381. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180382. * 1.0.21 10 10021 10.so.0.21[.0]
  180383. * 1.2.13 13 10213 12.so.0.13[.0]
  180384. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180385. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180386. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180387. * 1.0.22 10 10022 10.so.0.22[.0]
  180388. * 1.2.14 13 10214 12.so.0.14[.0]
  180389. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180390. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180391. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180392. * 1.0.23 10 10023 10.so.0.23[.0]
  180393. * 1.2.15 13 10215 12.so.0.15[.0]
  180394. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180395. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180396. * 1.0.24 10 10024 10.so.0.24[.0]
  180397. * 1.2.16 13 10216 12.so.0.16[.0]
  180398. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180399. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180400. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180401. * 1.0.25 10 10025 10.so.0.25[.0]
  180402. * 1.2.17 13 10217 12.so.0.17[.0]
  180403. * 1.0.26 10 10026 10.so.0.26[.0]
  180404. * 1.2.18 13 10218 12.so.0.18[.0]
  180405. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180406. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180407. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180408. * 1.0.27 10 10027 10.so.0.27[.0]
  180409. * 1.2.19 13 10219 12.so.0.19[.0]
  180410. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180411. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180412. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180413. * 1.0.28 10 10028 10.so.0.28[.0]
  180414. * 1.2.20 13 10220 12.so.0.20[.0]
  180415. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180416. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180417. * 1.0.29 10 10029 10.so.0.29[.0]
  180418. * 1.2.21 13 10221 12.so.0.21[.0]
  180419. *
  180420. * Henceforth the source version will match the shared-library major
  180421. * and minor numbers; the shared-library major version number will be
  180422. * used for changes in backward compatibility, as it is intended. The
  180423. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180424. * for applications, is an unsigned integer of the form xyyzz corresponding
  180425. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180426. * were given the previous public release number plus a letter, until
  180427. * version 1.0.6j; from then on they were given the upcoming public
  180428. * release number plus "betaNN" or "rcN".
  180429. *
  180430. * Binary incompatibility exists only when applications make direct access
  180431. * to the info_ptr or png_ptr members through png.h, and the compiled
  180432. * application is loaded with a different version of the library.
  180433. *
  180434. * DLLNUM will change each time there are forward or backward changes
  180435. * in binary compatibility (e.g., when a new feature is added).
  180436. *
  180437. * See libpng.txt or libpng.3 for more information. The PNG specification
  180438. * is available as a W3C Recommendation and as an ISO Specification,
  180439. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180440. */
  180441. /*
  180442. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180443. *
  180444. * If you modify libpng you may insert additional notices immediately following
  180445. * this sentence.
  180446. *
  180447. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180448. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180449. * distributed according to the same disclaimer and license as libpng-1.2.5
  180450. * with the following individual added to the list of Contributing Authors:
  180451. *
  180452. * Cosmin Truta
  180453. *
  180454. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180455. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180456. * distributed according to the same disclaimer and license as libpng-1.0.6
  180457. * with the following individuals added to the list of Contributing Authors:
  180458. *
  180459. * Simon-Pierre Cadieux
  180460. * Eric S. Raymond
  180461. * Gilles Vollant
  180462. *
  180463. * and with the following additions to the disclaimer:
  180464. *
  180465. * There is no warranty against interference with your enjoyment of the
  180466. * library or against infringement. There is no warranty that our
  180467. * efforts or the library will fulfill any of your particular purposes
  180468. * or needs. This library is provided with all faults, and the entire
  180469. * risk of satisfactory quality, performance, accuracy, and effort is with
  180470. * the user.
  180471. *
  180472. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180473. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180474. * distributed according to the same disclaimer and license as libpng-0.96,
  180475. * with the following individuals added to the list of Contributing Authors:
  180476. *
  180477. * Tom Lane
  180478. * Glenn Randers-Pehrson
  180479. * Willem van Schaik
  180480. *
  180481. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180482. * Copyright (c) 1996, 1997 Andreas Dilger
  180483. * Distributed according to the same disclaimer and license as libpng-0.88,
  180484. * with the following individuals added to the list of Contributing Authors:
  180485. *
  180486. * John Bowler
  180487. * Kevin Bracey
  180488. * Sam Bushell
  180489. * Magnus Holmgren
  180490. * Greg Roelofs
  180491. * Tom Tanner
  180492. *
  180493. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180494. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180495. *
  180496. * For the purposes of this copyright and license, "Contributing Authors"
  180497. * is defined as the following set of individuals:
  180498. *
  180499. * Andreas Dilger
  180500. * Dave Martindale
  180501. * Guy Eric Schalnat
  180502. * Paul Schmidt
  180503. * Tim Wegner
  180504. *
  180505. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180506. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180507. * including, without limitation, the warranties of merchantability and of
  180508. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180509. * assume no liability for direct, indirect, incidental, special, exemplary,
  180510. * or consequential damages, which may result from the use of the PNG
  180511. * Reference Library, even if advised of the possibility of such damage.
  180512. *
  180513. * Permission is hereby granted to use, copy, modify, and distribute this
  180514. * source code, or portions hereof, for any purpose, without fee, subject
  180515. * to the following restrictions:
  180516. *
  180517. * 1. The origin of this source code must not be misrepresented.
  180518. *
  180519. * 2. Altered versions must be plainly marked as such and
  180520. * must not be misrepresented as being the original source.
  180521. *
  180522. * 3. This Copyright notice may not be removed or altered from
  180523. * any source or altered source distribution.
  180524. *
  180525. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180526. * fee, and encourage the use of this source code as a component to
  180527. * supporting the PNG file format in commercial products. If you use this
  180528. * source code in a product, acknowledgment is not required but would be
  180529. * appreciated.
  180530. */
  180531. /*
  180532. * A "png_get_copyright" function is available, for convenient use in "about"
  180533. * boxes and the like:
  180534. *
  180535. * printf("%s",png_get_copyright(NULL));
  180536. *
  180537. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180538. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180539. */
  180540. /*
  180541. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180542. * certification mark of the Open Source Initiative.
  180543. */
  180544. /*
  180545. * The contributing authors would like to thank all those who helped
  180546. * with testing, bug fixes, and patience. This wouldn't have been
  180547. * possible without all of you.
  180548. *
  180549. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180550. */
  180551. /*
  180552. * Y2K compliance in libpng:
  180553. * =========================
  180554. *
  180555. * October 4, 2007
  180556. *
  180557. * Since the PNG Development group is an ad-hoc body, we can't make
  180558. * an official declaration.
  180559. *
  180560. * This is your unofficial assurance that libpng from version 0.71 and
  180561. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180562. * versions were also Y2K compliant.
  180563. *
  180564. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180565. * that will hold years up to 65535. The other two hold the date in text
  180566. * format, and will hold years up to 9999.
  180567. *
  180568. * The integer is
  180569. * "png_uint_16 year" in png_time_struct.
  180570. *
  180571. * The strings are
  180572. * "png_charp time_buffer" in png_struct and
  180573. * "near_time_buffer", which is a local character string in png.c.
  180574. *
  180575. * There are seven time-related functions:
  180576. * png.c: png_convert_to_rfc_1123() in png.c
  180577. * (formerly png_convert_to_rfc_1152() in error)
  180578. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180579. * png_convert_from_time_t() in pngwrite.c
  180580. * png_get_tIME() in pngget.c
  180581. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180582. * png_set_tIME() in pngset.c
  180583. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180584. *
  180585. * All handle dates properly in a Y2K environment. The
  180586. * png_convert_from_time_t() function calls gmtime() to convert from system
  180587. * clock time, which returns (year - 1900), which we properly convert to
  180588. * the full 4-digit year. There is a possibility that applications using
  180589. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180590. * function, or that they are incorrectly passing only a 2-digit year
  180591. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180592. * but this is not under our control. The libpng documentation has always
  180593. * stated that it works with 4-digit years, and the APIs have been
  180594. * documented as such.
  180595. *
  180596. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180597. * integer to hold the year, and can hold years as large as 65535.
  180598. *
  180599. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180600. * no date-related code.
  180601. *
  180602. * Glenn Randers-Pehrson
  180603. * libpng maintainer
  180604. * PNG Development Group
  180605. */
  180606. #ifndef PNG_H
  180607. #define PNG_H
  180608. /* This is not the place to learn how to use libpng. The file libpng.txt
  180609. * describes how to use libpng, and the file example.c summarizes it
  180610. * with some code on which to build. This file is useful for looking
  180611. * at the actual function definitions and structure components.
  180612. */
  180613. /* Version information for png.h - this should match the version in png.c */
  180614. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180615. #define PNG_HEADER_VERSION_STRING \
  180616. " libpng version 1.2.21 - October 4, 2007\n"
  180617. #define PNG_LIBPNG_VER_SONUM 0
  180618. #define PNG_LIBPNG_VER_DLLNUM 13
  180619. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180620. #define PNG_LIBPNG_VER_MAJOR 1
  180621. #define PNG_LIBPNG_VER_MINOR 2
  180622. #define PNG_LIBPNG_VER_RELEASE 21
  180623. /* This should match the numeric part of the final component of
  180624. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180625. #define PNG_LIBPNG_VER_BUILD 0
  180626. /* Release Status */
  180627. #define PNG_LIBPNG_BUILD_ALPHA 1
  180628. #define PNG_LIBPNG_BUILD_BETA 2
  180629. #define PNG_LIBPNG_BUILD_RC 3
  180630. #define PNG_LIBPNG_BUILD_STABLE 4
  180631. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180632. /* Release-Specific Flags */
  180633. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180634. PNG_LIBPNG_BUILD_STABLE only */
  180635. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180636. PNG_LIBPNG_BUILD_SPECIAL */
  180637. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180638. PNG_LIBPNG_BUILD_PRIVATE */
  180639. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180640. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180641. * We must not include leading zeros.
  180642. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180643. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180644. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180645. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180646. #ifndef PNG_VERSION_INFO_ONLY
  180647. /* include the compression library's header */
  180648. #endif
  180649. /* include all user configurable info, including optional assembler routines */
  180650. /*** Start of inlined file: pngconf.h ***/
  180651. /* pngconf.h - machine configurable file for libpng
  180652. *
  180653. * libpng version 1.2.21 - October 4, 2007
  180654. * For conditions of distribution and use, see copyright notice in png.h
  180655. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180656. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180657. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180658. */
  180659. /* Any machine specific code is near the front of this file, so if you
  180660. * are configuring libpng for a machine, you may want to read the section
  180661. * starting here down to where it starts to typedef png_color, png_text,
  180662. * and png_info.
  180663. */
  180664. #ifndef PNGCONF_H
  180665. #define PNGCONF_H
  180666. #define PNG_1_2_X
  180667. // These are some Juce config settings that should remove any unnecessary code bloat..
  180668. #define PNG_NO_STDIO 1
  180669. #define PNG_DEBUG 0
  180670. #define PNG_NO_WARNINGS 1
  180671. #define PNG_NO_ERROR_TEXT 1
  180672. #define PNG_NO_ERROR_NUMBERS 1
  180673. #define PNG_NO_USER_MEM 1
  180674. #define PNG_NO_READ_iCCP 1
  180675. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180676. #define PNG_NO_READ_USER_CHUNKS 1
  180677. #define PNG_NO_READ_iTXt 1
  180678. #define PNG_NO_READ_sCAL 1
  180679. #define PNG_NO_READ_sPLT 1
  180680. #define png_error(a, b) png_err(a)
  180681. #define png_warning(a, b)
  180682. #define png_chunk_error(a, b) png_err(a)
  180683. #define png_chunk_warning(a, b)
  180684. /*
  180685. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180686. * includes the resource compiler for Windows DLL configurations.
  180687. */
  180688. #ifdef PNG_USER_CONFIG
  180689. # ifndef PNG_USER_PRIVATEBUILD
  180690. # define PNG_USER_PRIVATEBUILD
  180691. # endif
  180692. #include "pngusr.h"
  180693. #endif
  180694. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180695. #ifdef PNG_CONFIGURE_LIBPNG
  180696. #ifdef HAVE_CONFIG_H
  180697. #include "config.h"
  180698. #endif
  180699. #endif
  180700. /*
  180701. * Added at libpng-1.2.8
  180702. *
  180703. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180704. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180705. * the DLL was built>
  180706. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180707. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180708. * distinguish your DLL from those of the official release. These
  180709. * correspond to the trailing letters that come after the version
  180710. * number and must match your private DLL name>
  180711. * e.g. // private DLL "libpng13gx.dll"
  180712. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180713. *
  180714. * The following macros are also at your disposal if you want to complete the
  180715. * DLL VERSIONINFO structure.
  180716. * - PNG_USER_VERSIONINFO_COMMENTS
  180717. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180718. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180719. */
  180720. #ifdef __STDC__
  180721. #ifdef SPECIALBUILD
  180722. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180723. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180724. #endif
  180725. #ifdef PRIVATEBUILD
  180726. # pragma message("PRIVATEBUILD is deprecated.\
  180727. Use PNG_USER_PRIVATEBUILD instead.")
  180728. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180729. #endif
  180730. #endif /* __STDC__ */
  180731. #ifndef PNG_VERSION_INFO_ONLY
  180732. /* End of material added to libpng-1.2.8 */
  180733. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180734. Restored at libpng-1.2.21 */
  180735. # define PNG_WARN_UNINITIALIZED_ROW 1
  180736. /* End of material added at libpng-1.2.19/1.2.21 */
  180737. /* This is the size of the compression buffer, and thus the size of
  180738. * an IDAT chunk. Make this whatever size you feel is best for your
  180739. * machine. One of these will be allocated per png_struct. When this
  180740. * is full, it writes the data to the disk, and does some other
  180741. * calculations. Making this an extremely small size will slow
  180742. * the library down, but you may want to experiment to determine
  180743. * where it becomes significant, if you are concerned with memory
  180744. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180745. * this describes the size of the buffer available to read the data in.
  180746. * Unless this gets smaller than the size of a row (compressed),
  180747. * it should not make much difference how big this is.
  180748. */
  180749. #ifndef PNG_ZBUF_SIZE
  180750. # define PNG_ZBUF_SIZE 8192
  180751. #endif
  180752. /* Enable if you want a write-only libpng */
  180753. #ifndef PNG_NO_READ_SUPPORTED
  180754. # define PNG_READ_SUPPORTED
  180755. #endif
  180756. /* Enable if you want a read-only libpng */
  180757. #ifndef PNG_NO_WRITE_SUPPORTED
  180758. # define PNG_WRITE_SUPPORTED
  180759. #endif
  180760. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180761. support PNGs that are embedded in MNG datastreams */
  180762. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180763. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180764. # define PNG_MNG_FEATURES_SUPPORTED
  180765. # endif
  180766. #endif
  180767. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180768. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180769. # define PNG_FLOATING_POINT_SUPPORTED
  180770. # endif
  180771. #endif
  180772. /* If you are running on a machine where you cannot allocate more
  180773. * than 64K of memory at once, uncomment this. While libpng will not
  180774. * normally need that much memory in a chunk (unless you load up a very
  180775. * large file), zlib needs to know how big of a chunk it can use, and
  180776. * libpng thus makes sure to check any memory allocation to verify it
  180777. * will fit into memory.
  180778. #define PNG_MAX_MALLOC_64K
  180779. */
  180780. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180781. # define PNG_MAX_MALLOC_64K
  180782. #endif
  180783. /* Special munging to support doing things the 'cygwin' way:
  180784. * 'Normal' png-on-win32 defines/defaults:
  180785. * PNG_BUILD_DLL -- building dll
  180786. * PNG_USE_DLL -- building an application, linking to dll
  180787. * (no define) -- building static library, or building an
  180788. * application and linking to the static lib
  180789. * 'Cygwin' defines/defaults:
  180790. * PNG_BUILD_DLL -- (ignored) building the dll
  180791. * (no define) -- (ignored) building an application, linking to the dll
  180792. * PNG_STATIC -- (ignored) building the static lib, or building an
  180793. * application that links to the static lib.
  180794. * ALL_STATIC -- (ignored) building various static libs, or building an
  180795. * application that links to the static libs.
  180796. * Thus,
  180797. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180798. * this bit of #ifdefs will define the 'correct' config variables based on
  180799. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180800. * unnecessary.
  180801. *
  180802. * Also, the precedence order is:
  180803. * ALL_STATIC (since we can't #undef something outside our namespace)
  180804. * PNG_BUILD_DLL
  180805. * PNG_STATIC
  180806. * (nothing) == PNG_USE_DLL
  180807. *
  180808. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180809. * of auto-import in binutils, we no longer need to worry about
  180810. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180811. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180812. * to __declspec() stuff. However, we DO need to worry about
  180813. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180814. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180815. */
  180816. #if defined(__CYGWIN__)
  180817. # if defined(ALL_STATIC)
  180818. # if defined(PNG_BUILD_DLL)
  180819. # undef PNG_BUILD_DLL
  180820. # endif
  180821. # if defined(PNG_USE_DLL)
  180822. # undef PNG_USE_DLL
  180823. # endif
  180824. # if defined(PNG_DLL)
  180825. # undef PNG_DLL
  180826. # endif
  180827. # if !defined(PNG_STATIC)
  180828. # define PNG_STATIC
  180829. # endif
  180830. # else
  180831. # if defined (PNG_BUILD_DLL)
  180832. # if defined(PNG_STATIC)
  180833. # undef PNG_STATIC
  180834. # endif
  180835. # if defined(PNG_USE_DLL)
  180836. # undef PNG_USE_DLL
  180837. # endif
  180838. # if !defined(PNG_DLL)
  180839. # define PNG_DLL
  180840. # endif
  180841. # else
  180842. # if defined(PNG_STATIC)
  180843. # if defined(PNG_USE_DLL)
  180844. # undef PNG_USE_DLL
  180845. # endif
  180846. # if defined(PNG_DLL)
  180847. # undef PNG_DLL
  180848. # endif
  180849. # else
  180850. # if !defined(PNG_USE_DLL)
  180851. # define PNG_USE_DLL
  180852. # endif
  180853. # if !defined(PNG_DLL)
  180854. # define PNG_DLL
  180855. # endif
  180856. # endif
  180857. # endif
  180858. # endif
  180859. #endif
  180860. /* This protects us against compilers that run on a windowing system
  180861. * and thus don't have or would rather us not use the stdio types:
  180862. * stdin, stdout, and stderr. The only one currently used is stderr
  180863. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180864. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180865. * will also prevent these, plus will prevent the entire set of stdio
  180866. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180867. * unless (PNG_DEBUG > 0) has been #defined.
  180868. *
  180869. * #define PNG_NO_CONSOLE_IO
  180870. * #define PNG_NO_STDIO
  180871. */
  180872. #if defined(_WIN32_WCE)
  180873. # include <windows.h>
  180874. /* Console I/O functions are not supported on WindowsCE */
  180875. # define PNG_NO_CONSOLE_IO
  180876. # ifdef PNG_DEBUG
  180877. # undef PNG_DEBUG
  180878. # endif
  180879. #endif
  180880. #ifdef PNG_BUILD_DLL
  180881. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180882. # ifndef PNG_NO_CONSOLE_IO
  180883. # define PNG_NO_CONSOLE_IO
  180884. # endif
  180885. # endif
  180886. #endif
  180887. # ifdef PNG_NO_STDIO
  180888. # ifndef PNG_NO_CONSOLE_IO
  180889. # define PNG_NO_CONSOLE_IO
  180890. # endif
  180891. # ifdef PNG_DEBUG
  180892. # if (PNG_DEBUG > 0)
  180893. # include <stdio.h>
  180894. # endif
  180895. # endif
  180896. # else
  180897. # if !defined(_WIN32_WCE)
  180898. /* "stdio.h" functions are not supported on WindowsCE */
  180899. # include <stdio.h>
  180900. # endif
  180901. # endif
  180902. /* This macro protects us against machines that don't have function
  180903. * prototypes (ie K&R style headers). If your compiler does not handle
  180904. * function prototypes, define this macro and use the included ansi2knr.
  180905. * I've always been able to use _NO_PROTO as the indicator, but you may
  180906. * need to drag the empty declaration out in front of here, or change the
  180907. * ifdef to suit your own needs.
  180908. */
  180909. #ifndef PNGARG
  180910. #ifdef OF /* zlib prototype munger */
  180911. # define PNGARG(arglist) OF(arglist)
  180912. #else
  180913. #ifdef _NO_PROTO
  180914. # define PNGARG(arglist) ()
  180915. # ifndef PNG_TYPECAST_NULL
  180916. # define PNG_TYPECAST_NULL
  180917. # endif
  180918. #else
  180919. # define PNGARG(arglist) arglist
  180920. #endif /* _NO_PROTO */
  180921. #endif /* OF */
  180922. #endif /* PNGARG */
  180923. /* Try to determine if we are compiling on a Mac. Note that testing for
  180924. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180925. * on non-Mac platforms.
  180926. */
  180927. #ifndef MACOS
  180928. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180929. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180930. # define MACOS
  180931. # endif
  180932. #endif
  180933. /* enough people need this for various reasons to include it here */
  180934. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180935. # include <sys/types.h>
  180936. #endif
  180937. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180938. # define PNG_SETJMP_SUPPORTED
  180939. #endif
  180940. #ifdef PNG_SETJMP_SUPPORTED
  180941. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180942. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180943. */
  180944. # ifdef __linux__
  180945. # ifdef _BSD_SOURCE
  180946. # define PNG_SAVE_BSD_SOURCE
  180947. # undef _BSD_SOURCE
  180948. # endif
  180949. # ifdef _SETJMP_H
  180950. /* If you encounter a compiler error here, see the explanation
  180951. * near the end of INSTALL.
  180952. */
  180953. __png.h__ already includes setjmp.h;
  180954. __dont__ include it again.;
  180955. # endif
  180956. # endif /* __linux__ */
  180957. /* include setjmp.h for error handling */
  180958. # include <setjmp.h>
  180959. # ifdef __linux__
  180960. # ifdef PNG_SAVE_BSD_SOURCE
  180961. # define _BSD_SOURCE
  180962. # undef PNG_SAVE_BSD_SOURCE
  180963. # endif
  180964. # endif /* __linux__ */
  180965. #endif /* PNG_SETJMP_SUPPORTED */
  180966. #ifdef BSD
  180967. #if ! JUCE_MAC
  180968. # include <strings.h>
  180969. #endif
  180970. #else
  180971. # include <string.h>
  180972. #endif
  180973. /* Other defines for things like memory and the like can go here. */
  180974. #ifdef PNG_INTERNAL
  180975. #include <stdlib.h>
  180976. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180977. * aren't usually used outside the library (as far as I know), so it is
  180978. * debatable if they should be exported at all. In the future, when it is
  180979. * possible to have run-time registry of chunk-handling functions, some of
  180980. * these will be made available again.
  180981. #define PNG_EXTERN extern
  180982. */
  180983. #define PNG_EXTERN
  180984. /* Other defines specific to compilers can go here. Try to keep
  180985. * them inside an appropriate ifdef/endif pair for portability.
  180986. */
  180987. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180988. # if defined(MACOS)
  180989. /* We need to check that <math.h> hasn't already been included earlier
  180990. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180991. * <fp.h> if possible.
  180992. */
  180993. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180994. # include <fp.h>
  180995. # endif
  180996. # else
  180997. # include <math.h>
  180998. # endif
  180999. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181000. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181001. * MATH=68881
  181002. */
  181003. # include <m68881.h>
  181004. # endif
  181005. #endif
  181006. /* Codewarrior on NT has linking problems without this. */
  181007. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181008. # define PNG_ALWAYS_EXTERN
  181009. #endif
  181010. /* This provides the non-ANSI (far) memory allocation routines. */
  181011. #if defined(__TURBOC__) && defined(__MSDOS__)
  181012. # include <mem.h>
  181013. # include <alloc.h>
  181014. #endif
  181015. /* I have no idea why is this necessary... */
  181016. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181017. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181018. # include <malloc.h>
  181019. #endif
  181020. /* This controls how fine the dithering gets. As this allocates
  181021. * a largish chunk of memory (32K), those who are not as concerned
  181022. * with dithering quality can decrease some or all of these.
  181023. */
  181024. #ifndef PNG_DITHER_RED_BITS
  181025. # define PNG_DITHER_RED_BITS 5
  181026. #endif
  181027. #ifndef PNG_DITHER_GREEN_BITS
  181028. # define PNG_DITHER_GREEN_BITS 5
  181029. #endif
  181030. #ifndef PNG_DITHER_BLUE_BITS
  181031. # define PNG_DITHER_BLUE_BITS 5
  181032. #endif
  181033. /* This controls how fine the gamma correction becomes when you
  181034. * are only interested in 8 bits anyway. Increasing this value
  181035. * results in more memory being used, and more pow() functions
  181036. * being called to fill in the gamma tables. Don't set this value
  181037. * less then 8, and even that may not work (I haven't tested it).
  181038. */
  181039. #ifndef PNG_MAX_GAMMA_8
  181040. # define PNG_MAX_GAMMA_8 11
  181041. #endif
  181042. /* This controls how much a difference in gamma we can tolerate before
  181043. * we actually start doing gamma conversion.
  181044. */
  181045. #ifndef PNG_GAMMA_THRESHOLD
  181046. # define PNG_GAMMA_THRESHOLD 0.05
  181047. #endif
  181048. #endif /* PNG_INTERNAL */
  181049. /* The following uses const char * instead of char * for error
  181050. * and warning message functions, so some compilers won't complain.
  181051. * If you do not want to use const, define PNG_NO_CONST here.
  181052. */
  181053. #ifndef PNG_NO_CONST
  181054. # define PNG_CONST const
  181055. #else
  181056. # define PNG_CONST
  181057. #endif
  181058. /* The following defines give you the ability to remove code from the
  181059. * library that you will not be using. I wish I could figure out how to
  181060. * automate this, but I can't do that without making it seriously hard
  181061. * on the users. So if you are not using an ability, change the #define
  181062. * to and #undef, and that part of the library will not be compiled. If
  181063. * your linker can't find a function, you may want to make sure the
  181064. * ability is defined here. Some of these depend upon some others being
  181065. * defined. I haven't figured out all the interactions here, so you may
  181066. * have to experiment awhile to get everything to compile. If you are
  181067. * creating or using a shared library, you probably shouldn't touch this,
  181068. * as it will affect the size of the structures, and this will cause bad
  181069. * things to happen if the library and/or application ever change.
  181070. */
  181071. /* Any features you will not be using can be undef'ed here */
  181072. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181073. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181074. * on the compile line, then pick and choose which ones to define without
  181075. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181076. * if you only want to have a png-compliant reader/writer but don't need
  181077. * any of the extra transformations. This saves about 80 kbytes in a
  181078. * typical installation of the library. (PNG_NO_* form added in version
  181079. * 1.0.1c, for consistency)
  181080. */
  181081. /* The size of the png_text structure changed in libpng-1.0.6 when
  181082. * iTXt support was added. iTXt support was turned off by default through
  181083. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181084. * instead of calling png_set_text() and letting libpng malloc it. It
  181085. * was turned on by default in libpng-1.3.0.
  181086. */
  181087. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181088. # ifndef PNG_NO_iTXt_SUPPORTED
  181089. # define PNG_NO_iTXt_SUPPORTED
  181090. # endif
  181091. # ifndef PNG_NO_READ_iTXt
  181092. # define PNG_NO_READ_iTXt
  181093. # endif
  181094. # ifndef PNG_NO_WRITE_iTXt
  181095. # define PNG_NO_WRITE_iTXt
  181096. # endif
  181097. #endif
  181098. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181099. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181100. # define PNG_READ_iTXt
  181101. # endif
  181102. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181103. # define PNG_WRITE_iTXt
  181104. # endif
  181105. #endif
  181106. /* The following support, added after version 1.0.0, can be turned off here en
  181107. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181108. * with old applications that require the length of png_struct and png_info
  181109. * to remain unchanged.
  181110. */
  181111. #ifdef PNG_LEGACY_SUPPORTED
  181112. # define PNG_NO_FREE_ME
  181113. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181114. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181115. # define PNG_NO_READ_USER_CHUNKS
  181116. # define PNG_NO_READ_iCCP
  181117. # define PNG_NO_WRITE_iCCP
  181118. # define PNG_NO_READ_iTXt
  181119. # define PNG_NO_WRITE_iTXt
  181120. # define PNG_NO_READ_sCAL
  181121. # define PNG_NO_WRITE_sCAL
  181122. # define PNG_NO_READ_sPLT
  181123. # define PNG_NO_WRITE_sPLT
  181124. # define PNG_NO_INFO_IMAGE
  181125. # define PNG_NO_READ_RGB_TO_GRAY
  181126. # define PNG_NO_READ_USER_TRANSFORM
  181127. # define PNG_NO_WRITE_USER_TRANSFORM
  181128. # define PNG_NO_USER_MEM
  181129. # define PNG_NO_READ_EMPTY_PLTE
  181130. # define PNG_NO_MNG_FEATURES
  181131. # define PNG_NO_FIXED_POINT_SUPPORTED
  181132. #endif
  181133. /* Ignore attempt to turn off both floating and fixed point support */
  181134. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181135. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181136. # define PNG_FIXED_POINT_SUPPORTED
  181137. #endif
  181138. #ifndef PNG_NO_FREE_ME
  181139. # define PNG_FREE_ME_SUPPORTED
  181140. #endif
  181141. #if defined(PNG_READ_SUPPORTED)
  181142. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181143. !defined(PNG_NO_READ_TRANSFORMS)
  181144. # define PNG_READ_TRANSFORMS_SUPPORTED
  181145. #endif
  181146. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181147. # ifndef PNG_NO_READ_EXPAND
  181148. # define PNG_READ_EXPAND_SUPPORTED
  181149. # endif
  181150. # ifndef PNG_NO_READ_SHIFT
  181151. # define PNG_READ_SHIFT_SUPPORTED
  181152. # endif
  181153. # ifndef PNG_NO_READ_PACK
  181154. # define PNG_READ_PACK_SUPPORTED
  181155. # endif
  181156. # ifndef PNG_NO_READ_BGR
  181157. # define PNG_READ_BGR_SUPPORTED
  181158. # endif
  181159. # ifndef PNG_NO_READ_SWAP
  181160. # define PNG_READ_SWAP_SUPPORTED
  181161. # endif
  181162. # ifndef PNG_NO_READ_PACKSWAP
  181163. # define PNG_READ_PACKSWAP_SUPPORTED
  181164. # endif
  181165. # ifndef PNG_NO_READ_INVERT
  181166. # define PNG_READ_INVERT_SUPPORTED
  181167. # endif
  181168. # ifndef PNG_NO_READ_DITHER
  181169. # define PNG_READ_DITHER_SUPPORTED
  181170. # endif
  181171. # ifndef PNG_NO_READ_BACKGROUND
  181172. # define PNG_READ_BACKGROUND_SUPPORTED
  181173. # endif
  181174. # ifndef PNG_NO_READ_16_TO_8
  181175. # define PNG_READ_16_TO_8_SUPPORTED
  181176. # endif
  181177. # ifndef PNG_NO_READ_FILLER
  181178. # define PNG_READ_FILLER_SUPPORTED
  181179. # endif
  181180. # ifndef PNG_NO_READ_GAMMA
  181181. # define PNG_READ_GAMMA_SUPPORTED
  181182. # endif
  181183. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181184. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181185. # endif
  181186. # ifndef PNG_NO_READ_SWAP_ALPHA
  181187. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181188. # endif
  181189. # ifndef PNG_NO_READ_INVERT_ALPHA
  181190. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181191. # endif
  181192. # ifndef PNG_NO_READ_STRIP_ALPHA
  181193. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181194. # endif
  181195. # ifndef PNG_NO_READ_USER_TRANSFORM
  181196. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181197. # endif
  181198. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181199. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181200. # endif
  181201. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181202. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181203. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181204. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181205. #endif /* about interlacing capability! You'll */
  181206. /* still have interlacing unless you change the following line: */
  181207. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181208. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181209. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181210. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181211. # endif
  181212. #endif
  181213. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181214. /* Deprecated, will be removed from version 2.0.0.
  181215. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181216. #ifndef PNG_NO_READ_EMPTY_PLTE
  181217. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181218. #endif
  181219. #endif
  181220. #endif /* PNG_READ_SUPPORTED */
  181221. #if defined(PNG_WRITE_SUPPORTED)
  181222. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181223. !defined(PNG_NO_WRITE_TRANSFORMS)
  181224. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181225. #endif
  181226. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181227. # ifndef PNG_NO_WRITE_SHIFT
  181228. # define PNG_WRITE_SHIFT_SUPPORTED
  181229. # endif
  181230. # ifndef PNG_NO_WRITE_PACK
  181231. # define PNG_WRITE_PACK_SUPPORTED
  181232. # endif
  181233. # ifndef PNG_NO_WRITE_BGR
  181234. # define PNG_WRITE_BGR_SUPPORTED
  181235. # endif
  181236. # ifndef PNG_NO_WRITE_SWAP
  181237. # define PNG_WRITE_SWAP_SUPPORTED
  181238. # endif
  181239. # ifndef PNG_NO_WRITE_PACKSWAP
  181240. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181241. # endif
  181242. # ifndef PNG_NO_WRITE_INVERT
  181243. # define PNG_WRITE_INVERT_SUPPORTED
  181244. # endif
  181245. # ifndef PNG_NO_WRITE_FILLER
  181246. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181247. # endif
  181248. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181249. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181250. # endif
  181251. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181252. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181253. # endif
  181254. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181255. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181256. # endif
  181257. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181258. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181259. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181260. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181261. encoders, but can cause trouble
  181262. if left undefined */
  181263. #endif
  181264. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181265. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181266. defined(PNG_FLOATING_POINT_SUPPORTED)
  181267. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181268. #endif
  181269. #ifndef PNG_NO_WRITE_FLUSH
  181270. # define PNG_WRITE_FLUSH_SUPPORTED
  181271. #endif
  181272. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181273. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181274. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181275. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181276. #endif
  181277. #endif
  181278. #endif /* PNG_WRITE_SUPPORTED */
  181279. #ifndef PNG_1_0_X
  181280. # ifndef PNG_NO_ERROR_NUMBERS
  181281. # define PNG_ERROR_NUMBERS_SUPPORTED
  181282. # endif
  181283. #endif /* PNG_1_0_X */
  181284. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181285. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181286. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181287. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181288. # endif
  181289. #endif
  181290. #ifndef PNG_NO_STDIO
  181291. # define PNG_TIME_RFC1123_SUPPORTED
  181292. #endif
  181293. /* This adds extra functions in pngget.c for accessing data from the
  181294. * info pointer (added in version 0.99)
  181295. * png_get_image_width()
  181296. * png_get_image_height()
  181297. * png_get_bit_depth()
  181298. * png_get_color_type()
  181299. * png_get_compression_type()
  181300. * png_get_filter_type()
  181301. * png_get_interlace_type()
  181302. * png_get_pixel_aspect_ratio()
  181303. * png_get_pixels_per_meter()
  181304. * png_get_x_offset_pixels()
  181305. * png_get_y_offset_pixels()
  181306. * png_get_x_offset_microns()
  181307. * png_get_y_offset_microns()
  181308. */
  181309. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181310. # define PNG_EASY_ACCESS_SUPPORTED
  181311. #endif
  181312. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181313. * and removed from version 1.2.20. The following will be removed
  181314. * from libpng-1.4.0
  181315. */
  181316. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181317. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181318. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181319. # endif
  181320. #endif
  181321. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181322. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181323. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181324. # endif
  181325. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181326. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181327. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181328. # define PNG_NO_MMX_CODE
  181329. # endif
  181330. # endif
  181331. # if defined(__APPLE__)
  181332. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181333. # define PNG_NO_MMX_CODE
  181334. # endif
  181335. # endif
  181336. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181337. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181338. # define PNG_NO_MMX_CODE
  181339. # endif
  181340. # endif
  181341. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181342. # define PNG_MMX_CODE_SUPPORTED
  181343. # endif
  181344. #endif
  181345. /* end of obsolete code to be removed from libpng-1.4.0 */
  181346. #if !defined(PNG_1_0_X)
  181347. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181348. # define PNG_USER_MEM_SUPPORTED
  181349. #endif
  181350. #endif /* PNG_1_0_X */
  181351. /* Added at libpng-1.2.6 */
  181352. #if !defined(PNG_1_0_X)
  181353. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181354. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181355. # define PNG_SET_USER_LIMITS_SUPPORTED
  181356. #endif
  181357. #endif
  181358. #endif /* PNG_1_0_X */
  181359. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181360. * how large, set these limits to 0x7fffffffL
  181361. */
  181362. #ifndef PNG_USER_WIDTH_MAX
  181363. # define PNG_USER_WIDTH_MAX 1000000L
  181364. #endif
  181365. #ifndef PNG_USER_HEIGHT_MAX
  181366. # define PNG_USER_HEIGHT_MAX 1000000L
  181367. #endif
  181368. /* These are currently experimental features, define them if you want */
  181369. /* very little testing */
  181370. /*
  181371. #ifdef PNG_READ_SUPPORTED
  181372. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181373. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181374. # endif
  181375. #endif
  181376. */
  181377. /* This is only for PowerPC big-endian and 680x0 systems */
  181378. /* some testing */
  181379. /*
  181380. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181381. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181382. #endif
  181383. */
  181384. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181385. /*
  181386. #define PNG_NO_POINTER_INDEXING
  181387. */
  181388. /* These functions are turned off by default, as they will be phased out. */
  181389. /*
  181390. #define PNG_USELESS_TESTS_SUPPORTED
  181391. #define PNG_CORRECT_PALETTE_SUPPORTED
  181392. */
  181393. /* Any chunks you are not interested in, you can undef here. The
  181394. * ones that allocate memory may be expecially important (hIST,
  181395. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181396. * a bit smaller.
  181397. */
  181398. #if defined(PNG_READ_SUPPORTED) && \
  181399. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181400. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181401. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181402. #endif
  181403. #if defined(PNG_WRITE_SUPPORTED) && \
  181404. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181405. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181406. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181407. #endif
  181408. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181409. #ifdef PNG_NO_READ_TEXT
  181410. # define PNG_NO_READ_iTXt
  181411. # define PNG_NO_READ_tEXt
  181412. # define PNG_NO_READ_zTXt
  181413. #endif
  181414. #ifndef PNG_NO_READ_bKGD
  181415. # define PNG_READ_bKGD_SUPPORTED
  181416. # define PNG_bKGD_SUPPORTED
  181417. #endif
  181418. #ifndef PNG_NO_READ_cHRM
  181419. # define PNG_READ_cHRM_SUPPORTED
  181420. # define PNG_cHRM_SUPPORTED
  181421. #endif
  181422. #ifndef PNG_NO_READ_gAMA
  181423. # define PNG_READ_gAMA_SUPPORTED
  181424. # define PNG_gAMA_SUPPORTED
  181425. #endif
  181426. #ifndef PNG_NO_READ_hIST
  181427. # define PNG_READ_hIST_SUPPORTED
  181428. # define PNG_hIST_SUPPORTED
  181429. #endif
  181430. #ifndef PNG_NO_READ_iCCP
  181431. # define PNG_READ_iCCP_SUPPORTED
  181432. # define PNG_iCCP_SUPPORTED
  181433. #endif
  181434. #ifndef PNG_NO_READ_iTXt
  181435. # ifndef PNG_READ_iTXt_SUPPORTED
  181436. # define PNG_READ_iTXt_SUPPORTED
  181437. # endif
  181438. # ifndef PNG_iTXt_SUPPORTED
  181439. # define PNG_iTXt_SUPPORTED
  181440. # endif
  181441. #endif
  181442. #ifndef PNG_NO_READ_oFFs
  181443. # define PNG_READ_oFFs_SUPPORTED
  181444. # define PNG_oFFs_SUPPORTED
  181445. #endif
  181446. #ifndef PNG_NO_READ_pCAL
  181447. # define PNG_READ_pCAL_SUPPORTED
  181448. # define PNG_pCAL_SUPPORTED
  181449. #endif
  181450. #ifndef PNG_NO_READ_sCAL
  181451. # define PNG_READ_sCAL_SUPPORTED
  181452. # define PNG_sCAL_SUPPORTED
  181453. #endif
  181454. #ifndef PNG_NO_READ_pHYs
  181455. # define PNG_READ_pHYs_SUPPORTED
  181456. # define PNG_pHYs_SUPPORTED
  181457. #endif
  181458. #ifndef PNG_NO_READ_sBIT
  181459. # define PNG_READ_sBIT_SUPPORTED
  181460. # define PNG_sBIT_SUPPORTED
  181461. #endif
  181462. #ifndef PNG_NO_READ_sPLT
  181463. # define PNG_READ_sPLT_SUPPORTED
  181464. # define PNG_sPLT_SUPPORTED
  181465. #endif
  181466. #ifndef PNG_NO_READ_sRGB
  181467. # define PNG_READ_sRGB_SUPPORTED
  181468. # define PNG_sRGB_SUPPORTED
  181469. #endif
  181470. #ifndef PNG_NO_READ_tEXt
  181471. # define PNG_READ_tEXt_SUPPORTED
  181472. # define PNG_tEXt_SUPPORTED
  181473. #endif
  181474. #ifndef PNG_NO_READ_tIME
  181475. # define PNG_READ_tIME_SUPPORTED
  181476. # define PNG_tIME_SUPPORTED
  181477. #endif
  181478. #ifndef PNG_NO_READ_tRNS
  181479. # define PNG_READ_tRNS_SUPPORTED
  181480. # define PNG_tRNS_SUPPORTED
  181481. #endif
  181482. #ifndef PNG_NO_READ_zTXt
  181483. # define PNG_READ_zTXt_SUPPORTED
  181484. # define PNG_zTXt_SUPPORTED
  181485. #endif
  181486. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181487. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181488. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181489. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181490. # endif
  181491. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181492. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181493. # endif
  181494. #endif
  181495. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181496. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181497. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181498. # define PNG_USER_CHUNKS_SUPPORTED
  181499. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181500. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181501. # endif
  181502. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181503. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181504. # endif
  181505. #endif
  181506. #ifndef PNG_NO_READ_OPT_PLTE
  181507. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181508. #endif /* optional PLTE chunk in RGB and RGBA images */
  181509. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181510. defined(PNG_READ_zTXt_SUPPORTED)
  181511. # define PNG_READ_TEXT_SUPPORTED
  181512. # define PNG_TEXT_SUPPORTED
  181513. #endif
  181514. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181515. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181516. #ifdef PNG_NO_WRITE_TEXT
  181517. # define PNG_NO_WRITE_iTXt
  181518. # define PNG_NO_WRITE_tEXt
  181519. # define PNG_NO_WRITE_zTXt
  181520. #endif
  181521. #ifndef PNG_NO_WRITE_bKGD
  181522. # define PNG_WRITE_bKGD_SUPPORTED
  181523. # ifndef PNG_bKGD_SUPPORTED
  181524. # define PNG_bKGD_SUPPORTED
  181525. # endif
  181526. #endif
  181527. #ifndef PNG_NO_WRITE_cHRM
  181528. # define PNG_WRITE_cHRM_SUPPORTED
  181529. # ifndef PNG_cHRM_SUPPORTED
  181530. # define PNG_cHRM_SUPPORTED
  181531. # endif
  181532. #endif
  181533. #ifndef PNG_NO_WRITE_gAMA
  181534. # define PNG_WRITE_gAMA_SUPPORTED
  181535. # ifndef PNG_gAMA_SUPPORTED
  181536. # define PNG_gAMA_SUPPORTED
  181537. # endif
  181538. #endif
  181539. #ifndef PNG_NO_WRITE_hIST
  181540. # define PNG_WRITE_hIST_SUPPORTED
  181541. # ifndef PNG_hIST_SUPPORTED
  181542. # define PNG_hIST_SUPPORTED
  181543. # endif
  181544. #endif
  181545. #ifndef PNG_NO_WRITE_iCCP
  181546. # define PNG_WRITE_iCCP_SUPPORTED
  181547. # ifndef PNG_iCCP_SUPPORTED
  181548. # define PNG_iCCP_SUPPORTED
  181549. # endif
  181550. #endif
  181551. #ifndef PNG_NO_WRITE_iTXt
  181552. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181553. # define PNG_WRITE_iTXt_SUPPORTED
  181554. # endif
  181555. # ifndef PNG_iTXt_SUPPORTED
  181556. # define PNG_iTXt_SUPPORTED
  181557. # endif
  181558. #endif
  181559. #ifndef PNG_NO_WRITE_oFFs
  181560. # define PNG_WRITE_oFFs_SUPPORTED
  181561. # ifndef PNG_oFFs_SUPPORTED
  181562. # define PNG_oFFs_SUPPORTED
  181563. # endif
  181564. #endif
  181565. #ifndef PNG_NO_WRITE_pCAL
  181566. # define PNG_WRITE_pCAL_SUPPORTED
  181567. # ifndef PNG_pCAL_SUPPORTED
  181568. # define PNG_pCAL_SUPPORTED
  181569. # endif
  181570. #endif
  181571. #ifndef PNG_NO_WRITE_sCAL
  181572. # define PNG_WRITE_sCAL_SUPPORTED
  181573. # ifndef PNG_sCAL_SUPPORTED
  181574. # define PNG_sCAL_SUPPORTED
  181575. # endif
  181576. #endif
  181577. #ifndef PNG_NO_WRITE_pHYs
  181578. # define PNG_WRITE_pHYs_SUPPORTED
  181579. # ifndef PNG_pHYs_SUPPORTED
  181580. # define PNG_pHYs_SUPPORTED
  181581. # endif
  181582. #endif
  181583. #ifndef PNG_NO_WRITE_sBIT
  181584. # define PNG_WRITE_sBIT_SUPPORTED
  181585. # ifndef PNG_sBIT_SUPPORTED
  181586. # define PNG_sBIT_SUPPORTED
  181587. # endif
  181588. #endif
  181589. #ifndef PNG_NO_WRITE_sPLT
  181590. # define PNG_WRITE_sPLT_SUPPORTED
  181591. # ifndef PNG_sPLT_SUPPORTED
  181592. # define PNG_sPLT_SUPPORTED
  181593. # endif
  181594. #endif
  181595. #ifndef PNG_NO_WRITE_sRGB
  181596. # define PNG_WRITE_sRGB_SUPPORTED
  181597. # ifndef PNG_sRGB_SUPPORTED
  181598. # define PNG_sRGB_SUPPORTED
  181599. # endif
  181600. #endif
  181601. #ifndef PNG_NO_WRITE_tEXt
  181602. # define PNG_WRITE_tEXt_SUPPORTED
  181603. # ifndef PNG_tEXt_SUPPORTED
  181604. # define PNG_tEXt_SUPPORTED
  181605. # endif
  181606. #endif
  181607. #ifndef PNG_NO_WRITE_tIME
  181608. # define PNG_WRITE_tIME_SUPPORTED
  181609. # ifndef PNG_tIME_SUPPORTED
  181610. # define PNG_tIME_SUPPORTED
  181611. # endif
  181612. #endif
  181613. #ifndef PNG_NO_WRITE_tRNS
  181614. # define PNG_WRITE_tRNS_SUPPORTED
  181615. # ifndef PNG_tRNS_SUPPORTED
  181616. # define PNG_tRNS_SUPPORTED
  181617. # endif
  181618. #endif
  181619. #ifndef PNG_NO_WRITE_zTXt
  181620. # define PNG_WRITE_zTXt_SUPPORTED
  181621. # ifndef PNG_zTXt_SUPPORTED
  181622. # define PNG_zTXt_SUPPORTED
  181623. # endif
  181624. #endif
  181625. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181626. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181627. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181628. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181629. # endif
  181630. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181631. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181632. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181633. # endif
  181634. # endif
  181635. #endif
  181636. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181637. defined(PNG_WRITE_zTXt_SUPPORTED)
  181638. # define PNG_WRITE_TEXT_SUPPORTED
  181639. # ifndef PNG_TEXT_SUPPORTED
  181640. # define PNG_TEXT_SUPPORTED
  181641. # endif
  181642. #endif
  181643. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181644. /* Turn this off to disable png_read_png() and
  181645. * png_write_png() and leave the row_pointers member
  181646. * out of the info structure.
  181647. */
  181648. #ifndef PNG_NO_INFO_IMAGE
  181649. # define PNG_INFO_IMAGE_SUPPORTED
  181650. #endif
  181651. /* need the time information for reading tIME chunks */
  181652. #if defined(PNG_tIME_SUPPORTED)
  181653. # if !defined(_WIN32_WCE)
  181654. /* "time.h" functions are not supported on WindowsCE */
  181655. # include <time.h>
  181656. # endif
  181657. #endif
  181658. /* Some typedefs to get us started. These should be safe on most of the
  181659. * common platforms. The typedefs should be at least as large as the
  181660. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181661. * don't have to be exactly that size. Some compilers dislike passing
  181662. * unsigned shorts as function parameters, so you may be better off using
  181663. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181664. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181665. */
  181666. typedef unsigned long png_uint_32;
  181667. typedef long png_int_32;
  181668. typedef unsigned short png_uint_16;
  181669. typedef short png_int_16;
  181670. typedef unsigned char png_byte;
  181671. /* This is usually size_t. It is typedef'ed just in case you need it to
  181672. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181673. #ifdef PNG_SIZE_T
  181674. typedef PNG_SIZE_T png_size_t;
  181675. # define png_sizeof(x) png_convert_size(sizeof (x))
  181676. #else
  181677. typedef size_t png_size_t;
  181678. # define png_sizeof(x) sizeof (x)
  181679. #endif
  181680. /* The following is needed for medium model support. It cannot be in the
  181681. * PNG_INTERNAL section. Needs modification for other compilers besides
  181682. * MSC. Model independent support declares all arrays and pointers to be
  181683. * large using the far keyword. The zlib version used must also support
  181684. * model independent data. As of version zlib 1.0.4, the necessary changes
  181685. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181686. * changes that are needed. (Tim Wegner)
  181687. */
  181688. /* Separate compiler dependencies (problem here is that zlib.h always
  181689. defines FAR. (SJT) */
  181690. #ifdef __BORLANDC__
  181691. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181692. # define LDATA 1
  181693. # else
  181694. # define LDATA 0
  181695. # endif
  181696. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181697. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181698. # define PNG_MAX_MALLOC_64K
  181699. # if (LDATA != 1)
  181700. # ifndef FAR
  181701. # define FAR __far
  181702. # endif
  181703. # define USE_FAR_KEYWORD
  181704. # endif /* LDATA != 1 */
  181705. /* Possibly useful for moving data out of default segment.
  181706. * Uncomment it if you want. Could also define FARDATA as
  181707. * const if your compiler supports it. (SJT)
  181708. # define FARDATA FAR
  181709. */
  181710. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181711. #endif /* __BORLANDC__ */
  181712. /* Suggest testing for specific compiler first before testing for
  181713. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181714. * making reliance oncertain keywords suspect. (SJT)
  181715. */
  181716. /* MSC Medium model */
  181717. #if defined(FAR)
  181718. # if defined(M_I86MM)
  181719. # define USE_FAR_KEYWORD
  181720. # define FARDATA FAR
  181721. # include <dos.h>
  181722. # endif
  181723. #endif
  181724. /* SJT: default case */
  181725. #ifndef FAR
  181726. # define FAR
  181727. #endif
  181728. /* At this point FAR is always defined */
  181729. #ifndef FARDATA
  181730. # define FARDATA
  181731. #endif
  181732. /* Typedef for floating-point numbers that are converted
  181733. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181734. typedef png_int_32 png_fixed_point;
  181735. /* Add typedefs for pointers */
  181736. typedef void FAR * png_voidp;
  181737. typedef png_byte FAR * png_bytep;
  181738. typedef png_uint_32 FAR * png_uint_32p;
  181739. typedef png_int_32 FAR * png_int_32p;
  181740. typedef png_uint_16 FAR * png_uint_16p;
  181741. typedef png_int_16 FAR * png_int_16p;
  181742. typedef PNG_CONST char FAR * png_const_charp;
  181743. typedef char FAR * png_charp;
  181744. typedef png_fixed_point FAR * png_fixed_point_p;
  181745. #ifndef PNG_NO_STDIO
  181746. #if defined(_WIN32_WCE)
  181747. typedef HANDLE png_FILE_p;
  181748. #else
  181749. typedef FILE * png_FILE_p;
  181750. #endif
  181751. #endif
  181752. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181753. typedef double FAR * png_doublep;
  181754. #endif
  181755. /* Pointers to pointers; i.e. arrays */
  181756. typedef png_byte FAR * FAR * png_bytepp;
  181757. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181758. typedef png_int_32 FAR * FAR * png_int_32pp;
  181759. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181760. typedef png_int_16 FAR * FAR * png_int_16pp;
  181761. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181762. typedef char FAR * FAR * png_charpp;
  181763. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181764. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181765. typedef double FAR * FAR * png_doublepp;
  181766. #endif
  181767. /* Pointers to pointers to pointers; i.e., pointer to array */
  181768. typedef char FAR * FAR * FAR * png_charppp;
  181769. #if 0
  181770. /* SPC - Is this stuff deprecated? */
  181771. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181772. /* libpng typedefs for types in zlib. If zlib changes
  181773. * or another compression library is used, then change these.
  181774. * Eliminates need to change all the source files.
  181775. */
  181776. typedef charf * png_zcharp;
  181777. typedef charf * FAR * png_zcharpp;
  181778. typedef z_stream FAR * png_zstreamp;
  181779. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181780. /*
  181781. * Define PNG_BUILD_DLL if the module being built is a Windows
  181782. * LIBPNG DLL.
  181783. *
  181784. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181785. * It is equivalent to Microsoft predefined macro _DLL that is
  181786. * automatically defined when you compile using the share
  181787. * version of the CRT (C Run-Time library)
  181788. *
  181789. * The cygwin mods make this behavior a little different:
  181790. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181791. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181792. * -or- if you are building an application that you want to link to the
  181793. * static library.
  181794. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181795. * the other flags is defined.
  181796. */
  181797. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181798. # define PNG_DLL
  181799. #endif
  181800. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181801. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181802. * command-line override
  181803. */
  181804. #if defined(__CYGWIN__)
  181805. # if !defined(PNG_STATIC)
  181806. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181807. # undef PNG_USE_GLOBAL_ARRAYS
  181808. # endif
  181809. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181810. # define PNG_USE_LOCAL_ARRAYS
  181811. # endif
  181812. # else
  181813. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181814. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181815. # undef PNG_USE_GLOBAL_ARRAYS
  181816. # endif
  181817. # endif
  181818. # endif
  181819. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181820. # define PNG_USE_LOCAL_ARRAYS
  181821. # endif
  181822. #endif
  181823. /* Do not use global arrays (helps with building DLL's)
  181824. * They are no longer used in libpng itself, since version 1.0.5c,
  181825. * but might be required for some pre-1.0.5c applications.
  181826. */
  181827. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181828. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181829. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181830. # define PNG_USE_LOCAL_ARRAYS
  181831. # else
  181832. # define PNG_USE_GLOBAL_ARRAYS
  181833. # endif
  181834. #endif
  181835. #if defined(__CYGWIN__)
  181836. # undef PNGAPI
  181837. # define PNGAPI __cdecl
  181838. # undef PNG_IMPEXP
  181839. # define PNG_IMPEXP
  181840. #endif
  181841. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181842. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181843. * Don't ignore those warnings; you must also reset the default calling
  181844. * convention in your compiler to match your PNGAPI, and you must build
  181845. * zlib and your applications the same way you build libpng.
  181846. */
  181847. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181848. # ifndef PNG_NO_MODULEDEF
  181849. # define PNG_NO_MODULEDEF
  181850. # endif
  181851. #endif
  181852. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181853. # define PNG_IMPEXP
  181854. #endif
  181855. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181856. (( defined(_Windows) || defined(_WINDOWS) || \
  181857. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181858. # ifndef PNGAPI
  181859. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181860. # define PNGAPI __cdecl
  181861. # else
  181862. # define PNGAPI _cdecl
  181863. # endif
  181864. # endif
  181865. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181866. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181867. # define PNG_IMPEXP
  181868. # endif
  181869. # if !defined(PNG_IMPEXP)
  181870. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181871. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181872. /* Borland/Microsoft */
  181873. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181874. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181875. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181876. # else
  181877. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181878. # if defined(PNG_BUILD_DLL)
  181879. # define PNG_IMPEXP __export
  181880. # else
  181881. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181882. VC++ */
  181883. # endif /* Exists in Borland C++ for
  181884. C++ classes (== huge) */
  181885. # endif
  181886. # endif
  181887. # if !defined(PNG_IMPEXP)
  181888. # if defined(PNG_BUILD_DLL)
  181889. # define PNG_IMPEXP __declspec(dllexport)
  181890. # else
  181891. # define PNG_IMPEXP __declspec(dllimport)
  181892. # endif
  181893. # endif
  181894. # endif /* PNG_IMPEXP */
  181895. #else /* !(DLL || non-cygwin WINDOWS) */
  181896. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181897. # ifndef PNGAPI
  181898. # define PNGAPI _System
  181899. # endif
  181900. # else
  181901. # if 0 /* ... other platforms, with other meanings */
  181902. # endif
  181903. # endif
  181904. #endif
  181905. #ifndef PNGAPI
  181906. # define PNGAPI
  181907. #endif
  181908. #ifndef PNG_IMPEXP
  181909. # define PNG_IMPEXP
  181910. #endif
  181911. #ifdef PNG_BUILDSYMS
  181912. # ifndef PNG_EXPORT
  181913. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181914. # endif
  181915. # ifdef PNG_USE_GLOBAL_ARRAYS
  181916. # ifndef PNG_EXPORT_VAR
  181917. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181918. # endif
  181919. # endif
  181920. #endif
  181921. #ifndef PNG_EXPORT
  181922. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181923. #endif
  181924. #ifdef PNG_USE_GLOBAL_ARRAYS
  181925. # ifndef PNG_EXPORT_VAR
  181926. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181927. # endif
  181928. #endif
  181929. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181930. * functions that are passed far data must be model independent.
  181931. */
  181932. #ifndef PNG_ABORT
  181933. # define PNG_ABORT() abort()
  181934. #endif
  181935. #ifdef PNG_SETJMP_SUPPORTED
  181936. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181937. #else
  181938. # define png_jmpbuf(png_ptr) \
  181939. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181940. #endif
  181941. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181942. /* use this to make far-to-near assignments */
  181943. # define CHECK 1
  181944. # define NOCHECK 0
  181945. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181946. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181947. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181948. # define png_strcpy _fstrcpy
  181949. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181950. # define png_strlen _fstrlen
  181951. # define png_memcmp _fmemcmp /* SJT: added */
  181952. # define png_memcpy _fmemcpy
  181953. # define png_memset _fmemset
  181954. #else /* use the usual functions */
  181955. # define CVT_PTR(ptr) (ptr)
  181956. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181957. # ifndef PNG_NO_SNPRINTF
  181958. # ifdef _MSC_VER
  181959. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181960. # define png_snprintf2 _snprintf
  181961. # define png_snprintf6 _snprintf
  181962. # else
  181963. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181964. # define png_snprintf2 snprintf
  181965. # define png_snprintf6 snprintf
  181966. # endif
  181967. # else
  181968. /* You don't have or don't want to use snprintf(). Caution: Using
  181969. * sprintf instead of snprintf exposes your application to accidental
  181970. * or malevolent buffer overflows. If you don't have snprintf()
  181971. * as a general rule you should provide one (you can get one from
  181972. * Portable OpenSSH). */
  181973. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181974. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181975. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181976. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181977. # endif
  181978. # define png_strcpy strcpy
  181979. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181980. # define png_strlen strlen
  181981. # define png_memcmp memcmp /* SJT: added */
  181982. # define png_memcpy memcpy
  181983. # define png_memset memset
  181984. #endif
  181985. /* End of memory model independent support */
  181986. /* Just a little check that someone hasn't tried to define something
  181987. * contradictory.
  181988. */
  181989. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181990. # undef PNG_ZBUF_SIZE
  181991. # define PNG_ZBUF_SIZE 65536L
  181992. #endif
  181993. /* Added at libpng-1.2.8 */
  181994. #endif /* PNG_VERSION_INFO_ONLY */
  181995. #endif /* PNGCONF_H */
  181996. /*** End of inlined file: pngconf.h ***/
  181997. #ifdef _MSC_VER
  181998. #pragma warning (disable: 4996 4100)
  181999. #endif
  182000. /*
  182001. * Added at libpng-1.2.8 */
  182002. /* Ref MSDN: Private as priority over Special
  182003. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182004. * procedures. If this value is given, the StringFileInfo block must
  182005. * contain a PrivateBuild string.
  182006. *
  182007. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182008. * standard release procedures but is a variation of the standard
  182009. * file of the same version number. If this value is given, the
  182010. * StringFileInfo block must contain a SpecialBuild string.
  182011. */
  182012. #if defined(PNG_USER_PRIVATEBUILD)
  182013. # define PNG_LIBPNG_BUILD_TYPE \
  182014. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182015. #else
  182016. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182017. # define PNG_LIBPNG_BUILD_TYPE \
  182018. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182019. # else
  182020. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182021. # endif
  182022. #endif
  182023. #ifndef PNG_VERSION_INFO_ONLY
  182024. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182025. #ifdef __cplusplus
  182026. //extern "C" {
  182027. #endif /* __cplusplus */
  182028. /* This file is arranged in several sections. The first section contains
  182029. * structure and type definitions. The second section contains the external
  182030. * library functions, while the third has the internal library functions,
  182031. * which applications aren't expected to use directly.
  182032. */
  182033. #ifndef PNG_NO_TYPECAST_NULL
  182034. #define int_p_NULL (int *)NULL
  182035. #define png_bytep_NULL (png_bytep)NULL
  182036. #define png_bytepp_NULL (png_bytepp)NULL
  182037. #define png_doublep_NULL (png_doublep)NULL
  182038. #define png_error_ptr_NULL (png_error_ptr)NULL
  182039. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182040. #define png_free_ptr_NULL (png_free_ptr)NULL
  182041. #define png_infopp_NULL (png_infopp)NULL
  182042. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182043. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182044. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182045. #define png_structp_NULL (png_structp)NULL
  182046. #define png_uint_16p_NULL (png_uint_16p)NULL
  182047. #define png_voidp_NULL (png_voidp)NULL
  182048. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182049. #else
  182050. #define int_p_NULL NULL
  182051. #define png_bytep_NULL NULL
  182052. #define png_bytepp_NULL NULL
  182053. #define png_doublep_NULL NULL
  182054. #define png_error_ptr_NULL NULL
  182055. #define png_flush_ptr_NULL NULL
  182056. #define png_free_ptr_NULL NULL
  182057. #define png_infopp_NULL NULL
  182058. #define png_malloc_ptr_NULL NULL
  182059. #define png_read_status_ptr_NULL NULL
  182060. #define png_rw_ptr_NULL NULL
  182061. #define png_structp_NULL NULL
  182062. #define png_uint_16p_NULL NULL
  182063. #define png_voidp_NULL NULL
  182064. #define png_write_status_ptr_NULL NULL
  182065. #endif
  182066. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182067. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182068. /* Version information for C files, stored in png.c. This had better match
  182069. * the version above.
  182070. */
  182071. #ifdef PNG_USE_GLOBAL_ARRAYS
  182072. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182073. /* need room for 99.99.99beta99z */
  182074. #else
  182075. #define png_libpng_ver png_get_header_ver(NULL)
  182076. #endif
  182077. #ifdef PNG_USE_GLOBAL_ARRAYS
  182078. /* This was removed in version 1.0.5c */
  182079. /* Structures to facilitate easy interlacing. See png.c for more details */
  182080. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182081. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182082. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182083. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182084. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182085. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182086. /* This isn't currently used. If you need it, see png.c for more details.
  182087. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182088. */
  182089. #endif
  182090. #endif /* PNG_NO_EXTERN */
  182091. /* Three color definitions. The order of the red, green, and blue, (and the
  182092. * exact size) is not important, although the size of the fields need to
  182093. * be png_byte or png_uint_16 (as defined below).
  182094. */
  182095. typedef struct png_color_struct
  182096. {
  182097. png_byte red;
  182098. png_byte green;
  182099. png_byte blue;
  182100. } png_color;
  182101. typedef png_color FAR * png_colorp;
  182102. typedef png_color FAR * FAR * png_colorpp;
  182103. typedef struct png_color_16_struct
  182104. {
  182105. png_byte index; /* used for palette files */
  182106. png_uint_16 red; /* for use in red green blue files */
  182107. png_uint_16 green;
  182108. png_uint_16 blue;
  182109. png_uint_16 gray; /* for use in grayscale files */
  182110. } png_color_16;
  182111. typedef png_color_16 FAR * png_color_16p;
  182112. typedef png_color_16 FAR * FAR * png_color_16pp;
  182113. typedef struct png_color_8_struct
  182114. {
  182115. png_byte red; /* for use in red green blue files */
  182116. png_byte green;
  182117. png_byte blue;
  182118. png_byte gray; /* for use in grayscale files */
  182119. png_byte alpha; /* for alpha channel files */
  182120. } png_color_8;
  182121. typedef png_color_8 FAR * png_color_8p;
  182122. typedef png_color_8 FAR * FAR * png_color_8pp;
  182123. /*
  182124. * The following two structures are used for the in-core representation
  182125. * of sPLT chunks.
  182126. */
  182127. typedef struct png_sPLT_entry_struct
  182128. {
  182129. png_uint_16 red;
  182130. png_uint_16 green;
  182131. png_uint_16 blue;
  182132. png_uint_16 alpha;
  182133. png_uint_16 frequency;
  182134. } png_sPLT_entry;
  182135. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182136. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182137. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182138. * occupy the LSB of their respective members, and the MSB of each member
  182139. * is zero-filled. The frequency member always occupies the full 16 bits.
  182140. */
  182141. typedef struct png_sPLT_struct
  182142. {
  182143. png_charp name; /* palette name */
  182144. png_byte depth; /* depth of palette samples */
  182145. png_sPLT_entryp entries; /* palette entries */
  182146. png_int_32 nentries; /* number of palette entries */
  182147. } png_sPLT_t;
  182148. typedef png_sPLT_t FAR * png_sPLT_tp;
  182149. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182150. #ifdef PNG_TEXT_SUPPORTED
  182151. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182152. * and whether that contents is compressed or not. The "key" field
  182153. * points to a regular zero-terminated C string. The "text", "lang", and
  182154. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182155. * However, the * structure returned by png_get_text() will always contain
  182156. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182157. * so they can be safely used in printf() and other string-handling functions.
  182158. */
  182159. typedef struct png_text_struct
  182160. {
  182161. int compression; /* compression value:
  182162. -1: tEXt, none
  182163. 0: zTXt, deflate
  182164. 1: iTXt, none
  182165. 2: iTXt, deflate */
  182166. png_charp key; /* keyword, 1-79 character description of "text" */
  182167. png_charp text; /* comment, may be an empty string (ie "")
  182168. or a NULL pointer */
  182169. png_size_t text_length; /* length of the text string */
  182170. #ifdef PNG_iTXt_SUPPORTED
  182171. png_size_t itxt_length; /* length of the itxt string */
  182172. png_charp lang; /* language code, 0-79 characters
  182173. or a NULL pointer */
  182174. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182175. chars or a NULL pointer */
  182176. #endif
  182177. } png_text;
  182178. typedef png_text FAR * png_textp;
  182179. typedef png_text FAR * FAR * png_textpp;
  182180. #endif
  182181. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182182. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182183. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182184. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182185. #define PNG_TEXT_COMPRESSION_NONE -1
  182186. #define PNG_TEXT_COMPRESSION_zTXt 0
  182187. #define PNG_ITXT_COMPRESSION_NONE 1
  182188. #define PNG_ITXT_COMPRESSION_zTXt 2
  182189. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182190. /* png_time is a way to hold the time in an machine independent way.
  182191. * Two conversions are provided, both from time_t and struct tm. There
  182192. * is no portable way to convert to either of these structures, as far
  182193. * as I know. If you know of a portable way, send it to me. As a side
  182194. * note - PNG has always been Year 2000 compliant!
  182195. */
  182196. typedef struct png_time_struct
  182197. {
  182198. png_uint_16 year; /* full year, as in, 1995 */
  182199. png_byte month; /* month of year, 1 - 12 */
  182200. png_byte day; /* day of month, 1 - 31 */
  182201. png_byte hour; /* hour of day, 0 - 23 */
  182202. png_byte minute; /* minute of hour, 0 - 59 */
  182203. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182204. } png_time;
  182205. typedef png_time FAR * png_timep;
  182206. typedef png_time FAR * FAR * png_timepp;
  182207. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182208. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182209. * no specific support. The idea is that we can use this to queue
  182210. * up private chunks for output even though the library doesn't actually
  182211. * know about their semantics.
  182212. */
  182213. typedef struct png_unknown_chunk_t
  182214. {
  182215. png_byte name[5];
  182216. png_byte *data;
  182217. png_size_t size;
  182218. /* libpng-using applications should NOT directly modify this byte. */
  182219. png_byte location; /* mode of operation at read time */
  182220. }
  182221. png_unknown_chunk;
  182222. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182223. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182224. #endif
  182225. /* png_info is a structure that holds the information in a PNG file so
  182226. * that the application can find out the characteristics of the image.
  182227. * If you are reading the file, this structure will tell you what is
  182228. * in the PNG file. If you are writing the file, fill in the information
  182229. * you want to put into the PNG file, then call png_write_info().
  182230. * The names chosen should be very close to the PNG specification, so
  182231. * consult that document for information about the meaning of each field.
  182232. *
  182233. * With libpng < 0.95, it was only possible to directly set and read the
  182234. * the values in the png_info_struct, which meant that the contents and
  182235. * order of the values had to remain fixed. With libpng 0.95 and later,
  182236. * however, there are now functions that abstract the contents of
  182237. * png_info_struct from the application, so this makes it easier to use
  182238. * libpng with dynamic libraries, and even makes it possible to use
  182239. * libraries that don't have all of the libpng ancillary chunk-handing
  182240. * functionality.
  182241. *
  182242. * In any case, the order of the parameters in png_info_struct should NOT
  182243. * be changed for as long as possible to keep compatibility with applications
  182244. * that use the old direct-access method with png_info_struct.
  182245. *
  182246. * The following members may have allocated storage attached that should be
  182247. * cleaned up before the structure is discarded: palette, trans, text,
  182248. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182249. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182250. * are automatically freed when the info structure is deallocated, if they were
  182251. * allocated internally by libpng. This behavior can be changed by means
  182252. * of the png_data_freer() function.
  182253. *
  182254. * More allocation details: all the chunk-reading functions that
  182255. * change these members go through the corresponding png_set_*
  182256. * functions. A function to clear these members is available: see
  182257. * png_free_data(). The png_set_* functions do not depend on being
  182258. * able to point info structure members to any of the storage they are
  182259. * passed (they make their own copies), EXCEPT that the png_set_text
  182260. * functions use the same storage passed to them in the text_ptr or
  182261. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182262. * functions do not make their own copies.
  182263. */
  182264. typedef struct png_info_struct
  182265. {
  182266. /* the following are necessary for every PNG file */
  182267. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182268. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182269. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182270. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182271. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182272. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182273. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182274. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182275. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182276. /* The following three should have been named *_method not *_type */
  182277. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182278. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182279. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182280. /* The following is informational only on read, and not used on writes. */
  182281. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182282. png_byte pixel_depth; /* number of bits per pixel */
  182283. png_byte spare_byte; /* to align the data, and for future use */
  182284. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182285. /* The rest of the data is optional. If you are reading, check the
  182286. * valid field to see if the information in these are valid. If you
  182287. * are writing, set the valid field to those chunks you want written,
  182288. * and initialize the appropriate fields below.
  182289. */
  182290. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182291. /* The gAMA chunk describes the gamma characteristics of the system
  182292. * on which the image was created, normally in the range [1.0, 2.5].
  182293. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182294. */
  182295. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182296. #endif
  182297. #if defined(PNG_sRGB_SUPPORTED)
  182298. /* GR-P, 0.96a */
  182299. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182300. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182301. #endif
  182302. #if defined(PNG_TEXT_SUPPORTED)
  182303. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182304. * uncompressed, compressed, and optionally compressed forms, respectively.
  182305. * The data in "text" is an array of pointers to uncompressed,
  182306. * null-terminated C strings. Each chunk has a keyword that describes the
  182307. * textual data contained in that chunk. Keywords are not required to be
  182308. * unique, and the text string may be empty. Any number of text chunks may
  182309. * be in an image.
  182310. */
  182311. int num_text; /* number of comments read/to write */
  182312. int max_text; /* current size of text array */
  182313. png_textp text; /* array of comments read/to write */
  182314. #endif /* PNG_TEXT_SUPPORTED */
  182315. #if defined(PNG_tIME_SUPPORTED)
  182316. /* The tIME chunk holds the last time the displayed image data was
  182317. * modified. See the png_time struct for the contents of this struct.
  182318. */
  182319. png_time mod_time;
  182320. #endif
  182321. #if defined(PNG_sBIT_SUPPORTED)
  182322. /* The sBIT chunk specifies the number of significant high-order bits
  182323. * in the pixel data. Values are in the range [1, bit_depth], and are
  182324. * only specified for the channels in the pixel data. The contents of
  182325. * the low-order bits is not specified. Data is valid if
  182326. * (valid & PNG_INFO_sBIT) is non-zero.
  182327. */
  182328. png_color_8 sig_bit; /* significant bits in color channels */
  182329. #endif
  182330. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182331. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182332. /* The tRNS chunk supplies transparency data for paletted images and
  182333. * other image types that don't need a full alpha channel. There are
  182334. * "num_trans" transparency values for a paletted image, stored in the
  182335. * same order as the palette colors, starting from index 0. Values
  182336. * for the data are in the range [0, 255], ranging from fully transparent
  182337. * to fully opaque, respectively. For non-paletted images, there is a
  182338. * single color specified that should be treated as fully transparent.
  182339. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182340. */
  182341. png_bytep trans; /* transparent values for paletted image */
  182342. png_color_16 trans_values; /* transparent color for non-palette image */
  182343. #endif
  182344. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182345. /* The bKGD chunk gives the suggested image background color if the
  182346. * display program does not have its own background color and the image
  182347. * is needs to composited onto a background before display. The colors
  182348. * in "background" are normally in the same color space/depth as the
  182349. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182350. */
  182351. png_color_16 background;
  182352. #endif
  182353. #if defined(PNG_oFFs_SUPPORTED)
  182354. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182355. * and downwards from the top-left corner of the display, page, or other
  182356. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182357. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182358. */
  182359. png_int_32 x_offset; /* x offset on page */
  182360. png_int_32 y_offset; /* y offset on page */
  182361. png_byte offset_unit_type; /* offset units type */
  182362. #endif
  182363. #if defined(PNG_pHYs_SUPPORTED)
  182364. /* The pHYs chunk gives the physical pixel density of the image for
  182365. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182366. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182367. */
  182368. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182369. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182370. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182371. #endif
  182372. #if defined(PNG_hIST_SUPPORTED)
  182373. /* The hIST chunk contains the relative frequency or importance of the
  182374. * various palette entries, so that a viewer can intelligently select a
  182375. * reduced-color palette, if required. Data is an array of "num_palette"
  182376. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182377. * is non-zero.
  182378. */
  182379. png_uint_16p hist;
  182380. #endif
  182381. #ifdef PNG_cHRM_SUPPORTED
  182382. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182383. * on which the PNG was created. This data allows the viewer to do gamut
  182384. * mapping of the input image to ensure that the viewer sees the same
  182385. * colors in the image as the creator. Values are in the range
  182386. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182387. */
  182388. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182389. float x_white;
  182390. float y_white;
  182391. float x_red;
  182392. float y_red;
  182393. float x_green;
  182394. float y_green;
  182395. float x_blue;
  182396. float y_blue;
  182397. #endif
  182398. #endif
  182399. #if defined(PNG_pCAL_SUPPORTED)
  182400. /* The pCAL chunk describes a transformation between the stored pixel
  182401. * values and original physical data values used to create the image.
  182402. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182403. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182404. * (possibly non-linear) transformation function given by "pcal_type"
  182405. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182406. * defines below, and the PNG-Group's PNG extensions document for a
  182407. * complete description of the transformations and how they should be
  182408. * implemented, and for a description of the ASCII parameter strings.
  182409. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182410. */
  182411. png_charp pcal_purpose; /* pCAL chunk description string */
  182412. png_int_32 pcal_X0; /* minimum value */
  182413. png_int_32 pcal_X1; /* maximum value */
  182414. png_charp pcal_units; /* Latin-1 string giving physical units */
  182415. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182416. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182417. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182418. #endif
  182419. /* New members added in libpng-1.0.6 */
  182420. #ifdef PNG_FREE_ME_SUPPORTED
  182421. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182422. #endif
  182423. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182424. /* storage for unknown chunks that the library doesn't recognize. */
  182425. png_unknown_chunkp unknown_chunks;
  182426. png_size_t unknown_chunks_num;
  182427. #endif
  182428. #if defined(PNG_iCCP_SUPPORTED)
  182429. /* iCCP chunk data. */
  182430. png_charp iccp_name; /* profile name */
  182431. png_charp iccp_profile; /* International Color Consortium profile data */
  182432. /* Note to maintainer: should be png_bytep */
  182433. png_uint_32 iccp_proflen; /* ICC profile data length */
  182434. png_byte iccp_compression; /* Always zero */
  182435. #endif
  182436. #if defined(PNG_sPLT_SUPPORTED)
  182437. /* data on sPLT chunks (there may be more than one). */
  182438. png_sPLT_tp splt_palettes;
  182439. png_uint_32 splt_palettes_num;
  182440. #endif
  182441. #if defined(PNG_sCAL_SUPPORTED)
  182442. /* The sCAL chunk describes the actual physical dimensions of the
  182443. * subject matter of the graphic. The chunk contains a unit specification
  182444. * a byte value, and two ASCII strings representing floating-point
  182445. * values. The values are width and height corresponsing to one pixel
  182446. * in the image. This external representation is converted to double
  182447. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182448. */
  182449. png_byte scal_unit; /* unit of physical scale */
  182450. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182451. double scal_pixel_width; /* width of one pixel */
  182452. double scal_pixel_height; /* height of one pixel */
  182453. #endif
  182454. #ifdef PNG_FIXED_POINT_SUPPORTED
  182455. png_charp scal_s_width; /* string containing height */
  182456. png_charp scal_s_height; /* string containing width */
  182457. #endif
  182458. #endif
  182459. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182460. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182461. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182462. png_bytepp row_pointers; /* the image bits */
  182463. #endif
  182464. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182465. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182466. #endif
  182467. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182468. png_fixed_point int_x_white;
  182469. png_fixed_point int_y_white;
  182470. png_fixed_point int_x_red;
  182471. png_fixed_point int_y_red;
  182472. png_fixed_point int_x_green;
  182473. png_fixed_point int_y_green;
  182474. png_fixed_point int_x_blue;
  182475. png_fixed_point int_y_blue;
  182476. #endif
  182477. } png_info;
  182478. typedef png_info FAR * png_infop;
  182479. typedef png_info FAR * FAR * png_infopp;
  182480. /* Maximum positive integer used in PNG is (2^31)-1 */
  182481. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182482. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182483. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182484. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182485. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182486. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182487. #endif
  182488. /* These describe the color_type field in png_info. */
  182489. /* color type masks */
  182490. #define PNG_COLOR_MASK_PALETTE 1
  182491. #define PNG_COLOR_MASK_COLOR 2
  182492. #define PNG_COLOR_MASK_ALPHA 4
  182493. /* color types. Note that not all combinations are legal */
  182494. #define PNG_COLOR_TYPE_GRAY 0
  182495. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182496. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182497. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182498. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182499. /* aliases */
  182500. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182501. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182502. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182503. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182504. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182505. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182506. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182507. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182508. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182509. /* These are for the interlacing type. These values should NOT be changed. */
  182510. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182511. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182512. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182513. /* These are for the oFFs chunk. These values should NOT be changed. */
  182514. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182515. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182516. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182517. /* These are for the pCAL chunk. These values should NOT be changed. */
  182518. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182519. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182520. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182521. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182522. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182523. /* These are for the sCAL chunk. These values should NOT be changed. */
  182524. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182525. #define PNG_SCALE_METER 1 /* meters per pixel */
  182526. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182527. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182528. /* These are for the pHYs chunk. These values should NOT be changed. */
  182529. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182530. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182531. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182532. /* These are for the sRGB chunk. These values should NOT be changed. */
  182533. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182534. #define PNG_sRGB_INTENT_RELATIVE 1
  182535. #define PNG_sRGB_INTENT_SATURATION 2
  182536. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182537. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182538. /* This is for text chunks */
  182539. #define PNG_KEYWORD_MAX_LENGTH 79
  182540. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182541. #define PNG_MAX_PALETTE_LENGTH 256
  182542. /* These determine if an ancillary chunk's data has been successfully read
  182543. * from the PNG header, or if the application has filled in the corresponding
  182544. * data in the info_struct to be written into the output file. The values
  182545. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182546. */
  182547. #define PNG_INFO_gAMA 0x0001
  182548. #define PNG_INFO_sBIT 0x0002
  182549. #define PNG_INFO_cHRM 0x0004
  182550. #define PNG_INFO_PLTE 0x0008
  182551. #define PNG_INFO_tRNS 0x0010
  182552. #define PNG_INFO_bKGD 0x0020
  182553. #define PNG_INFO_hIST 0x0040
  182554. #define PNG_INFO_pHYs 0x0080
  182555. #define PNG_INFO_oFFs 0x0100
  182556. #define PNG_INFO_tIME 0x0200
  182557. #define PNG_INFO_pCAL 0x0400
  182558. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182559. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182560. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182561. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182562. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182563. /* This is used for the transformation routines, as some of them
  182564. * change these values for the row. It also should enable using
  182565. * the routines for other purposes.
  182566. */
  182567. typedef struct png_row_info_struct
  182568. {
  182569. png_uint_32 width; /* width of row */
  182570. png_uint_32 rowbytes; /* number of bytes in row */
  182571. png_byte color_type; /* color type of row */
  182572. png_byte bit_depth; /* bit depth of row */
  182573. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182574. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182575. } png_row_info;
  182576. typedef png_row_info FAR * png_row_infop;
  182577. typedef png_row_info FAR * FAR * png_row_infopp;
  182578. /* These are the function types for the I/O functions and for the functions
  182579. * that allow the user to override the default I/O functions with his or her
  182580. * own. The png_error_ptr type should match that of user-supplied warning
  182581. * and error functions, while the png_rw_ptr type should match that of the
  182582. * user read/write data functions.
  182583. */
  182584. typedef struct png_struct_def png_struct;
  182585. typedef png_struct FAR * png_structp;
  182586. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182587. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182588. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182589. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182590. int));
  182591. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182592. int));
  182593. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182594. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182595. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182596. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182597. png_uint_32, int));
  182598. #endif
  182599. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182600. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182601. defined(PNG_LEGACY_SUPPORTED)
  182602. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182603. png_row_infop, png_bytep));
  182604. #endif
  182605. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182606. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182607. #endif
  182608. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182609. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182610. #endif
  182611. /* Transform masks for the high-level interface */
  182612. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182613. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182614. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182615. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182616. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182617. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182618. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182619. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182620. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182621. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182622. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182623. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182624. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182625. /* Flags for MNG supported features */
  182626. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182627. #define PNG_FLAG_MNG_FILTER_64 0x04
  182628. #define PNG_ALL_MNG_FEATURES 0x05
  182629. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182630. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182631. /* The structure that holds the information to read and write PNG files.
  182632. * The only people who need to care about what is inside of this are the
  182633. * people who will be modifying the library for their own special needs.
  182634. * It should NOT be accessed directly by an application, except to store
  182635. * the jmp_buf.
  182636. */
  182637. struct png_struct_def
  182638. {
  182639. #ifdef PNG_SETJMP_SUPPORTED
  182640. jmp_buf jmpbuf; /* used in png_error */
  182641. #endif
  182642. png_error_ptr error_fn; /* function for printing errors and aborting */
  182643. png_error_ptr warning_fn; /* function for printing warnings */
  182644. png_voidp error_ptr; /* user supplied struct for error functions */
  182645. png_rw_ptr write_data_fn; /* function for writing output data */
  182646. png_rw_ptr read_data_fn; /* function for reading input data */
  182647. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182648. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182649. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182650. #endif
  182651. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182652. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182653. #endif
  182654. /* These were added in libpng-1.0.2 */
  182655. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182656. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182657. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182658. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182659. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182660. png_byte user_transform_channels; /* channels in user transformed pixels */
  182661. #endif
  182662. #endif
  182663. png_uint_32 mode; /* tells us where we are in the PNG file */
  182664. png_uint_32 flags; /* flags indicating various things to libpng */
  182665. png_uint_32 transformations; /* which transformations to perform */
  182666. z_stream zstream; /* pointer to decompression structure (below) */
  182667. png_bytep zbuf; /* buffer for zlib */
  182668. png_size_t zbuf_size; /* size of zbuf */
  182669. int zlib_level; /* holds zlib compression level */
  182670. int zlib_method; /* holds zlib compression method */
  182671. int zlib_window_bits; /* holds zlib compression window bits */
  182672. int zlib_mem_level; /* holds zlib compression memory level */
  182673. int zlib_strategy; /* holds zlib compression strategy */
  182674. png_uint_32 width; /* width of image in pixels */
  182675. png_uint_32 height; /* height of image in pixels */
  182676. png_uint_32 num_rows; /* number of rows in current pass */
  182677. png_uint_32 usr_width; /* width of row at start of write */
  182678. png_uint_32 rowbytes; /* size of row in bytes */
  182679. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182680. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182681. png_uint_32 row_number; /* current row in interlace pass */
  182682. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182683. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182684. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182685. png_bytep up_row; /* buffer to save "up" row when filtering */
  182686. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182687. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182688. png_row_info row_info; /* used for transformation routines */
  182689. png_uint_32 idat_size; /* current IDAT size for read */
  182690. png_uint_32 crc; /* current chunk CRC value */
  182691. png_colorp palette; /* palette from the input file */
  182692. png_uint_16 num_palette; /* number of color entries in palette */
  182693. png_uint_16 num_trans; /* number of transparency values */
  182694. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182695. png_byte compression; /* file compression type (always 0) */
  182696. png_byte filter; /* file filter type (always 0) */
  182697. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182698. png_byte pass; /* current interlace pass (0 - 6) */
  182699. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182700. png_byte color_type; /* color type of file */
  182701. png_byte bit_depth; /* bit depth of file */
  182702. png_byte usr_bit_depth; /* bit depth of users row */
  182703. png_byte pixel_depth; /* number of bits per pixel */
  182704. png_byte channels; /* number of channels in file */
  182705. png_byte usr_channels; /* channels at start of write */
  182706. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182707. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182708. #ifdef PNG_LEGACY_SUPPORTED
  182709. png_byte filler; /* filler byte for pixel expansion */
  182710. #else
  182711. png_uint_16 filler; /* filler bytes for pixel expansion */
  182712. #endif
  182713. #endif
  182714. #if defined(PNG_bKGD_SUPPORTED)
  182715. png_byte background_gamma_type;
  182716. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182717. float background_gamma;
  182718. # endif
  182719. png_color_16 background; /* background color in screen gamma space */
  182720. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182721. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182722. #endif
  182723. #endif /* PNG_bKGD_SUPPORTED */
  182724. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182725. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182726. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182727. png_uint_32 flush_rows; /* number of rows written since last flush */
  182728. #endif
  182729. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182730. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182731. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182732. float gamma; /* file gamma value */
  182733. float screen_gamma; /* screen gamma value (display_exponent) */
  182734. #endif
  182735. #endif
  182736. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182737. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182738. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182739. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182740. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182741. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182742. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182743. #endif
  182744. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182745. png_color_8 sig_bit; /* significant bits in each available channel */
  182746. #endif
  182747. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182748. png_color_8 shift; /* shift for significant bit tranformation */
  182749. #endif
  182750. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182751. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182752. png_bytep trans; /* transparency values for paletted files */
  182753. png_color_16 trans_values; /* transparency values for non-paletted files */
  182754. #endif
  182755. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182756. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182757. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182758. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182759. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182760. png_progressive_end_ptr end_fn; /* called after image is complete */
  182761. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182762. png_bytep save_buffer; /* buffer for previously read data */
  182763. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182764. png_bytep current_buffer; /* buffer for recently used data */
  182765. png_uint_32 push_length; /* size of current input chunk */
  182766. png_uint_32 skip_length; /* bytes to skip in input data */
  182767. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182768. png_size_t save_buffer_max; /* total size of save_buffer */
  182769. png_size_t buffer_size; /* total amount of available input data */
  182770. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182771. int process_mode; /* what push library is currently doing */
  182772. int cur_palette; /* current push library palette index */
  182773. # if defined(PNG_TEXT_SUPPORTED)
  182774. png_size_t current_text_size; /* current size of text input data */
  182775. png_size_t current_text_left; /* how much text left to read in input */
  182776. png_charp current_text; /* current text chunk buffer */
  182777. png_charp current_text_ptr; /* current location in current_text */
  182778. # endif /* PNG_TEXT_SUPPORTED */
  182779. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182780. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182781. /* for the Borland special 64K segment handler */
  182782. png_bytepp offset_table_ptr;
  182783. png_bytep offset_table;
  182784. png_uint_16 offset_table_number;
  182785. png_uint_16 offset_table_count;
  182786. png_uint_16 offset_table_count_free;
  182787. #endif
  182788. #if defined(PNG_READ_DITHER_SUPPORTED)
  182789. png_bytep palette_lookup; /* lookup table for dithering */
  182790. png_bytep dither_index; /* index translation for palette files */
  182791. #endif
  182792. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182793. png_uint_16p hist; /* histogram */
  182794. #endif
  182795. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182796. png_byte heuristic_method; /* heuristic for row filter selection */
  182797. png_byte num_prev_filters; /* number of weights for previous rows */
  182798. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182799. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182800. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182801. png_uint_16p filter_costs; /* relative filter calculation cost */
  182802. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182803. #endif
  182804. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182805. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182806. #endif
  182807. /* New members added in libpng-1.0.6 */
  182808. #ifdef PNG_FREE_ME_SUPPORTED
  182809. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182810. #endif
  182811. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182812. png_voidp user_chunk_ptr;
  182813. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182814. #endif
  182815. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182816. int num_chunk_list;
  182817. png_bytep chunk_list;
  182818. #endif
  182819. /* New members added in libpng-1.0.3 */
  182820. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182821. png_byte rgb_to_gray_status;
  182822. /* These were changed from png_byte in libpng-1.0.6 */
  182823. png_uint_16 rgb_to_gray_red_coeff;
  182824. png_uint_16 rgb_to_gray_green_coeff;
  182825. png_uint_16 rgb_to_gray_blue_coeff;
  182826. #endif
  182827. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182828. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182829. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182830. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182831. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182832. #ifdef PNG_1_0_X
  182833. png_byte mng_features_permitted;
  182834. #else
  182835. png_uint_32 mng_features_permitted;
  182836. #endif /* PNG_1_0_X */
  182837. #endif
  182838. /* New member added in libpng-1.0.7 */
  182839. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182840. png_fixed_point int_gamma;
  182841. #endif
  182842. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182843. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182844. png_byte filter_type;
  182845. #endif
  182846. #if defined(PNG_1_0_X)
  182847. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182848. png_uint_32 row_buf_size;
  182849. #endif
  182850. /* New members added in libpng-1.2.0 */
  182851. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182852. # if !defined(PNG_1_0_X)
  182853. # if defined(PNG_MMX_CODE_SUPPORTED)
  182854. png_byte mmx_bitdepth_threshold;
  182855. png_uint_32 mmx_rowbytes_threshold;
  182856. # endif
  182857. png_uint_32 asm_flags;
  182858. # endif
  182859. #endif
  182860. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182861. #ifdef PNG_USER_MEM_SUPPORTED
  182862. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182863. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182864. png_free_ptr free_fn; /* function for freeing memory */
  182865. #endif
  182866. /* New member added in libpng-1.0.13 and 1.2.0 */
  182867. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182868. #if defined(PNG_READ_DITHER_SUPPORTED)
  182869. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182870. png_bytep dither_sort; /* working sort array */
  182871. png_bytep index_to_palette; /* where the original index currently is */
  182872. /* in the palette */
  182873. png_bytep palette_to_index; /* which original index points to this */
  182874. /* palette color */
  182875. #endif
  182876. /* New members added in libpng-1.0.16 and 1.2.6 */
  182877. png_byte compression_type;
  182878. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182879. png_uint_32 user_width_max;
  182880. png_uint_32 user_height_max;
  182881. #endif
  182882. /* New member added in libpng-1.0.25 and 1.2.17 */
  182883. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182884. /* storage for unknown chunk that the library doesn't recognize. */
  182885. png_unknown_chunk unknown_chunk;
  182886. #endif
  182887. };
  182888. /* This triggers a compiler error in png.c, if png.c and png.h
  182889. * do not agree upon the version number.
  182890. */
  182891. typedef png_structp version_1_2_21;
  182892. typedef png_struct FAR * FAR * png_structpp;
  182893. /* Here are the function definitions most commonly used. This is not
  182894. * the place to find out how to use libpng. See libpng.txt for the
  182895. * full explanation, see example.c for the summary. This just provides
  182896. * a simple one line description of the use of each function.
  182897. */
  182898. /* Returns the version number of the library */
  182899. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182900. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182901. * Handling more than 8 bytes from the beginning of the file is an error.
  182902. */
  182903. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182904. int num_bytes));
  182905. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182906. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182907. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182908. * start > 7 will always fail (ie return non-zero).
  182909. */
  182910. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182911. png_size_t num_to_check));
  182912. /* Simple signature checking function. This is the same as calling
  182913. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182914. */
  182915. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182916. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182917. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182918. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182919. png_error_ptr error_fn, png_error_ptr warn_fn));
  182920. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182921. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182922. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182923. png_error_ptr error_fn, png_error_ptr warn_fn));
  182924. #ifdef PNG_WRITE_SUPPORTED
  182925. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182926. PNGARG((png_structp png_ptr));
  182927. #endif
  182928. #ifdef PNG_WRITE_SUPPORTED
  182929. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182930. PNGARG((png_structp png_ptr, png_uint_32 size));
  182931. #endif
  182932. /* Reset the compression stream */
  182933. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182934. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182935. #ifdef PNG_USER_MEM_SUPPORTED
  182936. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182937. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182938. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182939. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182940. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182941. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182942. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182943. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182944. #endif
  182945. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182946. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182947. png_bytep chunk_name, png_bytep data, png_size_t length));
  182948. /* Write the start of a PNG chunk - length and chunk name. */
  182949. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182950. png_bytep chunk_name, png_uint_32 length));
  182951. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182952. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182953. png_bytep data, png_size_t length));
  182954. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182955. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182956. /* Allocate and initialize the info structure */
  182957. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182958. PNGARG((png_structp png_ptr));
  182959. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182960. /* Initialize the info structure (old interface - DEPRECATED) */
  182961. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182962. #undef png_info_init
  182963. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182964. png_sizeof(png_info));
  182965. #endif
  182966. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182967. png_size_t png_info_struct_size));
  182968. /* Writes all the PNG information before the image. */
  182969. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182970. png_infop info_ptr));
  182971. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182972. png_infop info_ptr));
  182973. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182974. /* read the information before the actual image data. */
  182975. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182976. png_infop info_ptr));
  182977. #endif
  182978. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182979. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182980. PNGARG((png_structp png_ptr, png_timep ptime));
  182981. #endif
  182982. #if !defined(_WIN32_WCE)
  182983. /* "time.h" functions are not supported on WindowsCE */
  182984. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182985. /* convert from a struct tm to png_time */
  182986. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182987. struct tm FAR * ttime));
  182988. /* convert from time_t to png_time. Uses gmtime() */
  182989. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182990. time_t ttime));
  182991. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182992. #endif /* _WIN32_WCE */
  182993. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182994. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182995. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182996. #if !defined(PNG_1_0_X)
  182997. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182998. png_ptr));
  182999. #endif
  183000. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183001. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183002. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183003. /* Deprecated */
  183004. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183005. #endif
  183006. #endif
  183007. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183008. /* Use blue, green, red order for pixels. */
  183009. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183010. #endif
  183011. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183012. /* Expand the grayscale to 24-bit RGB if necessary. */
  183013. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183014. #endif
  183015. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183016. /* Reduce RGB to grayscale. */
  183017. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183018. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183019. int error_action, double red, double green ));
  183020. #endif
  183021. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183022. int error_action, png_fixed_point red, png_fixed_point green ));
  183023. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183024. png_ptr));
  183025. #endif
  183026. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183027. png_colorp palette));
  183028. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183029. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183030. #endif
  183031. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183032. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183033. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183034. #endif
  183035. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183036. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183037. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183038. #endif
  183039. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183040. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183041. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183042. png_uint_32 filler, int flags));
  183043. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183044. #define PNG_FILLER_BEFORE 0
  183045. #define PNG_FILLER_AFTER 1
  183046. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183047. #if !defined(PNG_1_0_X)
  183048. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183049. png_uint_32 filler, int flags));
  183050. #endif
  183051. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183052. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183053. /* Swap bytes in 16-bit depth files. */
  183054. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183055. #endif
  183056. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183057. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183058. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183059. #endif
  183060. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183061. /* Swap packing order of pixels in bytes. */
  183062. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183063. #endif
  183064. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183065. /* Converts files to legal bit depths. */
  183066. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183067. png_color_8p true_bits));
  183068. #endif
  183069. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183070. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183071. /* Have the code handle the interlacing. Returns the number of passes. */
  183072. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183073. #endif
  183074. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183075. /* Invert monochrome files */
  183076. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183077. #endif
  183078. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183079. /* Handle alpha and tRNS by replacing with a background color. */
  183080. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183081. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183082. png_color_16p background_color, int background_gamma_code,
  183083. int need_expand, double background_gamma));
  183084. #endif
  183085. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183086. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183087. #define PNG_BACKGROUND_GAMMA_FILE 2
  183088. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183089. #endif
  183090. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183091. /* strip the second byte of information from a 16-bit depth file. */
  183092. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183093. #endif
  183094. #if defined(PNG_READ_DITHER_SUPPORTED)
  183095. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183096. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183097. png_colorp palette, int num_palette, int maximum_colors,
  183098. png_uint_16p histogram, int full_dither));
  183099. #endif
  183100. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183101. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183102. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183103. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183104. double screen_gamma, double default_file_gamma));
  183105. #endif
  183106. #endif
  183107. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183108. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183109. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183110. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183111. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183112. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183113. int empty_plte_permitted));
  183114. #endif
  183115. #endif
  183116. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183117. /* Set how many lines between output flushes - 0 for no flushing */
  183118. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183119. /* Flush the current PNG output buffer */
  183120. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183121. #endif
  183122. /* optional update palette with requested transformations */
  183123. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183124. /* optional call to update the users info structure */
  183125. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183126. png_infop info_ptr));
  183127. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183128. /* read one or more rows of image data. */
  183129. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183130. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183131. #endif
  183132. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183133. /* read a row of data. */
  183134. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183135. png_bytep row,
  183136. png_bytep display_row));
  183137. #endif
  183138. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183139. /* read the whole image into memory at once. */
  183140. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183141. png_bytepp image));
  183142. #endif
  183143. /* write a row of image data */
  183144. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183145. png_bytep row));
  183146. /* write a few rows of image data */
  183147. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183148. png_bytepp row, png_uint_32 num_rows));
  183149. /* write the image data */
  183150. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183151. png_bytepp image));
  183152. /* writes the end of the PNG file. */
  183153. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183154. png_infop info_ptr));
  183155. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183156. /* read the end of the PNG file. */
  183157. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183158. png_infop info_ptr));
  183159. #endif
  183160. /* free any memory associated with the png_info_struct */
  183161. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183162. png_infopp info_ptr_ptr));
  183163. /* free any memory associated with the png_struct and the png_info_structs */
  183164. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183165. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183166. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183167. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183168. png_infop end_info_ptr));
  183169. /* free any memory associated with the png_struct and the png_info_structs */
  183170. extern PNG_EXPORT(void,png_destroy_write_struct)
  183171. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183172. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183173. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183174. /* set the libpng method of handling chunk CRC errors */
  183175. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183176. int crit_action, int ancil_action));
  183177. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183178. * ancillary and critical chunks, and whether to use the data contained
  183179. * therein. Note that it is impossible to "discard" data in a critical
  183180. * chunk. For versions prior to 0.90, the action was always error/quit,
  183181. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183182. * chunks is warn/discard. These values should NOT be changed.
  183183. *
  183184. * value action:critical action:ancillary
  183185. */
  183186. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183187. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183188. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183189. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183190. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183191. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183192. /* These functions give the user control over the scan-line filtering in
  183193. * libpng and the compression methods used by zlib. These functions are
  183194. * mainly useful for testing, as the defaults should work with most users.
  183195. * Those users who are tight on memory or want faster performance at the
  183196. * expense of compression can modify them. See the compression library
  183197. * header file (zlib.h) for an explination of the compression functions.
  183198. */
  183199. /* set the filtering method(s) used by libpng. Currently, the only valid
  183200. * value for "method" is 0.
  183201. */
  183202. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183203. int filters));
  183204. /* Flags for png_set_filter() to say which filters to use. The flags
  183205. * are chosen so that they don't conflict with real filter types
  183206. * below, in case they are supplied instead of the #defined constants.
  183207. * These values should NOT be changed.
  183208. */
  183209. #define PNG_NO_FILTERS 0x00
  183210. #define PNG_FILTER_NONE 0x08
  183211. #define PNG_FILTER_SUB 0x10
  183212. #define PNG_FILTER_UP 0x20
  183213. #define PNG_FILTER_AVG 0x40
  183214. #define PNG_FILTER_PAETH 0x80
  183215. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183216. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183217. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183218. * These defines should NOT be changed.
  183219. */
  183220. #define PNG_FILTER_VALUE_NONE 0
  183221. #define PNG_FILTER_VALUE_SUB 1
  183222. #define PNG_FILTER_VALUE_UP 2
  183223. #define PNG_FILTER_VALUE_AVG 3
  183224. #define PNG_FILTER_VALUE_PAETH 4
  183225. #define PNG_FILTER_VALUE_LAST 5
  183226. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183227. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183228. * defines, either the default (minimum-sum-of-absolute-differences), or
  183229. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183230. *
  183231. * Weights are factors >= 1.0, indicating how important it is to keep the
  183232. * filter type consistent between rows. Larger numbers mean the current
  183233. * filter is that many times as likely to be the same as the "num_weights"
  183234. * previous filters. This is cumulative for each previous row with a weight.
  183235. * There needs to be "num_weights" values in "filter_weights", or it can be
  183236. * NULL if the weights aren't being specified. Weights have no influence on
  183237. * the selection of the first row filter. Well chosen weights can (in theory)
  183238. * improve the compression for a given image.
  183239. *
  183240. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183241. * filter type. Higher costs indicate more decoding expense, and are
  183242. * therefore less likely to be selected over a filter with lower computational
  183243. * costs. There needs to be a value in "filter_costs" for each valid filter
  183244. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183245. * setting the costs. Costs try to improve the speed of decompression without
  183246. * unduly increasing the compressed image size.
  183247. *
  183248. * A negative weight or cost indicates the default value is to be used, and
  183249. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183250. * The default values for both weights and costs are currently 1.0, but may
  183251. * change if good general weighting/cost heuristics can be found. If both
  183252. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183253. * to the UNWEIGHTED method, but with added encoding time/computation.
  183254. */
  183255. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183256. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183257. int heuristic_method, int num_weights, png_doublep filter_weights,
  183258. png_doublep filter_costs));
  183259. #endif
  183260. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183261. /* Heuristic used for row filter selection. These defines should NOT be
  183262. * changed.
  183263. */
  183264. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183265. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183266. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183267. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183268. /* Set the library compression level. Currently, valid values range from
  183269. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183270. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183271. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183272. * for PNG images, and do considerably fewer caclulations. In the future,
  183273. * these values may not correspond directly to the zlib compression levels.
  183274. */
  183275. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183276. int level));
  183277. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183278. PNGARG((png_structp png_ptr, int mem_level));
  183279. extern PNG_EXPORT(void,png_set_compression_strategy)
  183280. PNGARG((png_structp png_ptr, int strategy));
  183281. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183282. PNGARG((png_structp png_ptr, int window_bits));
  183283. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183284. int method));
  183285. /* These next functions are called for input/output, memory, and error
  183286. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183287. * and call standard C I/O routines such as fread(), fwrite(), and
  183288. * fprintf(). These functions can be made to use other I/O routines
  183289. * at run time for those applications that need to handle I/O in a
  183290. * different manner by calling png_set_???_fn(). See libpng.txt for
  183291. * more information.
  183292. */
  183293. #if !defined(PNG_NO_STDIO)
  183294. /* Initialize the input/output for the PNG file to the default functions. */
  183295. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183296. #endif
  183297. /* Replace the (error and abort), and warning functions with user
  183298. * supplied functions. If no messages are to be printed you must still
  183299. * write and use replacement functions. The replacement error_fn should
  183300. * still do a longjmp to the last setjmp location if you are using this
  183301. * method of error handling. If error_fn or warning_fn is NULL, the
  183302. * default function will be used.
  183303. */
  183304. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183305. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183306. /* Return the user pointer associated with the error functions */
  183307. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183308. /* Replace the default data output functions with a user supplied one(s).
  183309. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183310. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183311. * output_flush_fn will be ignored (and thus can be NULL).
  183312. */
  183313. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183314. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183315. /* Replace the default data input function with a user supplied one. */
  183316. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183317. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183318. /* Return the user pointer associated with the I/O functions */
  183319. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183320. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183321. png_read_status_ptr read_row_fn));
  183322. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183323. png_write_status_ptr write_row_fn));
  183324. #ifdef PNG_USER_MEM_SUPPORTED
  183325. /* Replace the default memory allocation functions with user supplied one(s). */
  183326. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183327. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183328. /* Return the user pointer associated with the memory functions */
  183329. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183330. #endif
  183331. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183332. defined(PNG_LEGACY_SUPPORTED)
  183333. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183334. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183335. #endif
  183336. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183337. defined(PNG_LEGACY_SUPPORTED)
  183338. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183339. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183340. #endif
  183341. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183342. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183343. defined(PNG_LEGACY_SUPPORTED)
  183344. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183345. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183346. int user_transform_channels));
  183347. /* Return the user pointer associated with the user transform functions */
  183348. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183349. PNGARG((png_structp png_ptr));
  183350. #endif
  183351. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183352. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183353. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183354. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183355. png_ptr));
  183356. #endif
  183357. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183358. /* Sets the function callbacks for the push reader, and a pointer to a
  183359. * user-defined structure available to the callback functions.
  183360. */
  183361. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183362. png_voidp progressive_ptr,
  183363. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183364. png_progressive_end_ptr end_fn));
  183365. /* returns the user pointer associated with the push read functions */
  183366. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183367. PNGARG((png_structp png_ptr));
  183368. /* function to be called when data becomes available */
  183369. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183370. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183371. /* function that combines rows. Not very much different than the
  183372. * png_combine_row() call. Is this even used?????
  183373. */
  183374. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183375. png_bytep old_row, png_bytep new_row));
  183376. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183377. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183378. png_uint_32 size));
  183379. #if defined(PNG_1_0_X)
  183380. # define png_malloc_warn png_malloc
  183381. #else
  183382. /* Added at libpng version 1.2.4 */
  183383. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183384. png_uint_32 size));
  183385. #endif
  183386. /* frees a pointer allocated by png_malloc() */
  183387. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183388. #if defined(PNG_1_0_X)
  183389. /* Function to allocate memory for zlib. */
  183390. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183391. uInt size));
  183392. /* Function to free memory for zlib */
  183393. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183394. #endif
  183395. /* Free data that was allocated internally */
  183396. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183397. png_infop info_ptr, png_uint_32 free_me, int num));
  183398. #ifdef PNG_FREE_ME_SUPPORTED
  183399. /* Reassign responsibility for freeing existing data, whether allocated
  183400. * by libpng or by the application */
  183401. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183402. png_infop info_ptr, int freer, png_uint_32 mask));
  183403. #endif
  183404. /* assignments for png_data_freer */
  183405. #define PNG_DESTROY_WILL_FREE_DATA 1
  183406. #define PNG_SET_WILL_FREE_DATA 1
  183407. #define PNG_USER_WILL_FREE_DATA 2
  183408. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183409. #define PNG_FREE_HIST 0x0008
  183410. #define PNG_FREE_ICCP 0x0010
  183411. #define PNG_FREE_SPLT 0x0020
  183412. #define PNG_FREE_ROWS 0x0040
  183413. #define PNG_FREE_PCAL 0x0080
  183414. #define PNG_FREE_SCAL 0x0100
  183415. #define PNG_FREE_UNKN 0x0200
  183416. #define PNG_FREE_LIST 0x0400
  183417. #define PNG_FREE_PLTE 0x1000
  183418. #define PNG_FREE_TRNS 0x2000
  183419. #define PNG_FREE_TEXT 0x4000
  183420. #define PNG_FREE_ALL 0x7fff
  183421. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183422. #ifdef PNG_USER_MEM_SUPPORTED
  183423. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183424. png_uint_32 size));
  183425. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183426. png_voidp ptr));
  183427. #endif
  183428. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183429. png_voidp s1, png_voidp s2, png_uint_32 size));
  183430. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183431. png_voidp s1, int value, png_uint_32 size));
  183432. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183433. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183434. int check));
  183435. #endif /* USE_FAR_KEYWORD */
  183436. #ifndef PNG_NO_ERROR_TEXT
  183437. /* Fatal error in PNG image of libpng - can't continue */
  183438. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183439. png_const_charp error_message));
  183440. /* The same, but the chunk name is prepended to the error string. */
  183441. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183442. png_const_charp error_message));
  183443. #else
  183444. /* Fatal error in PNG image of libpng - can't continue */
  183445. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183446. #endif
  183447. #ifndef PNG_NO_WARNINGS
  183448. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183449. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183450. png_const_charp warning_message));
  183451. #ifdef PNG_READ_SUPPORTED
  183452. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183453. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183454. png_const_charp warning_message));
  183455. #endif /* PNG_READ_SUPPORTED */
  183456. #endif /* PNG_NO_WARNINGS */
  183457. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183458. * Similarly, the png_get_<chunk> calls are used to read values from the
  183459. * png_info_struct, either storing the parameters in the passed variables, or
  183460. * setting pointers into the png_info_struct where the data is stored. The
  183461. * png_get_<chunk> functions return a non-zero value if the data was available
  183462. * in info_ptr, or return zero and do not change any of the parameters if the
  183463. * data was not available.
  183464. *
  183465. * These functions should be used instead of directly accessing png_info
  183466. * to avoid problems with future changes in the size and internal layout of
  183467. * png_info_struct.
  183468. */
  183469. /* Returns "flag" if chunk data is valid in info_ptr. */
  183470. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183471. png_infop info_ptr, png_uint_32 flag));
  183472. /* Returns number of bytes needed to hold a transformed row. */
  183473. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183474. png_infop info_ptr));
  183475. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183476. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183477. returned from png_read_png(). */
  183478. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183479. png_infop info_ptr));
  183480. /* Set row_pointers, which is an array of pointers to scanlines for use
  183481. by png_write_png(). */
  183482. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183483. png_infop info_ptr, png_bytepp row_pointers));
  183484. #endif
  183485. /* Returns number of color channels in image. */
  183486. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183487. png_infop info_ptr));
  183488. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183489. /* Returns image width in pixels. */
  183490. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183491. png_ptr, png_infop info_ptr));
  183492. /* Returns image height in pixels. */
  183493. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183494. png_ptr, png_infop info_ptr));
  183495. /* Returns image bit_depth. */
  183496. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183497. png_ptr, png_infop info_ptr));
  183498. /* Returns image color_type. */
  183499. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183500. png_ptr, png_infop info_ptr));
  183501. /* Returns image filter_type. */
  183502. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183503. png_ptr, png_infop info_ptr));
  183504. /* Returns image interlace_type. */
  183505. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183506. png_ptr, png_infop info_ptr));
  183507. /* Returns image compression_type. */
  183508. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183509. png_ptr, png_infop info_ptr));
  183510. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183511. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183512. png_ptr, png_infop info_ptr));
  183513. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183514. png_ptr, png_infop info_ptr));
  183515. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183516. png_ptr, png_infop info_ptr));
  183517. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183518. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183519. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183520. png_ptr, png_infop info_ptr));
  183521. #endif
  183522. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183523. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183524. png_ptr, png_infop info_ptr));
  183525. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183526. png_ptr, png_infop info_ptr));
  183527. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183528. png_ptr, png_infop info_ptr));
  183529. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183530. png_ptr, png_infop info_ptr));
  183531. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183532. /* Returns pointer to signature string read from PNG header */
  183533. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183534. png_infop info_ptr));
  183535. #if defined(PNG_bKGD_SUPPORTED)
  183536. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183537. png_infop info_ptr, png_color_16p *background));
  183538. #endif
  183539. #if defined(PNG_bKGD_SUPPORTED)
  183540. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183541. png_infop info_ptr, png_color_16p background));
  183542. #endif
  183543. #if defined(PNG_cHRM_SUPPORTED)
  183544. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183545. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183546. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183547. double *red_y, double *green_x, double *green_y, double *blue_x,
  183548. double *blue_y));
  183549. #endif
  183550. #ifdef PNG_FIXED_POINT_SUPPORTED
  183551. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183552. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183553. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183554. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183555. *int_blue_x, png_fixed_point *int_blue_y));
  183556. #endif
  183557. #endif
  183558. #if defined(PNG_cHRM_SUPPORTED)
  183559. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183560. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183561. png_infop info_ptr, double white_x, double white_y, double red_x,
  183562. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183563. #endif
  183564. #ifdef PNG_FIXED_POINT_SUPPORTED
  183565. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183566. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183567. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183568. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183569. png_fixed_point int_blue_y));
  183570. #endif
  183571. #endif
  183572. #if defined(PNG_gAMA_SUPPORTED)
  183573. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183574. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183575. png_infop info_ptr, double *file_gamma));
  183576. #endif
  183577. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183578. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183579. #endif
  183580. #if defined(PNG_gAMA_SUPPORTED)
  183581. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183582. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183583. png_infop info_ptr, double file_gamma));
  183584. #endif
  183585. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183586. png_infop info_ptr, png_fixed_point int_file_gamma));
  183587. #endif
  183588. #if defined(PNG_hIST_SUPPORTED)
  183589. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183590. png_infop info_ptr, png_uint_16p *hist));
  183591. #endif
  183592. #if defined(PNG_hIST_SUPPORTED)
  183593. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183594. png_infop info_ptr, png_uint_16p hist));
  183595. #endif
  183596. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183597. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183598. int *bit_depth, int *color_type, int *interlace_method,
  183599. int *compression_method, int *filter_method));
  183600. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183601. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183602. int color_type, int interlace_method, int compression_method,
  183603. int filter_method));
  183604. #if defined(PNG_oFFs_SUPPORTED)
  183605. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183606. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183607. int *unit_type));
  183608. #endif
  183609. #if defined(PNG_oFFs_SUPPORTED)
  183610. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183611. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183612. int unit_type));
  183613. #endif
  183614. #if defined(PNG_pCAL_SUPPORTED)
  183615. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183616. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183617. int *type, int *nparams, png_charp *units, png_charpp *params));
  183618. #endif
  183619. #if defined(PNG_pCAL_SUPPORTED)
  183620. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183621. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183622. int type, int nparams, png_charp units, png_charpp params));
  183623. #endif
  183624. #if defined(PNG_pHYs_SUPPORTED)
  183625. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183626. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183627. #endif
  183628. #if defined(PNG_pHYs_SUPPORTED)
  183629. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183630. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183631. #endif
  183632. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183633. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183634. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183635. png_infop info_ptr, png_colorp palette, int num_palette));
  183636. #if defined(PNG_sBIT_SUPPORTED)
  183637. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183638. png_infop info_ptr, png_color_8p *sig_bit));
  183639. #endif
  183640. #if defined(PNG_sBIT_SUPPORTED)
  183641. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183642. png_infop info_ptr, png_color_8p sig_bit));
  183643. #endif
  183644. #if defined(PNG_sRGB_SUPPORTED)
  183645. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183646. png_infop info_ptr, int *intent));
  183647. #endif
  183648. #if defined(PNG_sRGB_SUPPORTED)
  183649. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183650. png_infop info_ptr, int intent));
  183651. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183652. png_infop info_ptr, int intent));
  183653. #endif
  183654. #if defined(PNG_iCCP_SUPPORTED)
  183655. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183656. png_infop info_ptr, png_charpp name, int *compression_type,
  183657. png_charpp profile, png_uint_32 *proflen));
  183658. /* Note to maintainer: profile should be png_bytepp */
  183659. #endif
  183660. #if defined(PNG_iCCP_SUPPORTED)
  183661. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183662. png_infop info_ptr, png_charp name, int compression_type,
  183663. png_charp profile, png_uint_32 proflen));
  183664. /* Note to maintainer: profile should be png_bytep */
  183665. #endif
  183666. #if defined(PNG_sPLT_SUPPORTED)
  183667. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183668. png_infop info_ptr, png_sPLT_tpp entries));
  183669. #endif
  183670. #if defined(PNG_sPLT_SUPPORTED)
  183671. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183672. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183673. #endif
  183674. #if defined(PNG_TEXT_SUPPORTED)
  183675. /* png_get_text also returns the number of text chunks in *num_text */
  183676. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183677. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183678. #endif
  183679. /*
  183680. * Note while png_set_text() will accept a structure whose text,
  183681. * language, and translated keywords are NULL pointers, the structure
  183682. * returned by png_get_text will always contain regular
  183683. * zero-terminated C strings. They might be empty strings but
  183684. * they will never be NULL pointers.
  183685. */
  183686. #if defined(PNG_TEXT_SUPPORTED)
  183687. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183688. png_infop info_ptr, png_textp text_ptr, int num_text));
  183689. #endif
  183690. #if defined(PNG_tIME_SUPPORTED)
  183691. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183692. png_infop info_ptr, png_timep *mod_time));
  183693. #endif
  183694. #if defined(PNG_tIME_SUPPORTED)
  183695. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183696. png_infop info_ptr, png_timep mod_time));
  183697. #endif
  183698. #if defined(PNG_tRNS_SUPPORTED)
  183699. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183700. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183701. png_color_16p *trans_values));
  183702. #endif
  183703. #if defined(PNG_tRNS_SUPPORTED)
  183704. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183705. png_infop info_ptr, png_bytep trans, int num_trans,
  183706. png_color_16p trans_values));
  183707. #endif
  183708. #if defined(PNG_tRNS_SUPPORTED)
  183709. #endif
  183710. #if defined(PNG_sCAL_SUPPORTED)
  183711. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183712. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183713. png_infop info_ptr, int *unit, double *width, double *height));
  183714. #else
  183715. #ifdef PNG_FIXED_POINT_SUPPORTED
  183716. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183717. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183718. #endif
  183719. #endif
  183720. #endif /* PNG_sCAL_SUPPORTED */
  183721. #if defined(PNG_sCAL_SUPPORTED)
  183722. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183723. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183724. png_infop info_ptr, int unit, double width, double height));
  183725. #else
  183726. #ifdef PNG_FIXED_POINT_SUPPORTED
  183727. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183728. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183729. #endif
  183730. #endif
  183731. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183732. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183733. /* provide a list of chunks and how they are to be handled, if the built-in
  183734. handling or default unknown chunk handling is not desired. Any chunks not
  183735. listed will be handled in the default manner. The IHDR and IEND chunks
  183736. must not be listed.
  183737. keep = 0: follow default behaviour
  183738. = 1: do not keep
  183739. = 2: keep only if safe-to-copy
  183740. = 3: keep even if unsafe-to-copy
  183741. */
  183742. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183743. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183744. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183745. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183746. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183747. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183748. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183749. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183750. #endif
  183751. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183752. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183753. chunk_name));
  183754. #endif
  183755. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183756. If you need to turn it off for a chunk that your application has freed,
  183757. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183758. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183759. png_infop info_ptr, int mask));
  183760. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183761. /* The "params" pointer is currently not used and is for future expansion. */
  183762. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183763. png_infop info_ptr,
  183764. int transforms,
  183765. png_voidp params));
  183766. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183767. png_infop info_ptr,
  183768. int transforms,
  183769. png_voidp params));
  183770. #endif
  183771. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183772. * numbers for PNG_DEBUG mean more debugging information. This has
  183773. * only been added since version 0.95 so it is not implemented throughout
  183774. * libpng yet, but more support will be added as needed.
  183775. */
  183776. #ifdef PNG_DEBUG
  183777. #if (PNG_DEBUG > 0)
  183778. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183779. #include <crtdbg.h>
  183780. #if (PNG_DEBUG > 1)
  183781. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183782. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183783. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183784. #endif
  183785. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183786. #ifndef PNG_DEBUG_FILE
  183787. #define PNG_DEBUG_FILE stderr
  183788. #endif /* PNG_DEBUG_FILE */
  183789. #if (PNG_DEBUG > 1)
  183790. #define png_debug(l,m) \
  183791. { \
  183792. int num_tabs=l; \
  183793. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183794. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183795. }
  183796. #define png_debug1(l,m,p1) \
  183797. { \
  183798. int num_tabs=l; \
  183799. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183800. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183801. }
  183802. #define png_debug2(l,m,p1,p2) \
  183803. { \
  183804. int num_tabs=l; \
  183805. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183806. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183807. }
  183808. #endif /* (PNG_DEBUG > 1) */
  183809. #endif /* _MSC_VER */
  183810. #endif /* (PNG_DEBUG > 0) */
  183811. #endif /* PNG_DEBUG */
  183812. #ifndef png_debug
  183813. #define png_debug(l, m)
  183814. #endif
  183815. #ifndef png_debug1
  183816. #define png_debug1(l, m, p1)
  183817. #endif
  183818. #ifndef png_debug2
  183819. #define png_debug2(l, m, p1, p2)
  183820. #endif
  183821. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183822. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183823. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183824. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183825. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183826. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183827. png_ptr, png_uint_32 mng_features_permitted));
  183828. #endif
  183829. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183830. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183831. #define PNG_HANDLE_CHUNK_NEVER 1
  183832. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183833. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183834. /* Added to version 1.2.0 */
  183835. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183836. #if defined(PNG_MMX_CODE_SUPPORTED)
  183837. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183838. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183839. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183840. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183841. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183842. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183843. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183844. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183845. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183846. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183847. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183848. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183849. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183850. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183851. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183852. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183853. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183854. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183855. | PNG_MMX_READ_FLAGS \
  183856. | PNG_MMX_WRITE_FLAGS )
  183857. #define PNG_SELECT_READ 1
  183858. #define PNG_SELECT_WRITE 2
  183859. #endif /* PNG_MMX_CODE_SUPPORTED */
  183860. #if !defined(PNG_1_0_X)
  183861. /* pngget.c */
  183862. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183863. PNGARG((int flag_select, int *compilerID));
  183864. /* pngget.c */
  183865. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183866. PNGARG((int flag_select));
  183867. /* pngget.c */
  183868. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183869. PNGARG((png_structp png_ptr));
  183870. /* pngget.c */
  183871. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183872. PNGARG((png_structp png_ptr));
  183873. /* pngget.c */
  183874. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183875. PNGARG((png_structp png_ptr));
  183876. /* pngset.c */
  183877. extern PNG_EXPORT(void,png_set_asm_flags)
  183878. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183879. /* pngset.c */
  183880. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183881. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183882. png_uint_32 mmx_rowbytes_threshold));
  183883. #endif /* PNG_1_0_X */
  183884. #if !defined(PNG_1_0_X)
  183885. /* png.c, pnggccrd.c, or pngvcrd.c */
  183886. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183887. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183888. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183889. * messages before passing them to the error or warning handler. */
  183890. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183891. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183892. png_ptr, png_uint_32 strip_mode));
  183893. #endif
  183894. #endif /* PNG_1_0_X */
  183895. /* Added at libpng-1.2.6 */
  183896. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183897. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183898. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183899. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183900. png_ptr));
  183901. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183902. png_ptr));
  183903. #endif
  183904. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183905. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183906. /* With these routines we avoid an integer divide, which will be slower on
  183907. * most machines. However, it does take more operations than the corresponding
  183908. * divide method, so it may be slower on a few RISC systems. There are two
  183909. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183910. *
  183911. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183912. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183913. * standard method.
  183914. *
  183915. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183916. */
  183917. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183918. # define png_composite(composite, fg, alpha, bg) \
  183919. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183920. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183921. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183922. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183923. # define png_composite_16(composite, fg, alpha, bg) \
  183924. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183925. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183926. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183927. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183928. #else /* standard method using integer division */
  183929. # define png_composite(composite, fg, alpha, bg) \
  183930. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183931. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183932. (png_uint_16)127) / 255)
  183933. # define png_composite_16(composite, fg, alpha, bg) \
  183934. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183935. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183936. (png_uint_32)32767) / (png_uint_32)65535L)
  183937. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183938. /* Inline macros to do direct reads of bytes from the input buffer. These
  183939. * require that you are using an architecture that uses PNG byte ordering
  183940. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183941. * in big-endian mode and 680x0 are the only ones that will support this.
  183942. * The x86 line of processors definitely do not. The png_get_int_32()
  183943. * routine also assumes we are using two's complement format for negative
  183944. * values, which is almost certainly true.
  183945. */
  183946. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183947. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183948. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183949. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183950. #else
  183951. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183952. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183953. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183954. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183955. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183956. PNGARG((png_structp png_ptr, png_bytep buf));
  183957. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183958. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183959. */
  183960. extern PNG_EXPORT(void,png_save_uint_32)
  183961. PNGARG((png_bytep buf, png_uint_32 i));
  183962. extern PNG_EXPORT(void,png_save_int_32)
  183963. PNGARG((png_bytep buf, png_int_32 i));
  183964. /* Place a 16-bit number into a buffer in PNG byte order.
  183965. * The parameter is declared unsigned int, not png_uint_16,
  183966. * just to avoid potential problems on pre-ANSI C compilers.
  183967. */
  183968. extern PNG_EXPORT(void,png_save_uint_16)
  183969. PNGARG((png_bytep buf, unsigned int i));
  183970. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183971. /* ************************************************************************* */
  183972. /* These next functions are used internally in the code. They generally
  183973. * shouldn't be used unless you are writing code to add or replace some
  183974. * functionality in libpng. More information about most functions can
  183975. * be found in the files where the functions are located.
  183976. */
  183977. /* Various modes of operation, that are visible to applications because
  183978. * they are used for unknown chunk location.
  183979. */
  183980. #define PNG_HAVE_IHDR 0x01
  183981. #define PNG_HAVE_PLTE 0x02
  183982. #define PNG_HAVE_IDAT 0x04
  183983. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183984. #define PNG_HAVE_IEND 0x10
  183985. #if defined(PNG_INTERNAL)
  183986. /* More modes of operation. Note that after an init, mode is set to
  183987. * zero automatically when the structure is created.
  183988. */
  183989. #define PNG_HAVE_gAMA 0x20
  183990. #define PNG_HAVE_cHRM 0x40
  183991. #define PNG_HAVE_sRGB 0x80
  183992. #define PNG_HAVE_CHUNK_HEADER 0x100
  183993. #define PNG_WROTE_tIME 0x200
  183994. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183995. #define PNG_BACKGROUND_IS_GRAY 0x800
  183996. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183997. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183998. /* flags for the transformations the PNG library does on the image data */
  183999. #define PNG_BGR 0x0001
  184000. #define PNG_INTERLACE 0x0002
  184001. #define PNG_PACK 0x0004
  184002. #define PNG_SHIFT 0x0008
  184003. #define PNG_SWAP_BYTES 0x0010
  184004. #define PNG_INVERT_MONO 0x0020
  184005. #define PNG_DITHER 0x0040
  184006. #define PNG_BACKGROUND 0x0080
  184007. #define PNG_BACKGROUND_EXPAND 0x0100
  184008. /* 0x0200 unused */
  184009. #define PNG_16_TO_8 0x0400
  184010. #define PNG_RGBA 0x0800
  184011. #define PNG_EXPAND 0x1000
  184012. #define PNG_GAMMA 0x2000
  184013. #define PNG_GRAY_TO_RGB 0x4000
  184014. #define PNG_FILLER 0x8000L
  184015. #define PNG_PACKSWAP 0x10000L
  184016. #define PNG_SWAP_ALPHA 0x20000L
  184017. #define PNG_STRIP_ALPHA 0x40000L
  184018. #define PNG_INVERT_ALPHA 0x80000L
  184019. #define PNG_USER_TRANSFORM 0x100000L
  184020. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184021. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184022. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184023. /* 0x800000L Unused */
  184024. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184025. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184026. /* 0x4000000L unused */
  184027. /* 0x8000000L unused */
  184028. /* 0x10000000L unused */
  184029. /* 0x20000000L unused */
  184030. /* 0x40000000L unused */
  184031. /* flags for png_create_struct */
  184032. #define PNG_STRUCT_PNG 0x0001
  184033. #define PNG_STRUCT_INFO 0x0002
  184034. /* Scaling factor for filter heuristic weighting calculations */
  184035. #define PNG_WEIGHT_SHIFT 8
  184036. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184037. #define PNG_COST_SHIFT 3
  184038. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184039. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184040. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184041. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184042. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184043. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184044. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184045. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184046. #define PNG_FLAG_ROW_INIT 0x0040
  184047. #define PNG_FLAG_FILLER_AFTER 0x0080
  184048. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184049. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184050. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184051. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184052. #define PNG_FLAG_FREE_PLTE 0x1000
  184053. #define PNG_FLAG_FREE_TRNS 0x2000
  184054. #define PNG_FLAG_FREE_HIST 0x4000
  184055. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184056. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184057. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184058. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184059. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184060. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184061. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184062. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184063. /* 0x800000L unused */
  184064. /* 0x1000000L unused */
  184065. /* 0x2000000L unused */
  184066. /* 0x4000000L unused */
  184067. /* 0x8000000L unused */
  184068. /* 0x10000000L unused */
  184069. /* 0x20000000L unused */
  184070. /* 0x40000000L unused */
  184071. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184072. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184073. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184074. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184075. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184076. PNG_FLAG_CRC_CRITICAL_MASK)
  184077. /* save typing and make code easier to understand */
  184078. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184079. abs((int)((c1).green) - (int)((c2).green)) + \
  184080. abs((int)((c1).blue) - (int)((c2).blue)))
  184081. /* Added to libpng-1.2.6 JB */
  184082. #define PNG_ROWBYTES(pixel_bits, width) \
  184083. ((pixel_bits) >= 8 ? \
  184084. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184085. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184086. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184087. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184088. "ideal" and "delta" should be constants, normally simple
  184089. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184090. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184091. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184092. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184093. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184094. /* place to hold the signature string for a PNG file. */
  184095. #ifdef PNG_USE_GLOBAL_ARRAYS
  184096. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184097. #else
  184098. #endif
  184099. #endif /* PNG_NO_EXTERN */
  184100. /* Constant strings for known chunk types. If you need to add a chunk,
  184101. * define the name here, and add an invocation of the macro in png.c and
  184102. * wherever it's needed.
  184103. */
  184104. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184105. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184106. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184107. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184108. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184109. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184110. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184111. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184112. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184113. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184114. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184115. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184116. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184117. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184118. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184119. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184120. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184121. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184122. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184123. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184124. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184125. #ifdef PNG_USE_GLOBAL_ARRAYS
  184126. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184127. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184128. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184129. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184130. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184131. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184132. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184133. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184134. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184135. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184136. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184137. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184138. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184139. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184140. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184141. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184142. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184143. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184144. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184145. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184146. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184147. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184148. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184149. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184150. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184151. */
  184152. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184153. #undef png_read_init
  184154. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184155. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184156. #endif
  184157. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184158. png_const_charp user_png_ver, png_size_t png_struct_size));
  184159. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184160. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184161. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184162. png_info_size));
  184163. #endif
  184164. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184165. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184166. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184167. */
  184168. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184169. #undef png_write_init
  184170. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184171. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184172. #endif
  184173. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184174. png_const_charp user_png_ver, png_size_t png_struct_size));
  184175. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184176. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184177. png_info_size));
  184178. /* Allocate memory for an internal libpng struct */
  184179. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184180. /* Free memory from internal libpng struct */
  184181. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184182. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184183. malloc_fn, png_voidp mem_ptr));
  184184. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184185. png_free_ptr free_fn, png_voidp mem_ptr));
  184186. /* Free any memory that info_ptr points to and reset struct. */
  184187. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184188. png_infop info_ptr));
  184189. #ifndef PNG_1_0_X
  184190. /* Function to allocate memory for zlib. */
  184191. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184192. /* Function to free memory for zlib */
  184193. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184194. #ifdef PNG_SIZE_T
  184195. /* Function to convert a sizeof an item to png_sizeof item */
  184196. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184197. #endif
  184198. /* Next four functions are used internally as callbacks. PNGAPI is required
  184199. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184200. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184201. png_bytep data, png_size_t length));
  184202. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184203. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184204. png_bytep buffer, png_size_t length));
  184205. #endif
  184206. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184207. png_bytep data, png_size_t length));
  184208. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184209. #if !defined(PNG_NO_STDIO)
  184210. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184211. #endif
  184212. #endif
  184213. #else /* PNG_1_0_X */
  184214. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184215. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184216. png_bytep buffer, png_size_t length));
  184217. #endif
  184218. #endif /* PNG_1_0_X */
  184219. /* Reset the CRC variable */
  184220. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184221. /* Write the "data" buffer to whatever output you are using. */
  184222. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184223. png_size_t length));
  184224. /* Read data from whatever input you are using into the "data" buffer */
  184225. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184226. png_size_t length));
  184227. /* Read bytes into buf, and update png_ptr->crc */
  184228. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184229. png_size_t length));
  184230. /* Decompress data in a chunk that uses compression */
  184231. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184232. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184233. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184234. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184235. png_size_t prefix_length, png_size_t *data_length));
  184236. #endif
  184237. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184238. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184239. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184240. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184241. /* Calculate the CRC over a section of data. Note that we are only
  184242. * passing a maximum of 64K on systems that have this as a memory limit,
  184243. * since this is the maximum buffer size we can specify.
  184244. */
  184245. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184246. png_size_t length));
  184247. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184248. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184249. #endif
  184250. /* simple function to write the signature */
  184251. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184252. /* write various chunks */
  184253. /* Write the IHDR chunk, and update the png_struct with the necessary
  184254. * information.
  184255. */
  184256. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184257. png_uint_32 height,
  184258. int bit_depth, int color_type, int compression_method, int filter_method,
  184259. int interlace_method));
  184260. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184261. png_uint_32 num_pal));
  184262. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184263. png_size_t length));
  184264. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184265. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184266. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184267. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184268. #endif
  184269. #ifdef PNG_FIXED_POINT_SUPPORTED
  184270. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184271. file_gamma));
  184272. #endif
  184273. #endif
  184274. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184275. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184276. int color_type));
  184277. #endif
  184278. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184279. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184280. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184281. double white_x, double white_y,
  184282. double red_x, double red_y, double green_x, double green_y,
  184283. double blue_x, double blue_y));
  184284. #endif
  184285. #ifdef PNG_FIXED_POINT_SUPPORTED
  184286. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184287. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184288. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184289. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184290. png_fixed_point int_blue_y));
  184291. #endif
  184292. #endif
  184293. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184294. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184295. int intent));
  184296. #endif
  184297. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184298. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184299. png_charp name, int compression_type,
  184300. png_charp profile, int proflen));
  184301. /* Note to maintainer: profile should be png_bytep */
  184302. #endif
  184303. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184304. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184305. png_sPLT_tp palette));
  184306. #endif
  184307. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184308. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184309. png_color_16p values, int number, int color_type));
  184310. #endif
  184311. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184312. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184313. png_color_16p values, int color_type));
  184314. #endif
  184315. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184316. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184317. int num_hist));
  184318. #endif
  184319. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184320. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184321. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184322. png_charp key, png_charpp new_key));
  184323. #endif
  184324. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184325. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184326. png_charp text, png_size_t text_len));
  184327. #endif
  184328. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184329. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184330. png_charp text, png_size_t text_len, int compression));
  184331. #endif
  184332. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184333. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184334. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184335. png_charp text));
  184336. #endif
  184337. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184338. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184339. png_infop info_ptr, png_textp text_ptr, int num_text));
  184340. #endif
  184341. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184342. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184343. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184344. #endif
  184345. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184346. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184347. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184348. png_charp units, png_charpp params));
  184349. #endif
  184350. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184351. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184352. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184353. int unit_type));
  184354. #endif
  184355. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184356. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184357. png_timep mod_time));
  184358. #endif
  184359. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184360. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184361. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184362. int unit, double width, double height));
  184363. #else
  184364. #ifdef PNG_FIXED_POINT_SUPPORTED
  184365. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184366. int unit, png_charp width, png_charp height));
  184367. #endif
  184368. #endif
  184369. #endif
  184370. /* Called when finished processing a row of data */
  184371. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184372. /* Internal use only. Called before first row of data */
  184373. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184374. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184375. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184376. #endif
  184377. /* combine a row of data, dealing with alpha, etc. if requested */
  184378. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184379. int mask));
  184380. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184381. /* expand an interlaced row */
  184382. /* OLD pre-1.0.9 interface:
  184383. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184384. png_bytep row, int pass, png_uint_32 transformations));
  184385. */
  184386. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184387. #endif
  184388. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184389. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184390. /* grab pixels out of a row for an interlaced pass */
  184391. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184392. png_bytep row, int pass));
  184393. #endif
  184394. /* unfilter a row */
  184395. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184396. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184397. /* Choose the best filter to use and filter the row data */
  184398. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184399. png_row_infop row_info));
  184400. /* Write out the filtered row. */
  184401. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184402. png_bytep filtered_row));
  184403. /* finish a row while reading, dealing with interlacing passes, etc. */
  184404. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184405. /* initialize the row buffers, etc. */
  184406. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184407. /* optional call to update the users info structure */
  184408. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184409. png_infop info_ptr));
  184410. /* these are the functions that do the transformations */
  184411. #if defined(PNG_READ_FILLER_SUPPORTED)
  184412. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184413. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184414. #endif
  184415. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184416. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184417. png_bytep row));
  184418. #endif
  184419. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184420. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184421. png_bytep row));
  184422. #endif
  184423. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184424. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184425. png_bytep row));
  184426. #endif
  184427. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184428. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184429. png_bytep row));
  184430. #endif
  184431. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184432. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184433. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184434. png_bytep row, png_uint_32 flags));
  184435. #endif
  184436. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184437. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184438. #endif
  184439. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184440. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184441. #endif
  184442. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184443. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184444. row_info, png_bytep row));
  184445. #endif
  184446. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184447. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184448. png_bytep row));
  184449. #endif
  184450. #if defined(PNG_READ_PACK_SUPPORTED)
  184451. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184452. #endif
  184453. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184454. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184455. png_color_8p sig_bits));
  184456. #endif
  184457. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184458. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184459. #endif
  184460. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184461. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184462. #endif
  184463. #if defined(PNG_READ_DITHER_SUPPORTED)
  184464. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184465. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184466. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184467. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184468. png_colorp palette, int num_palette));
  184469. # endif
  184470. #endif
  184471. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184472. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184473. #endif
  184474. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184475. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184476. png_bytep row, png_uint_32 bit_depth));
  184477. #endif
  184478. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184479. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184480. png_color_8p bit_depth));
  184481. #endif
  184482. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184483. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184484. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184485. png_color_16p trans_values, png_color_16p background,
  184486. png_color_16p background_1,
  184487. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184488. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184489. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184490. #else
  184491. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184492. png_color_16p trans_values, png_color_16p background));
  184493. #endif
  184494. #endif
  184495. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184496. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184497. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184498. int gamma_shift));
  184499. #endif
  184500. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184501. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184502. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184503. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184504. png_bytep row, png_color_16p trans_value));
  184505. #endif
  184506. /* The following decodes the appropriate chunks, and does error correction,
  184507. * then calls the appropriate callback for the chunk if it is valid.
  184508. */
  184509. /* decode the IHDR chunk */
  184510. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184511. png_uint_32 length));
  184512. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184513. png_uint_32 length));
  184514. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184515. png_uint_32 length));
  184516. #if defined(PNG_READ_bKGD_SUPPORTED)
  184517. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184518. png_uint_32 length));
  184519. #endif
  184520. #if defined(PNG_READ_cHRM_SUPPORTED)
  184521. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184522. png_uint_32 length));
  184523. #endif
  184524. #if defined(PNG_READ_gAMA_SUPPORTED)
  184525. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184526. png_uint_32 length));
  184527. #endif
  184528. #if defined(PNG_READ_hIST_SUPPORTED)
  184529. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184530. png_uint_32 length));
  184531. #endif
  184532. #if defined(PNG_READ_iCCP_SUPPORTED)
  184533. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184534. png_uint_32 length));
  184535. #endif /* PNG_READ_iCCP_SUPPORTED */
  184536. #if defined(PNG_READ_iTXt_SUPPORTED)
  184537. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184538. png_uint_32 length));
  184539. #endif
  184540. #if defined(PNG_READ_oFFs_SUPPORTED)
  184541. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184542. png_uint_32 length));
  184543. #endif
  184544. #if defined(PNG_READ_pCAL_SUPPORTED)
  184545. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184546. png_uint_32 length));
  184547. #endif
  184548. #if defined(PNG_READ_pHYs_SUPPORTED)
  184549. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184550. png_uint_32 length));
  184551. #endif
  184552. #if defined(PNG_READ_sBIT_SUPPORTED)
  184553. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184554. png_uint_32 length));
  184555. #endif
  184556. #if defined(PNG_READ_sCAL_SUPPORTED)
  184557. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184558. png_uint_32 length));
  184559. #endif
  184560. #if defined(PNG_READ_sPLT_SUPPORTED)
  184561. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184562. png_uint_32 length));
  184563. #endif /* PNG_READ_sPLT_SUPPORTED */
  184564. #if defined(PNG_READ_sRGB_SUPPORTED)
  184565. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184566. png_uint_32 length));
  184567. #endif
  184568. #if defined(PNG_READ_tEXt_SUPPORTED)
  184569. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184570. png_uint_32 length));
  184571. #endif
  184572. #if defined(PNG_READ_tIME_SUPPORTED)
  184573. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184574. png_uint_32 length));
  184575. #endif
  184576. #if defined(PNG_READ_tRNS_SUPPORTED)
  184577. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184578. png_uint_32 length));
  184579. #endif
  184580. #if defined(PNG_READ_zTXt_SUPPORTED)
  184581. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184582. png_uint_32 length));
  184583. #endif
  184584. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184585. png_infop info_ptr, png_uint_32 length));
  184586. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184587. png_bytep chunk_name));
  184588. /* handle the transformations for reading and writing */
  184589. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184590. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184591. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184592. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184593. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184594. png_infop info_ptr));
  184595. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184596. png_infop info_ptr));
  184597. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184598. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184599. png_uint_32 length));
  184600. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184601. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184602. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184603. png_bytep buffer, png_size_t buffer_length));
  184604. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184605. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184606. png_bytep buffer, png_size_t buffer_length));
  184607. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184608. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184609. png_infop info_ptr, png_uint_32 length));
  184610. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184611. png_infop info_ptr));
  184612. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184613. png_infop info_ptr));
  184614. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184615. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184616. png_infop info_ptr));
  184617. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184618. png_infop info_ptr));
  184619. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184620. #if defined(PNG_READ_tEXt_SUPPORTED)
  184621. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184622. png_infop info_ptr, png_uint_32 length));
  184623. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184624. png_infop info_ptr));
  184625. #endif
  184626. #if defined(PNG_READ_zTXt_SUPPORTED)
  184627. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184628. png_infop info_ptr, png_uint_32 length));
  184629. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184630. png_infop info_ptr));
  184631. #endif
  184632. #if defined(PNG_READ_iTXt_SUPPORTED)
  184633. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184634. png_infop info_ptr, png_uint_32 length));
  184635. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184636. png_infop info_ptr));
  184637. #endif
  184638. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184639. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184640. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184641. png_bytep row));
  184642. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184643. png_bytep row));
  184644. #endif
  184645. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184646. #if defined(PNG_MMX_CODE_SUPPORTED)
  184647. /* png.c */ /* PRIVATE */
  184648. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184649. #endif
  184650. #endif
  184651. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184652. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184653. png_infop info_ptr));
  184654. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184655. png_infop info_ptr));
  184656. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184657. png_infop info_ptr));
  184658. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184659. png_infop info_ptr));
  184660. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184661. png_infop info_ptr));
  184662. #if defined(PNG_pHYs_SUPPORTED)
  184663. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184664. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184665. #endif /* PNG_pHYs_SUPPORTED */
  184666. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184667. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184668. #endif /* PNG_INTERNAL */
  184669. #ifdef __cplusplus
  184670. //}
  184671. #endif
  184672. #endif /* PNG_VERSION_INFO_ONLY */
  184673. /* do not put anything past this line */
  184674. #endif /* PNG_H */
  184675. /*** End of inlined file: png.h ***/
  184676. #define PNG_NO_EXTERN
  184677. /*** Start of inlined file: png.c ***/
  184678. /* png.c - location for general purpose libpng functions
  184679. *
  184680. * Last changed in libpng 1.2.21 [October 4, 2007]
  184681. * For conditions of distribution and use, see copyright notice in png.h
  184682. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184683. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184684. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184685. */
  184686. #define PNG_INTERNAL
  184687. #define PNG_NO_EXTERN
  184688. /* Generate a compiler error if there is an old png.h in the search path. */
  184689. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184690. /* Version information for C files. This had better match the version
  184691. * string defined in png.h. */
  184692. #ifdef PNG_USE_GLOBAL_ARRAYS
  184693. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184694. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184695. #ifdef PNG_READ_SUPPORTED
  184696. /* png_sig was changed to a function in version 1.0.5c */
  184697. /* Place to hold the signature string for a PNG file. */
  184698. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184699. #endif /* PNG_READ_SUPPORTED */
  184700. /* Invoke global declarations for constant strings for known chunk types */
  184701. PNG_IHDR;
  184702. PNG_IDAT;
  184703. PNG_IEND;
  184704. PNG_PLTE;
  184705. PNG_bKGD;
  184706. PNG_cHRM;
  184707. PNG_gAMA;
  184708. PNG_hIST;
  184709. PNG_iCCP;
  184710. PNG_iTXt;
  184711. PNG_oFFs;
  184712. PNG_pCAL;
  184713. PNG_sCAL;
  184714. PNG_pHYs;
  184715. PNG_sBIT;
  184716. PNG_sPLT;
  184717. PNG_sRGB;
  184718. PNG_tEXt;
  184719. PNG_tIME;
  184720. PNG_tRNS;
  184721. PNG_zTXt;
  184722. #ifdef PNG_READ_SUPPORTED
  184723. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184724. /* start of interlace block */
  184725. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184726. /* offset to next interlace block */
  184727. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184728. /* start of interlace block in the y direction */
  184729. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184730. /* offset to next interlace block in the y direction */
  184731. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184732. /* Height of interlace block. This is not currently used - if you need
  184733. * it, uncomment it here and in png.h
  184734. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184735. */
  184736. /* Mask to determine which pixels are valid in a pass */
  184737. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184738. /* Mask to determine which pixels to overwrite while displaying */
  184739. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184740. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184741. #endif /* PNG_READ_SUPPORTED */
  184742. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184743. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184744. * of the PNG file signature. If the PNG data is embedded into another
  184745. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184746. * or write any of the magic bytes before it starts on the IHDR.
  184747. */
  184748. #ifdef PNG_READ_SUPPORTED
  184749. void PNGAPI
  184750. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184751. {
  184752. if(png_ptr == NULL) return;
  184753. png_debug(1, "in png_set_sig_bytes\n");
  184754. if (num_bytes > 8)
  184755. png_error(png_ptr, "Too many bytes for PNG signature.");
  184756. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184757. }
  184758. /* Checks whether the supplied bytes match the PNG signature. We allow
  184759. * checking less than the full 8-byte signature so that those apps that
  184760. * already read the first few bytes of a file to determine the file type
  184761. * can simply check the remaining bytes for extra assurance. Returns
  184762. * an integer less than, equal to, or greater than zero if sig is found,
  184763. * respectively, to be less than, to match, or be greater than the correct
  184764. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184765. */
  184766. int PNGAPI
  184767. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184768. {
  184769. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184770. if (num_to_check > 8)
  184771. num_to_check = 8;
  184772. else if (num_to_check < 1)
  184773. return (-1);
  184774. if (start > 7)
  184775. return (-1);
  184776. if (start + num_to_check > 8)
  184777. num_to_check = 8 - start;
  184778. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184779. }
  184780. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184781. /* (Obsolete) function to check signature bytes. It does not allow one
  184782. * to check a partial signature. This function might be removed in the
  184783. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184784. */
  184785. int PNGAPI
  184786. png_check_sig(png_bytep sig, int num)
  184787. {
  184788. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184789. }
  184790. #endif
  184791. #endif /* PNG_READ_SUPPORTED */
  184792. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184793. /* Function to allocate memory for zlib and clear it to 0. */
  184794. #ifdef PNG_1_0_X
  184795. voidpf PNGAPI
  184796. #else
  184797. voidpf /* private */
  184798. #endif
  184799. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184800. {
  184801. png_voidp ptr;
  184802. png_structp p=(png_structp)png_ptr;
  184803. png_uint_32 save_flags=p->flags;
  184804. png_uint_32 num_bytes;
  184805. if(png_ptr == NULL) return (NULL);
  184806. if (items > PNG_UINT_32_MAX/size)
  184807. {
  184808. png_warning (p, "Potential overflow in png_zalloc()");
  184809. return (NULL);
  184810. }
  184811. num_bytes = (png_uint_32)items * size;
  184812. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184813. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184814. p->flags=save_flags;
  184815. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184816. if (ptr == NULL)
  184817. return ((voidpf)ptr);
  184818. if (num_bytes > (png_uint_32)0x8000L)
  184819. {
  184820. png_memset(ptr, 0, (png_size_t)0x8000L);
  184821. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184822. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184823. }
  184824. else
  184825. {
  184826. png_memset(ptr, 0, (png_size_t)num_bytes);
  184827. }
  184828. #endif
  184829. return ((voidpf)ptr);
  184830. }
  184831. /* function to free memory for zlib */
  184832. #ifdef PNG_1_0_X
  184833. void PNGAPI
  184834. #else
  184835. void /* private */
  184836. #endif
  184837. png_zfree(voidpf png_ptr, voidpf ptr)
  184838. {
  184839. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184840. }
  184841. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184842. * in case CRC is > 32 bits to leave the top bits 0.
  184843. */
  184844. void /* PRIVATE */
  184845. png_reset_crc(png_structp png_ptr)
  184846. {
  184847. png_ptr->crc = crc32(0, Z_NULL, 0);
  184848. }
  184849. /* Calculate the CRC over a section of data. We can only pass as
  184850. * much data to this routine as the largest single buffer size. We
  184851. * also check that this data will actually be used before going to the
  184852. * trouble of calculating it.
  184853. */
  184854. void /* PRIVATE */
  184855. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184856. {
  184857. int need_crc = 1;
  184858. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184859. {
  184860. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184861. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184862. need_crc = 0;
  184863. }
  184864. else /* critical */
  184865. {
  184866. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184867. need_crc = 0;
  184868. }
  184869. if (need_crc)
  184870. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184871. }
  184872. /* Allocate the memory for an info_struct for the application. We don't
  184873. * really need the png_ptr, but it could potentially be useful in the
  184874. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184875. * and png_info_init() so that applications that want to use a shared
  184876. * libpng don't have to be recompiled if png_info changes size.
  184877. */
  184878. png_infop PNGAPI
  184879. png_create_info_struct(png_structp png_ptr)
  184880. {
  184881. png_infop info_ptr;
  184882. png_debug(1, "in png_create_info_struct\n");
  184883. if(png_ptr == NULL) return (NULL);
  184884. #ifdef PNG_USER_MEM_SUPPORTED
  184885. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184886. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184887. #else
  184888. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184889. #endif
  184890. if (info_ptr != NULL)
  184891. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184892. return (info_ptr);
  184893. }
  184894. /* This function frees the memory associated with a single info struct.
  184895. * Normally, one would use either png_destroy_read_struct() or
  184896. * png_destroy_write_struct() to free an info struct, but this may be
  184897. * useful for some applications.
  184898. */
  184899. void PNGAPI
  184900. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184901. {
  184902. png_infop info_ptr = NULL;
  184903. if(png_ptr == NULL) return;
  184904. png_debug(1, "in png_destroy_info_struct\n");
  184905. if (info_ptr_ptr != NULL)
  184906. info_ptr = *info_ptr_ptr;
  184907. if (info_ptr != NULL)
  184908. {
  184909. png_info_destroy(png_ptr, info_ptr);
  184910. #ifdef PNG_USER_MEM_SUPPORTED
  184911. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184912. png_ptr->mem_ptr);
  184913. #else
  184914. png_destroy_struct((png_voidp)info_ptr);
  184915. #endif
  184916. *info_ptr_ptr = NULL;
  184917. }
  184918. }
  184919. /* Initialize the info structure. This is now an internal function (0.89)
  184920. * and applications using it are urged to use png_create_info_struct()
  184921. * instead.
  184922. */
  184923. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184924. #undef png_info_init
  184925. void PNGAPI
  184926. png_info_init(png_infop info_ptr)
  184927. {
  184928. /* We only come here via pre-1.0.12-compiled applications */
  184929. png_info_init_3(&info_ptr, 0);
  184930. }
  184931. #endif
  184932. void PNGAPI
  184933. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184934. {
  184935. png_infop info_ptr = *ptr_ptr;
  184936. if(info_ptr == NULL) return;
  184937. png_debug(1, "in png_info_init_3\n");
  184938. if(png_sizeof(png_info) > png_info_struct_size)
  184939. {
  184940. png_destroy_struct(info_ptr);
  184941. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184942. *ptr_ptr = info_ptr;
  184943. }
  184944. /* set everything to 0 */
  184945. png_memset(info_ptr, 0, png_sizeof (png_info));
  184946. }
  184947. #ifdef PNG_FREE_ME_SUPPORTED
  184948. void PNGAPI
  184949. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184950. int freer, png_uint_32 mask)
  184951. {
  184952. png_debug(1, "in png_data_freer\n");
  184953. if (png_ptr == NULL || info_ptr == NULL)
  184954. return;
  184955. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184956. info_ptr->free_me |= mask;
  184957. else if(freer == PNG_USER_WILL_FREE_DATA)
  184958. info_ptr->free_me &= ~mask;
  184959. else
  184960. png_warning(png_ptr,
  184961. "Unknown freer parameter in png_data_freer.");
  184962. }
  184963. #endif
  184964. void PNGAPI
  184965. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184966. int num)
  184967. {
  184968. png_debug(1, "in png_free_data\n");
  184969. if (png_ptr == NULL || info_ptr == NULL)
  184970. return;
  184971. #if defined(PNG_TEXT_SUPPORTED)
  184972. /* free text item num or (if num == -1) all text items */
  184973. #ifdef PNG_FREE_ME_SUPPORTED
  184974. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184975. #else
  184976. if (mask & PNG_FREE_TEXT)
  184977. #endif
  184978. {
  184979. if (num != -1)
  184980. {
  184981. if (info_ptr->text && info_ptr->text[num].key)
  184982. {
  184983. png_free(png_ptr, info_ptr->text[num].key);
  184984. info_ptr->text[num].key = NULL;
  184985. }
  184986. }
  184987. else
  184988. {
  184989. int i;
  184990. for (i = 0; i < info_ptr->num_text; i++)
  184991. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184992. png_free(png_ptr, info_ptr->text);
  184993. info_ptr->text = NULL;
  184994. info_ptr->num_text=0;
  184995. }
  184996. }
  184997. #endif
  184998. #if defined(PNG_tRNS_SUPPORTED)
  184999. /* free any tRNS entry */
  185000. #ifdef PNG_FREE_ME_SUPPORTED
  185001. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185002. #else
  185003. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185004. #endif
  185005. {
  185006. png_free(png_ptr, info_ptr->trans);
  185007. info_ptr->valid &= ~PNG_INFO_tRNS;
  185008. #ifndef PNG_FREE_ME_SUPPORTED
  185009. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185010. #endif
  185011. info_ptr->trans = NULL;
  185012. }
  185013. #endif
  185014. #if defined(PNG_sCAL_SUPPORTED)
  185015. /* free any sCAL entry */
  185016. #ifdef PNG_FREE_ME_SUPPORTED
  185017. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185018. #else
  185019. if (mask & PNG_FREE_SCAL)
  185020. #endif
  185021. {
  185022. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185023. png_free(png_ptr, info_ptr->scal_s_width);
  185024. png_free(png_ptr, info_ptr->scal_s_height);
  185025. info_ptr->scal_s_width = NULL;
  185026. info_ptr->scal_s_height = NULL;
  185027. #endif
  185028. info_ptr->valid &= ~PNG_INFO_sCAL;
  185029. }
  185030. #endif
  185031. #if defined(PNG_pCAL_SUPPORTED)
  185032. /* free any pCAL entry */
  185033. #ifdef PNG_FREE_ME_SUPPORTED
  185034. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185035. #else
  185036. if (mask & PNG_FREE_PCAL)
  185037. #endif
  185038. {
  185039. png_free(png_ptr, info_ptr->pcal_purpose);
  185040. png_free(png_ptr, info_ptr->pcal_units);
  185041. info_ptr->pcal_purpose = NULL;
  185042. info_ptr->pcal_units = NULL;
  185043. if (info_ptr->pcal_params != NULL)
  185044. {
  185045. int i;
  185046. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185047. {
  185048. png_free(png_ptr, info_ptr->pcal_params[i]);
  185049. info_ptr->pcal_params[i]=NULL;
  185050. }
  185051. png_free(png_ptr, info_ptr->pcal_params);
  185052. info_ptr->pcal_params = NULL;
  185053. }
  185054. info_ptr->valid &= ~PNG_INFO_pCAL;
  185055. }
  185056. #endif
  185057. #if defined(PNG_iCCP_SUPPORTED)
  185058. /* free any iCCP entry */
  185059. #ifdef PNG_FREE_ME_SUPPORTED
  185060. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185061. #else
  185062. if (mask & PNG_FREE_ICCP)
  185063. #endif
  185064. {
  185065. png_free(png_ptr, info_ptr->iccp_name);
  185066. png_free(png_ptr, info_ptr->iccp_profile);
  185067. info_ptr->iccp_name = NULL;
  185068. info_ptr->iccp_profile = NULL;
  185069. info_ptr->valid &= ~PNG_INFO_iCCP;
  185070. }
  185071. #endif
  185072. #if defined(PNG_sPLT_SUPPORTED)
  185073. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185074. #ifdef PNG_FREE_ME_SUPPORTED
  185075. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185076. #else
  185077. if (mask & PNG_FREE_SPLT)
  185078. #endif
  185079. {
  185080. if (num != -1)
  185081. {
  185082. if(info_ptr->splt_palettes)
  185083. {
  185084. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185085. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185086. info_ptr->splt_palettes[num].name = NULL;
  185087. info_ptr->splt_palettes[num].entries = NULL;
  185088. }
  185089. }
  185090. else
  185091. {
  185092. if(info_ptr->splt_palettes_num)
  185093. {
  185094. int i;
  185095. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185096. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185097. png_free(png_ptr, info_ptr->splt_palettes);
  185098. info_ptr->splt_palettes = NULL;
  185099. info_ptr->splt_palettes_num = 0;
  185100. }
  185101. info_ptr->valid &= ~PNG_INFO_sPLT;
  185102. }
  185103. }
  185104. #endif
  185105. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185106. if(png_ptr->unknown_chunk.data)
  185107. {
  185108. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185109. png_ptr->unknown_chunk.data = NULL;
  185110. }
  185111. #ifdef PNG_FREE_ME_SUPPORTED
  185112. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185113. #else
  185114. if (mask & PNG_FREE_UNKN)
  185115. #endif
  185116. {
  185117. if (num != -1)
  185118. {
  185119. if(info_ptr->unknown_chunks)
  185120. {
  185121. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185122. info_ptr->unknown_chunks[num].data = NULL;
  185123. }
  185124. }
  185125. else
  185126. {
  185127. int i;
  185128. if(info_ptr->unknown_chunks_num)
  185129. {
  185130. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185131. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185132. png_free(png_ptr, info_ptr->unknown_chunks);
  185133. info_ptr->unknown_chunks = NULL;
  185134. info_ptr->unknown_chunks_num = 0;
  185135. }
  185136. }
  185137. }
  185138. #endif
  185139. #if defined(PNG_hIST_SUPPORTED)
  185140. /* free any hIST entry */
  185141. #ifdef PNG_FREE_ME_SUPPORTED
  185142. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185143. #else
  185144. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185145. #endif
  185146. {
  185147. png_free(png_ptr, info_ptr->hist);
  185148. info_ptr->hist = NULL;
  185149. info_ptr->valid &= ~PNG_INFO_hIST;
  185150. #ifndef PNG_FREE_ME_SUPPORTED
  185151. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185152. #endif
  185153. }
  185154. #endif
  185155. /* free any PLTE entry that was internally allocated */
  185156. #ifdef PNG_FREE_ME_SUPPORTED
  185157. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185158. #else
  185159. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185160. #endif
  185161. {
  185162. png_zfree(png_ptr, info_ptr->palette);
  185163. info_ptr->palette = NULL;
  185164. info_ptr->valid &= ~PNG_INFO_PLTE;
  185165. #ifndef PNG_FREE_ME_SUPPORTED
  185166. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185167. #endif
  185168. info_ptr->num_palette = 0;
  185169. }
  185170. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185171. /* free any image bits attached to the info structure */
  185172. #ifdef PNG_FREE_ME_SUPPORTED
  185173. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185174. #else
  185175. if (mask & PNG_FREE_ROWS)
  185176. #endif
  185177. {
  185178. if(info_ptr->row_pointers)
  185179. {
  185180. int row;
  185181. for (row = 0; row < (int)info_ptr->height; row++)
  185182. {
  185183. png_free(png_ptr, info_ptr->row_pointers[row]);
  185184. info_ptr->row_pointers[row]=NULL;
  185185. }
  185186. png_free(png_ptr, info_ptr->row_pointers);
  185187. info_ptr->row_pointers=NULL;
  185188. }
  185189. info_ptr->valid &= ~PNG_INFO_IDAT;
  185190. }
  185191. #endif
  185192. #ifdef PNG_FREE_ME_SUPPORTED
  185193. if(num == -1)
  185194. info_ptr->free_me &= ~mask;
  185195. else
  185196. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185197. #endif
  185198. }
  185199. /* This is an internal routine to free any memory that the info struct is
  185200. * pointing to before re-using it or freeing the struct itself. Recall
  185201. * that png_free() checks for NULL pointers for us.
  185202. */
  185203. void /* PRIVATE */
  185204. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185205. {
  185206. png_debug(1, "in png_info_destroy\n");
  185207. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185208. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185209. if (png_ptr->num_chunk_list)
  185210. {
  185211. png_free(png_ptr, png_ptr->chunk_list);
  185212. png_ptr->chunk_list=NULL;
  185213. png_ptr->num_chunk_list=0;
  185214. }
  185215. #endif
  185216. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185217. }
  185218. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185219. /* This function returns a pointer to the io_ptr associated with the user
  185220. * functions. The application should free any memory associated with this
  185221. * pointer before png_write_destroy() or png_read_destroy() are called.
  185222. */
  185223. png_voidp PNGAPI
  185224. png_get_io_ptr(png_structp png_ptr)
  185225. {
  185226. if(png_ptr == NULL) return (NULL);
  185227. return (png_ptr->io_ptr);
  185228. }
  185229. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185230. #if !defined(PNG_NO_STDIO)
  185231. /* Initialize the default input/output functions for the PNG file. If you
  185232. * use your own read or write routines, you can call either png_set_read_fn()
  185233. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185234. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185235. * necessarily available.
  185236. */
  185237. void PNGAPI
  185238. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185239. {
  185240. png_debug(1, "in png_init_io\n");
  185241. if(png_ptr == NULL) return;
  185242. png_ptr->io_ptr = (png_voidp)fp;
  185243. }
  185244. #endif
  185245. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185246. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185247. * a "Creation Time" or other text-based time string.
  185248. */
  185249. png_charp PNGAPI
  185250. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185251. {
  185252. static PNG_CONST char short_months[12][4] =
  185253. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185254. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185255. if(png_ptr == NULL) return (NULL);
  185256. if (png_ptr->time_buffer == NULL)
  185257. {
  185258. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185259. png_sizeof(char)));
  185260. }
  185261. #if defined(_WIN32_WCE)
  185262. {
  185263. wchar_t time_buf[29];
  185264. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185265. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185266. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185267. ptime->second % 61);
  185268. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185269. NULL, NULL);
  185270. }
  185271. #else
  185272. #ifdef USE_FAR_KEYWORD
  185273. {
  185274. char near_time_buf[29];
  185275. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185276. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185277. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185278. ptime->second % 61);
  185279. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185280. 29*png_sizeof(char));
  185281. }
  185282. #else
  185283. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185284. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185285. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185286. ptime->second % 61);
  185287. #endif
  185288. #endif /* _WIN32_WCE */
  185289. return ((png_charp)png_ptr->time_buffer);
  185290. }
  185291. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185292. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185293. png_charp PNGAPI
  185294. png_get_copyright(png_structp png_ptr)
  185295. {
  185296. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185297. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185298. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185299. Copyright (c) 1996-1997 Andreas Dilger\n\
  185300. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185301. }
  185302. /* The following return the library version as a short string in the
  185303. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185304. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185305. * is defined in png.h.
  185306. * Note: now there is no difference between png_get_libpng_ver() and
  185307. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185308. * it is guaranteed that png.c uses the correct version of png.h.
  185309. */
  185310. png_charp PNGAPI
  185311. png_get_libpng_ver(png_structp png_ptr)
  185312. {
  185313. /* Version of *.c files used when building libpng */
  185314. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185315. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185316. }
  185317. png_charp PNGAPI
  185318. png_get_header_ver(png_structp png_ptr)
  185319. {
  185320. /* Version of *.h files used when building libpng */
  185321. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185322. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185323. }
  185324. png_charp PNGAPI
  185325. png_get_header_version(png_structp png_ptr)
  185326. {
  185327. /* Returns longer string containing both version and date */
  185328. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185329. return ((png_charp) PNG_HEADER_VERSION_STRING
  185330. #ifndef PNG_READ_SUPPORTED
  185331. " (NO READ SUPPORT)"
  185332. #endif
  185333. "\n");
  185334. }
  185335. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185336. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185337. int PNGAPI
  185338. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185339. {
  185340. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185341. int i;
  185342. png_bytep p;
  185343. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185344. return 0;
  185345. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185346. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185347. if (!png_memcmp(chunk_name, p, 4))
  185348. return ((int)*(p+4));
  185349. return 0;
  185350. }
  185351. #endif
  185352. /* This function, added to libpng-1.0.6g, is untested. */
  185353. int PNGAPI
  185354. png_reset_zstream(png_structp png_ptr)
  185355. {
  185356. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185357. return (inflateReset(&png_ptr->zstream));
  185358. }
  185359. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185360. /* This function was added to libpng-1.0.7 */
  185361. png_uint_32 PNGAPI
  185362. png_access_version_number(void)
  185363. {
  185364. /* Version of *.c files used when building libpng */
  185365. return((png_uint_32) PNG_LIBPNG_VER);
  185366. }
  185367. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185368. #if !defined(PNG_1_0_X)
  185369. /* this function was added to libpng 1.2.0 */
  185370. int PNGAPI
  185371. png_mmx_support(void)
  185372. {
  185373. /* obsolete, to be removed from libpng-1.4.0 */
  185374. return -1;
  185375. }
  185376. #endif /* PNG_1_0_X */
  185377. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185378. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185379. #ifdef PNG_SIZE_T
  185380. /* Added at libpng version 1.2.6 */
  185381. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185382. png_size_t PNGAPI
  185383. png_convert_size(size_t size)
  185384. {
  185385. if (size > (png_size_t)-1)
  185386. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185387. return ((png_size_t)size);
  185388. }
  185389. #endif /* PNG_SIZE_T */
  185390. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185391. /*** End of inlined file: png.c ***/
  185392. /*** Start of inlined file: pngerror.c ***/
  185393. /* pngerror.c - stub functions for i/o and memory allocation
  185394. *
  185395. * Last changed in libpng 1.2.20 October 4, 2007
  185396. * For conditions of distribution and use, see copyright notice in png.h
  185397. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185398. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185399. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185400. *
  185401. * This file provides a location for all error handling. Users who
  185402. * need special error handling are expected to write replacement functions
  185403. * and use png_set_error_fn() to use those functions. See the instructions
  185404. * at each function.
  185405. */
  185406. #define PNG_INTERNAL
  185407. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185408. static void /* PRIVATE */
  185409. png_default_error PNGARG((png_structp png_ptr,
  185410. png_const_charp error_message));
  185411. #ifndef PNG_NO_WARNINGS
  185412. static void /* PRIVATE */
  185413. png_default_warning PNGARG((png_structp png_ptr,
  185414. png_const_charp warning_message));
  185415. #endif /* PNG_NO_WARNINGS */
  185416. /* This function is called whenever there is a fatal error. This function
  185417. * should not be changed. If there is a need to handle errors differently,
  185418. * you should supply a replacement error function and use png_set_error_fn()
  185419. * to replace the error function at run-time.
  185420. */
  185421. #ifndef PNG_NO_ERROR_TEXT
  185422. void PNGAPI
  185423. png_error(png_structp png_ptr, png_const_charp error_message)
  185424. {
  185425. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185426. char msg[16];
  185427. if (png_ptr != NULL)
  185428. {
  185429. if (png_ptr->flags&
  185430. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185431. {
  185432. if (*error_message == '#')
  185433. {
  185434. int offset;
  185435. for (offset=1; offset<15; offset++)
  185436. if (*(error_message+offset) == ' ')
  185437. break;
  185438. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185439. {
  185440. int i;
  185441. for (i=0; i<offset-1; i++)
  185442. msg[i]=error_message[i+1];
  185443. msg[i]='\0';
  185444. error_message=msg;
  185445. }
  185446. else
  185447. error_message+=offset;
  185448. }
  185449. else
  185450. {
  185451. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185452. {
  185453. msg[0]='0';
  185454. msg[1]='\0';
  185455. error_message=msg;
  185456. }
  185457. }
  185458. }
  185459. }
  185460. #endif
  185461. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185462. (*(png_ptr->error_fn))(png_ptr, error_message);
  185463. /* If the custom handler doesn't exist, or if it returns,
  185464. use the default handler, which will not return. */
  185465. png_default_error(png_ptr, error_message);
  185466. }
  185467. #else
  185468. void PNGAPI
  185469. png_err(png_structp png_ptr)
  185470. {
  185471. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185472. (*(png_ptr->error_fn))(png_ptr, '\0');
  185473. /* If the custom handler doesn't exist, or if it returns,
  185474. use the default handler, which will not return. */
  185475. png_default_error(png_ptr, '\0');
  185476. }
  185477. #endif /* PNG_NO_ERROR_TEXT */
  185478. #ifndef PNG_NO_WARNINGS
  185479. /* This function is called whenever there is a non-fatal error. This function
  185480. * should not be changed. If there is a need to handle warnings differently,
  185481. * you should supply a replacement warning function and use
  185482. * png_set_error_fn() to replace the warning function at run-time.
  185483. */
  185484. void PNGAPI
  185485. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185486. {
  185487. int offset = 0;
  185488. if (png_ptr != NULL)
  185489. {
  185490. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185491. if (png_ptr->flags&
  185492. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185493. #endif
  185494. {
  185495. if (*warning_message == '#')
  185496. {
  185497. for (offset=1; offset<15; offset++)
  185498. if (*(warning_message+offset) == ' ')
  185499. break;
  185500. }
  185501. }
  185502. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185503. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185504. }
  185505. else
  185506. png_default_warning(png_ptr, warning_message+offset);
  185507. }
  185508. #endif /* PNG_NO_WARNINGS */
  185509. /* These utilities are used internally to build an error message that relates
  185510. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185511. * this is used to prefix the message. The message is limited in length
  185512. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185513. * if the character is invalid.
  185514. */
  185515. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185516. /*static PNG_CONST char png_digit[16] = {
  185517. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185518. 'A', 'B', 'C', 'D', 'E', 'F'
  185519. };*/
  185520. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185521. static void /* PRIVATE */
  185522. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185523. error_message)
  185524. {
  185525. int iout = 0, iin = 0;
  185526. while (iin < 4)
  185527. {
  185528. int c = png_ptr->chunk_name[iin++];
  185529. if (isnonalpha(c))
  185530. {
  185531. buffer[iout++] = '[';
  185532. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185533. buffer[iout++] = png_digit[c & 0x0f];
  185534. buffer[iout++] = ']';
  185535. }
  185536. else
  185537. {
  185538. buffer[iout++] = (png_byte)c;
  185539. }
  185540. }
  185541. if (error_message == NULL)
  185542. buffer[iout] = 0;
  185543. else
  185544. {
  185545. buffer[iout++] = ':';
  185546. buffer[iout++] = ' ';
  185547. png_strncpy(buffer+iout, error_message, 63);
  185548. buffer[iout+63] = 0;
  185549. }
  185550. }
  185551. #ifdef PNG_READ_SUPPORTED
  185552. void PNGAPI
  185553. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185554. {
  185555. char msg[18+64];
  185556. if (png_ptr == NULL)
  185557. png_error(png_ptr, error_message);
  185558. else
  185559. {
  185560. png_format_buffer(png_ptr, msg, error_message);
  185561. png_error(png_ptr, msg);
  185562. }
  185563. }
  185564. #endif /* PNG_READ_SUPPORTED */
  185565. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185566. #ifndef PNG_NO_WARNINGS
  185567. void PNGAPI
  185568. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185569. {
  185570. char msg[18+64];
  185571. if (png_ptr == NULL)
  185572. png_warning(png_ptr, warning_message);
  185573. else
  185574. {
  185575. png_format_buffer(png_ptr, msg, warning_message);
  185576. png_warning(png_ptr, msg);
  185577. }
  185578. }
  185579. #endif /* PNG_NO_WARNINGS */
  185580. /* This is the default error handling function. Note that replacements for
  185581. * this function MUST NOT RETURN, or the program will likely crash. This
  185582. * function is used by default, or if the program supplies NULL for the
  185583. * error function pointer in png_set_error_fn().
  185584. */
  185585. static void /* PRIVATE */
  185586. png_default_error(png_structp, png_const_charp error_message)
  185587. {
  185588. #ifndef PNG_NO_CONSOLE_IO
  185589. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185590. if (*error_message == '#')
  185591. {
  185592. int offset;
  185593. char error_number[16];
  185594. for (offset=0; offset<15; offset++)
  185595. {
  185596. error_number[offset] = *(error_message+offset+1);
  185597. if (*(error_message+offset) == ' ')
  185598. break;
  185599. }
  185600. if((offset > 1) && (offset < 15))
  185601. {
  185602. error_number[offset-1]='\0';
  185603. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185604. error_message+offset);
  185605. }
  185606. else
  185607. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185608. }
  185609. else
  185610. #endif
  185611. fprintf(stderr, "libpng error: %s\n", error_message);
  185612. #endif
  185613. #ifdef PNG_SETJMP_SUPPORTED
  185614. if (png_ptr)
  185615. {
  185616. # ifdef USE_FAR_KEYWORD
  185617. {
  185618. jmp_buf jmpbuf;
  185619. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185620. longjmp(jmpbuf, 1);
  185621. }
  185622. # else
  185623. longjmp(png_ptr->jmpbuf, 1);
  185624. # endif
  185625. }
  185626. #else
  185627. PNG_ABORT();
  185628. #endif
  185629. #ifdef PNG_NO_CONSOLE_IO
  185630. error_message = error_message; /* make compiler happy */
  185631. #endif
  185632. }
  185633. #ifndef PNG_NO_WARNINGS
  185634. /* This function is called when there is a warning, but the library thinks
  185635. * it can continue anyway. Replacement functions don't have to do anything
  185636. * here if you don't want them to. In the default configuration, png_ptr is
  185637. * not used, but it is passed in case it may be useful.
  185638. */
  185639. static void /* PRIVATE */
  185640. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185641. {
  185642. #ifndef PNG_NO_CONSOLE_IO
  185643. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185644. if (*warning_message == '#')
  185645. {
  185646. int offset;
  185647. char warning_number[16];
  185648. for (offset=0; offset<15; offset++)
  185649. {
  185650. warning_number[offset]=*(warning_message+offset+1);
  185651. if (*(warning_message+offset) == ' ')
  185652. break;
  185653. }
  185654. if((offset > 1) && (offset < 15))
  185655. {
  185656. warning_number[offset-1]='\0';
  185657. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185658. warning_message+offset);
  185659. }
  185660. else
  185661. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185662. }
  185663. else
  185664. # endif
  185665. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185666. #else
  185667. warning_message = warning_message; /* make compiler happy */
  185668. #endif
  185669. png_ptr = png_ptr; /* make compiler happy */
  185670. }
  185671. #endif /* PNG_NO_WARNINGS */
  185672. /* This function is called when the application wants to use another method
  185673. * of handling errors and warnings. Note that the error function MUST NOT
  185674. * return to the calling routine or serious problems will occur. The return
  185675. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185676. */
  185677. void PNGAPI
  185678. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185679. png_error_ptr error_fn, png_error_ptr warning_fn)
  185680. {
  185681. if (png_ptr == NULL)
  185682. return;
  185683. png_ptr->error_ptr = error_ptr;
  185684. png_ptr->error_fn = error_fn;
  185685. png_ptr->warning_fn = warning_fn;
  185686. }
  185687. /* This function returns a pointer to the error_ptr associated with the user
  185688. * functions. The application should free any memory associated with this
  185689. * pointer before png_write_destroy and png_read_destroy are called.
  185690. */
  185691. png_voidp PNGAPI
  185692. png_get_error_ptr(png_structp png_ptr)
  185693. {
  185694. if (png_ptr == NULL)
  185695. return NULL;
  185696. return ((png_voidp)png_ptr->error_ptr);
  185697. }
  185698. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185699. void PNGAPI
  185700. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185701. {
  185702. if(png_ptr != NULL)
  185703. {
  185704. png_ptr->flags &=
  185705. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185706. }
  185707. }
  185708. #endif
  185709. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185710. /*** End of inlined file: pngerror.c ***/
  185711. /*** Start of inlined file: pngget.c ***/
  185712. /* pngget.c - retrieval of values from info struct
  185713. *
  185714. * Last changed in libpng 1.2.15 January 5, 2007
  185715. * For conditions of distribution and use, see copyright notice in png.h
  185716. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185717. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185718. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185719. */
  185720. #define PNG_INTERNAL
  185721. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185722. png_uint_32 PNGAPI
  185723. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185724. {
  185725. if (png_ptr != NULL && info_ptr != NULL)
  185726. return(info_ptr->valid & flag);
  185727. else
  185728. return(0);
  185729. }
  185730. png_uint_32 PNGAPI
  185731. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185732. {
  185733. if (png_ptr != NULL && info_ptr != NULL)
  185734. return(info_ptr->rowbytes);
  185735. else
  185736. return(0);
  185737. }
  185738. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185739. png_bytepp PNGAPI
  185740. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185741. {
  185742. if (png_ptr != NULL && info_ptr != NULL)
  185743. return(info_ptr->row_pointers);
  185744. else
  185745. return(0);
  185746. }
  185747. #endif
  185748. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185749. /* easy access to info, added in libpng-0.99 */
  185750. png_uint_32 PNGAPI
  185751. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185752. {
  185753. if (png_ptr != NULL && info_ptr != NULL)
  185754. {
  185755. return info_ptr->width;
  185756. }
  185757. return (0);
  185758. }
  185759. png_uint_32 PNGAPI
  185760. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185761. {
  185762. if (png_ptr != NULL && info_ptr != NULL)
  185763. {
  185764. return info_ptr->height;
  185765. }
  185766. return (0);
  185767. }
  185768. png_byte PNGAPI
  185769. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185770. {
  185771. if (png_ptr != NULL && info_ptr != NULL)
  185772. {
  185773. return info_ptr->bit_depth;
  185774. }
  185775. return (0);
  185776. }
  185777. png_byte PNGAPI
  185778. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185779. {
  185780. if (png_ptr != NULL && info_ptr != NULL)
  185781. {
  185782. return info_ptr->color_type;
  185783. }
  185784. return (0);
  185785. }
  185786. png_byte PNGAPI
  185787. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185788. {
  185789. if (png_ptr != NULL && info_ptr != NULL)
  185790. {
  185791. return info_ptr->filter_type;
  185792. }
  185793. return (0);
  185794. }
  185795. png_byte PNGAPI
  185796. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185797. {
  185798. if (png_ptr != NULL && info_ptr != NULL)
  185799. {
  185800. return info_ptr->interlace_type;
  185801. }
  185802. return (0);
  185803. }
  185804. png_byte PNGAPI
  185805. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185806. {
  185807. if (png_ptr != NULL && info_ptr != NULL)
  185808. {
  185809. return info_ptr->compression_type;
  185810. }
  185811. return (0);
  185812. }
  185813. png_uint_32 PNGAPI
  185814. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185815. {
  185816. if (png_ptr != NULL && info_ptr != NULL)
  185817. #if defined(PNG_pHYs_SUPPORTED)
  185818. if (info_ptr->valid & PNG_INFO_pHYs)
  185819. {
  185820. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185821. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185822. return (0);
  185823. else return (info_ptr->x_pixels_per_unit);
  185824. }
  185825. #else
  185826. return (0);
  185827. #endif
  185828. return (0);
  185829. }
  185830. png_uint_32 PNGAPI
  185831. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185832. {
  185833. if (png_ptr != NULL && info_ptr != NULL)
  185834. #if defined(PNG_pHYs_SUPPORTED)
  185835. if (info_ptr->valid & PNG_INFO_pHYs)
  185836. {
  185837. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185838. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185839. return (0);
  185840. else return (info_ptr->y_pixels_per_unit);
  185841. }
  185842. #else
  185843. return (0);
  185844. #endif
  185845. return (0);
  185846. }
  185847. png_uint_32 PNGAPI
  185848. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185849. {
  185850. if (png_ptr != NULL && info_ptr != NULL)
  185851. #if defined(PNG_pHYs_SUPPORTED)
  185852. if (info_ptr->valid & PNG_INFO_pHYs)
  185853. {
  185854. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185855. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185856. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185857. return (0);
  185858. else return (info_ptr->x_pixels_per_unit);
  185859. }
  185860. #else
  185861. return (0);
  185862. #endif
  185863. return (0);
  185864. }
  185865. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185866. float PNGAPI
  185867. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185868. {
  185869. if (png_ptr != NULL && info_ptr != NULL)
  185870. #if defined(PNG_pHYs_SUPPORTED)
  185871. if (info_ptr->valid & PNG_INFO_pHYs)
  185872. {
  185873. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185874. if (info_ptr->x_pixels_per_unit == 0)
  185875. return ((float)0.0);
  185876. else
  185877. return ((float)((float)info_ptr->y_pixels_per_unit
  185878. /(float)info_ptr->x_pixels_per_unit));
  185879. }
  185880. #else
  185881. return (0.0);
  185882. #endif
  185883. return ((float)0.0);
  185884. }
  185885. #endif
  185886. png_int_32 PNGAPI
  185887. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185888. {
  185889. if (png_ptr != NULL && info_ptr != NULL)
  185890. #if defined(PNG_oFFs_SUPPORTED)
  185891. if (info_ptr->valid & PNG_INFO_oFFs)
  185892. {
  185893. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185894. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185895. return (0);
  185896. else return (info_ptr->x_offset);
  185897. }
  185898. #else
  185899. return (0);
  185900. #endif
  185901. return (0);
  185902. }
  185903. png_int_32 PNGAPI
  185904. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185905. {
  185906. if (png_ptr != NULL && info_ptr != NULL)
  185907. #if defined(PNG_oFFs_SUPPORTED)
  185908. if (info_ptr->valid & PNG_INFO_oFFs)
  185909. {
  185910. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185911. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185912. return (0);
  185913. else return (info_ptr->y_offset);
  185914. }
  185915. #else
  185916. return (0);
  185917. #endif
  185918. return (0);
  185919. }
  185920. png_int_32 PNGAPI
  185921. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185922. {
  185923. if (png_ptr != NULL && info_ptr != NULL)
  185924. #if defined(PNG_oFFs_SUPPORTED)
  185925. if (info_ptr->valid & PNG_INFO_oFFs)
  185926. {
  185927. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185928. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185929. return (0);
  185930. else return (info_ptr->x_offset);
  185931. }
  185932. #else
  185933. return (0);
  185934. #endif
  185935. return (0);
  185936. }
  185937. png_int_32 PNGAPI
  185938. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185939. {
  185940. if (png_ptr != NULL && info_ptr != NULL)
  185941. #if defined(PNG_oFFs_SUPPORTED)
  185942. if (info_ptr->valid & PNG_INFO_oFFs)
  185943. {
  185944. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185945. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185946. return (0);
  185947. else return (info_ptr->y_offset);
  185948. }
  185949. #else
  185950. return (0);
  185951. #endif
  185952. return (0);
  185953. }
  185954. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185955. png_uint_32 PNGAPI
  185956. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185957. {
  185958. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185959. *.0254 +.5));
  185960. }
  185961. png_uint_32 PNGAPI
  185962. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185963. {
  185964. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185965. *.0254 +.5));
  185966. }
  185967. png_uint_32 PNGAPI
  185968. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185969. {
  185970. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185971. *.0254 +.5));
  185972. }
  185973. float PNGAPI
  185974. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185975. {
  185976. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185977. *.00003937);
  185978. }
  185979. float PNGAPI
  185980. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185981. {
  185982. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185983. *.00003937);
  185984. }
  185985. #if defined(PNG_pHYs_SUPPORTED)
  185986. png_uint_32 PNGAPI
  185987. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185988. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185989. {
  185990. png_uint_32 retval = 0;
  185991. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185992. {
  185993. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185994. if (res_x != NULL)
  185995. {
  185996. *res_x = info_ptr->x_pixels_per_unit;
  185997. retval |= PNG_INFO_pHYs;
  185998. }
  185999. if (res_y != NULL)
  186000. {
  186001. *res_y = info_ptr->y_pixels_per_unit;
  186002. retval |= PNG_INFO_pHYs;
  186003. }
  186004. if (unit_type != NULL)
  186005. {
  186006. *unit_type = (int)info_ptr->phys_unit_type;
  186007. retval |= PNG_INFO_pHYs;
  186008. if(*unit_type == 1)
  186009. {
  186010. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186011. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186012. }
  186013. }
  186014. }
  186015. return (retval);
  186016. }
  186017. #endif /* PNG_pHYs_SUPPORTED */
  186018. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186019. /* png_get_channels really belongs in here, too, but it's been around longer */
  186020. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186021. png_byte PNGAPI
  186022. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186023. {
  186024. if (png_ptr != NULL && info_ptr != NULL)
  186025. return(info_ptr->channels);
  186026. else
  186027. return (0);
  186028. }
  186029. png_bytep PNGAPI
  186030. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186031. {
  186032. if (png_ptr != NULL && info_ptr != NULL)
  186033. return(info_ptr->signature);
  186034. else
  186035. return (NULL);
  186036. }
  186037. #if defined(PNG_bKGD_SUPPORTED)
  186038. png_uint_32 PNGAPI
  186039. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186040. png_color_16p *background)
  186041. {
  186042. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186043. && background != NULL)
  186044. {
  186045. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186046. *background = &(info_ptr->background);
  186047. return (PNG_INFO_bKGD);
  186048. }
  186049. return (0);
  186050. }
  186051. #endif
  186052. #if defined(PNG_cHRM_SUPPORTED)
  186053. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186054. png_uint_32 PNGAPI
  186055. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186056. double *white_x, double *white_y, double *red_x, double *red_y,
  186057. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186058. {
  186059. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186060. {
  186061. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186062. if (white_x != NULL)
  186063. *white_x = (double)info_ptr->x_white;
  186064. if (white_y != NULL)
  186065. *white_y = (double)info_ptr->y_white;
  186066. if (red_x != NULL)
  186067. *red_x = (double)info_ptr->x_red;
  186068. if (red_y != NULL)
  186069. *red_y = (double)info_ptr->y_red;
  186070. if (green_x != NULL)
  186071. *green_x = (double)info_ptr->x_green;
  186072. if (green_y != NULL)
  186073. *green_y = (double)info_ptr->y_green;
  186074. if (blue_x != NULL)
  186075. *blue_x = (double)info_ptr->x_blue;
  186076. if (blue_y != NULL)
  186077. *blue_y = (double)info_ptr->y_blue;
  186078. return (PNG_INFO_cHRM);
  186079. }
  186080. return (0);
  186081. }
  186082. #endif
  186083. #ifdef PNG_FIXED_POINT_SUPPORTED
  186084. png_uint_32 PNGAPI
  186085. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186086. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186087. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186088. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186089. {
  186090. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186091. {
  186092. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186093. if (white_x != NULL)
  186094. *white_x = info_ptr->int_x_white;
  186095. if (white_y != NULL)
  186096. *white_y = info_ptr->int_y_white;
  186097. if (red_x != NULL)
  186098. *red_x = info_ptr->int_x_red;
  186099. if (red_y != NULL)
  186100. *red_y = info_ptr->int_y_red;
  186101. if (green_x != NULL)
  186102. *green_x = info_ptr->int_x_green;
  186103. if (green_y != NULL)
  186104. *green_y = info_ptr->int_y_green;
  186105. if (blue_x != NULL)
  186106. *blue_x = info_ptr->int_x_blue;
  186107. if (blue_y != NULL)
  186108. *blue_y = info_ptr->int_y_blue;
  186109. return (PNG_INFO_cHRM);
  186110. }
  186111. return (0);
  186112. }
  186113. #endif
  186114. #endif
  186115. #if defined(PNG_gAMA_SUPPORTED)
  186116. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186117. png_uint_32 PNGAPI
  186118. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186119. {
  186120. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186121. && file_gamma != NULL)
  186122. {
  186123. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186124. *file_gamma = (double)info_ptr->gamma;
  186125. return (PNG_INFO_gAMA);
  186126. }
  186127. return (0);
  186128. }
  186129. #endif
  186130. #ifdef PNG_FIXED_POINT_SUPPORTED
  186131. png_uint_32 PNGAPI
  186132. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186133. png_fixed_point *int_file_gamma)
  186134. {
  186135. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186136. && int_file_gamma != NULL)
  186137. {
  186138. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186139. *int_file_gamma = info_ptr->int_gamma;
  186140. return (PNG_INFO_gAMA);
  186141. }
  186142. return (0);
  186143. }
  186144. #endif
  186145. #endif
  186146. #if defined(PNG_sRGB_SUPPORTED)
  186147. png_uint_32 PNGAPI
  186148. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186149. {
  186150. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186151. && file_srgb_intent != NULL)
  186152. {
  186153. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186154. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186155. return (PNG_INFO_sRGB);
  186156. }
  186157. return (0);
  186158. }
  186159. #endif
  186160. #if defined(PNG_iCCP_SUPPORTED)
  186161. png_uint_32 PNGAPI
  186162. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186163. png_charpp name, int *compression_type,
  186164. png_charpp profile, png_uint_32 *proflen)
  186165. {
  186166. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186167. && name != NULL && profile != NULL && proflen != NULL)
  186168. {
  186169. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186170. *name = info_ptr->iccp_name;
  186171. *profile = info_ptr->iccp_profile;
  186172. /* compression_type is a dummy so the API won't have to change
  186173. if we introduce multiple compression types later. */
  186174. *proflen = (int)info_ptr->iccp_proflen;
  186175. *compression_type = (int)info_ptr->iccp_compression;
  186176. return (PNG_INFO_iCCP);
  186177. }
  186178. return (0);
  186179. }
  186180. #endif
  186181. #if defined(PNG_sPLT_SUPPORTED)
  186182. png_uint_32 PNGAPI
  186183. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186184. png_sPLT_tpp spalettes)
  186185. {
  186186. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186187. {
  186188. *spalettes = info_ptr->splt_palettes;
  186189. return ((png_uint_32)info_ptr->splt_palettes_num);
  186190. }
  186191. return (0);
  186192. }
  186193. #endif
  186194. #if defined(PNG_hIST_SUPPORTED)
  186195. png_uint_32 PNGAPI
  186196. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186197. {
  186198. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186199. && hist != NULL)
  186200. {
  186201. png_debug1(1, "in %s retrieval function\n", "hIST");
  186202. *hist = info_ptr->hist;
  186203. return (PNG_INFO_hIST);
  186204. }
  186205. return (0);
  186206. }
  186207. #endif
  186208. png_uint_32 PNGAPI
  186209. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186210. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186211. int *color_type, int *interlace_type, int *compression_type,
  186212. int *filter_type)
  186213. {
  186214. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186215. bit_depth != NULL && color_type != NULL)
  186216. {
  186217. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186218. *width = info_ptr->width;
  186219. *height = info_ptr->height;
  186220. *bit_depth = info_ptr->bit_depth;
  186221. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186222. png_error(png_ptr, "Invalid bit depth");
  186223. *color_type = info_ptr->color_type;
  186224. if (info_ptr->color_type > 6)
  186225. png_error(png_ptr, "Invalid color type");
  186226. if (compression_type != NULL)
  186227. *compression_type = info_ptr->compression_type;
  186228. if (filter_type != NULL)
  186229. *filter_type = info_ptr->filter_type;
  186230. if (interlace_type != NULL)
  186231. *interlace_type = info_ptr->interlace_type;
  186232. /* check for potential overflow of rowbytes */
  186233. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186234. png_error(png_ptr, "Invalid image width");
  186235. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186236. png_error(png_ptr, "Invalid image height");
  186237. if (info_ptr->width > (PNG_UINT_32_MAX
  186238. >> 3) /* 8-byte RGBA pixels */
  186239. - 64 /* bigrowbuf hack */
  186240. - 1 /* filter byte */
  186241. - 7*8 /* rounding of width to multiple of 8 pixels */
  186242. - 8) /* extra max_pixel_depth pad */
  186243. {
  186244. png_warning(png_ptr,
  186245. "Width too large for libpng to process image data.");
  186246. }
  186247. return (1);
  186248. }
  186249. return (0);
  186250. }
  186251. #if defined(PNG_oFFs_SUPPORTED)
  186252. png_uint_32 PNGAPI
  186253. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186254. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186255. {
  186256. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186257. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186258. {
  186259. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186260. *offset_x = info_ptr->x_offset;
  186261. *offset_y = info_ptr->y_offset;
  186262. *unit_type = (int)info_ptr->offset_unit_type;
  186263. return (PNG_INFO_oFFs);
  186264. }
  186265. return (0);
  186266. }
  186267. #endif
  186268. #if defined(PNG_pCAL_SUPPORTED)
  186269. png_uint_32 PNGAPI
  186270. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186271. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186272. png_charp *units, png_charpp *params)
  186273. {
  186274. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186275. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186276. nparams != NULL && units != NULL && params != NULL)
  186277. {
  186278. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186279. *purpose = info_ptr->pcal_purpose;
  186280. *X0 = info_ptr->pcal_X0;
  186281. *X1 = info_ptr->pcal_X1;
  186282. *type = (int)info_ptr->pcal_type;
  186283. *nparams = (int)info_ptr->pcal_nparams;
  186284. *units = info_ptr->pcal_units;
  186285. *params = info_ptr->pcal_params;
  186286. return (PNG_INFO_pCAL);
  186287. }
  186288. return (0);
  186289. }
  186290. #endif
  186291. #if defined(PNG_sCAL_SUPPORTED)
  186292. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186293. png_uint_32 PNGAPI
  186294. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186295. int *unit, double *width, double *height)
  186296. {
  186297. if (png_ptr != NULL && info_ptr != NULL &&
  186298. (info_ptr->valid & PNG_INFO_sCAL))
  186299. {
  186300. *unit = info_ptr->scal_unit;
  186301. *width = info_ptr->scal_pixel_width;
  186302. *height = info_ptr->scal_pixel_height;
  186303. return (PNG_INFO_sCAL);
  186304. }
  186305. return(0);
  186306. }
  186307. #else
  186308. #ifdef PNG_FIXED_POINT_SUPPORTED
  186309. png_uint_32 PNGAPI
  186310. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186311. int *unit, png_charpp width, png_charpp height)
  186312. {
  186313. if (png_ptr != NULL && info_ptr != NULL &&
  186314. (info_ptr->valid & PNG_INFO_sCAL))
  186315. {
  186316. *unit = info_ptr->scal_unit;
  186317. *width = info_ptr->scal_s_width;
  186318. *height = info_ptr->scal_s_height;
  186319. return (PNG_INFO_sCAL);
  186320. }
  186321. return(0);
  186322. }
  186323. #endif
  186324. #endif
  186325. #endif
  186326. #if defined(PNG_pHYs_SUPPORTED)
  186327. png_uint_32 PNGAPI
  186328. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186329. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186330. {
  186331. png_uint_32 retval = 0;
  186332. if (png_ptr != NULL && info_ptr != NULL &&
  186333. (info_ptr->valid & PNG_INFO_pHYs))
  186334. {
  186335. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186336. if (res_x != NULL)
  186337. {
  186338. *res_x = info_ptr->x_pixels_per_unit;
  186339. retval |= PNG_INFO_pHYs;
  186340. }
  186341. if (res_y != NULL)
  186342. {
  186343. *res_y = info_ptr->y_pixels_per_unit;
  186344. retval |= PNG_INFO_pHYs;
  186345. }
  186346. if (unit_type != NULL)
  186347. {
  186348. *unit_type = (int)info_ptr->phys_unit_type;
  186349. retval |= PNG_INFO_pHYs;
  186350. }
  186351. }
  186352. return (retval);
  186353. }
  186354. #endif
  186355. png_uint_32 PNGAPI
  186356. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186357. int *num_palette)
  186358. {
  186359. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186360. && palette != NULL)
  186361. {
  186362. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186363. *palette = info_ptr->palette;
  186364. *num_palette = info_ptr->num_palette;
  186365. png_debug1(3, "num_palette = %d\n", *num_palette);
  186366. return (PNG_INFO_PLTE);
  186367. }
  186368. return (0);
  186369. }
  186370. #if defined(PNG_sBIT_SUPPORTED)
  186371. png_uint_32 PNGAPI
  186372. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186373. {
  186374. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186375. && sig_bit != NULL)
  186376. {
  186377. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186378. *sig_bit = &(info_ptr->sig_bit);
  186379. return (PNG_INFO_sBIT);
  186380. }
  186381. return (0);
  186382. }
  186383. #endif
  186384. #if defined(PNG_TEXT_SUPPORTED)
  186385. png_uint_32 PNGAPI
  186386. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186387. int *num_text)
  186388. {
  186389. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186390. {
  186391. png_debug1(1, "in %s retrieval function\n",
  186392. (png_ptr->chunk_name[0] == '\0' ? "text"
  186393. : (png_const_charp)png_ptr->chunk_name));
  186394. if (text_ptr != NULL)
  186395. *text_ptr = info_ptr->text;
  186396. if (num_text != NULL)
  186397. *num_text = info_ptr->num_text;
  186398. return ((png_uint_32)info_ptr->num_text);
  186399. }
  186400. if (num_text != NULL)
  186401. *num_text = 0;
  186402. return(0);
  186403. }
  186404. #endif
  186405. #if defined(PNG_tIME_SUPPORTED)
  186406. png_uint_32 PNGAPI
  186407. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186408. {
  186409. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186410. && mod_time != NULL)
  186411. {
  186412. png_debug1(1, "in %s retrieval function\n", "tIME");
  186413. *mod_time = &(info_ptr->mod_time);
  186414. return (PNG_INFO_tIME);
  186415. }
  186416. return (0);
  186417. }
  186418. #endif
  186419. #if defined(PNG_tRNS_SUPPORTED)
  186420. png_uint_32 PNGAPI
  186421. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186422. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186423. {
  186424. png_uint_32 retval = 0;
  186425. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186426. {
  186427. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186428. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186429. {
  186430. if (trans != NULL)
  186431. {
  186432. *trans = info_ptr->trans;
  186433. retval |= PNG_INFO_tRNS;
  186434. }
  186435. if (trans_values != NULL)
  186436. *trans_values = &(info_ptr->trans_values);
  186437. }
  186438. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186439. {
  186440. if (trans_values != NULL)
  186441. {
  186442. *trans_values = &(info_ptr->trans_values);
  186443. retval |= PNG_INFO_tRNS;
  186444. }
  186445. if(trans != NULL)
  186446. *trans = NULL;
  186447. }
  186448. if(num_trans != NULL)
  186449. {
  186450. *num_trans = info_ptr->num_trans;
  186451. retval |= PNG_INFO_tRNS;
  186452. }
  186453. }
  186454. return (retval);
  186455. }
  186456. #endif
  186457. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186458. png_uint_32 PNGAPI
  186459. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186460. png_unknown_chunkpp unknowns)
  186461. {
  186462. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186463. {
  186464. *unknowns = info_ptr->unknown_chunks;
  186465. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186466. }
  186467. return (0);
  186468. }
  186469. #endif
  186470. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186471. png_byte PNGAPI
  186472. png_get_rgb_to_gray_status (png_structp png_ptr)
  186473. {
  186474. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186475. }
  186476. #endif
  186477. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186478. png_voidp PNGAPI
  186479. png_get_user_chunk_ptr(png_structp png_ptr)
  186480. {
  186481. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186482. }
  186483. #endif
  186484. #ifdef PNG_WRITE_SUPPORTED
  186485. png_uint_32 PNGAPI
  186486. png_get_compression_buffer_size(png_structp png_ptr)
  186487. {
  186488. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186489. }
  186490. #endif
  186491. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186492. #ifndef PNG_1_0_X
  186493. /* this function was added to libpng 1.2.0 and should exist by default */
  186494. png_uint_32 PNGAPI
  186495. png_get_asm_flags (png_structp png_ptr)
  186496. {
  186497. /* obsolete, to be removed from libpng-1.4.0 */
  186498. return (png_ptr? 0L: 0L);
  186499. }
  186500. /* this function was added to libpng 1.2.0 and should exist by default */
  186501. png_uint_32 PNGAPI
  186502. png_get_asm_flagmask (int flag_select)
  186503. {
  186504. /* obsolete, to be removed from libpng-1.4.0 */
  186505. flag_select=flag_select;
  186506. return 0L;
  186507. }
  186508. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186509. /* this function was added to libpng 1.2.0 */
  186510. png_uint_32 PNGAPI
  186511. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186512. {
  186513. /* obsolete, to be removed from libpng-1.4.0 */
  186514. flag_select=flag_select;
  186515. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186516. return 0L;
  186517. }
  186518. /* this function was added to libpng 1.2.0 */
  186519. png_byte PNGAPI
  186520. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186521. {
  186522. /* obsolete, to be removed from libpng-1.4.0 */
  186523. return (png_ptr? 0: 0);
  186524. }
  186525. /* this function was added to libpng 1.2.0 */
  186526. png_uint_32 PNGAPI
  186527. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186528. {
  186529. /* obsolete, to be removed from libpng-1.4.0 */
  186530. return (png_ptr? 0L: 0L);
  186531. }
  186532. #endif /* ?PNG_1_0_X */
  186533. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186534. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186535. /* these functions were added to libpng 1.2.6 */
  186536. png_uint_32 PNGAPI
  186537. png_get_user_width_max (png_structp png_ptr)
  186538. {
  186539. return (png_ptr? png_ptr->user_width_max : 0);
  186540. }
  186541. png_uint_32 PNGAPI
  186542. png_get_user_height_max (png_structp png_ptr)
  186543. {
  186544. return (png_ptr? png_ptr->user_height_max : 0);
  186545. }
  186546. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186547. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186548. /*** End of inlined file: pngget.c ***/
  186549. /*** Start of inlined file: pngmem.c ***/
  186550. /* pngmem.c - stub functions for memory allocation
  186551. *
  186552. * Last changed in libpng 1.2.13 November 13, 2006
  186553. * For conditions of distribution and use, see copyright notice in png.h
  186554. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186555. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186556. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186557. *
  186558. * This file provides a location for all memory allocation. Users who
  186559. * need special memory handling are expected to supply replacement
  186560. * functions for png_malloc() and png_free(), and to use
  186561. * png_create_read_struct_2() and png_create_write_struct_2() to
  186562. * identify the replacement functions.
  186563. */
  186564. #define PNG_INTERNAL
  186565. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186566. /* Borland DOS special memory handler */
  186567. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186568. /* if you change this, be sure to change the one in png.h also */
  186569. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186570. by a single call to calloc() if this is thought to improve performance. */
  186571. png_voidp /* PRIVATE */
  186572. png_create_struct(int type)
  186573. {
  186574. #ifdef PNG_USER_MEM_SUPPORTED
  186575. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186576. }
  186577. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186578. png_voidp /* PRIVATE */
  186579. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186580. {
  186581. #endif /* PNG_USER_MEM_SUPPORTED */
  186582. png_size_t size;
  186583. png_voidp struct_ptr;
  186584. if (type == PNG_STRUCT_INFO)
  186585. size = png_sizeof(png_info);
  186586. else if (type == PNG_STRUCT_PNG)
  186587. size = png_sizeof(png_struct);
  186588. else
  186589. return (png_get_copyright(NULL));
  186590. #ifdef PNG_USER_MEM_SUPPORTED
  186591. if(malloc_fn != NULL)
  186592. {
  186593. png_struct dummy_struct;
  186594. png_structp png_ptr = &dummy_struct;
  186595. png_ptr->mem_ptr=mem_ptr;
  186596. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186597. }
  186598. else
  186599. #endif /* PNG_USER_MEM_SUPPORTED */
  186600. struct_ptr = (png_voidp)farmalloc(size);
  186601. if (struct_ptr != NULL)
  186602. png_memset(struct_ptr, 0, size);
  186603. return (struct_ptr);
  186604. }
  186605. /* Free memory allocated by a png_create_struct() call */
  186606. void /* PRIVATE */
  186607. png_destroy_struct(png_voidp struct_ptr)
  186608. {
  186609. #ifdef PNG_USER_MEM_SUPPORTED
  186610. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186611. }
  186612. /* Free memory allocated by a png_create_struct() call */
  186613. void /* PRIVATE */
  186614. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186615. png_voidp mem_ptr)
  186616. {
  186617. #endif
  186618. if (struct_ptr != NULL)
  186619. {
  186620. #ifdef PNG_USER_MEM_SUPPORTED
  186621. if(free_fn != NULL)
  186622. {
  186623. png_struct dummy_struct;
  186624. png_structp png_ptr = &dummy_struct;
  186625. png_ptr->mem_ptr=mem_ptr;
  186626. (*(free_fn))(png_ptr, struct_ptr);
  186627. return;
  186628. }
  186629. #endif /* PNG_USER_MEM_SUPPORTED */
  186630. farfree (struct_ptr);
  186631. }
  186632. }
  186633. /* Allocate memory. For reasonable files, size should never exceed
  186634. * 64K. However, zlib may allocate more then 64K if you don't tell
  186635. * it not to. See zconf.h and png.h for more information. zlib does
  186636. * need to allocate exactly 64K, so whatever you call here must
  186637. * have the ability to do that.
  186638. *
  186639. * Borland seems to have a problem in DOS mode for exactly 64K.
  186640. * It gives you a segment with an offset of 8 (perhaps to store its
  186641. * memory stuff). zlib doesn't like this at all, so we have to
  186642. * detect and deal with it. This code should not be needed in
  186643. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186644. * been updated by Alexander Lehmann for version 0.89 to waste less
  186645. * memory.
  186646. *
  186647. * Note that we can't use png_size_t for the "size" declaration,
  186648. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186649. * result, we would be truncating potentially larger memory requests
  186650. * (which should cause a fatal error) and introducing major problems.
  186651. */
  186652. png_voidp PNGAPI
  186653. png_malloc(png_structp png_ptr, png_uint_32 size)
  186654. {
  186655. png_voidp ret;
  186656. if (png_ptr == NULL || size == 0)
  186657. return (NULL);
  186658. #ifdef PNG_USER_MEM_SUPPORTED
  186659. if(png_ptr->malloc_fn != NULL)
  186660. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186661. else
  186662. ret = (png_malloc_default(png_ptr, size));
  186663. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186664. png_error(png_ptr, "Out of memory!");
  186665. return (ret);
  186666. }
  186667. png_voidp PNGAPI
  186668. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186669. {
  186670. png_voidp ret;
  186671. #endif /* PNG_USER_MEM_SUPPORTED */
  186672. if (png_ptr == NULL || size == 0)
  186673. return (NULL);
  186674. #ifdef PNG_MAX_MALLOC_64K
  186675. if (size > (png_uint_32)65536L)
  186676. {
  186677. png_warning(png_ptr, "Cannot Allocate > 64K");
  186678. ret = NULL;
  186679. }
  186680. else
  186681. #endif
  186682. if (size != (size_t)size)
  186683. ret = NULL;
  186684. else if (size == (png_uint_32)65536L)
  186685. {
  186686. if (png_ptr->offset_table == NULL)
  186687. {
  186688. /* try to see if we need to do any of this fancy stuff */
  186689. ret = farmalloc(size);
  186690. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186691. {
  186692. int num_blocks;
  186693. png_uint_32 total_size;
  186694. png_bytep table;
  186695. int i;
  186696. png_byte huge * hptr;
  186697. if (ret != NULL)
  186698. {
  186699. farfree(ret);
  186700. ret = NULL;
  186701. }
  186702. if(png_ptr->zlib_window_bits > 14)
  186703. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186704. else
  186705. num_blocks = 1;
  186706. if (png_ptr->zlib_mem_level >= 7)
  186707. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186708. else
  186709. num_blocks++;
  186710. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186711. table = farmalloc(total_size);
  186712. if (table == NULL)
  186713. {
  186714. #ifndef PNG_USER_MEM_SUPPORTED
  186715. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186716. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186717. else
  186718. png_warning(png_ptr, "Out Of Memory.");
  186719. #endif
  186720. return (NULL);
  186721. }
  186722. if ((png_size_t)table & 0xfff0)
  186723. {
  186724. #ifndef PNG_USER_MEM_SUPPORTED
  186725. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186726. png_error(png_ptr,
  186727. "Farmalloc didn't return normalized pointer");
  186728. else
  186729. png_warning(png_ptr,
  186730. "Farmalloc didn't return normalized pointer");
  186731. #endif
  186732. return (NULL);
  186733. }
  186734. png_ptr->offset_table = table;
  186735. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186736. png_sizeof (png_bytep));
  186737. if (png_ptr->offset_table_ptr == NULL)
  186738. {
  186739. #ifndef PNG_USER_MEM_SUPPORTED
  186740. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186741. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186742. else
  186743. png_warning(png_ptr, "Out Of memory.");
  186744. #endif
  186745. return (NULL);
  186746. }
  186747. hptr = (png_byte huge *)table;
  186748. if ((png_size_t)hptr & 0xf)
  186749. {
  186750. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186751. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186752. }
  186753. for (i = 0; i < num_blocks; i++)
  186754. {
  186755. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186756. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186757. }
  186758. png_ptr->offset_table_number = num_blocks;
  186759. png_ptr->offset_table_count = 0;
  186760. png_ptr->offset_table_count_free = 0;
  186761. }
  186762. }
  186763. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186764. {
  186765. #ifndef PNG_USER_MEM_SUPPORTED
  186766. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186767. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186768. else
  186769. png_warning(png_ptr, "Out of Memory.");
  186770. #endif
  186771. return (NULL);
  186772. }
  186773. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186774. }
  186775. else
  186776. ret = farmalloc(size);
  186777. #ifndef PNG_USER_MEM_SUPPORTED
  186778. if (ret == NULL)
  186779. {
  186780. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186781. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186782. else
  186783. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186784. }
  186785. #endif
  186786. return (ret);
  186787. }
  186788. /* free a pointer allocated by png_malloc(). In the default
  186789. configuration, png_ptr is not used, but is passed in case it
  186790. is needed. If ptr is NULL, return without taking any action. */
  186791. void PNGAPI
  186792. png_free(png_structp png_ptr, png_voidp ptr)
  186793. {
  186794. if (png_ptr == NULL || ptr == NULL)
  186795. return;
  186796. #ifdef PNG_USER_MEM_SUPPORTED
  186797. if (png_ptr->free_fn != NULL)
  186798. {
  186799. (*(png_ptr->free_fn))(png_ptr, ptr);
  186800. return;
  186801. }
  186802. else png_free_default(png_ptr, ptr);
  186803. }
  186804. void PNGAPI
  186805. png_free_default(png_structp png_ptr, png_voidp ptr)
  186806. {
  186807. #endif /* PNG_USER_MEM_SUPPORTED */
  186808. if(png_ptr == NULL) return;
  186809. if (png_ptr->offset_table != NULL)
  186810. {
  186811. int i;
  186812. for (i = 0; i < png_ptr->offset_table_count; i++)
  186813. {
  186814. if (ptr == png_ptr->offset_table_ptr[i])
  186815. {
  186816. ptr = NULL;
  186817. png_ptr->offset_table_count_free++;
  186818. break;
  186819. }
  186820. }
  186821. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186822. {
  186823. farfree(png_ptr->offset_table);
  186824. farfree(png_ptr->offset_table_ptr);
  186825. png_ptr->offset_table = NULL;
  186826. png_ptr->offset_table_ptr = NULL;
  186827. }
  186828. }
  186829. if (ptr != NULL)
  186830. {
  186831. farfree(ptr);
  186832. }
  186833. }
  186834. #else /* Not the Borland DOS special memory handler */
  186835. /* Allocate memory for a png_struct or a png_info. The malloc and
  186836. memset can be replaced by a single call to calloc() if this is thought
  186837. to improve performance noticably. */
  186838. png_voidp /* PRIVATE */
  186839. png_create_struct(int type)
  186840. {
  186841. #ifdef PNG_USER_MEM_SUPPORTED
  186842. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186843. }
  186844. /* Allocate memory for a png_struct or a png_info. The malloc and
  186845. memset can be replaced by a single call to calloc() if this is thought
  186846. to improve performance noticably. */
  186847. png_voidp /* PRIVATE */
  186848. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186849. {
  186850. #endif /* PNG_USER_MEM_SUPPORTED */
  186851. png_size_t size;
  186852. png_voidp struct_ptr;
  186853. if (type == PNG_STRUCT_INFO)
  186854. size = png_sizeof(png_info);
  186855. else if (type == PNG_STRUCT_PNG)
  186856. size = png_sizeof(png_struct);
  186857. else
  186858. return (NULL);
  186859. #ifdef PNG_USER_MEM_SUPPORTED
  186860. if(malloc_fn != NULL)
  186861. {
  186862. png_struct dummy_struct;
  186863. png_structp png_ptr = &dummy_struct;
  186864. png_ptr->mem_ptr=mem_ptr;
  186865. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186866. if (struct_ptr != NULL)
  186867. png_memset(struct_ptr, 0, size);
  186868. return (struct_ptr);
  186869. }
  186870. #endif /* PNG_USER_MEM_SUPPORTED */
  186871. #if defined(__TURBOC__) && !defined(__FLAT__)
  186872. struct_ptr = (png_voidp)farmalloc(size);
  186873. #else
  186874. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186875. struct_ptr = (png_voidp)halloc(size,1);
  186876. # else
  186877. struct_ptr = (png_voidp)malloc(size);
  186878. # endif
  186879. #endif
  186880. if (struct_ptr != NULL)
  186881. png_memset(struct_ptr, 0, size);
  186882. return (struct_ptr);
  186883. }
  186884. /* Free memory allocated by a png_create_struct() call */
  186885. void /* PRIVATE */
  186886. png_destroy_struct(png_voidp struct_ptr)
  186887. {
  186888. #ifdef PNG_USER_MEM_SUPPORTED
  186889. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186890. }
  186891. /* Free memory allocated by a png_create_struct() call */
  186892. void /* PRIVATE */
  186893. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186894. png_voidp mem_ptr)
  186895. {
  186896. #endif /* PNG_USER_MEM_SUPPORTED */
  186897. if (struct_ptr != NULL)
  186898. {
  186899. #ifdef PNG_USER_MEM_SUPPORTED
  186900. if(free_fn != NULL)
  186901. {
  186902. png_struct dummy_struct;
  186903. png_structp png_ptr = &dummy_struct;
  186904. png_ptr->mem_ptr=mem_ptr;
  186905. (*(free_fn))(png_ptr, struct_ptr);
  186906. return;
  186907. }
  186908. #endif /* PNG_USER_MEM_SUPPORTED */
  186909. #if defined(__TURBOC__) && !defined(__FLAT__)
  186910. farfree(struct_ptr);
  186911. #else
  186912. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186913. hfree(struct_ptr);
  186914. # else
  186915. free(struct_ptr);
  186916. # endif
  186917. #endif
  186918. }
  186919. }
  186920. /* Allocate memory. For reasonable files, size should never exceed
  186921. 64K. However, zlib may allocate more then 64K if you don't tell
  186922. it not to. See zconf.h and png.h for more information. zlib does
  186923. need to allocate exactly 64K, so whatever you call here must
  186924. have the ability to do that. */
  186925. png_voidp PNGAPI
  186926. png_malloc(png_structp png_ptr, png_uint_32 size)
  186927. {
  186928. png_voidp ret;
  186929. #ifdef PNG_USER_MEM_SUPPORTED
  186930. if (png_ptr == NULL || size == 0)
  186931. return (NULL);
  186932. if(png_ptr->malloc_fn != NULL)
  186933. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186934. else
  186935. ret = (png_malloc_default(png_ptr, size));
  186936. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186937. png_error(png_ptr, "Out of Memory!");
  186938. return (ret);
  186939. }
  186940. png_voidp PNGAPI
  186941. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186942. {
  186943. png_voidp ret;
  186944. #endif /* PNG_USER_MEM_SUPPORTED */
  186945. if (png_ptr == NULL || size == 0)
  186946. return (NULL);
  186947. #ifdef PNG_MAX_MALLOC_64K
  186948. if (size > (png_uint_32)65536L)
  186949. {
  186950. #ifndef PNG_USER_MEM_SUPPORTED
  186951. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186952. png_error(png_ptr, "Cannot Allocate > 64K");
  186953. else
  186954. #endif
  186955. return NULL;
  186956. }
  186957. #endif
  186958. /* Check for overflow */
  186959. #if defined(__TURBOC__) && !defined(__FLAT__)
  186960. if (size != (unsigned long)size)
  186961. ret = NULL;
  186962. else
  186963. ret = farmalloc(size);
  186964. #else
  186965. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186966. if (size != (unsigned long)size)
  186967. ret = NULL;
  186968. else
  186969. ret = halloc(size, 1);
  186970. # else
  186971. if (size != (size_t)size)
  186972. ret = NULL;
  186973. else
  186974. ret = malloc((size_t)size);
  186975. # endif
  186976. #endif
  186977. #ifndef PNG_USER_MEM_SUPPORTED
  186978. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186979. png_error(png_ptr, "Out of Memory");
  186980. #endif
  186981. return (ret);
  186982. }
  186983. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186984. without taking any action. */
  186985. void PNGAPI
  186986. png_free(png_structp png_ptr, png_voidp ptr)
  186987. {
  186988. if (png_ptr == NULL || ptr == NULL)
  186989. return;
  186990. #ifdef PNG_USER_MEM_SUPPORTED
  186991. if (png_ptr->free_fn != NULL)
  186992. {
  186993. (*(png_ptr->free_fn))(png_ptr, ptr);
  186994. return;
  186995. }
  186996. else png_free_default(png_ptr, ptr);
  186997. }
  186998. void PNGAPI
  186999. png_free_default(png_structp png_ptr, png_voidp ptr)
  187000. {
  187001. if (png_ptr == NULL || ptr == NULL)
  187002. return;
  187003. #endif /* PNG_USER_MEM_SUPPORTED */
  187004. #if defined(__TURBOC__) && !defined(__FLAT__)
  187005. farfree(ptr);
  187006. #else
  187007. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187008. hfree(ptr);
  187009. # else
  187010. free(ptr);
  187011. # endif
  187012. #endif
  187013. }
  187014. #endif /* Not Borland DOS special memory handler */
  187015. #if defined(PNG_1_0_X)
  187016. # define png_malloc_warn png_malloc
  187017. #else
  187018. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187019. * function will set up png_malloc() to issue a png_warning and return NULL
  187020. * instead of issuing a png_error, if it fails to allocate the requested
  187021. * memory.
  187022. */
  187023. png_voidp PNGAPI
  187024. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187025. {
  187026. png_voidp ptr;
  187027. png_uint_32 save_flags;
  187028. if(png_ptr == NULL) return (NULL);
  187029. save_flags=png_ptr->flags;
  187030. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187031. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187032. png_ptr->flags=save_flags;
  187033. return(ptr);
  187034. }
  187035. #endif
  187036. png_voidp PNGAPI
  187037. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187038. png_uint_32 length)
  187039. {
  187040. png_size_t size;
  187041. size = (png_size_t)length;
  187042. if ((png_uint_32)size != length)
  187043. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187044. return(png_memcpy (s1, s2, size));
  187045. }
  187046. png_voidp PNGAPI
  187047. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187048. png_uint_32 length)
  187049. {
  187050. png_size_t size;
  187051. size = (png_size_t)length;
  187052. if ((png_uint_32)size != length)
  187053. png_error(png_ptr,"Overflow in png_memset_check.");
  187054. return (png_memset (s1, value, size));
  187055. }
  187056. #ifdef PNG_USER_MEM_SUPPORTED
  187057. /* This function is called when the application wants to use another method
  187058. * of allocating and freeing memory.
  187059. */
  187060. void PNGAPI
  187061. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187062. malloc_fn, png_free_ptr free_fn)
  187063. {
  187064. if(png_ptr != NULL) {
  187065. png_ptr->mem_ptr = mem_ptr;
  187066. png_ptr->malloc_fn = malloc_fn;
  187067. png_ptr->free_fn = free_fn;
  187068. }
  187069. }
  187070. /* This function returns a pointer to the mem_ptr associated with the user
  187071. * functions. The application should free any memory associated with this
  187072. * pointer before png_write_destroy and png_read_destroy are called.
  187073. */
  187074. png_voidp PNGAPI
  187075. png_get_mem_ptr(png_structp png_ptr)
  187076. {
  187077. if(png_ptr == NULL) return (NULL);
  187078. return ((png_voidp)png_ptr->mem_ptr);
  187079. }
  187080. #endif /* PNG_USER_MEM_SUPPORTED */
  187081. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187082. /*** End of inlined file: pngmem.c ***/
  187083. /*** Start of inlined file: pngread.c ***/
  187084. /* pngread.c - read a PNG file
  187085. *
  187086. * Last changed in libpng 1.2.20 September 7, 2007
  187087. * For conditions of distribution and use, see copyright notice in png.h
  187088. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187089. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187090. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187091. *
  187092. * This file contains routines that an application calls directly to
  187093. * read a PNG file or stream.
  187094. */
  187095. #define PNG_INTERNAL
  187096. #if defined(PNG_READ_SUPPORTED)
  187097. /* Create a PNG structure for reading, and allocate any memory needed. */
  187098. png_structp PNGAPI
  187099. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187100. png_error_ptr error_fn, png_error_ptr warn_fn)
  187101. {
  187102. #ifdef PNG_USER_MEM_SUPPORTED
  187103. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187104. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187105. }
  187106. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187107. png_structp PNGAPI
  187108. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187109. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187110. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187111. {
  187112. #endif /* PNG_USER_MEM_SUPPORTED */
  187113. png_structp png_ptr;
  187114. #ifdef PNG_SETJMP_SUPPORTED
  187115. #ifdef USE_FAR_KEYWORD
  187116. jmp_buf jmpbuf;
  187117. #endif
  187118. #endif
  187119. int i;
  187120. png_debug(1, "in png_create_read_struct\n");
  187121. #ifdef PNG_USER_MEM_SUPPORTED
  187122. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187123. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187124. #else
  187125. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187126. #endif
  187127. if (png_ptr == NULL)
  187128. return (NULL);
  187129. /* added at libpng-1.2.6 */
  187130. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187131. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187132. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187133. #endif
  187134. #ifdef PNG_SETJMP_SUPPORTED
  187135. #ifdef USE_FAR_KEYWORD
  187136. if (setjmp(jmpbuf))
  187137. #else
  187138. if (setjmp(png_ptr->jmpbuf))
  187139. #endif
  187140. {
  187141. png_free(png_ptr, png_ptr->zbuf);
  187142. png_ptr->zbuf=NULL;
  187143. #ifdef PNG_USER_MEM_SUPPORTED
  187144. png_destroy_struct_2((png_voidp)png_ptr,
  187145. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187146. #else
  187147. png_destroy_struct((png_voidp)png_ptr);
  187148. #endif
  187149. return (NULL);
  187150. }
  187151. #ifdef USE_FAR_KEYWORD
  187152. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187153. #endif
  187154. #endif
  187155. #ifdef PNG_USER_MEM_SUPPORTED
  187156. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187157. #endif
  187158. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187159. i=0;
  187160. do
  187161. {
  187162. if(user_png_ver[i] != png_libpng_ver[i])
  187163. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187164. } while (png_libpng_ver[i++]);
  187165. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187166. {
  187167. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187168. * we must recompile any applications that use any older library version.
  187169. * For versions after libpng 1.0, we will be compatible, so we need
  187170. * only check the first digit.
  187171. */
  187172. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187173. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187174. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187175. {
  187176. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187177. char msg[80];
  187178. if (user_png_ver)
  187179. {
  187180. png_snprintf(msg, 80,
  187181. "Application was compiled with png.h from libpng-%.20s",
  187182. user_png_ver);
  187183. png_warning(png_ptr, msg);
  187184. }
  187185. png_snprintf(msg, 80,
  187186. "Application is running with png.c from libpng-%.20s",
  187187. png_libpng_ver);
  187188. png_warning(png_ptr, msg);
  187189. #endif
  187190. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187191. png_ptr->flags=0;
  187192. #endif
  187193. png_error(png_ptr,
  187194. "Incompatible libpng version in application and library");
  187195. }
  187196. }
  187197. /* initialize zbuf - compression buffer */
  187198. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187199. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187200. (png_uint_32)png_ptr->zbuf_size);
  187201. png_ptr->zstream.zalloc = png_zalloc;
  187202. png_ptr->zstream.zfree = png_zfree;
  187203. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187204. switch (inflateInit(&png_ptr->zstream))
  187205. {
  187206. case Z_OK: /* Do nothing */ break;
  187207. case Z_MEM_ERROR:
  187208. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187209. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187210. default: png_error(png_ptr, "Unknown zlib error");
  187211. }
  187212. png_ptr->zstream.next_out = png_ptr->zbuf;
  187213. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187214. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187215. #ifdef PNG_SETJMP_SUPPORTED
  187216. /* Applications that neglect to set up their own setjmp() and then encounter
  187217. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187218. abort instead of returning. */
  187219. #ifdef USE_FAR_KEYWORD
  187220. if (setjmp(jmpbuf))
  187221. PNG_ABORT();
  187222. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187223. #else
  187224. if (setjmp(png_ptr->jmpbuf))
  187225. PNG_ABORT();
  187226. #endif
  187227. #endif
  187228. return (png_ptr);
  187229. }
  187230. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187231. /* Initialize PNG structure for reading, and allocate any memory needed.
  187232. This interface is deprecated in favour of the png_create_read_struct(),
  187233. and it will disappear as of libpng-1.3.0. */
  187234. #undef png_read_init
  187235. void PNGAPI
  187236. png_read_init(png_structp png_ptr)
  187237. {
  187238. /* We only come here via pre-1.0.7-compiled applications */
  187239. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187240. }
  187241. void PNGAPI
  187242. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187243. png_size_t png_struct_size, png_size_t png_info_size)
  187244. {
  187245. /* We only come here via pre-1.0.12-compiled applications */
  187246. if(png_ptr == NULL) return;
  187247. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187248. if(png_sizeof(png_struct) > png_struct_size ||
  187249. png_sizeof(png_info) > png_info_size)
  187250. {
  187251. char msg[80];
  187252. png_ptr->warning_fn=NULL;
  187253. if (user_png_ver)
  187254. {
  187255. png_snprintf(msg, 80,
  187256. "Application was compiled with png.h from libpng-%.20s",
  187257. user_png_ver);
  187258. png_warning(png_ptr, msg);
  187259. }
  187260. png_snprintf(msg, 80,
  187261. "Application is running with png.c from libpng-%.20s",
  187262. png_libpng_ver);
  187263. png_warning(png_ptr, msg);
  187264. }
  187265. #endif
  187266. if(png_sizeof(png_struct) > png_struct_size)
  187267. {
  187268. png_ptr->error_fn=NULL;
  187269. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187270. png_ptr->flags=0;
  187271. #endif
  187272. png_error(png_ptr,
  187273. "The png struct allocated by the application for reading is too small.");
  187274. }
  187275. if(png_sizeof(png_info) > png_info_size)
  187276. {
  187277. png_ptr->error_fn=NULL;
  187278. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187279. png_ptr->flags=0;
  187280. #endif
  187281. png_error(png_ptr,
  187282. "The info struct allocated by application for reading is too small.");
  187283. }
  187284. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187285. }
  187286. #endif /* PNG_1_0_X || PNG_1_2_X */
  187287. void PNGAPI
  187288. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187289. png_size_t png_struct_size)
  187290. {
  187291. #ifdef PNG_SETJMP_SUPPORTED
  187292. jmp_buf tmp_jmp; /* to save current jump buffer */
  187293. #endif
  187294. int i=0;
  187295. png_structp png_ptr=*ptr_ptr;
  187296. if(png_ptr == NULL) return;
  187297. do
  187298. {
  187299. if(user_png_ver[i] != png_libpng_ver[i])
  187300. {
  187301. #ifdef PNG_LEGACY_SUPPORTED
  187302. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187303. #else
  187304. png_ptr->warning_fn=NULL;
  187305. png_warning(png_ptr,
  187306. "Application uses deprecated png_read_init() and should be recompiled.");
  187307. break;
  187308. #endif
  187309. }
  187310. } while (png_libpng_ver[i++]);
  187311. png_debug(1, "in png_read_init_3\n");
  187312. #ifdef PNG_SETJMP_SUPPORTED
  187313. /* save jump buffer and error functions */
  187314. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187315. #endif
  187316. if(png_sizeof(png_struct) > png_struct_size)
  187317. {
  187318. png_destroy_struct(png_ptr);
  187319. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187320. png_ptr = *ptr_ptr;
  187321. }
  187322. /* reset all variables to 0 */
  187323. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187324. #ifdef PNG_SETJMP_SUPPORTED
  187325. /* restore jump buffer */
  187326. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187327. #endif
  187328. /* added at libpng-1.2.6 */
  187329. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187330. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187331. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187332. #endif
  187333. /* initialize zbuf - compression buffer */
  187334. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187335. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187336. (png_uint_32)png_ptr->zbuf_size);
  187337. png_ptr->zstream.zalloc = png_zalloc;
  187338. png_ptr->zstream.zfree = png_zfree;
  187339. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187340. switch (inflateInit(&png_ptr->zstream))
  187341. {
  187342. case Z_OK: /* Do nothing */ break;
  187343. case Z_MEM_ERROR:
  187344. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187345. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187346. default: png_error(png_ptr, "Unknown zlib error");
  187347. }
  187348. png_ptr->zstream.next_out = png_ptr->zbuf;
  187349. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187350. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187351. }
  187352. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187353. /* Read the information before the actual image data. This has been
  187354. * changed in v0.90 to allow reading a file that already has the magic
  187355. * bytes read from the stream. You can tell libpng how many bytes have
  187356. * been read from the beginning of the stream (up to the maximum of 8)
  187357. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187358. * here. The application can then have access to the signature bytes we
  187359. * read if it is determined that this isn't a valid PNG file.
  187360. */
  187361. void PNGAPI
  187362. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187363. {
  187364. if(png_ptr == NULL) return;
  187365. png_debug(1, "in png_read_info\n");
  187366. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187367. if (png_ptr->sig_bytes < 8)
  187368. {
  187369. png_size_t num_checked = png_ptr->sig_bytes,
  187370. num_to_check = 8 - num_checked;
  187371. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187372. png_ptr->sig_bytes = 8;
  187373. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187374. {
  187375. if (num_checked < 4 &&
  187376. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187377. png_error(png_ptr, "Not a PNG file");
  187378. else
  187379. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187380. }
  187381. if (num_checked < 3)
  187382. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187383. }
  187384. for(;;)
  187385. {
  187386. #ifdef PNG_USE_LOCAL_ARRAYS
  187387. PNG_CONST PNG_IHDR;
  187388. PNG_CONST PNG_IDAT;
  187389. PNG_CONST PNG_IEND;
  187390. PNG_CONST PNG_PLTE;
  187391. #if defined(PNG_READ_bKGD_SUPPORTED)
  187392. PNG_CONST PNG_bKGD;
  187393. #endif
  187394. #if defined(PNG_READ_cHRM_SUPPORTED)
  187395. PNG_CONST PNG_cHRM;
  187396. #endif
  187397. #if defined(PNG_READ_gAMA_SUPPORTED)
  187398. PNG_CONST PNG_gAMA;
  187399. #endif
  187400. #if defined(PNG_READ_hIST_SUPPORTED)
  187401. PNG_CONST PNG_hIST;
  187402. #endif
  187403. #if defined(PNG_READ_iCCP_SUPPORTED)
  187404. PNG_CONST PNG_iCCP;
  187405. #endif
  187406. #if defined(PNG_READ_iTXt_SUPPORTED)
  187407. PNG_CONST PNG_iTXt;
  187408. #endif
  187409. #if defined(PNG_READ_oFFs_SUPPORTED)
  187410. PNG_CONST PNG_oFFs;
  187411. #endif
  187412. #if defined(PNG_READ_pCAL_SUPPORTED)
  187413. PNG_CONST PNG_pCAL;
  187414. #endif
  187415. #if defined(PNG_READ_pHYs_SUPPORTED)
  187416. PNG_CONST PNG_pHYs;
  187417. #endif
  187418. #if defined(PNG_READ_sBIT_SUPPORTED)
  187419. PNG_CONST PNG_sBIT;
  187420. #endif
  187421. #if defined(PNG_READ_sCAL_SUPPORTED)
  187422. PNG_CONST PNG_sCAL;
  187423. #endif
  187424. #if defined(PNG_READ_sPLT_SUPPORTED)
  187425. PNG_CONST PNG_sPLT;
  187426. #endif
  187427. #if defined(PNG_READ_sRGB_SUPPORTED)
  187428. PNG_CONST PNG_sRGB;
  187429. #endif
  187430. #if defined(PNG_READ_tEXt_SUPPORTED)
  187431. PNG_CONST PNG_tEXt;
  187432. #endif
  187433. #if defined(PNG_READ_tIME_SUPPORTED)
  187434. PNG_CONST PNG_tIME;
  187435. #endif
  187436. #if defined(PNG_READ_tRNS_SUPPORTED)
  187437. PNG_CONST PNG_tRNS;
  187438. #endif
  187439. #if defined(PNG_READ_zTXt_SUPPORTED)
  187440. PNG_CONST PNG_zTXt;
  187441. #endif
  187442. #endif /* PNG_USE_LOCAL_ARRAYS */
  187443. png_byte chunk_length[4];
  187444. png_uint_32 length;
  187445. png_read_data(png_ptr, chunk_length, 4);
  187446. length = png_get_uint_31(png_ptr,chunk_length);
  187447. png_reset_crc(png_ptr);
  187448. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187449. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187450. length);
  187451. /* This should be a binary subdivision search or a hash for
  187452. * matching the chunk name rather than a linear search.
  187453. */
  187454. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187455. if(png_ptr->mode & PNG_AFTER_IDAT)
  187456. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187457. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187458. png_handle_IHDR(png_ptr, info_ptr, length);
  187459. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187460. png_handle_IEND(png_ptr, info_ptr, length);
  187461. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187462. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187463. {
  187464. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187465. png_ptr->mode |= PNG_HAVE_IDAT;
  187466. png_handle_unknown(png_ptr, info_ptr, length);
  187467. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187468. png_ptr->mode |= PNG_HAVE_PLTE;
  187469. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187470. {
  187471. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187472. png_error(png_ptr, "Missing IHDR before IDAT");
  187473. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187474. !(png_ptr->mode & PNG_HAVE_PLTE))
  187475. png_error(png_ptr, "Missing PLTE before IDAT");
  187476. break;
  187477. }
  187478. }
  187479. #endif
  187480. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187481. png_handle_PLTE(png_ptr, info_ptr, length);
  187482. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187483. {
  187484. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187485. png_error(png_ptr, "Missing IHDR before IDAT");
  187486. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187487. !(png_ptr->mode & PNG_HAVE_PLTE))
  187488. png_error(png_ptr, "Missing PLTE before IDAT");
  187489. png_ptr->idat_size = length;
  187490. png_ptr->mode |= PNG_HAVE_IDAT;
  187491. break;
  187492. }
  187493. #if defined(PNG_READ_bKGD_SUPPORTED)
  187494. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187495. png_handle_bKGD(png_ptr, info_ptr, length);
  187496. #endif
  187497. #if defined(PNG_READ_cHRM_SUPPORTED)
  187498. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187499. png_handle_cHRM(png_ptr, info_ptr, length);
  187500. #endif
  187501. #if defined(PNG_READ_gAMA_SUPPORTED)
  187502. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187503. png_handle_gAMA(png_ptr, info_ptr, length);
  187504. #endif
  187505. #if defined(PNG_READ_hIST_SUPPORTED)
  187506. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187507. png_handle_hIST(png_ptr, info_ptr, length);
  187508. #endif
  187509. #if defined(PNG_READ_oFFs_SUPPORTED)
  187510. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187511. png_handle_oFFs(png_ptr, info_ptr, length);
  187512. #endif
  187513. #if defined(PNG_READ_pCAL_SUPPORTED)
  187514. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187515. png_handle_pCAL(png_ptr, info_ptr, length);
  187516. #endif
  187517. #if defined(PNG_READ_sCAL_SUPPORTED)
  187518. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187519. png_handle_sCAL(png_ptr, info_ptr, length);
  187520. #endif
  187521. #if defined(PNG_READ_pHYs_SUPPORTED)
  187522. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187523. png_handle_pHYs(png_ptr, info_ptr, length);
  187524. #endif
  187525. #if defined(PNG_READ_sBIT_SUPPORTED)
  187526. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187527. png_handle_sBIT(png_ptr, info_ptr, length);
  187528. #endif
  187529. #if defined(PNG_READ_sRGB_SUPPORTED)
  187530. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187531. png_handle_sRGB(png_ptr, info_ptr, length);
  187532. #endif
  187533. #if defined(PNG_READ_iCCP_SUPPORTED)
  187534. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187535. png_handle_iCCP(png_ptr, info_ptr, length);
  187536. #endif
  187537. #if defined(PNG_READ_sPLT_SUPPORTED)
  187538. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187539. png_handle_sPLT(png_ptr, info_ptr, length);
  187540. #endif
  187541. #if defined(PNG_READ_tEXt_SUPPORTED)
  187542. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187543. png_handle_tEXt(png_ptr, info_ptr, length);
  187544. #endif
  187545. #if defined(PNG_READ_tIME_SUPPORTED)
  187546. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187547. png_handle_tIME(png_ptr, info_ptr, length);
  187548. #endif
  187549. #if defined(PNG_READ_tRNS_SUPPORTED)
  187550. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187551. png_handle_tRNS(png_ptr, info_ptr, length);
  187552. #endif
  187553. #if defined(PNG_READ_zTXt_SUPPORTED)
  187554. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187555. png_handle_zTXt(png_ptr, info_ptr, length);
  187556. #endif
  187557. #if defined(PNG_READ_iTXt_SUPPORTED)
  187558. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187559. png_handle_iTXt(png_ptr, info_ptr, length);
  187560. #endif
  187561. else
  187562. png_handle_unknown(png_ptr, info_ptr, length);
  187563. }
  187564. }
  187565. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187566. /* optional call to update the users info_ptr structure */
  187567. void PNGAPI
  187568. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187569. {
  187570. png_debug(1, "in png_read_update_info\n");
  187571. if(png_ptr == NULL) return;
  187572. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187573. png_read_start_row(png_ptr);
  187574. else
  187575. png_warning(png_ptr,
  187576. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187577. png_read_transform_info(png_ptr, info_ptr);
  187578. }
  187579. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187580. /* Initialize palette, background, etc, after transformations
  187581. * are set, but before any reading takes place. This allows
  187582. * the user to obtain a gamma-corrected palette, for example.
  187583. * If the user doesn't call this, we will do it ourselves.
  187584. */
  187585. void PNGAPI
  187586. png_start_read_image(png_structp png_ptr)
  187587. {
  187588. png_debug(1, "in png_start_read_image\n");
  187589. if(png_ptr == NULL) return;
  187590. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187591. png_read_start_row(png_ptr);
  187592. }
  187593. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187594. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187595. void PNGAPI
  187596. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187597. {
  187598. #ifdef PNG_USE_LOCAL_ARRAYS
  187599. PNG_CONST PNG_IDAT;
  187600. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187601. 0xff};
  187602. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187603. #endif
  187604. int ret;
  187605. if(png_ptr == NULL) return;
  187606. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187607. png_ptr->row_number, png_ptr->pass);
  187608. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187609. png_read_start_row(png_ptr);
  187610. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187611. {
  187612. /* check for transforms that have been set but were defined out */
  187613. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187614. if (png_ptr->transformations & PNG_INVERT_MONO)
  187615. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187616. #endif
  187617. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187618. if (png_ptr->transformations & PNG_FILLER)
  187619. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187620. #endif
  187621. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187622. if (png_ptr->transformations & PNG_PACKSWAP)
  187623. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187624. #endif
  187625. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187626. if (png_ptr->transformations & PNG_PACK)
  187627. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187628. #endif
  187629. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187630. if (png_ptr->transformations & PNG_SHIFT)
  187631. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187632. #endif
  187633. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187634. if (png_ptr->transformations & PNG_BGR)
  187635. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187636. #endif
  187637. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187638. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187639. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187640. #endif
  187641. }
  187642. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187643. /* if interlaced and we do not need a new row, combine row and return */
  187644. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187645. {
  187646. switch (png_ptr->pass)
  187647. {
  187648. case 0:
  187649. if (png_ptr->row_number & 0x07)
  187650. {
  187651. if (dsp_row != NULL)
  187652. png_combine_row(png_ptr, dsp_row,
  187653. png_pass_dsp_mask[png_ptr->pass]);
  187654. png_read_finish_row(png_ptr);
  187655. return;
  187656. }
  187657. break;
  187658. case 1:
  187659. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187660. {
  187661. if (dsp_row != NULL)
  187662. png_combine_row(png_ptr, dsp_row,
  187663. png_pass_dsp_mask[png_ptr->pass]);
  187664. png_read_finish_row(png_ptr);
  187665. return;
  187666. }
  187667. break;
  187668. case 2:
  187669. if ((png_ptr->row_number & 0x07) != 4)
  187670. {
  187671. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187672. png_combine_row(png_ptr, dsp_row,
  187673. png_pass_dsp_mask[png_ptr->pass]);
  187674. png_read_finish_row(png_ptr);
  187675. return;
  187676. }
  187677. break;
  187678. case 3:
  187679. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187680. {
  187681. if (dsp_row != NULL)
  187682. png_combine_row(png_ptr, dsp_row,
  187683. png_pass_dsp_mask[png_ptr->pass]);
  187684. png_read_finish_row(png_ptr);
  187685. return;
  187686. }
  187687. break;
  187688. case 4:
  187689. if ((png_ptr->row_number & 3) != 2)
  187690. {
  187691. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187692. png_combine_row(png_ptr, dsp_row,
  187693. png_pass_dsp_mask[png_ptr->pass]);
  187694. png_read_finish_row(png_ptr);
  187695. return;
  187696. }
  187697. break;
  187698. case 5:
  187699. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187700. {
  187701. if (dsp_row != NULL)
  187702. png_combine_row(png_ptr, dsp_row,
  187703. png_pass_dsp_mask[png_ptr->pass]);
  187704. png_read_finish_row(png_ptr);
  187705. return;
  187706. }
  187707. break;
  187708. case 6:
  187709. if (!(png_ptr->row_number & 1))
  187710. {
  187711. png_read_finish_row(png_ptr);
  187712. return;
  187713. }
  187714. break;
  187715. }
  187716. }
  187717. #endif
  187718. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187719. png_error(png_ptr, "Invalid attempt to read row data");
  187720. png_ptr->zstream.next_out = png_ptr->row_buf;
  187721. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187722. do
  187723. {
  187724. if (!(png_ptr->zstream.avail_in))
  187725. {
  187726. while (!png_ptr->idat_size)
  187727. {
  187728. png_byte chunk_length[4];
  187729. png_crc_finish(png_ptr, 0);
  187730. png_read_data(png_ptr, chunk_length, 4);
  187731. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187732. png_reset_crc(png_ptr);
  187733. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187734. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187735. png_error(png_ptr, "Not enough image data");
  187736. }
  187737. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187738. png_ptr->zstream.next_in = png_ptr->zbuf;
  187739. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187740. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187741. png_crc_read(png_ptr, png_ptr->zbuf,
  187742. (png_size_t)png_ptr->zstream.avail_in);
  187743. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187744. }
  187745. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187746. if (ret == Z_STREAM_END)
  187747. {
  187748. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187749. png_ptr->idat_size)
  187750. png_error(png_ptr, "Extra compressed data");
  187751. png_ptr->mode |= PNG_AFTER_IDAT;
  187752. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187753. break;
  187754. }
  187755. if (ret != Z_OK)
  187756. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187757. "Decompression error");
  187758. } while (png_ptr->zstream.avail_out);
  187759. png_ptr->row_info.color_type = png_ptr->color_type;
  187760. png_ptr->row_info.width = png_ptr->iwidth;
  187761. png_ptr->row_info.channels = png_ptr->channels;
  187762. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187763. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187764. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187765. png_ptr->row_info.width);
  187766. if(png_ptr->row_buf[0])
  187767. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187768. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187769. (int)(png_ptr->row_buf[0]));
  187770. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187771. png_ptr->rowbytes + 1);
  187772. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187773. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187774. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187775. {
  187776. /* Intrapixel differencing */
  187777. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187778. }
  187779. #endif
  187780. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187781. png_do_read_transformations(png_ptr);
  187782. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187783. /* blow up interlaced rows to full size */
  187784. if (png_ptr->interlaced &&
  187785. (png_ptr->transformations & PNG_INTERLACE))
  187786. {
  187787. if (png_ptr->pass < 6)
  187788. /* old interface (pre-1.0.9):
  187789. png_do_read_interlace(&(png_ptr->row_info),
  187790. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187791. */
  187792. png_do_read_interlace(png_ptr);
  187793. if (dsp_row != NULL)
  187794. png_combine_row(png_ptr, dsp_row,
  187795. png_pass_dsp_mask[png_ptr->pass]);
  187796. if (row != NULL)
  187797. png_combine_row(png_ptr, row,
  187798. png_pass_mask[png_ptr->pass]);
  187799. }
  187800. else
  187801. #endif
  187802. {
  187803. if (row != NULL)
  187804. png_combine_row(png_ptr, row, 0xff);
  187805. if (dsp_row != NULL)
  187806. png_combine_row(png_ptr, dsp_row, 0xff);
  187807. }
  187808. png_read_finish_row(png_ptr);
  187809. if (png_ptr->read_row_fn != NULL)
  187810. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187811. }
  187812. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187813. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187814. /* Read one or more rows of image data. If the image is interlaced,
  187815. * and png_set_interlace_handling() has been called, the rows need to
  187816. * contain the contents of the rows from the previous pass. If the
  187817. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187818. * called, the rows contents must be initialized to the contents of the
  187819. * screen.
  187820. *
  187821. * "row" holds the actual image, and pixels are placed in it
  187822. * as they arrive. If the image is displayed after each pass, it will
  187823. * appear to "sparkle" in. "display_row" can be used to display a
  187824. * "chunky" progressive image, with finer detail added as it becomes
  187825. * available. If you do not want this "chunky" display, you may pass
  187826. * NULL for display_row. If you do not want the sparkle display, and
  187827. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187828. * If you have called png_handle_alpha(), and the image has either an
  187829. * alpha channel or a transparency chunk, you must provide a buffer for
  187830. * rows. In this case, you do not have to provide a display_row buffer
  187831. * also, but you may. If the image is not interlaced, or if you have
  187832. * not called png_set_interlace_handling(), the display_row buffer will
  187833. * be ignored, so pass NULL to it.
  187834. *
  187835. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187836. */
  187837. void PNGAPI
  187838. png_read_rows(png_structp png_ptr, png_bytepp row,
  187839. png_bytepp display_row, png_uint_32 num_rows)
  187840. {
  187841. png_uint_32 i;
  187842. png_bytepp rp;
  187843. png_bytepp dp;
  187844. png_debug(1, "in png_read_rows\n");
  187845. if(png_ptr == NULL) return;
  187846. rp = row;
  187847. dp = display_row;
  187848. if (rp != NULL && dp != NULL)
  187849. for (i = 0; i < num_rows; i++)
  187850. {
  187851. png_bytep rptr = *rp++;
  187852. png_bytep dptr = *dp++;
  187853. png_read_row(png_ptr, rptr, dptr);
  187854. }
  187855. else if(rp != NULL)
  187856. for (i = 0; i < num_rows; i++)
  187857. {
  187858. png_bytep rptr = *rp;
  187859. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187860. rp++;
  187861. }
  187862. else if(dp != NULL)
  187863. for (i = 0; i < num_rows; i++)
  187864. {
  187865. png_bytep dptr = *dp;
  187866. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187867. dp++;
  187868. }
  187869. }
  187870. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187871. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187872. /* Read the entire image. If the image has an alpha channel or a tRNS
  187873. * chunk, and you have called png_handle_alpha()[*], you will need to
  187874. * initialize the image to the current image that PNG will be overlaying.
  187875. * We set the num_rows again here, in case it was incorrectly set in
  187876. * png_read_start_row() by a call to png_read_update_info() or
  187877. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187878. * prior to either of these functions like it should have been. You can
  187879. * only call this function once. If you desire to have an image for
  187880. * each pass of a interlaced image, use png_read_rows() instead.
  187881. *
  187882. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187883. */
  187884. void PNGAPI
  187885. png_read_image(png_structp png_ptr, png_bytepp image)
  187886. {
  187887. png_uint_32 i,image_height;
  187888. int pass, j;
  187889. png_bytepp rp;
  187890. png_debug(1, "in png_read_image\n");
  187891. if(png_ptr == NULL) return;
  187892. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187893. pass = png_set_interlace_handling(png_ptr);
  187894. #else
  187895. if (png_ptr->interlaced)
  187896. png_error(png_ptr,
  187897. "Cannot read interlaced image -- interlace handler disabled.");
  187898. pass = 1;
  187899. #endif
  187900. image_height=png_ptr->height;
  187901. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187902. for (j = 0; j < pass; j++)
  187903. {
  187904. rp = image;
  187905. for (i = 0; i < image_height; i++)
  187906. {
  187907. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187908. rp++;
  187909. }
  187910. }
  187911. }
  187912. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187913. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187914. /* Read the end of the PNG file. Will not read past the end of the
  187915. * file, will verify the end is accurate, and will read any comments
  187916. * or time information at the end of the file, if info is not NULL.
  187917. */
  187918. void PNGAPI
  187919. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187920. {
  187921. png_byte chunk_length[4];
  187922. png_uint_32 length;
  187923. png_debug(1, "in png_read_end\n");
  187924. if(png_ptr == NULL) return;
  187925. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187926. do
  187927. {
  187928. #ifdef PNG_USE_LOCAL_ARRAYS
  187929. PNG_CONST PNG_IHDR;
  187930. PNG_CONST PNG_IDAT;
  187931. PNG_CONST PNG_IEND;
  187932. PNG_CONST PNG_PLTE;
  187933. #if defined(PNG_READ_bKGD_SUPPORTED)
  187934. PNG_CONST PNG_bKGD;
  187935. #endif
  187936. #if defined(PNG_READ_cHRM_SUPPORTED)
  187937. PNG_CONST PNG_cHRM;
  187938. #endif
  187939. #if defined(PNG_READ_gAMA_SUPPORTED)
  187940. PNG_CONST PNG_gAMA;
  187941. #endif
  187942. #if defined(PNG_READ_hIST_SUPPORTED)
  187943. PNG_CONST PNG_hIST;
  187944. #endif
  187945. #if defined(PNG_READ_iCCP_SUPPORTED)
  187946. PNG_CONST PNG_iCCP;
  187947. #endif
  187948. #if defined(PNG_READ_iTXt_SUPPORTED)
  187949. PNG_CONST PNG_iTXt;
  187950. #endif
  187951. #if defined(PNG_READ_oFFs_SUPPORTED)
  187952. PNG_CONST PNG_oFFs;
  187953. #endif
  187954. #if defined(PNG_READ_pCAL_SUPPORTED)
  187955. PNG_CONST PNG_pCAL;
  187956. #endif
  187957. #if defined(PNG_READ_pHYs_SUPPORTED)
  187958. PNG_CONST PNG_pHYs;
  187959. #endif
  187960. #if defined(PNG_READ_sBIT_SUPPORTED)
  187961. PNG_CONST PNG_sBIT;
  187962. #endif
  187963. #if defined(PNG_READ_sCAL_SUPPORTED)
  187964. PNG_CONST PNG_sCAL;
  187965. #endif
  187966. #if defined(PNG_READ_sPLT_SUPPORTED)
  187967. PNG_CONST PNG_sPLT;
  187968. #endif
  187969. #if defined(PNG_READ_sRGB_SUPPORTED)
  187970. PNG_CONST PNG_sRGB;
  187971. #endif
  187972. #if defined(PNG_READ_tEXt_SUPPORTED)
  187973. PNG_CONST PNG_tEXt;
  187974. #endif
  187975. #if defined(PNG_READ_tIME_SUPPORTED)
  187976. PNG_CONST PNG_tIME;
  187977. #endif
  187978. #if defined(PNG_READ_tRNS_SUPPORTED)
  187979. PNG_CONST PNG_tRNS;
  187980. #endif
  187981. #if defined(PNG_READ_zTXt_SUPPORTED)
  187982. PNG_CONST PNG_zTXt;
  187983. #endif
  187984. #endif /* PNG_USE_LOCAL_ARRAYS */
  187985. png_read_data(png_ptr, chunk_length, 4);
  187986. length = png_get_uint_31(png_ptr,chunk_length);
  187987. png_reset_crc(png_ptr);
  187988. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187989. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187990. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187991. png_handle_IHDR(png_ptr, info_ptr, length);
  187992. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187993. png_handle_IEND(png_ptr, info_ptr, length);
  187994. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187995. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187996. {
  187997. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187998. {
  187999. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188000. png_error(png_ptr, "Too many IDAT's found");
  188001. }
  188002. png_handle_unknown(png_ptr, info_ptr, length);
  188003. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188004. png_ptr->mode |= PNG_HAVE_PLTE;
  188005. }
  188006. #endif
  188007. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188008. {
  188009. /* Zero length IDATs are legal after the last IDAT has been
  188010. * read, but not after other chunks have been read.
  188011. */
  188012. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188013. png_error(png_ptr, "Too many IDAT's found");
  188014. png_crc_finish(png_ptr, length);
  188015. }
  188016. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188017. png_handle_PLTE(png_ptr, info_ptr, length);
  188018. #if defined(PNG_READ_bKGD_SUPPORTED)
  188019. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188020. png_handle_bKGD(png_ptr, info_ptr, length);
  188021. #endif
  188022. #if defined(PNG_READ_cHRM_SUPPORTED)
  188023. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188024. png_handle_cHRM(png_ptr, info_ptr, length);
  188025. #endif
  188026. #if defined(PNG_READ_gAMA_SUPPORTED)
  188027. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188028. png_handle_gAMA(png_ptr, info_ptr, length);
  188029. #endif
  188030. #if defined(PNG_READ_hIST_SUPPORTED)
  188031. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188032. png_handle_hIST(png_ptr, info_ptr, length);
  188033. #endif
  188034. #if defined(PNG_READ_oFFs_SUPPORTED)
  188035. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188036. png_handle_oFFs(png_ptr, info_ptr, length);
  188037. #endif
  188038. #if defined(PNG_READ_pCAL_SUPPORTED)
  188039. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188040. png_handle_pCAL(png_ptr, info_ptr, length);
  188041. #endif
  188042. #if defined(PNG_READ_sCAL_SUPPORTED)
  188043. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188044. png_handle_sCAL(png_ptr, info_ptr, length);
  188045. #endif
  188046. #if defined(PNG_READ_pHYs_SUPPORTED)
  188047. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188048. png_handle_pHYs(png_ptr, info_ptr, length);
  188049. #endif
  188050. #if defined(PNG_READ_sBIT_SUPPORTED)
  188051. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188052. png_handle_sBIT(png_ptr, info_ptr, length);
  188053. #endif
  188054. #if defined(PNG_READ_sRGB_SUPPORTED)
  188055. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188056. png_handle_sRGB(png_ptr, info_ptr, length);
  188057. #endif
  188058. #if defined(PNG_READ_iCCP_SUPPORTED)
  188059. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188060. png_handle_iCCP(png_ptr, info_ptr, length);
  188061. #endif
  188062. #if defined(PNG_READ_sPLT_SUPPORTED)
  188063. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188064. png_handle_sPLT(png_ptr, info_ptr, length);
  188065. #endif
  188066. #if defined(PNG_READ_tEXt_SUPPORTED)
  188067. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188068. png_handle_tEXt(png_ptr, info_ptr, length);
  188069. #endif
  188070. #if defined(PNG_READ_tIME_SUPPORTED)
  188071. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188072. png_handle_tIME(png_ptr, info_ptr, length);
  188073. #endif
  188074. #if defined(PNG_READ_tRNS_SUPPORTED)
  188075. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188076. png_handle_tRNS(png_ptr, info_ptr, length);
  188077. #endif
  188078. #if defined(PNG_READ_zTXt_SUPPORTED)
  188079. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188080. png_handle_zTXt(png_ptr, info_ptr, length);
  188081. #endif
  188082. #if defined(PNG_READ_iTXt_SUPPORTED)
  188083. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188084. png_handle_iTXt(png_ptr, info_ptr, length);
  188085. #endif
  188086. else
  188087. png_handle_unknown(png_ptr, info_ptr, length);
  188088. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188089. }
  188090. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188091. /* free all memory used by the read */
  188092. void PNGAPI
  188093. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188094. png_infopp end_info_ptr_ptr)
  188095. {
  188096. png_structp png_ptr = NULL;
  188097. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188098. #ifdef PNG_USER_MEM_SUPPORTED
  188099. png_free_ptr free_fn;
  188100. png_voidp mem_ptr;
  188101. #endif
  188102. png_debug(1, "in png_destroy_read_struct\n");
  188103. if (png_ptr_ptr != NULL)
  188104. png_ptr = *png_ptr_ptr;
  188105. if (info_ptr_ptr != NULL)
  188106. info_ptr = *info_ptr_ptr;
  188107. if (end_info_ptr_ptr != NULL)
  188108. end_info_ptr = *end_info_ptr_ptr;
  188109. #ifdef PNG_USER_MEM_SUPPORTED
  188110. free_fn = png_ptr->free_fn;
  188111. mem_ptr = png_ptr->mem_ptr;
  188112. #endif
  188113. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188114. if (info_ptr != NULL)
  188115. {
  188116. #if defined(PNG_TEXT_SUPPORTED)
  188117. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188118. #endif
  188119. #ifdef PNG_USER_MEM_SUPPORTED
  188120. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188121. (png_voidp)mem_ptr);
  188122. #else
  188123. png_destroy_struct((png_voidp)info_ptr);
  188124. #endif
  188125. *info_ptr_ptr = NULL;
  188126. }
  188127. if (end_info_ptr != NULL)
  188128. {
  188129. #if defined(PNG_READ_TEXT_SUPPORTED)
  188130. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188131. #endif
  188132. #ifdef PNG_USER_MEM_SUPPORTED
  188133. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188134. (png_voidp)mem_ptr);
  188135. #else
  188136. png_destroy_struct((png_voidp)end_info_ptr);
  188137. #endif
  188138. *end_info_ptr_ptr = NULL;
  188139. }
  188140. if (png_ptr != NULL)
  188141. {
  188142. #ifdef PNG_USER_MEM_SUPPORTED
  188143. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188144. (png_voidp)mem_ptr);
  188145. #else
  188146. png_destroy_struct((png_voidp)png_ptr);
  188147. #endif
  188148. *png_ptr_ptr = NULL;
  188149. }
  188150. }
  188151. /* free all memory used by the read (old method) */
  188152. void /* PRIVATE */
  188153. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188154. {
  188155. #ifdef PNG_SETJMP_SUPPORTED
  188156. jmp_buf tmp_jmp;
  188157. #endif
  188158. png_error_ptr error_fn;
  188159. png_error_ptr warning_fn;
  188160. png_voidp error_ptr;
  188161. #ifdef PNG_USER_MEM_SUPPORTED
  188162. png_free_ptr free_fn;
  188163. #endif
  188164. png_debug(1, "in png_read_destroy\n");
  188165. if (info_ptr != NULL)
  188166. png_info_destroy(png_ptr, info_ptr);
  188167. if (end_info_ptr != NULL)
  188168. png_info_destroy(png_ptr, end_info_ptr);
  188169. png_free(png_ptr, png_ptr->zbuf);
  188170. png_free(png_ptr, png_ptr->big_row_buf);
  188171. png_free(png_ptr, png_ptr->prev_row);
  188172. #if defined(PNG_READ_DITHER_SUPPORTED)
  188173. png_free(png_ptr, png_ptr->palette_lookup);
  188174. png_free(png_ptr, png_ptr->dither_index);
  188175. #endif
  188176. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188177. png_free(png_ptr, png_ptr->gamma_table);
  188178. #endif
  188179. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188180. png_free(png_ptr, png_ptr->gamma_from_1);
  188181. png_free(png_ptr, png_ptr->gamma_to_1);
  188182. #endif
  188183. #ifdef PNG_FREE_ME_SUPPORTED
  188184. if (png_ptr->free_me & PNG_FREE_PLTE)
  188185. png_zfree(png_ptr, png_ptr->palette);
  188186. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188187. #else
  188188. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188189. png_zfree(png_ptr, png_ptr->palette);
  188190. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188191. #endif
  188192. #if defined(PNG_tRNS_SUPPORTED) || \
  188193. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188194. #ifdef PNG_FREE_ME_SUPPORTED
  188195. if (png_ptr->free_me & PNG_FREE_TRNS)
  188196. png_free(png_ptr, png_ptr->trans);
  188197. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188198. #else
  188199. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188200. png_free(png_ptr, png_ptr->trans);
  188201. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188202. #endif
  188203. #endif
  188204. #if defined(PNG_READ_hIST_SUPPORTED)
  188205. #ifdef PNG_FREE_ME_SUPPORTED
  188206. if (png_ptr->free_me & PNG_FREE_HIST)
  188207. png_free(png_ptr, png_ptr->hist);
  188208. png_ptr->free_me &= ~PNG_FREE_HIST;
  188209. #else
  188210. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188211. png_free(png_ptr, png_ptr->hist);
  188212. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188213. #endif
  188214. #endif
  188215. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188216. if (png_ptr->gamma_16_table != NULL)
  188217. {
  188218. int i;
  188219. int istop = (1 << (8 - png_ptr->gamma_shift));
  188220. for (i = 0; i < istop; i++)
  188221. {
  188222. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188223. }
  188224. png_free(png_ptr, png_ptr->gamma_16_table);
  188225. }
  188226. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188227. if (png_ptr->gamma_16_from_1 != NULL)
  188228. {
  188229. int i;
  188230. int istop = (1 << (8 - png_ptr->gamma_shift));
  188231. for (i = 0; i < istop; i++)
  188232. {
  188233. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188234. }
  188235. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188236. }
  188237. if (png_ptr->gamma_16_to_1 != NULL)
  188238. {
  188239. int i;
  188240. int istop = (1 << (8 - png_ptr->gamma_shift));
  188241. for (i = 0; i < istop; i++)
  188242. {
  188243. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188244. }
  188245. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188246. }
  188247. #endif
  188248. #endif
  188249. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188250. png_free(png_ptr, png_ptr->time_buffer);
  188251. #endif
  188252. inflateEnd(&png_ptr->zstream);
  188253. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188254. png_free(png_ptr, png_ptr->save_buffer);
  188255. #endif
  188256. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188257. #ifdef PNG_TEXT_SUPPORTED
  188258. png_free(png_ptr, png_ptr->current_text);
  188259. #endif /* PNG_TEXT_SUPPORTED */
  188260. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188261. /* Save the important info out of the png_struct, in case it is
  188262. * being used again.
  188263. */
  188264. #ifdef PNG_SETJMP_SUPPORTED
  188265. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188266. #endif
  188267. error_fn = png_ptr->error_fn;
  188268. warning_fn = png_ptr->warning_fn;
  188269. error_ptr = png_ptr->error_ptr;
  188270. #ifdef PNG_USER_MEM_SUPPORTED
  188271. free_fn = png_ptr->free_fn;
  188272. #endif
  188273. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188274. png_ptr->error_fn = error_fn;
  188275. png_ptr->warning_fn = warning_fn;
  188276. png_ptr->error_ptr = error_ptr;
  188277. #ifdef PNG_USER_MEM_SUPPORTED
  188278. png_ptr->free_fn = free_fn;
  188279. #endif
  188280. #ifdef PNG_SETJMP_SUPPORTED
  188281. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188282. #endif
  188283. }
  188284. void PNGAPI
  188285. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188286. {
  188287. if(png_ptr == NULL) return;
  188288. png_ptr->read_row_fn = read_row_fn;
  188289. }
  188290. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188291. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188292. void PNGAPI
  188293. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188294. int transforms,
  188295. voidp params)
  188296. {
  188297. int row;
  188298. if(png_ptr == NULL) return;
  188299. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188300. /* invert the alpha channel from opacity to transparency
  188301. */
  188302. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188303. png_set_invert_alpha(png_ptr);
  188304. #endif
  188305. /* png_read_info() gives us all of the information from the
  188306. * PNG file before the first IDAT (image data chunk).
  188307. */
  188308. png_read_info(png_ptr, info_ptr);
  188309. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188310. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188311. /* -------------- image transformations start here ------------------- */
  188312. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188313. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188314. */
  188315. if (transforms & PNG_TRANSFORM_STRIP_16)
  188316. png_set_strip_16(png_ptr);
  188317. #endif
  188318. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188319. /* Strip alpha bytes from the input data without combining with
  188320. * the background (not recommended).
  188321. */
  188322. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188323. png_set_strip_alpha(png_ptr);
  188324. #endif
  188325. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188326. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188327. * byte into separate bytes (useful for paletted and grayscale images).
  188328. */
  188329. if (transforms & PNG_TRANSFORM_PACKING)
  188330. png_set_packing(png_ptr);
  188331. #endif
  188332. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188333. /* Change the order of packed pixels to least significant bit first
  188334. * (not useful if you are using png_set_packing).
  188335. */
  188336. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188337. png_set_packswap(png_ptr);
  188338. #endif
  188339. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188340. /* Expand paletted colors into true RGB triplets
  188341. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188342. * Expand paletted or RGB images with transparency to full alpha
  188343. * channels so the data will be available as RGBA quartets.
  188344. */
  188345. if (transforms & PNG_TRANSFORM_EXPAND)
  188346. if ((png_ptr->bit_depth < 8) ||
  188347. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188348. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188349. png_set_expand(png_ptr);
  188350. #endif
  188351. /* We don't handle background color or gamma transformation or dithering.
  188352. */
  188353. #if defined(PNG_READ_INVERT_SUPPORTED)
  188354. /* invert monochrome files to have 0 as white and 1 as black
  188355. */
  188356. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188357. png_set_invert_mono(png_ptr);
  188358. #endif
  188359. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188360. /* If you want to shift the pixel values from the range [0,255] or
  188361. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188362. * colors were originally in:
  188363. */
  188364. if ((transforms & PNG_TRANSFORM_SHIFT)
  188365. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188366. {
  188367. png_color_8p sig_bit;
  188368. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188369. png_set_shift(png_ptr, sig_bit);
  188370. }
  188371. #endif
  188372. #if defined(PNG_READ_BGR_SUPPORTED)
  188373. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188374. */
  188375. if (transforms & PNG_TRANSFORM_BGR)
  188376. png_set_bgr(png_ptr);
  188377. #endif
  188378. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188379. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188380. */
  188381. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188382. png_set_swap_alpha(png_ptr);
  188383. #endif
  188384. #if defined(PNG_READ_SWAP_SUPPORTED)
  188385. /* swap bytes of 16 bit files to least significant byte first
  188386. */
  188387. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188388. png_set_swap(png_ptr);
  188389. #endif
  188390. /* We don't handle adding filler bytes */
  188391. /* Optional call to gamma correct and add the background to the palette
  188392. * and update info structure. REQUIRED if you are expecting libpng to
  188393. * update the palette for you (i.e., you selected such a transform above).
  188394. */
  188395. png_read_update_info(png_ptr, info_ptr);
  188396. /* -------------- image transformations end here ------------------- */
  188397. #ifdef PNG_FREE_ME_SUPPORTED
  188398. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188399. #endif
  188400. if(info_ptr->row_pointers == NULL)
  188401. {
  188402. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188403. info_ptr->height * png_sizeof(png_bytep));
  188404. #ifdef PNG_FREE_ME_SUPPORTED
  188405. info_ptr->free_me |= PNG_FREE_ROWS;
  188406. #endif
  188407. for (row = 0; row < (int)info_ptr->height; row++)
  188408. {
  188409. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188410. png_get_rowbytes(png_ptr, info_ptr));
  188411. }
  188412. }
  188413. png_read_image(png_ptr, info_ptr->row_pointers);
  188414. info_ptr->valid |= PNG_INFO_IDAT;
  188415. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188416. png_read_end(png_ptr, info_ptr);
  188417. transforms = transforms; /* quiet compiler warnings */
  188418. params = params;
  188419. }
  188420. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188421. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188422. #endif /* PNG_READ_SUPPORTED */
  188423. /*** End of inlined file: pngread.c ***/
  188424. /*** Start of inlined file: pngpread.c ***/
  188425. /* pngpread.c - read a png file in push mode
  188426. *
  188427. * Last changed in libpng 1.2.21 October 4, 2007
  188428. * For conditions of distribution and use, see copyright notice in png.h
  188429. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188430. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188431. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188432. */
  188433. #define PNG_INTERNAL
  188434. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188435. /* push model modes */
  188436. #define PNG_READ_SIG_MODE 0
  188437. #define PNG_READ_CHUNK_MODE 1
  188438. #define PNG_READ_IDAT_MODE 2
  188439. #define PNG_SKIP_MODE 3
  188440. #define PNG_READ_tEXt_MODE 4
  188441. #define PNG_READ_zTXt_MODE 5
  188442. #define PNG_READ_DONE_MODE 6
  188443. #define PNG_READ_iTXt_MODE 7
  188444. #define PNG_ERROR_MODE 8
  188445. void PNGAPI
  188446. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188447. png_bytep buffer, png_size_t buffer_size)
  188448. {
  188449. if(png_ptr == NULL) return;
  188450. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188451. while (png_ptr->buffer_size)
  188452. {
  188453. png_process_some_data(png_ptr, info_ptr);
  188454. }
  188455. }
  188456. /* What we do with the incoming data depends on what we were previously
  188457. * doing before we ran out of data...
  188458. */
  188459. void /* PRIVATE */
  188460. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188461. {
  188462. if(png_ptr == NULL) return;
  188463. switch (png_ptr->process_mode)
  188464. {
  188465. case PNG_READ_SIG_MODE:
  188466. {
  188467. png_push_read_sig(png_ptr, info_ptr);
  188468. break;
  188469. }
  188470. case PNG_READ_CHUNK_MODE:
  188471. {
  188472. png_push_read_chunk(png_ptr, info_ptr);
  188473. break;
  188474. }
  188475. case PNG_READ_IDAT_MODE:
  188476. {
  188477. png_push_read_IDAT(png_ptr);
  188478. break;
  188479. }
  188480. #if defined(PNG_READ_tEXt_SUPPORTED)
  188481. case PNG_READ_tEXt_MODE:
  188482. {
  188483. png_push_read_tEXt(png_ptr, info_ptr);
  188484. break;
  188485. }
  188486. #endif
  188487. #if defined(PNG_READ_zTXt_SUPPORTED)
  188488. case PNG_READ_zTXt_MODE:
  188489. {
  188490. png_push_read_zTXt(png_ptr, info_ptr);
  188491. break;
  188492. }
  188493. #endif
  188494. #if defined(PNG_READ_iTXt_SUPPORTED)
  188495. case PNG_READ_iTXt_MODE:
  188496. {
  188497. png_push_read_iTXt(png_ptr, info_ptr);
  188498. break;
  188499. }
  188500. #endif
  188501. case PNG_SKIP_MODE:
  188502. {
  188503. png_push_crc_finish(png_ptr);
  188504. break;
  188505. }
  188506. default:
  188507. {
  188508. png_ptr->buffer_size = 0;
  188509. break;
  188510. }
  188511. }
  188512. }
  188513. /* Read any remaining signature bytes from the stream and compare them with
  188514. * the correct PNG signature. It is possible that this routine is called
  188515. * with bytes already read from the signature, either because they have been
  188516. * checked by the calling application, or because of multiple calls to this
  188517. * routine.
  188518. */
  188519. void /* PRIVATE */
  188520. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188521. {
  188522. png_size_t num_checked = png_ptr->sig_bytes,
  188523. num_to_check = 8 - num_checked;
  188524. if (png_ptr->buffer_size < num_to_check)
  188525. {
  188526. num_to_check = png_ptr->buffer_size;
  188527. }
  188528. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188529. num_to_check);
  188530. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188531. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188532. {
  188533. if (num_checked < 4 &&
  188534. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188535. png_error(png_ptr, "Not a PNG file");
  188536. else
  188537. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188538. }
  188539. else
  188540. {
  188541. if (png_ptr->sig_bytes >= 8)
  188542. {
  188543. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188544. }
  188545. }
  188546. }
  188547. void /* PRIVATE */
  188548. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188549. {
  188550. #ifdef PNG_USE_LOCAL_ARRAYS
  188551. PNG_CONST PNG_IHDR;
  188552. PNG_CONST PNG_IDAT;
  188553. PNG_CONST PNG_IEND;
  188554. PNG_CONST PNG_PLTE;
  188555. #if defined(PNG_READ_bKGD_SUPPORTED)
  188556. PNG_CONST PNG_bKGD;
  188557. #endif
  188558. #if defined(PNG_READ_cHRM_SUPPORTED)
  188559. PNG_CONST PNG_cHRM;
  188560. #endif
  188561. #if defined(PNG_READ_gAMA_SUPPORTED)
  188562. PNG_CONST PNG_gAMA;
  188563. #endif
  188564. #if defined(PNG_READ_hIST_SUPPORTED)
  188565. PNG_CONST PNG_hIST;
  188566. #endif
  188567. #if defined(PNG_READ_iCCP_SUPPORTED)
  188568. PNG_CONST PNG_iCCP;
  188569. #endif
  188570. #if defined(PNG_READ_iTXt_SUPPORTED)
  188571. PNG_CONST PNG_iTXt;
  188572. #endif
  188573. #if defined(PNG_READ_oFFs_SUPPORTED)
  188574. PNG_CONST PNG_oFFs;
  188575. #endif
  188576. #if defined(PNG_READ_pCAL_SUPPORTED)
  188577. PNG_CONST PNG_pCAL;
  188578. #endif
  188579. #if defined(PNG_READ_pHYs_SUPPORTED)
  188580. PNG_CONST PNG_pHYs;
  188581. #endif
  188582. #if defined(PNG_READ_sBIT_SUPPORTED)
  188583. PNG_CONST PNG_sBIT;
  188584. #endif
  188585. #if defined(PNG_READ_sCAL_SUPPORTED)
  188586. PNG_CONST PNG_sCAL;
  188587. #endif
  188588. #if defined(PNG_READ_sRGB_SUPPORTED)
  188589. PNG_CONST PNG_sRGB;
  188590. #endif
  188591. #if defined(PNG_READ_sPLT_SUPPORTED)
  188592. PNG_CONST PNG_sPLT;
  188593. #endif
  188594. #if defined(PNG_READ_tEXt_SUPPORTED)
  188595. PNG_CONST PNG_tEXt;
  188596. #endif
  188597. #if defined(PNG_READ_tIME_SUPPORTED)
  188598. PNG_CONST PNG_tIME;
  188599. #endif
  188600. #if defined(PNG_READ_tRNS_SUPPORTED)
  188601. PNG_CONST PNG_tRNS;
  188602. #endif
  188603. #if defined(PNG_READ_zTXt_SUPPORTED)
  188604. PNG_CONST PNG_zTXt;
  188605. #endif
  188606. #endif /* PNG_USE_LOCAL_ARRAYS */
  188607. /* First we make sure we have enough data for the 4 byte chunk name
  188608. * and the 4 byte chunk length before proceeding with decoding the
  188609. * chunk data. To fully decode each of these chunks, we also make
  188610. * sure we have enough data in the buffer for the 4 byte CRC at the
  188611. * end of every chunk (except IDAT, which is handled separately).
  188612. */
  188613. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188614. {
  188615. png_byte chunk_length[4];
  188616. if (png_ptr->buffer_size < 8)
  188617. {
  188618. png_push_save_buffer(png_ptr);
  188619. return;
  188620. }
  188621. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188622. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188623. png_reset_crc(png_ptr);
  188624. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188625. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188626. }
  188627. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188628. if(png_ptr->mode & PNG_AFTER_IDAT)
  188629. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188630. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188631. {
  188632. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188633. {
  188634. png_push_save_buffer(png_ptr);
  188635. return;
  188636. }
  188637. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188638. }
  188639. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188640. {
  188641. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188642. {
  188643. png_push_save_buffer(png_ptr);
  188644. return;
  188645. }
  188646. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188647. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188648. png_push_have_end(png_ptr, info_ptr);
  188649. }
  188650. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188651. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188652. {
  188653. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188654. {
  188655. png_push_save_buffer(png_ptr);
  188656. return;
  188657. }
  188658. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188659. png_ptr->mode |= PNG_HAVE_IDAT;
  188660. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188661. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188662. png_ptr->mode |= PNG_HAVE_PLTE;
  188663. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188664. {
  188665. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188666. png_error(png_ptr, "Missing IHDR before IDAT");
  188667. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188668. !(png_ptr->mode & PNG_HAVE_PLTE))
  188669. png_error(png_ptr, "Missing PLTE before IDAT");
  188670. }
  188671. }
  188672. #endif
  188673. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188674. {
  188675. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188676. {
  188677. png_push_save_buffer(png_ptr);
  188678. return;
  188679. }
  188680. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188681. }
  188682. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188683. {
  188684. /* If we reach an IDAT chunk, this means we have read all of the
  188685. * header chunks, and we can start reading the image (or if this
  188686. * is called after the image has been read - we have an error).
  188687. */
  188688. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188689. png_error(png_ptr, "Missing IHDR before IDAT");
  188690. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188691. !(png_ptr->mode & PNG_HAVE_PLTE))
  188692. png_error(png_ptr, "Missing PLTE before IDAT");
  188693. if (png_ptr->mode & PNG_HAVE_IDAT)
  188694. {
  188695. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188696. if (png_ptr->push_length == 0)
  188697. return;
  188698. if (png_ptr->mode & PNG_AFTER_IDAT)
  188699. png_error(png_ptr, "Too many IDAT's found");
  188700. }
  188701. png_ptr->idat_size = png_ptr->push_length;
  188702. png_ptr->mode |= PNG_HAVE_IDAT;
  188703. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188704. png_push_have_info(png_ptr, info_ptr);
  188705. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188706. png_ptr->zstream.next_out = png_ptr->row_buf;
  188707. return;
  188708. }
  188709. #if defined(PNG_READ_gAMA_SUPPORTED)
  188710. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188711. {
  188712. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188713. {
  188714. png_push_save_buffer(png_ptr);
  188715. return;
  188716. }
  188717. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188718. }
  188719. #endif
  188720. #if defined(PNG_READ_sBIT_SUPPORTED)
  188721. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188722. {
  188723. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188724. {
  188725. png_push_save_buffer(png_ptr);
  188726. return;
  188727. }
  188728. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188729. }
  188730. #endif
  188731. #if defined(PNG_READ_cHRM_SUPPORTED)
  188732. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188733. {
  188734. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188735. {
  188736. png_push_save_buffer(png_ptr);
  188737. return;
  188738. }
  188739. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188740. }
  188741. #endif
  188742. #if defined(PNG_READ_sRGB_SUPPORTED)
  188743. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188744. {
  188745. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188746. {
  188747. png_push_save_buffer(png_ptr);
  188748. return;
  188749. }
  188750. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188751. }
  188752. #endif
  188753. #if defined(PNG_READ_iCCP_SUPPORTED)
  188754. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188755. {
  188756. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188757. {
  188758. png_push_save_buffer(png_ptr);
  188759. return;
  188760. }
  188761. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188762. }
  188763. #endif
  188764. #if defined(PNG_READ_sPLT_SUPPORTED)
  188765. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188766. {
  188767. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188768. {
  188769. png_push_save_buffer(png_ptr);
  188770. return;
  188771. }
  188772. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188773. }
  188774. #endif
  188775. #if defined(PNG_READ_tRNS_SUPPORTED)
  188776. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188777. {
  188778. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188779. {
  188780. png_push_save_buffer(png_ptr);
  188781. return;
  188782. }
  188783. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188784. }
  188785. #endif
  188786. #if defined(PNG_READ_bKGD_SUPPORTED)
  188787. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188788. {
  188789. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188790. {
  188791. png_push_save_buffer(png_ptr);
  188792. return;
  188793. }
  188794. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188795. }
  188796. #endif
  188797. #if defined(PNG_READ_hIST_SUPPORTED)
  188798. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188799. {
  188800. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188801. {
  188802. png_push_save_buffer(png_ptr);
  188803. return;
  188804. }
  188805. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188806. }
  188807. #endif
  188808. #if defined(PNG_READ_pHYs_SUPPORTED)
  188809. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188810. {
  188811. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188812. {
  188813. png_push_save_buffer(png_ptr);
  188814. return;
  188815. }
  188816. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188817. }
  188818. #endif
  188819. #if defined(PNG_READ_oFFs_SUPPORTED)
  188820. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188821. {
  188822. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188823. {
  188824. png_push_save_buffer(png_ptr);
  188825. return;
  188826. }
  188827. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188828. }
  188829. #endif
  188830. #if defined(PNG_READ_pCAL_SUPPORTED)
  188831. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 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_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188839. }
  188840. #endif
  188841. #if defined(PNG_READ_sCAL_SUPPORTED)
  188842. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188843. {
  188844. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188845. {
  188846. png_push_save_buffer(png_ptr);
  188847. return;
  188848. }
  188849. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188850. }
  188851. #endif
  188852. #if defined(PNG_READ_tIME_SUPPORTED)
  188853. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188854. {
  188855. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188856. {
  188857. png_push_save_buffer(png_ptr);
  188858. return;
  188859. }
  188860. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188861. }
  188862. #endif
  188863. #if defined(PNG_READ_tEXt_SUPPORTED)
  188864. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188865. {
  188866. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188867. {
  188868. png_push_save_buffer(png_ptr);
  188869. return;
  188870. }
  188871. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188872. }
  188873. #endif
  188874. #if defined(PNG_READ_zTXt_SUPPORTED)
  188875. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188876. {
  188877. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188878. {
  188879. png_push_save_buffer(png_ptr);
  188880. return;
  188881. }
  188882. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188883. }
  188884. #endif
  188885. #if defined(PNG_READ_iTXt_SUPPORTED)
  188886. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188887. {
  188888. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188889. {
  188890. png_push_save_buffer(png_ptr);
  188891. return;
  188892. }
  188893. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188894. }
  188895. #endif
  188896. else
  188897. {
  188898. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188899. {
  188900. png_push_save_buffer(png_ptr);
  188901. return;
  188902. }
  188903. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188904. }
  188905. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188906. }
  188907. void /* PRIVATE */
  188908. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188909. {
  188910. png_ptr->process_mode = PNG_SKIP_MODE;
  188911. png_ptr->skip_length = skip;
  188912. }
  188913. void /* PRIVATE */
  188914. png_push_crc_finish(png_structp png_ptr)
  188915. {
  188916. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188917. {
  188918. png_size_t save_size;
  188919. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188920. save_size = (png_size_t)png_ptr->skip_length;
  188921. else
  188922. save_size = png_ptr->save_buffer_size;
  188923. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188924. png_ptr->skip_length -= save_size;
  188925. png_ptr->buffer_size -= save_size;
  188926. png_ptr->save_buffer_size -= save_size;
  188927. png_ptr->save_buffer_ptr += save_size;
  188928. }
  188929. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188930. {
  188931. png_size_t save_size;
  188932. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188933. save_size = (png_size_t)png_ptr->skip_length;
  188934. else
  188935. save_size = png_ptr->current_buffer_size;
  188936. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188937. png_ptr->skip_length -= save_size;
  188938. png_ptr->buffer_size -= save_size;
  188939. png_ptr->current_buffer_size -= save_size;
  188940. png_ptr->current_buffer_ptr += save_size;
  188941. }
  188942. if (!png_ptr->skip_length)
  188943. {
  188944. if (png_ptr->buffer_size < 4)
  188945. {
  188946. png_push_save_buffer(png_ptr);
  188947. return;
  188948. }
  188949. png_crc_finish(png_ptr, 0);
  188950. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188951. }
  188952. }
  188953. void PNGAPI
  188954. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188955. {
  188956. png_bytep ptr;
  188957. if(png_ptr == NULL) return;
  188958. ptr = buffer;
  188959. if (png_ptr->save_buffer_size)
  188960. {
  188961. png_size_t save_size;
  188962. if (length < png_ptr->save_buffer_size)
  188963. save_size = length;
  188964. else
  188965. save_size = png_ptr->save_buffer_size;
  188966. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188967. length -= save_size;
  188968. ptr += save_size;
  188969. png_ptr->buffer_size -= save_size;
  188970. png_ptr->save_buffer_size -= save_size;
  188971. png_ptr->save_buffer_ptr += save_size;
  188972. }
  188973. if (length && png_ptr->current_buffer_size)
  188974. {
  188975. png_size_t save_size;
  188976. if (length < png_ptr->current_buffer_size)
  188977. save_size = length;
  188978. else
  188979. save_size = png_ptr->current_buffer_size;
  188980. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188981. png_ptr->buffer_size -= save_size;
  188982. png_ptr->current_buffer_size -= save_size;
  188983. png_ptr->current_buffer_ptr += save_size;
  188984. }
  188985. }
  188986. void /* PRIVATE */
  188987. png_push_save_buffer(png_structp png_ptr)
  188988. {
  188989. if (png_ptr->save_buffer_size)
  188990. {
  188991. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188992. {
  188993. png_size_t i,istop;
  188994. png_bytep sp;
  188995. png_bytep dp;
  188996. istop = png_ptr->save_buffer_size;
  188997. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188998. i < istop; i++, sp++, dp++)
  188999. {
  189000. *dp = *sp;
  189001. }
  189002. }
  189003. }
  189004. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189005. png_ptr->save_buffer_max)
  189006. {
  189007. png_size_t new_max;
  189008. png_bytep old_buffer;
  189009. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189010. (png_ptr->current_buffer_size + 256))
  189011. {
  189012. png_error(png_ptr, "Potential overflow of save_buffer");
  189013. }
  189014. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189015. old_buffer = png_ptr->save_buffer;
  189016. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189017. (png_uint_32)new_max);
  189018. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189019. png_free(png_ptr, old_buffer);
  189020. png_ptr->save_buffer_max = new_max;
  189021. }
  189022. if (png_ptr->current_buffer_size)
  189023. {
  189024. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189025. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189026. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189027. png_ptr->current_buffer_size = 0;
  189028. }
  189029. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189030. png_ptr->buffer_size = 0;
  189031. }
  189032. void /* PRIVATE */
  189033. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189034. png_size_t buffer_length)
  189035. {
  189036. png_ptr->current_buffer = buffer;
  189037. png_ptr->current_buffer_size = buffer_length;
  189038. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189039. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189040. }
  189041. void /* PRIVATE */
  189042. png_push_read_IDAT(png_structp png_ptr)
  189043. {
  189044. #ifdef PNG_USE_LOCAL_ARRAYS
  189045. PNG_CONST PNG_IDAT;
  189046. #endif
  189047. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189048. {
  189049. png_byte chunk_length[4];
  189050. if (png_ptr->buffer_size < 8)
  189051. {
  189052. png_push_save_buffer(png_ptr);
  189053. return;
  189054. }
  189055. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189056. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189057. png_reset_crc(png_ptr);
  189058. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189059. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189060. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189061. {
  189062. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189063. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189064. png_error(png_ptr, "Not enough compressed data");
  189065. return;
  189066. }
  189067. png_ptr->idat_size = png_ptr->push_length;
  189068. }
  189069. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189070. {
  189071. png_size_t save_size;
  189072. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189073. {
  189074. save_size = (png_size_t)png_ptr->idat_size;
  189075. /* check for overflow */
  189076. if((png_uint_32)save_size != png_ptr->idat_size)
  189077. png_error(png_ptr, "save_size overflowed in pngpread");
  189078. }
  189079. else
  189080. save_size = png_ptr->save_buffer_size;
  189081. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189082. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189083. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189084. png_ptr->idat_size -= save_size;
  189085. png_ptr->buffer_size -= save_size;
  189086. png_ptr->save_buffer_size -= save_size;
  189087. png_ptr->save_buffer_ptr += save_size;
  189088. }
  189089. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189090. {
  189091. png_size_t save_size;
  189092. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189093. {
  189094. save_size = (png_size_t)png_ptr->idat_size;
  189095. /* check for overflow */
  189096. if((png_uint_32)save_size != png_ptr->idat_size)
  189097. png_error(png_ptr, "save_size overflowed in pngpread");
  189098. }
  189099. else
  189100. save_size = png_ptr->current_buffer_size;
  189101. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189102. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189103. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189104. png_ptr->idat_size -= save_size;
  189105. png_ptr->buffer_size -= save_size;
  189106. png_ptr->current_buffer_size -= save_size;
  189107. png_ptr->current_buffer_ptr += save_size;
  189108. }
  189109. if (!png_ptr->idat_size)
  189110. {
  189111. if (png_ptr->buffer_size < 4)
  189112. {
  189113. png_push_save_buffer(png_ptr);
  189114. return;
  189115. }
  189116. png_crc_finish(png_ptr, 0);
  189117. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189118. png_ptr->mode |= PNG_AFTER_IDAT;
  189119. }
  189120. }
  189121. void /* PRIVATE */
  189122. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189123. png_size_t buffer_length)
  189124. {
  189125. int ret;
  189126. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189127. png_error(png_ptr, "Extra compression data");
  189128. png_ptr->zstream.next_in = buffer;
  189129. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189130. for(;;)
  189131. {
  189132. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189133. if (ret != Z_OK)
  189134. {
  189135. if (ret == Z_STREAM_END)
  189136. {
  189137. if (png_ptr->zstream.avail_in)
  189138. png_error(png_ptr, "Extra compressed data");
  189139. if (!(png_ptr->zstream.avail_out))
  189140. {
  189141. png_push_process_row(png_ptr);
  189142. }
  189143. png_ptr->mode |= PNG_AFTER_IDAT;
  189144. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189145. break;
  189146. }
  189147. else if (ret == Z_BUF_ERROR)
  189148. break;
  189149. else
  189150. png_error(png_ptr, "Decompression Error");
  189151. }
  189152. if (!(png_ptr->zstream.avail_out))
  189153. {
  189154. if ((
  189155. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189156. png_ptr->interlaced && png_ptr->pass > 6) ||
  189157. (!png_ptr->interlaced &&
  189158. #endif
  189159. png_ptr->row_number == png_ptr->num_rows))
  189160. {
  189161. if (png_ptr->zstream.avail_in)
  189162. {
  189163. png_warning(png_ptr, "Too much data in IDAT chunks");
  189164. }
  189165. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189166. break;
  189167. }
  189168. png_push_process_row(png_ptr);
  189169. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189170. png_ptr->zstream.next_out = png_ptr->row_buf;
  189171. }
  189172. else
  189173. break;
  189174. }
  189175. }
  189176. void /* PRIVATE */
  189177. png_push_process_row(png_structp png_ptr)
  189178. {
  189179. png_ptr->row_info.color_type = png_ptr->color_type;
  189180. png_ptr->row_info.width = png_ptr->iwidth;
  189181. png_ptr->row_info.channels = png_ptr->channels;
  189182. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189183. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189184. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189185. png_ptr->row_info.width);
  189186. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189187. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189188. (int)(png_ptr->row_buf[0]));
  189189. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189190. png_ptr->rowbytes + 1);
  189191. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189192. png_do_read_transformations(png_ptr);
  189193. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189194. /* blow up interlaced rows to full size */
  189195. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189196. {
  189197. if (png_ptr->pass < 6)
  189198. /* old interface (pre-1.0.9):
  189199. png_do_read_interlace(&(png_ptr->row_info),
  189200. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189201. */
  189202. png_do_read_interlace(png_ptr);
  189203. switch (png_ptr->pass)
  189204. {
  189205. case 0:
  189206. {
  189207. int i;
  189208. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189209. {
  189210. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189211. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189212. }
  189213. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189214. {
  189215. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189216. {
  189217. png_push_have_row(png_ptr, png_bytep_NULL);
  189218. png_read_push_finish_row(png_ptr);
  189219. }
  189220. }
  189221. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189222. {
  189223. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189224. {
  189225. png_push_have_row(png_ptr, png_bytep_NULL);
  189226. png_read_push_finish_row(png_ptr);
  189227. }
  189228. }
  189229. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189230. {
  189231. png_push_have_row(png_ptr, png_bytep_NULL);
  189232. png_read_push_finish_row(png_ptr);
  189233. }
  189234. break;
  189235. }
  189236. case 1:
  189237. {
  189238. int i;
  189239. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189240. {
  189241. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189242. png_read_push_finish_row(png_ptr);
  189243. }
  189244. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189245. {
  189246. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189247. {
  189248. png_push_have_row(png_ptr, png_bytep_NULL);
  189249. png_read_push_finish_row(png_ptr);
  189250. }
  189251. }
  189252. break;
  189253. }
  189254. case 2:
  189255. {
  189256. int i;
  189257. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189258. {
  189259. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189260. png_read_push_finish_row(png_ptr);
  189261. }
  189262. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189263. {
  189264. png_push_have_row(png_ptr, png_bytep_NULL);
  189265. png_read_push_finish_row(png_ptr);
  189266. }
  189267. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189268. {
  189269. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189270. {
  189271. png_push_have_row(png_ptr, png_bytep_NULL);
  189272. png_read_push_finish_row(png_ptr);
  189273. }
  189274. }
  189275. break;
  189276. }
  189277. case 3:
  189278. {
  189279. int i;
  189280. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189281. {
  189282. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189283. png_read_push_finish_row(png_ptr);
  189284. }
  189285. if (png_ptr->pass == 4) /* skip top two generated rows */
  189286. {
  189287. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189288. {
  189289. png_push_have_row(png_ptr, png_bytep_NULL);
  189290. png_read_push_finish_row(png_ptr);
  189291. }
  189292. }
  189293. break;
  189294. }
  189295. case 4:
  189296. {
  189297. int i;
  189298. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189299. {
  189300. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189301. png_read_push_finish_row(png_ptr);
  189302. }
  189303. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189304. {
  189305. png_push_have_row(png_ptr, png_bytep_NULL);
  189306. png_read_push_finish_row(png_ptr);
  189307. }
  189308. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189309. {
  189310. png_push_have_row(png_ptr, png_bytep_NULL);
  189311. png_read_push_finish_row(png_ptr);
  189312. }
  189313. break;
  189314. }
  189315. case 5:
  189316. {
  189317. int i;
  189318. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189319. {
  189320. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189321. png_read_push_finish_row(png_ptr);
  189322. }
  189323. if (png_ptr->pass == 6) /* skip top generated row */
  189324. {
  189325. png_push_have_row(png_ptr, png_bytep_NULL);
  189326. png_read_push_finish_row(png_ptr);
  189327. }
  189328. break;
  189329. }
  189330. case 6:
  189331. {
  189332. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189333. png_read_push_finish_row(png_ptr);
  189334. if (png_ptr->pass != 6)
  189335. break;
  189336. png_push_have_row(png_ptr, png_bytep_NULL);
  189337. png_read_push_finish_row(png_ptr);
  189338. }
  189339. }
  189340. }
  189341. else
  189342. #endif
  189343. {
  189344. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189345. png_read_push_finish_row(png_ptr);
  189346. }
  189347. }
  189348. void /* PRIVATE */
  189349. png_read_push_finish_row(png_structp png_ptr)
  189350. {
  189351. #ifdef PNG_USE_LOCAL_ARRAYS
  189352. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189353. /* start of interlace block */
  189354. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189355. /* offset to next interlace block */
  189356. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189357. /* start of interlace block in the y direction */
  189358. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189359. /* offset to next interlace block in the y direction */
  189360. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189361. /* Height of interlace block. This is not currently used - if you need
  189362. * it, uncomment it here and in png.h
  189363. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189364. */
  189365. #endif
  189366. png_ptr->row_number++;
  189367. if (png_ptr->row_number < png_ptr->num_rows)
  189368. return;
  189369. if (png_ptr->interlaced)
  189370. {
  189371. png_ptr->row_number = 0;
  189372. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189373. png_ptr->rowbytes + 1);
  189374. do
  189375. {
  189376. png_ptr->pass++;
  189377. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189378. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189379. (png_ptr->pass == 5 && png_ptr->width < 2))
  189380. png_ptr->pass++;
  189381. if (png_ptr->pass > 7)
  189382. png_ptr->pass--;
  189383. if (png_ptr->pass >= 7)
  189384. break;
  189385. png_ptr->iwidth = (png_ptr->width +
  189386. png_pass_inc[png_ptr->pass] - 1 -
  189387. png_pass_start[png_ptr->pass]) /
  189388. png_pass_inc[png_ptr->pass];
  189389. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189390. png_ptr->iwidth) + 1;
  189391. if (png_ptr->transformations & PNG_INTERLACE)
  189392. break;
  189393. png_ptr->num_rows = (png_ptr->height +
  189394. png_pass_yinc[png_ptr->pass] - 1 -
  189395. png_pass_ystart[png_ptr->pass]) /
  189396. png_pass_yinc[png_ptr->pass];
  189397. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189398. }
  189399. }
  189400. #if defined(PNG_READ_tEXt_SUPPORTED)
  189401. void /* PRIVATE */
  189402. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189403. length)
  189404. {
  189405. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189406. {
  189407. png_error(png_ptr, "Out of place tEXt");
  189408. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189409. }
  189410. #ifdef PNG_MAX_MALLOC_64K
  189411. png_ptr->skip_length = 0; /* This may not be necessary */
  189412. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189413. {
  189414. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189415. png_ptr->skip_length = length - (png_uint_32)65535L;
  189416. length = (png_uint_32)65535L;
  189417. }
  189418. #endif
  189419. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189420. (png_uint_32)(length+1));
  189421. png_ptr->current_text[length] = '\0';
  189422. png_ptr->current_text_ptr = png_ptr->current_text;
  189423. png_ptr->current_text_size = (png_size_t)length;
  189424. png_ptr->current_text_left = (png_size_t)length;
  189425. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189426. }
  189427. void /* PRIVATE */
  189428. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189429. {
  189430. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189431. {
  189432. png_size_t text_size;
  189433. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189434. text_size = png_ptr->buffer_size;
  189435. else
  189436. text_size = png_ptr->current_text_left;
  189437. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189438. png_ptr->current_text_left -= text_size;
  189439. png_ptr->current_text_ptr += text_size;
  189440. }
  189441. if (!(png_ptr->current_text_left))
  189442. {
  189443. png_textp text_ptr;
  189444. png_charp text;
  189445. png_charp key;
  189446. int ret;
  189447. if (png_ptr->buffer_size < 4)
  189448. {
  189449. png_push_save_buffer(png_ptr);
  189450. return;
  189451. }
  189452. png_push_crc_finish(png_ptr);
  189453. #if defined(PNG_MAX_MALLOC_64K)
  189454. if (png_ptr->skip_length)
  189455. return;
  189456. #endif
  189457. key = png_ptr->current_text;
  189458. for (text = key; *text; text++)
  189459. /* empty loop */ ;
  189460. if (text < key + png_ptr->current_text_size)
  189461. text++;
  189462. text_ptr = (png_textp)png_malloc(png_ptr,
  189463. (png_uint_32)png_sizeof(png_text));
  189464. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189465. text_ptr->key = key;
  189466. #ifdef PNG_iTXt_SUPPORTED
  189467. text_ptr->lang = NULL;
  189468. text_ptr->lang_key = NULL;
  189469. #endif
  189470. text_ptr->text = text;
  189471. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189472. png_free(png_ptr, key);
  189473. png_free(png_ptr, text_ptr);
  189474. png_ptr->current_text = NULL;
  189475. if (ret)
  189476. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189477. }
  189478. }
  189479. #endif
  189480. #if defined(PNG_READ_zTXt_SUPPORTED)
  189481. void /* PRIVATE */
  189482. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189483. length)
  189484. {
  189485. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189486. {
  189487. png_error(png_ptr, "Out of place zTXt");
  189488. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189489. }
  189490. #ifdef PNG_MAX_MALLOC_64K
  189491. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189492. * to be able to store the uncompressed data. Actually, the threshold
  189493. * is probably around 32K, but it isn't as definite as 64K is.
  189494. */
  189495. if (length > (png_uint_32)65535L)
  189496. {
  189497. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189498. png_push_crc_skip(png_ptr, length);
  189499. return;
  189500. }
  189501. #endif
  189502. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189503. (png_uint_32)(length+1));
  189504. png_ptr->current_text[length] = '\0';
  189505. png_ptr->current_text_ptr = png_ptr->current_text;
  189506. png_ptr->current_text_size = (png_size_t)length;
  189507. png_ptr->current_text_left = (png_size_t)length;
  189508. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189509. }
  189510. void /* PRIVATE */
  189511. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189512. {
  189513. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189514. {
  189515. png_size_t text_size;
  189516. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189517. text_size = png_ptr->buffer_size;
  189518. else
  189519. text_size = png_ptr->current_text_left;
  189520. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189521. png_ptr->current_text_left -= text_size;
  189522. png_ptr->current_text_ptr += text_size;
  189523. }
  189524. if (!(png_ptr->current_text_left))
  189525. {
  189526. png_textp text_ptr;
  189527. png_charp text;
  189528. png_charp key;
  189529. int ret;
  189530. png_size_t text_size, key_size;
  189531. if (png_ptr->buffer_size < 4)
  189532. {
  189533. png_push_save_buffer(png_ptr);
  189534. return;
  189535. }
  189536. png_push_crc_finish(png_ptr);
  189537. key = png_ptr->current_text;
  189538. for (text = key; *text; text++)
  189539. /* empty loop */ ;
  189540. /* zTXt can't have zero text */
  189541. if (text >= key + png_ptr->current_text_size)
  189542. {
  189543. png_ptr->current_text = NULL;
  189544. png_free(png_ptr, key);
  189545. return;
  189546. }
  189547. text++;
  189548. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189549. {
  189550. png_ptr->current_text = NULL;
  189551. png_free(png_ptr, key);
  189552. return;
  189553. }
  189554. text++;
  189555. png_ptr->zstream.next_in = (png_bytep )text;
  189556. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189557. (text - key));
  189558. png_ptr->zstream.next_out = png_ptr->zbuf;
  189559. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189560. key_size = text - key;
  189561. text_size = 0;
  189562. text = NULL;
  189563. ret = Z_STREAM_END;
  189564. while (png_ptr->zstream.avail_in)
  189565. {
  189566. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189567. if (ret != Z_OK && ret != Z_STREAM_END)
  189568. {
  189569. inflateReset(&png_ptr->zstream);
  189570. png_ptr->zstream.avail_in = 0;
  189571. png_ptr->current_text = NULL;
  189572. png_free(png_ptr, key);
  189573. png_free(png_ptr, text);
  189574. return;
  189575. }
  189576. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189577. {
  189578. if (text == NULL)
  189579. {
  189580. text = (png_charp)png_malloc(png_ptr,
  189581. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189582. + key_size + 1));
  189583. png_memcpy(text + key_size, png_ptr->zbuf,
  189584. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189585. png_memcpy(text, key, key_size);
  189586. text_size = key_size + png_ptr->zbuf_size -
  189587. png_ptr->zstream.avail_out;
  189588. *(text + text_size) = '\0';
  189589. }
  189590. else
  189591. {
  189592. png_charp tmp;
  189593. tmp = text;
  189594. text = (png_charp)png_malloc(png_ptr, text_size +
  189595. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189596. + 1));
  189597. png_memcpy(text, tmp, text_size);
  189598. png_free(png_ptr, tmp);
  189599. png_memcpy(text + text_size, png_ptr->zbuf,
  189600. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189601. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189602. *(text + text_size) = '\0';
  189603. }
  189604. if (ret != Z_STREAM_END)
  189605. {
  189606. png_ptr->zstream.next_out = png_ptr->zbuf;
  189607. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189608. }
  189609. }
  189610. else
  189611. {
  189612. break;
  189613. }
  189614. if (ret == Z_STREAM_END)
  189615. break;
  189616. }
  189617. inflateReset(&png_ptr->zstream);
  189618. png_ptr->zstream.avail_in = 0;
  189619. if (ret != Z_STREAM_END)
  189620. {
  189621. png_ptr->current_text = NULL;
  189622. png_free(png_ptr, key);
  189623. png_free(png_ptr, text);
  189624. return;
  189625. }
  189626. png_ptr->current_text = NULL;
  189627. png_free(png_ptr, key);
  189628. key = text;
  189629. text += key_size;
  189630. text_ptr = (png_textp)png_malloc(png_ptr,
  189631. (png_uint_32)png_sizeof(png_text));
  189632. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189633. text_ptr->key = key;
  189634. #ifdef PNG_iTXt_SUPPORTED
  189635. text_ptr->lang = NULL;
  189636. text_ptr->lang_key = NULL;
  189637. #endif
  189638. text_ptr->text = text;
  189639. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189640. png_free(png_ptr, key);
  189641. png_free(png_ptr, text_ptr);
  189642. if (ret)
  189643. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189644. }
  189645. }
  189646. #endif
  189647. #if defined(PNG_READ_iTXt_SUPPORTED)
  189648. void /* PRIVATE */
  189649. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189650. length)
  189651. {
  189652. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189653. {
  189654. png_error(png_ptr, "Out of place iTXt");
  189655. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189656. }
  189657. #ifdef PNG_MAX_MALLOC_64K
  189658. png_ptr->skip_length = 0; /* This may not be necessary */
  189659. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189660. {
  189661. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189662. png_ptr->skip_length = length - (png_uint_32)65535L;
  189663. length = (png_uint_32)65535L;
  189664. }
  189665. #endif
  189666. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189667. (png_uint_32)(length+1));
  189668. png_ptr->current_text[length] = '\0';
  189669. png_ptr->current_text_ptr = png_ptr->current_text;
  189670. png_ptr->current_text_size = (png_size_t)length;
  189671. png_ptr->current_text_left = (png_size_t)length;
  189672. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189673. }
  189674. void /* PRIVATE */
  189675. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189676. {
  189677. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189678. {
  189679. png_size_t text_size;
  189680. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189681. text_size = png_ptr->buffer_size;
  189682. else
  189683. text_size = png_ptr->current_text_left;
  189684. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189685. png_ptr->current_text_left -= text_size;
  189686. png_ptr->current_text_ptr += text_size;
  189687. }
  189688. if (!(png_ptr->current_text_left))
  189689. {
  189690. png_textp text_ptr;
  189691. png_charp key;
  189692. int comp_flag;
  189693. png_charp lang;
  189694. png_charp lang_key;
  189695. png_charp text;
  189696. int ret;
  189697. if (png_ptr->buffer_size < 4)
  189698. {
  189699. png_push_save_buffer(png_ptr);
  189700. return;
  189701. }
  189702. png_push_crc_finish(png_ptr);
  189703. #if defined(PNG_MAX_MALLOC_64K)
  189704. if (png_ptr->skip_length)
  189705. return;
  189706. #endif
  189707. key = png_ptr->current_text;
  189708. for (lang = key; *lang; lang++)
  189709. /* empty loop */ ;
  189710. if (lang < key + png_ptr->current_text_size - 3)
  189711. lang++;
  189712. comp_flag = *lang++;
  189713. lang++; /* skip comp_type, always zero */
  189714. for (lang_key = lang; *lang_key; lang_key++)
  189715. /* empty loop */ ;
  189716. lang_key++; /* skip NUL separator */
  189717. text=lang_key;
  189718. if (lang_key < key + png_ptr->current_text_size - 1)
  189719. {
  189720. for (; *text; text++)
  189721. /* empty loop */ ;
  189722. }
  189723. if (text < key + png_ptr->current_text_size)
  189724. text++;
  189725. text_ptr = (png_textp)png_malloc(png_ptr,
  189726. (png_uint_32)png_sizeof(png_text));
  189727. text_ptr->compression = comp_flag + 2;
  189728. text_ptr->key = key;
  189729. text_ptr->lang = lang;
  189730. text_ptr->lang_key = lang_key;
  189731. text_ptr->text = text;
  189732. text_ptr->text_length = 0;
  189733. text_ptr->itxt_length = png_strlen(text);
  189734. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189735. png_ptr->current_text = NULL;
  189736. png_free(png_ptr, text_ptr);
  189737. if (ret)
  189738. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189739. }
  189740. }
  189741. #endif
  189742. /* This function is called when we haven't found a handler for this
  189743. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189744. * name or a critical chunk), the chunk is (currently) silently ignored.
  189745. */
  189746. void /* PRIVATE */
  189747. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189748. length)
  189749. {
  189750. png_uint_32 skip=0;
  189751. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189752. if (!(png_ptr->chunk_name[0] & 0x20))
  189753. {
  189754. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189755. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189756. PNG_HANDLE_CHUNK_ALWAYS
  189757. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189758. && png_ptr->read_user_chunk_fn == NULL
  189759. #endif
  189760. )
  189761. #endif
  189762. png_chunk_error(png_ptr, "unknown critical chunk");
  189763. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189764. }
  189765. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189766. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189767. {
  189768. #ifdef PNG_MAX_MALLOC_64K
  189769. if (length > (png_uint_32)65535L)
  189770. {
  189771. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189772. skip = length - (png_uint_32)65535L;
  189773. length = (png_uint_32)65535L;
  189774. }
  189775. #endif
  189776. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189777. (png_charp)png_ptr->chunk_name, 5);
  189778. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189779. png_ptr->unknown_chunk.size = (png_size_t)length;
  189780. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189781. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189782. if(png_ptr->read_user_chunk_fn != NULL)
  189783. {
  189784. /* callback to user unknown chunk handler */
  189785. int ret;
  189786. ret = (*(png_ptr->read_user_chunk_fn))
  189787. (png_ptr, &png_ptr->unknown_chunk);
  189788. if (ret < 0)
  189789. png_chunk_error(png_ptr, "error in user chunk");
  189790. if (ret == 0)
  189791. {
  189792. if (!(png_ptr->chunk_name[0] & 0x20))
  189793. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189794. PNG_HANDLE_CHUNK_ALWAYS)
  189795. png_chunk_error(png_ptr, "unknown critical chunk");
  189796. png_set_unknown_chunks(png_ptr, info_ptr,
  189797. &png_ptr->unknown_chunk, 1);
  189798. }
  189799. }
  189800. #else
  189801. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189802. #endif
  189803. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189804. png_ptr->unknown_chunk.data = NULL;
  189805. }
  189806. else
  189807. #endif
  189808. skip=length;
  189809. png_push_crc_skip(png_ptr, skip);
  189810. }
  189811. void /* PRIVATE */
  189812. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189813. {
  189814. if (png_ptr->info_fn != NULL)
  189815. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189816. }
  189817. void /* PRIVATE */
  189818. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189819. {
  189820. if (png_ptr->end_fn != NULL)
  189821. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189822. }
  189823. void /* PRIVATE */
  189824. png_push_have_row(png_structp png_ptr, png_bytep row)
  189825. {
  189826. if (png_ptr->row_fn != NULL)
  189827. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189828. (int)png_ptr->pass);
  189829. }
  189830. void PNGAPI
  189831. png_progressive_combine_row (png_structp png_ptr,
  189832. png_bytep old_row, png_bytep new_row)
  189833. {
  189834. #ifdef PNG_USE_LOCAL_ARRAYS
  189835. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189836. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189837. #endif
  189838. if(png_ptr == NULL) return;
  189839. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189840. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189841. }
  189842. void PNGAPI
  189843. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189844. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189845. png_progressive_end_ptr end_fn)
  189846. {
  189847. if(png_ptr == NULL) return;
  189848. png_ptr->info_fn = info_fn;
  189849. png_ptr->row_fn = row_fn;
  189850. png_ptr->end_fn = end_fn;
  189851. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189852. }
  189853. png_voidp PNGAPI
  189854. png_get_progressive_ptr(png_structp png_ptr)
  189855. {
  189856. if(png_ptr == NULL) return (NULL);
  189857. return png_ptr->io_ptr;
  189858. }
  189859. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189860. /*** End of inlined file: pngpread.c ***/
  189861. /*** Start of inlined file: pngrio.c ***/
  189862. /* pngrio.c - functions for data input
  189863. *
  189864. * Last changed in libpng 1.2.13 November 13, 2006
  189865. * For conditions of distribution and use, see copyright notice in png.h
  189866. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189867. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189868. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189869. *
  189870. * This file provides a location for all input. Users who need
  189871. * special handling are expected to write a function that has the same
  189872. * arguments as this and performs a similar function, but that possibly
  189873. * has a different input method. Note that you shouldn't change this
  189874. * function, but rather write a replacement function and then make
  189875. * libpng use it at run time with png_set_read_fn(...).
  189876. */
  189877. #define PNG_INTERNAL
  189878. #if defined(PNG_READ_SUPPORTED)
  189879. /* Read the data from whatever input you are using. The default routine
  189880. reads from a file pointer. Note that this routine sometimes gets called
  189881. with very small lengths, so you should implement some kind of simple
  189882. buffering if you are using unbuffered reads. This should never be asked
  189883. to read more then 64K on a 16 bit machine. */
  189884. void /* PRIVATE */
  189885. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189886. {
  189887. png_debug1(4,"reading %d bytes\n", (int)length);
  189888. if (png_ptr->read_data_fn != NULL)
  189889. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189890. else
  189891. png_error(png_ptr, "Call to NULL read function");
  189892. }
  189893. #if !defined(PNG_NO_STDIO)
  189894. /* This is the function that does the actual reading of data. If you are
  189895. not reading from a standard C stream, you should create a replacement
  189896. read_data function and use it at run time with png_set_read_fn(), rather
  189897. than changing the library. */
  189898. #ifndef USE_FAR_KEYWORD
  189899. void PNGAPI
  189900. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189901. {
  189902. png_size_t check;
  189903. if(png_ptr == NULL) return;
  189904. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189905. * instead of an int, which is what fread() actually returns.
  189906. */
  189907. #if defined(_WIN32_WCE)
  189908. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189909. check = 0;
  189910. #else
  189911. check = (png_size_t)fread(data, (png_size_t)1, length,
  189912. (png_FILE_p)png_ptr->io_ptr);
  189913. #endif
  189914. if (check != length)
  189915. png_error(png_ptr, "Read Error");
  189916. }
  189917. #else
  189918. /* this is the model-independent version. Since the standard I/O library
  189919. can't handle far buffers in the medium and small models, we have to copy
  189920. the data.
  189921. */
  189922. #define NEAR_BUF_SIZE 1024
  189923. #define MIN(a,b) (a <= b ? a : b)
  189924. static void PNGAPI
  189925. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189926. {
  189927. int check;
  189928. png_byte *n_data;
  189929. png_FILE_p io_ptr;
  189930. if(png_ptr == NULL) return;
  189931. /* Check if data really is near. If so, use usual code. */
  189932. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189933. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189934. if ((png_bytep)n_data == data)
  189935. {
  189936. #if defined(_WIN32_WCE)
  189937. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189938. check = 0;
  189939. #else
  189940. check = fread(n_data, 1, length, io_ptr);
  189941. #endif
  189942. }
  189943. else
  189944. {
  189945. png_byte buf[NEAR_BUF_SIZE];
  189946. png_size_t read, remaining, err;
  189947. check = 0;
  189948. remaining = length;
  189949. do
  189950. {
  189951. read = MIN(NEAR_BUF_SIZE, remaining);
  189952. #if defined(_WIN32_WCE)
  189953. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189954. err = 0;
  189955. #else
  189956. err = fread(buf, (png_size_t)1, read, io_ptr);
  189957. #endif
  189958. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189959. if(err != read)
  189960. break;
  189961. else
  189962. check += err;
  189963. data += read;
  189964. remaining -= read;
  189965. }
  189966. while (remaining != 0);
  189967. }
  189968. if ((png_uint_32)check != (png_uint_32)length)
  189969. png_error(png_ptr, "read Error");
  189970. }
  189971. #endif
  189972. #endif
  189973. /* This function allows the application to supply a new input function
  189974. for libpng if standard C streams aren't being used.
  189975. This function takes as its arguments:
  189976. png_ptr - pointer to a png input data structure
  189977. io_ptr - pointer to user supplied structure containing info about
  189978. the input functions. May be NULL.
  189979. read_data_fn - pointer to a new input function that takes as its
  189980. arguments a pointer to a png_struct, a pointer to
  189981. a location where input data can be stored, and a 32-bit
  189982. unsigned int that is the number of bytes to be read.
  189983. To exit and output any fatal error messages the new write
  189984. function should call png_error(png_ptr, "Error msg"). */
  189985. void PNGAPI
  189986. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189987. png_rw_ptr read_data_fn)
  189988. {
  189989. if(png_ptr == NULL) return;
  189990. png_ptr->io_ptr = io_ptr;
  189991. #if !defined(PNG_NO_STDIO)
  189992. if (read_data_fn != NULL)
  189993. png_ptr->read_data_fn = read_data_fn;
  189994. else
  189995. png_ptr->read_data_fn = png_default_read_data;
  189996. #else
  189997. png_ptr->read_data_fn = read_data_fn;
  189998. #endif
  189999. /* It is an error to write to a read device */
  190000. if (png_ptr->write_data_fn != NULL)
  190001. {
  190002. png_ptr->write_data_fn = NULL;
  190003. png_warning(png_ptr,
  190004. "It's an error to set both read_data_fn and write_data_fn in the ");
  190005. png_warning(png_ptr,
  190006. "same structure. Resetting write_data_fn to NULL.");
  190007. }
  190008. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190009. png_ptr->output_flush_fn = NULL;
  190010. #endif
  190011. }
  190012. #endif /* PNG_READ_SUPPORTED */
  190013. /*** End of inlined file: pngrio.c ***/
  190014. /*** Start of inlined file: pngrtran.c ***/
  190015. /* pngrtran.c - transforms the data in a row for PNG readers
  190016. *
  190017. * Last changed in libpng 1.2.21 [October 4, 2007]
  190018. * For conditions of distribution and use, see copyright notice in png.h
  190019. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190020. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190021. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190022. *
  190023. * This file contains functions optionally called by an application
  190024. * in order to tell libpng how to handle data when reading a PNG.
  190025. * Transformations that are used in both reading and writing are
  190026. * in pngtrans.c.
  190027. */
  190028. #define PNG_INTERNAL
  190029. #if defined(PNG_READ_SUPPORTED)
  190030. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190031. void PNGAPI
  190032. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190033. {
  190034. png_debug(1, "in png_set_crc_action\n");
  190035. /* Tell libpng how we react to CRC errors in critical chunks */
  190036. if(png_ptr == NULL) return;
  190037. switch (crit_action)
  190038. {
  190039. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190040. break;
  190041. case PNG_CRC_WARN_USE: /* warn/use data */
  190042. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190043. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190044. break;
  190045. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190046. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190047. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190048. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190049. break;
  190050. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190051. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190052. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190053. case PNG_CRC_DEFAULT:
  190054. default:
  190055. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190056. break;
  190057. }
  190058. switch (ancil_action)
  190059. {
  190060. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190061. break;
  190062. case PNG_CRC_WARN_USE: /* warn/use data */
  190063. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190064. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190065. break;
  190066. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190067. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190068. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190069. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190070. break;
  190071. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190072. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190073. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190074. break;
  190075. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190076. case PNG_CRC_DEFAULT:
  190077. default:
  190078. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190079. break;
  190080. }
  190081. }
  190082. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190083. defined(PNG_FLOATING_POINT_SUPPORTED)
  190084. /* handle alpha and tRNS via a background color */
  190085. void PNGAPI
  190086. png_set_background(png_structp png_ptr,
  190087. png_color_16p background_color, int background_gamma_code,
  190088. int need_expand, double background_gamma)
  190089. {
  190090. png_debug(1, "in png_set_background\n");
  190091. if(png_ptr == NULL) return;
  190092. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190093. {
  190094. png_warning(png_ptr, "Application must supply a known background gamma");
  190095. return;
  190096. }
  190097. png_ptr->transformations |= PNG_BACKGROUND;
  190098. png_memcpy(&(png_ptr->background), background_color,
  190099. png_sizeof(png_color_16));
  190100. png_ptr->background_gamma = (float)background_gamma;
  190101. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190102. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190103. }
  190104. #endif
  190105. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190106. /* strip 16 bit depth files to 8 bit depth */
  190107. void PNGAPI
  190108. png_set_strip_16(png_structp png_ptr)
  190109. {
  190110. png_debug(1, "in png_set_strip_16\n");
  190111. if(png_ptr == NULL) return;
  190112. png_ptr->transformations |= PNG_16_TO_8;
  190113. }
  190114. #endif
  190115. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190116. void PNGAPI
  190117. png_set_strip_alpha(png_structp png_ptr)
  190118. {
  190119. png_debug(1, "in png_set_strip_alpha\n");
  190120. if(png_ptr == NULL) return;
  190121. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190122. }
  190123. #endif
  190124. #if defined(PNG_READ_DITHER_SUPPORTED)
  190125. /* Dither file to 8 bit. Supply a palette, the current number
  190126. * of elements in the palette, the maximum number of elements
  190127. * allowed, and a histogram if possible. If the current number
  190128. * of colors is greater then the maximum number, the palette will be
  190129. * modified to fit in the maximum number. "full_dither" indicates
  190130. * whether we need a dithering cube set up for RGB images, or if we
  190131. * simply are reducing the number of colors in a paletted image.
  190132. */
  190133. typedef struct png_dsort_struct
  190134. {
  190135. struct png_dsort_struct FAR * next;
  190136. png_byte left;
  190137. png_byte right;
  190138. } png_dsort;
  190139. typedef png_dsort FAR * png_dsortp;
  190140. typedef png_dsort FAR * FAR * png_dsortpp;
  190141. void PNGAPI
  190142. png_set_dither(png_structp png_ptr, png_colorp palette,
  190143. int num_palette, int maximum_colors, png_uint_16p histogram,
  190144. int full_dither)
  190145. {
  190146. png_debug(1, "in png_set_dither\n");
  190147. if(png_ptr == NULL) return;
  190148. png_ptr->transformations |= PNG_DITHER;
  190149. if (!full_dither)
  190150. {
  190151. int i;
  190152. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190153. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190154. for (i = 0; i < num_palette; i++)
  190155. png_ptr->dither_index[i] = (png_byte)i;
  190156. }
  190157. if (num_palette > maximum_colors)
  190158. {
  190159. if (histogram != NULL)
  190160. {
  190161. /* This is easy enough, just throw out the least used colors.
  190162. Perhaps not the best solution, but good enough. */
  190163. int i;
  190164. /* initialize an array to sort colors */
  190165. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190166. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190167. /* initialize the dither_sort array */
  190168. for (i = 0; i < num_palette; i++)
  190169. png_ptr->dither_sort[i] = (png_byte)i;
  190170. /* Find the least used palette entries by starting a
  190171. bubble sort, and running it until we have sorted
  190172. out enough colors. Note that we don't care about
  190173. sorting all the colors, just finding which are
  190174. least used. */
  190175. for (i = num_palette - 1; i >= maximum_colors; i--)
  190176. {
  190177. int done; /* to stop early if the list is pre-sorted */
  190178. int j;
  190179. done = 1;
  190180. for (j = 0; j < i; j++)
  190181. {
  190182. if (histogram[png_ptr->dither_sort[j]]
  190183. < histogram[png_ptr->dither_sort[j + 1]])
  190184. {
  190185. png_byte t;
  190186. t = png_ptr->dither_sort[j];
  190187. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190188. png_ptr->dither_sort[j + 1] = t;
  190189. done = 0;
  190190. }
  190191. }
  190192. if (done)
  190193. break;
  190194. }
  190195. /* swap the palette around, and set up a table, if necessary */
  190196. if (full_dither)
  190197. {
  190198. int j = num_palette;
  190199. /* put all the useful colors within the max, but don't
  190200. move the others */
  190201. for (i = 0; i < maximum_colors; i++)
  190202. {
  190203. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190204. {
  190205. do
  190206. j--;
  190207. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190208. palette[i] = palette[j];
  190209. }
  190210. }
  190211. }
  190212. else
  190213. {
  190214. int j = num_palette;
  190215. /* move all the used colors inside the max limit, and
  190216. develop a translation table */
  190217. for (i = 0; i < maximum_colors; i++)
  190218. {
  190219. /* only move the colors we need to */
  190220. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190221. {
  190222. png_color tmp_color;
  190223. do
  190224. j--;
  190225. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190226. tmp_color = palette[j];
  190227. palette[j] = palette[i];
  190228. palette[i] = tmp_color;
  190229. /* indicate where the color went */
  190230. png_ptr->dither_index[j] = (png_byte)i;
  190231. png_ptr->dither_index[i] = (png_byte)j;
  190232. }
  190233. }
  190234. /* find closest color for those colors we are not using */
  190235. for (i = 0; i < num_palette; i++)
  190236. {
  190237. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190238. {
  190239. int min_d, k, min_k, d_index;
  190240. /* find the closest color to one we threw out */
  190241. d_index = png_ptr->dither_index[i];
  190242. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190243. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190244. {
  190245. int d;
  190246. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190247. if (d < min_d)
  190248. {
  190249. min_d = d;
  190250. min_k = k;
  190251. }
  190252. }
  190253. /* point to closest color */
  190254. png_ptr->dither_index[i] = (png_byte)min_k;
  190255. }
  190256. }
  190257. }
  190258. png_free(png_ptr, png_ptr->dither_sort);
  190259. png_ptr->dither_sort=NULL;
  190260. }
  190261. else
  190262. {
  190263. /* This is much harder to do simply (and quickly). Perhaps
  190264. we need to go through a median cut routine, but those
  190265. don't always behave themselves with only a few colors
  190266. as input. So we will just find the closest two colors,
  190267. and throw out one of them (chosen somewhat randomly).
  190268. [We don't understand this at all, so if someone wants to
  190269. work on improving it, be our guest - AED, GRP]
  190270. */
  190271. int i;
  190272. int max_d;
  190273. int num_new_palette;
  190274. png_dsortp t;
  190275. png_dsortpp hash;
  190276. t=NULL;
  190277. /* initialize palette index arrays */
  190278. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190279. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190280. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190281. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190282. /* initialize the sort array */
  190283. for (i = 0; i < num_palette; i++)
  190284. {
  190285. png_ptr->index_to_palette[i] = (png_byte)i;
  190286. png_ptr->palette_to_index[i] = (png_byte)i;
  190287. }
  190288. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190289. png_sizeof (png_dsortp)));
  190290. for (i = 0; i < 769; i++)
  190291. hash[i] = NULL;
  190292. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190293. num_new_palette = num_palette;
  190294. /* initial wild guess at how far apart the farthest pixel
  190295. pair we will be eliminating will be. Larger
  190296. numbers mean more areas will be allocated, Smaller
  190297. numbers run the risk of not saving enough data, and
  190298. having to do this all over again.
  190299. I have not done extensive checking on this number.
  190300. */
  190301. max_d = 96;
  190302. while (num_new_palette > maximum_colors)
  190303. {
  190304. for (i = 0; i < num_new_palette - 1; i++)
  190305. {
  190306. int j;
  190307. for (j = i + 1; j < num_new_palette; j++)
  190308. {
  190309. int d;
  190310. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190311. if (d <= max_d)
  190312. {
  190313. t = (png_dsortp)png_malloc_warn(png_ptr,
  190314. (png_uint_32)(png_sizeof(png_dsort)));
  190315. if (t == NULL)
  190316. break;
  190317. t->next = hash[d];
  190318. t->left = (png_byte)i;
  190319. t->right = (png_byte)j;
  190320. hash[d] = t;
  190321. }
  190322. }
  190323. if (t == NULL)
  190324. break;
  190325. }
  190326. if (t != NULL)
  190327. for (i = 0; i <= max_d; i++)
  190328. {
  190329. if (hash[i] != NULL)
  190330. {
  190331. png_dsortp p;
  190332. for (p = hash[i]; p; p = p->next)
  190333. {
  190334. if ((int)png_ptr->index_to_palette[p->left]
  190335. < num_new_palette &&
  190336. (int)png_ptr->index_to_palette[p->right]
  190337. < num_new_palette)
  190338. {
  190339. int j, next_j;
  190340. if (num_new_palette & 0x01)
  190341. {
  190342. j = p->left;
  190343. next_j = p->right;
  190344. }
  190345. else
  190346. {
  190347. j = p->right;
  190348. next_j = p->left;
  190349. }
  190350. num_new_palette--;
  190351. palette[png_ptr->index_to_palette[j]]
  190352. = palette[num_new_palette];
  190353. if (!full_dither)
  190354. {
  190355. int k;
  190356. for (k = 0; k < num_palette; k++)
  190357. {
  190358. if (png_ptr->dither_index[k] ==
  190359. png_ptr->index_to_palette[j])
  190360. png_ptr->dither_index[k] =
  190361. png_ptr->index_to_palette[next_j];
  190362. if ((int)png_ptr->dither_index[k] ==
  190363. num_new_palette)
  190364. png_ptr->dither_index[k] =
  190365. png_ptr->index_to_palette[j];
  190366. }
  190367. }
  190368. png_ptr->index_to_palette[png_ptr->palette_to_index
  190369. [num_new_palette]] = png_ptr->index_to_palette[j];
  190370. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190371. = png_ptr->palette_to_index[num_new_palette];
  190372. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190373. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190374. }
  190375. if (num_new_palette <= maximum_colors)
  190376. break;
  190377. }
  190378. if (num_new_palette <= maximum_colors)
  190379. break;
  190380. }
  190381. }
  190382. for (i = 0; i < 769; i++)
  190383. {
  190384. if (hash[i] != NULL)
  190385. {
  190386. png_dsortp p = hash[i];
  190387. while (p)
  190388. {
  190389. t = p->next;
  190390. png_free(png_ptr, p);
  190391. p = t;
  190392. }
  190393. }
  190394. hash[i] = 0;
  190395. }
  190396. max_d += 96;
  190397. }
  190398. png_free(png_ptr, hash);
  190399. png_free(png_ptr, png_ptr->palette_to_index);
  190400. png_free(png_ptr, png_ptr->index_to_palette);
  190401. png_ptr->palette_to_index=NULL;
  190402. png_ptr->index_to_palette=NULL;
  190403. }
  190404. num_palette = maximum_colors;
  190405. }
  190406. if (png_ptr->palette == NULL)
  190407. {
  190408. png_ptr->palette = palette;
  190409. }
  190410. png_ptr->num_palette = (png_uint_16)num_palette;
  190411. if (full_dither)
  190412. {
  190413. int i;
  190414. png_bytep distance;
  190415. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190416. PNG_DITHER_BLUE_BITS;
  190417. int num_red = (1 << PNG_DITHER_RED_BITS);
  190418. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190419. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190420. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190421. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190422. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190423. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190424. png_sizeof (png_byte));
  190425. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190426. png_sizeof(png_byte)));
  190427. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190428. for (i = 0; i < num_palette; i++)
  190429. {
  190430. int ir, ig, ib;
  190431. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190432. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190433. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190434. for (ir = 0; ir < num_red; ir++)
  190435. {
  190436. /* int dr = abs(ir - r); */
  190437. int dr = ((ir > r) ? ir - r : r - ir);
  190438. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190439. for (ig = 0; ig < num_green; ig++)
  190440. {
  190441. /* int dg = abs(ig - g); */
  190442. int dg = ((ig > g) ? ig - g : g - ig);
  190443. int dt = dr + dg;
  190444. int dm = ((dr > dg) ? dr : dg);
  190445. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190446. for (ib = 0; ib < num_blue; ib++)
  190447. {
  190448. int d_index = index_g | ib;
  190449. /* int db = abs(ib - b); */
  190450. int db = ((ib > b) ? ib - b : b - ib);
  190451. int dmax = ((dm > db) ? dm : db);
  190452. int d = dmax + dt + db;
  190453. if (d < (int)distance[d_index])
  190454. {
  190455. distance[d_index] = (png_byte)d;
  190456. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190457. }
  190458. }
  190459. }
  190460. }
  190461. }
  190462. png_free(png_ptr, distance);
  190463. }
  190464. }
  190465. #endif
  190466. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190467. /* Transform the image from the file_gamma to the screen_gamma. We
  190468. * only do transformations on images where the file_gamma and screen_gamma
  190469. * are not close reciprocals, otherwise it slows things down slightly, and
  190470. * also needlessly introduces small errors.
  190471. *
  190472. * We will turn off gamma transformation later if no semitransparent entries
  190473. * are present in the tRNS array for palette images. We can't do it here
  190474. * because we don't necessarily have the tRNS chunk yet.
  190475. */
  190476. void PNGAPI
  190477. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190478. {
  190479. png_debug(1, "in png_set_gamma\n");
  190480. if(png_ptr == NULL) return;
  190481. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190482. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190483. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190484. png_ptr->transformations |= PNG_GAMMA;
  190485. png_ptr->gamma = (float)file_gamma;
  190486. png_ptr->screen_gamma = (float)scrn_gamma;
  190487. }
  190488. #endif
  190489. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190490. /* Expand paletted images to RGB, expand grayscale images of
  190491. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190492. * to alpha channels.
  190493. */
  190494. void PNGAPI
  190495. png_set_expand(png_structp png_ptr)
  190496. {
  190497. png_debug(1, "in png_set_expand\n");
  190498. if(png_ptr == NULL) return;
  190499. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190500. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190501. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190502. #endif
  190503. }
  190504. /* GRR 19990627: the following three functions currently are identical
  190505. * to png_set_expand(). However, it is entirely reasonable that someone
  190506. * might wish to expand an indexed image to RGB but *not* expand a single,
  190507. * fully transparent palette entry to a full alpha channel--perhaps instead
  190508. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190509. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190510. * IOW, a future version of the library may make the transformations flag
  190511. * a bit more fine-grained, with separate bits for each of these three
  190512. * functions.
  190513. *
  190514. * More to the point, these functions make it obvious what libpng will be
  190515. * doing, whereas "expand" can (and does) mean any number of things.
  190516. *
  190517. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190518. * to expand only the sample depth but not to expand the tRNS to alpha.
  190519. */
  190520. /* Expand paletted images to RGB. */
  190521. void PNGAPI
  190522. png_set_palette_to_rgb(png_structp png_ptr)
  190523. {
  190524. png_debug(1, "in png_set_palette_to_rgb\n");
  190525. if(png_ptr == NULL) return;
  190526. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190527. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190528. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190529. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190530. #endif
  190531. }
  190532. #if !defined(PNG_1_0_X)
  190533. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190534. void PNGAPI
  190535. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190536. {
  190537. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190538. if(png_ptr == NULL) return;
  190539. png_ptr->transformations |= PNG_EXPAND;
  190540. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190541. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190542. #endif
  190543. }
  190544. #endif
  190545. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190546. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190547. /* Deprecated as of libpng-1.2.9 */
  190548. void PNGAPI
  190549. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190550. {
  190551. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190552. if(png_ptr == NULL) return;
  190553. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190554. }
  190555. #endif
  190556. /* Expand tRNS chunks to alpha channels. */
  190557. void PNGAPI
  190558. png_set_tRNS_to_alpha(png_structp png_ptr)
  190559. {
  190560. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190561. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190562. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190563. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190564. #endif
  190565. }
  190566. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190567. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190568. void PNGAPI
  190569. png_set_gray_to_rgb(png_structp png_ptr)
  190570. {
  190571. png_debug(1, "in png_set_gray_to_rgb\n");
  190572. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190573. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190574. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190575. #endif
  190576. }
  190577. #endif
  190578. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190579. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190580. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190581. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190582. */
  190583. void PNGAPI
  190584. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190585. double green)
  190586. {
  190587. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190588. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190589. if(png_ptr == NULL) return;
  190590. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190591. }
  190592. #endif
  190593. void PNGAPI
  190594. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190595. png_fixed_point red, png_fixed_point green)
  190596. {
  190597. png_debug(1, "in png_set_rgb_to_gray\n");
  190598. if(png_ptr == NULL) return;
  190599. switch(error_action)
  190600. {
  190601. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190602. break;
  190603. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190604. break;
  190605. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190606. }
  190607. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190608. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190609. png_ptr->transformations |= PNG_EXPAND;
  190610. #else
  190611. {
  190612. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190613. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190614. }
  190615. #endif
  190616. {
  190617. png_uint_16 red_int, green_int;
  190618. if(red < 0 || green < 0)
  190619. {
  190620. red_int = 6968; /* .212671 * 32768 + .5 */
  190621. green_int = 23434; /* .715160 * 32768 + .5 */
  190622. }
  190623. else if(red + green < 100000L)
  190624. {
  190625. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190626. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190627. }
  190628. else
  190629. {
  190630. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190631. red_int = 6968;
  190632. green_int = 23434;
  190633. }
  190634. png_ptr->rgb_to_gray_red_coeff = red_int;
  190635. png_ptr->rgb_to_gray_green_coeff = green_int;
  190636. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190637. }
  190638. }
  190639. #endif
  190640. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190641. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190642. defined(PNG_LEGACY_SUPPORTED)
  190643. void PNGAPI
  190644. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190645. read_user_transform_fn)
  190646. {
  190647. png_debug(1, "in png_set_read_user_transform_fn\n");
  190648. if(png_ptr == NULL) return;
  190649. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190650. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190651. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190652. #endif
  190653. #ifdef PNG_LEGACY_SUPPORTED
  190654. if(read_user_transform_fn)
  190655. png_warning(png_ptr,
  190656. "This version of libpng does not support user transforms");
  190657. #endif
  190658. }
  190659. #endif
  190660. /* Initialize everything needed for the read. This includes modifying
  190661. * the palette.
  190662. */
  190663. void /* PRIVATE */
  190664. png_init_read_transformations(png_structp png_ptr)
  190665. {
  190666. png_debug(1, "in png_init_read_transformations\n");
  190667. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190668. if(png_ptr != NULL)
  190669. #endif
  190670. {
  190671. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190672. || defined(PNG_READ_GAMMA_SUPPORTED)
  190673. int color_type = png_ptr->color_type;
  190674. #endif
  190675. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190676. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190677. /* Detect gray background and attempt to enable optimization
  190678. * for gray --> RGB case */
  190679. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190680. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190681. * background color might actually be gray yet not be flagged as such.
  190682. * This is not a problem for the current code, which uses
  190683. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190684. * png_do_gray_to_rgb() transformation.
  190685. */
  190686. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190687. !(color_type & PNG_COLOR_MASK_COLOR))
  190688. {
  190689. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190690. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190691. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190692. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190693. png_ptr->background.red == png_ptr->background.green &&
  190694. png_ptr->background.red == png_ptr->background.blue)
  190695. {
  190696. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190697. png_ptr->background.gray = png_ptr->background.red;
  190698. }
  190699. #endif
  190700. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190701. (png_ptr->transformations & PNG_EXPAND))
  190702. {
  190703. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190704. {
  190705. /* expand background and tRNS chunks */
  190706. switch (png_ptr->bit_depth)
  190707. {
  190708. case 1:
  190709. png_ptr->background.gray *= (png_uint_16)0xff;
  190710. png_ptr->background.red = png_ptr->background.green
  190711. = png_ptr->background.blue = png_ptr->background.gray;
  190712. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190713. {
  190714. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190715. png_ptr->trans_values.red = png_ptr->trans_values.green
  190716. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190717. }
  190718. break;
  190719. case 2:
  190720. png_ptr->background.gray *= (png_uint_16)0x55;
  190721. png_ptr->background.red = png_ptr->background.green
  190722. = png_ptr->background.blue = png_ptr->background.gray;
  190723. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190724. {
  190725. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190726. png_ptr->trans_values.red = png_ptr->trans_values.green
  190727. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190728. }
  190729. break;
  190730. case 4:
  190731. png_ptr->background.gray *= (png_uint_16)0x11;
  190732. png_ptr->background.red = png_ptr->background.green
  190733. = png_ptr->background.blue = png_ptr->background.gray;
  190734. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190735. {
  190736. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190737. png_ptr->trans_values.red = png_ptr->trans_values.green
  190738. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190739. }
  190740. break;
  190741. case 8:
  190742. case 16:
  190743. png_ptr->background.red = png_ptr->background.green
  190744. = png_ptr->background.blue = png_ptr->background.gray;
  190745. break;
  190746. }
  190747. }
  190748. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190749. {
  190750. png_ptr->background.red =
  190751. png_ptr->palette[png_ptr->background.index].red;
  190752. png_ptr->background.green =
  190753. png_ptr->palette[png_ptr->background.index].green;
  190754. png_ptr->background.blue =
  190755. png_ptr->palette[png_ptr->background.index].blue;
  190756. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190757. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190758. {
  190759. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190760. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190761. #endif
  190762. {
  190763. /* invert the alpha channel (in tRNS) unless the pixels are
  190764. going to be expanded, in which case leave it for later */
  190765. int i,istop;
  190766. istop=(int)png_ptr->num_trans;
  190767. for (i=0; i<istop; i++)
  190768. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190769. }
  190770. }
  190771. #endif
  190772. }
  190773. }
  190774. #endif
  190775. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190776. png_ptr->background_1 = png_ptr->background;
  190777. #endif
  190778. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190779. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190780. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190781. < PNG_GAMMA_THRESHOLD))
  190782. {
  190783. int i,k;
  190784. k=0;
  190785. for (i=0; i<png_ptr->num_trans; i++)
  190786. {
  190787. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190788. k=1; /* partial transparency is present */
  190789. }
  190790. if (k == 0)
  190791. png_ptr->transformations &= (~PNG_GAMMA);
  190792. }
  190793. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190794. png_ptr->gamma != 0.0)
  190795. {
  190796. png_build_gamma_table(png_ptr);
  190797. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190798. if (png_ptr->transformations & PNG_BACKGROUND)
  190799. {
  190800. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190801. {
  190802. /* could skip if no transparency and
  190803. */
  190804. png_color back, back_1;
  190805. png_colorp palette = png_ptr->palette;
  190806. int num_palette = png_ptr->num_palette;
  190807. int i;
  190808. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190809. {
  190810. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190811. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190812. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190813. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190814. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190815. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190816. }
  190817. else
  190818. {
  190819. double g, gs;
  190820. switch (png_ptr->background_gamma_type)
  190821. {
  190822. case PNG_BACKGROUND_GAMMA_SCREEN:
  190823. g = (png_ptr->screen_gamma);
  190824. gs = 1.0;
  190825. break;
  190826. case PNG_BACKGROUND_GAMMA_FILE:
  190827. g = 1.0 / (png_ptr->gamma);
  190828. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190829. break;
  190830. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190831. g = 1.0 / (png_ptr->background_gamma);
  190832. gs = 1.0 / (png_ptr->background_gamma *
  190833. png_ptr->screen_gamma);
  190834. break;
  190835. default:
  190836. g = 1.0; /* back_1 */
  190837. gs = 1.0; /* back */
  190838. }
  190839. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190840. {
  190841. back.red = (png_byte)png_ptr->background.red;
  190842. back.green = (png_byte)png_ptr->background.green;
  190843. back.blue = (png_byte)png_ptr->background.blue;
  190844. }
  190845. else
  190846. {
  190847. back.red = (png_byte)(pow(
  190848. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190849. back.green = (png_byte)(pow(
  190850. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190851. back.blue = (png_byte)(pow(
  190852. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190853. }
  190854. back_1.red = (png_byte)(pow(
  190855. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190856. back_1.green = (png_byte)(pow(
  190857. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190858. back_1.blue = (png_byte)(pow(
  190859. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190860. }
  190861. for (i = 0; i < num_palette; i++)
  190862. {
  190863. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190864. {
  190865. if (png_ptr->trans[i] == 0)
  190866. {
  190867. palette[i] = back;
  190868. }
  190869. else /* if (png_ptr->trans[i] != 0xff) */
  190870. {
  190871. png_byte v, w;
  190872. v = png_ptr->gamma_to_1[palette[i].red];
  190873. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190874. palette[i].red = png_ptr->gamma_from_1[w];
  190875. v = png_ptr->gamma_to_1[palette[i].green];
  190876. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190877. palette[i].green = png_ptr->gamma_from_1[w];
  190878. v = png_ptr->gamma_to_1[palette[i].blue];
  190879. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190880. palette[i].blue = png_ptr->gamma_from_1[w];
  190881. }
  190882. }
  190883. else
  190884. {
  190885. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190886. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190887. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190888. }
  190889. }
  190890. }
  190891. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190892. else
  190893. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190894. {
  190895. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190896. double g = 1.0;
  190897. double gs = 1.0;
  190898. switch (png_ptr->background_gamma_type)
  190899. {
  190900. case PNG_BACKGROUND_GAMMA_SCREEN:
  190901. g = (png_ptr->screen_gamma);
  190902. gs = 1.0;
  190903. break;
  190904. case PNG_BACKGROUND_GAMMA_FILE:
  190905. g = 1.0 / (png_ptr->gamma);
  190906. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190907. break;
  190908. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190909. g = 1.0 / (png_ptr->background_gamma);
  190910. gs = 1.0 / (png_ptr->background_gamma *
  190911. png_ptr->screen_gamma);
  190912. break;
  190913. }
  190914. png_ptr->background_1.gray = (png_uint_16)(pow(
  190915. (double)png_ptr->background.gray / m, g) * m + .5);
  190916. png_ptr->background.gray = (png_uint_16)(pow(
  190917. (double)png_ptr->background.gray / m, gs) * m + .5);
  190918. if ((png_ptr->background.red != png_ptr->background.green) ||
  190919. (png_ptr->background.red != png_ptr->background.blue) ||
  190920. (png_ptr->background.red != png_ptr->background.gray))
  190921. {
  190922. /* RGB or RGBA with color background */
  190923. png_ptr->background_1.red = (png_uint_16)(pow(
  190924. (double)png_ptr->background.red / m, g) * m + .5);
  190925. png_ptr->background_1.green = (png_uint_16)(pow(
  190926. (double)png_ptr->background.green / m, g) * m + .5);
  190927. png_ptr->background_1.blue = (png_uint_16)(pow(
  190928. (double)png_ptr->background.blue / m, g) * m + .5);
  190929. png_ptr->background.red = (png_uint_16)(pow(
  190930. (double)png_ptr->background.red / m, gs) * m + .5);
  190931. png_ptr->background.green = (png_uint_16)(pow(
  190932. (double)png_ptr->background.green / m, gs) * m + .5);
  190933. png_ptr->background.blue = (png_uint_16)(pow(
  190934. (double)png_ptr->background.blue / m, gs) * m + .5);
  190935. }
  190936. else
  190937. {
  190938. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190939. png_ptr->background_1.red = png_ptr->background_1.green
  190940. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190941. png_ptr->background.red = png_ptr->background.green
  190942. = png_ptr->background.blue = png_ptr->background.gray;
  190943. }
  190944. }
  190945. }
  190946. else
  190947. /* transformation does not include PNG_BACKGROUND */
  190948. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190949. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190950. {
  190951. png_colorp palette = png_ptr->palette;
  190952. int num_palette = png_ptr->num_palette;
  190953. int i;
  190954. for (i = 0; i < num_palette; i++)
  190955. {
  190956. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190957. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190958. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190959. }
  190960. }
  190961. }
  190962. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190963. else
  190964. #endif
  190965. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190966. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190967. /* No GAMMA transformation */
  190968. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190969. (color_type == PNG_COLOR_TYPE_PALETTE))
  190970. {
  190971. int i;
  190972. int istop = (int)png_ptr->num_trans;
  190973. png_color back;
  190974. png_colorp palette = png_ptr->palette;
  190975. back.red = (png_byte)png_ptr->background.red;
  190976. back.green = (png_byte)png_ptr->background.green;
  190977. back.blue = (png_byte)png_ptr->background.blue;
  190978. for (i = 0; i < istop; i++)
  190979. {
  190980. if (png_ptr->trans[i] == 0)
  190981. {
  190982. palette[i] = back;
  190983. }
  190984. else if (png_ptr->trans[i] != 0xff)
  190985. {
  190986. /* The png_composite() macro is defined in png.h */
  190987. png_composite(palette[i].red, palette[i].red,
  190988. png_ptr->trans[i], back.red);
  190989. png_composite(palette[i].green, palette[i].green,
  190990. png_ptr->trans[i], back.green);
  190991. png_composite(palette[i].blue, palette[i].blue,
  190992. png_ptr->trans[i], back.blue);
  190993. }
  190994. }
  190995. }
  190996. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190997. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190998. if ((png_ptr->transformations & PNG_SHIFT) &&
  190999. (color_type == PNG_COLOR_TYPE_PALETTE))
  191000. {
  191001. png_uint_16 i;
  191002. png_uint_16 istop = png_ptr->num_palette;
  191003. int sr = 8 - png_ptr->sig_bit.red;
  191004. int sg = 8 - png_ptr->sig_bit.green;
  191005. int sb = 8 - png_ptr->sig_bit.blue;
  191006. if (sr < 0 || sr > 8)
  191007. sr = 0;
  191008. if (sg < 0 || sg > 8)
  191009. sg = 0;
  191010. if (sb < 0 || sb > 8)
  191011. sb = 0;
  191012. for (i = 0; i < istop; i++)
  191013. {
  191014. png_ptr->palette[i].red >>= sr;
  191015. png_ptr->palette[i].green >>= sg;
  191016. png_ptr->palette[i].blue >>= sb;
  191017. }
  191018. }
  191019. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191020. }
  191021. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191022. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191023. if(png_ptr)
  191024. return;
  191025. #endif
  191026. }
  191027. /* Modify the info structure to reflect the transformations. The
  191028. * info should be updated so a PNG file could be written with it,
  191029. * assuming the transformations result in valid PNG data.
  191030. */
  191031. void /* PRIVATE */
  191032. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191033. {
  191034. png_debug(1, "in png_read_transform_info\n");
  191035. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191036. if (png_ptr->transformations & PNG_EXPAND)
  191037. {
  191038. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191039. {
  191040. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191041. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191042. else
  191043. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191044. info_ptr->bit_depth = 8;
  191045. info_ptr->num_trans = 0;
  191046. }
  191047. else
  191048. {
  191049. if (png_ptr->num_trans)
  191050. {
  191051. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191052. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191053. else
  191054. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191055. }
  191056. if (info_ptr->bit_depth < 8)
  191057. info_ptr->bit_depth = 8;
  191058. info_ptr->num_trans = 0;
  191059. }
  191060. }
  191061. #endif
  191062. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191063. if (png_ptr->transformations & PNG_BACKGROUND)
  191064. {
  191065. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191066. info_ptr->num_trans = 0;
  191067. info_ptr->background = png_ptr->background;
  191068. }
  191069. #endif
  191070. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191071. if (png_ptr->transformations & PNG_GAMMA)
  191072. {
  191073. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191074. info_ptr->gamma = png_ptr->gamma;
  191075. #endif
  191076. #ifdef PNG_FIXED_POINT_SUPPORTED
  191077. info_ptr->int_gamma = png_ptr->int_gamma;
  191078. #endif
  191079. }
  191080. #endif
  191081. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191082. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191083. info_ptr->bit_depth = 8;
  191084. #endif
  191085. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191086. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191087. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191088. #endif
  191089. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191090. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191091. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191092. #endif
  191093. #if defined(PNG_READ_DITHER_SUPPORTED)
  191094. if (png_ptr->transformations & PNG_DITHER)
  191095. {
  191096. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191097. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191098. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191099. {
  191100. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191101. }
  191102. }
  191103. #endif
  191104. #if defined(PNG_READ_PACK_SUPPORTED)
  191105. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191106. info_ptr->bit_depth = 8;
  191107. #endif
  191108. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191109. info_ptr->channels = 1;
  191110. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191111. info_ptr->channels = 3;
  191112. else
  191113. info_ptr->channels = 1;
  191114. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191115. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191116. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191117. #endif
  191118. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191119. info_ptr->channels++;
  191120. #if defined(PNG_READ_FILLER_SUPPORTED)
  191121. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191122. if ((png_ptr->transformations & PNG_FILLER) &&
  191123. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191124. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191125. {
  191126. info_ptr->channels++;
  191127. /* if adding a true alpha channel not just filler */
  191128. #if !defined(PNG_1_0_X)
  191129. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191130. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191131. #endif
  191132. }
  191133. #endif
  191134. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191135. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191136. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191137. {
  191138. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191139. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191140. if(info_ptr->channels < png_ptr->user_transform_channels)
  191141. info_ptr->channels = png_ptr->user_transform_channels;
  191142. }
  191143. #endif
  191144. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191145. info_ptr->bit_depth);
  191146. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191147. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191148. if(png_ptr)
  191149. return;
  191150. #endif
  191151. }
  191152. /* Transform the row. The order of transformations is significant,
  191153. * and is very touchy. If you add a transformation, take care to
  191154. * decide how it fits in with the other transformations here.
  191155. */
  191156. void /* PRIVATE */
  191157. png_do_read_transformations(png_structp png_ptr)
  191158. {
  191159. png_debug(1, "in png_do_read_transformations\n");
  191160. if (png_ptr->row_buf == NULL)
  191161. {
  191162. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191163. char msg[50];
  191164. png_snprintf2(msg, 50,
  191165. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191166. png_ptr->pass);
  191167. png_error(png_ptr, msg);
  191168. #else
  191169. png_error(png_ptr, "NULL row buffer");
  191170. #endif
  191171. }
  191172. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191173. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191174. /* Application has failed to call either png_read_start_image()
  191175. * or png_read_update_info() after setting transforms that expand
  191176. * pixels. This check added to libpng-1.2.19 */
  191177. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191178. png_error(png_ptr, "Uninitialized row");
  191179. #else
  191180. png_warning(png_ptr, "Uninitialized row");
  191181. #endif
  191182. #endif
  191183. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191184. if (png_ptr->transformations & PNG_EXPAND)
  191185. {
  191186. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191187. {
  191188. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191189. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191190. }
  191191. else
  191192. {
  191193. if (png_ptr->num_trans &&
  191194. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191195. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191196. &(png_ptr->trans_values));
  191197. else
  191198. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191199. NULL);
  191200. }
  191201. }
  191202. #endif
  191203. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191204. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191205. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191206. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191207. #endif
  191208. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191209. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191210. {
  191211. int rgb_error =
  191212. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191213. if(rgb_error)
  191214. {
  191215. png_ptr->rgb_to_gray_status=1;
  191216. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191217. PNG_RGB_TO_GRAY_WARN)
  191218. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191219. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191220. PNG_RGB_TO_GRAY_ERR)
  191221. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191222. }
  191223. }
  191224. #endif
  191225. /*
  191226. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191227. In most cases, the "simple transparency" should be done prior to doing
  191228. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191229. pixel is transparent. You would also need to make sure that the
  191230. transparency information is upgraded to RGB.
  191231. To summarize, the current flow is:
  191232. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191233. with background "in place" if transparent,
  191234. convert to RGB if necessary
  191235. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191236. convert to RGB if necessary
  191237. To support RGB backgrounds for gray images we need:
  191238. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191239. 3 or 6 bytes and composite with background
  191240. "in place" if transparent (3x compare/pixel
  191241. compared to doing composite with gray bkgrnd)
  191242. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191243. remove alpha bytes (3x float operations/pixel
  191244. compared with composite on gray background)
  191245. Greg's change will do this. The reason it wasn't done before is for
  191246. performance, as this increases the per-pixel operations. If we would check
  191247. in advance if the background was gray or RGB, and position the gray-to-RGB
  191248. transform appropriately, then it would save a lot of work/time.
  191249. */
  191250. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191251. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191252. * for performance reasons */
  191253. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191254. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191255. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191256. #endif
  191257. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191258. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191259. ((png_ptr->num_trans != 0 ) ||
  191260. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191261. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191262. &(png_ptr->trans_values), &(png_ptr->background)
  191263. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191264. , &(png_ptr->background_1),
  191265. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191266. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191267. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191268. png_ptr->gamma_shift
  191269. #endif
  191270. );
  191271. #endif
  191272. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191273. if ((png_ptr->transformations & PNG_GAMMA) &&
  191274. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191275. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191276. ((png_ptr->num_trans != 0) ||
  191277. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191278. #endif
  191279. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191280. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191281. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191282. png_ptr->gamma_shift);
  191283. #endif
  191284. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191285. if (png_ptr->transformations & PNG_16_TO_8)
  191286. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191287. #endif
  191288. #if defined(PNG_READ_DITHER_SUPPORTED)
  191289. if (png_ptr->transformations & PNG_DITHER)
  191290. {
  191291. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191292. png_ptr->palette_lookup, png_ptr->dither_index);
  191293. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191294. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191295. }
  191296. #endif
  191297. #if defined(PNG_READ_INVERT_SUPPORTED)
  191298. if (png_ptr->transformations & PNG_INVERT_MONO)
  191299. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191300. #endif
  191301. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191302. if (png_ptr->transformations & PNG_SHIFT)
  191303. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191304. &(png_ptr->shift));
  191305. #endif
  191306. #if defined(PNG_READ_PACK_SUPPORTED)
  191307. if (png_ptr->transformations & PNG_PACK)
  191308. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191309. #endif
  191310. #if defined(PNG_READ_BGR_SUPPORTED)
  191311. if (png_ptr->transformations & PNG_BGR)
  191312. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191313. #endif
  191314. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191315. if (png_ptr->transformations & PNG_PACKSWAP)
  191316. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191317. #endif
  191318. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191319. /* if gray -> RGB, do so now only if we did not do so above */
  191320. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191321. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191322. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191323. #endif
  191324. #if defined(PNG_READ_FILLER_SUPPORTED)
  191325. if (png_ptr->transformations & PNG_FILLER)
  191326. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191327. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191328. #endif
  191329. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191330. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191331. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191332. #endif
  191333. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191334. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191335. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191336. #endif
  191337. #if defined(PNG_READ_SWAP_SUPPORTED)
  191338. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191339. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191340. #endif
  191341. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191342. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191343. {
  191344. if(png_ptr->read_user_transform_fn != NULL)
  191345. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191346. (png_ptr, /* png_ptr */
  191347. &(png_ptr->row_info), /* row_info: */
  191348. /* png_uint_32 width; width of row */
  191349. /* png_uint_32 rowbytes; number of bytes in row */
  191350. /* png_byte color_type; color type of pixels */
  191351. /* png_byte bit_depth; bit depth of samples */
  191352. /* png_byte channels; number of channels (1-4) */
  191353. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191354. png_ptr->row_buf + 1); /* start of pixel data for row */
  191355. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191356. if(png_ptr->user_transform_depth)
  191357. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191358. if(png_ptr->user_transform_channels)
  191359. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191360. #endif
  191361. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191362. png_ptr->row_info.channels);
  191363. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191364. png_ptr->row_info.width);
  191365. }
  191366. #endif
  191367. }
  191368. #if defined(PNG_READ_PACK_SUPPORTED)
  191369. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191370. * without changing the actual values. Thus, if you had a row with
  191371. * a bit depth of 1, you would end up with bytes that only contained
  191372. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191373. * png_do_shift() after this.
  191374. */
  191375. void /* PRIVATE */
  191376. png_do_unpack(png_row_infop row_info, png_bytep row)
  191377. {
  191378. png_debug(1, "in png_do_unpack\n");
  191379. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191380. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191381. #else
  191382. if (row_info->bit_depth < 8)
  191383. #endif
  191384. {
  191385. png_uint_32 i;
  191386. png_uint_32 row_width=row_info->width;
  191387. switch (row_info->bit_depth)
  191388. {
  191389. case 1:
  191390. {
  191391. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191392. png_bytep dp = row + (png_size_t)row_width - 1;
  191393. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191394. for (i = 0; i < row_width; i++)
  191395. {
  191396. *dp = (png_byte)((*sp >> shift) & 0x01);
  191397. if (shift == 7)
  191398. {
  191399. shift = 0;
  191400. sp--;
  191401. }
  191402. else
  191403. shift++;
  191404. dp--;
  191405. }
  191406. break;
  191407. }
  191408. case 2:
  191409. {
  191410. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191411. png_bytep dp = row + (png_size_t)row_width - 1;
  191412. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191413. for (i = 0; i < row_width; i++)
  191414. {
  191415. *dp = (png_byte)((*sp >> shift) & 0x03);
  191416. if (shift == 6)
  191417. {
  191418. shift = 0;
  191419. sp--;
  191420. }
  191421. else
  191422. shift += 2;
  191423. dp--;
  191424. }
  191425. break;
  191426. }
  191427. case 4:
  191428. {
  191429. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191430. png_bytep dp = row + (png_size_t)row_width - 1;
  191431. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191432. for (i = 0; i < row_width; i++)
  191433. {
  191434. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191435. if (shift == 4)
  191436. {
  191437. shift = 0;
  191438. sp--;
  191439. }
  191440. else
  191441. shift = 4;
  191442. dp--;
  191443. }
  191444. break;
  191445. }
  191446. }
  191447. row_info->bit_depth = 8;
  191448. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191449. row_info->rowbytes = row_width * row_info->channels;
  191450. }
  191451. }
  191452. #endif
  191453. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191454. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191455. * pixels back to their significant bits values. Thus, if you have
  191456. * a row of bit depth 8, but only 5 are significant, this will shift
  191457. * the values back to 0 through 31.
  191458. */
  191459. void /* PRIVATE */
  191460. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191461. {
  191462. png_debug(1, "in png_do_unshift\n");
  191463. if (
  191464. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191465. row != NULL && row_info != NULL && sig_bits != NULL &&
  191466. #endif
  191467. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191468. {
  191469. int shift[4];
  191470. int channels = 0;
  191471. int c;
  191472. png_uint_16 value = 0;
  191473. png_uint_32 row_width = row_info->width;
  191474. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191475. {
  191476. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191477. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191478. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191479. }
  191480. else
  191481. {
  191482. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191483. }
  191484. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191485. {
  191486. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191487. }
  191488. for (c = 0; c < channels; c++)
  191489. {
  191490. if (shift[c] <= 0)
  191491. shift[c] = 0;
  191492. else
  191493. value = 1;
  191494. }
  191495. if (!value)
  191496. return;
  191497. switch (row_info->bit_depth)
  191498. {
  191499. case 2:
  191500. {
  191501. png_bytep bp;
  191502. png_uint_32 i;
  191503. png_uint_32 istop = row_info->rowbytes;
  191504. for (bp = row, i = 0; i < istop; i++)
  191505. {
  191506. *bp >>= 1;
  191507. *bp++ &= 0x55;
  191508. }
  191509. break;
  191510. }
  191511. case 4:
  191512. {
  191513. png_bytep bp = row;
  191514. png_uint_32 i;
  191515. png_uint_32 istop = row_info->rowbytes;
  191516. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191517. (png_byte)((int)0xf >> shift[0]));
  191518. for (i = 0; i < istop; i++)
  191519. {
  191520. *bp >>= shift[0];
  191521. *bp++ &= mask;
  191522. }
  191523. break;
  191524. }
  191525. case 8:
  191526. {
  191527. png_bytep bp = row;
  191528. png_uint_32 i;
  191529. png_uint_32 istop = row_width * channels;
  191530. for (i = 0; i < istop; i++)
  191531. {
  191532. *bp++ >>= shift[i%channels];
  191533. }
  191534. break;
  191535. }
  191536. case 16:
  191537. {
  191538. png_bytep bp = row;
  191539. png_uint_32 i;
  191540. png_uint_32 istop = channels * row_width;
  191541. for (i = 0; i < istop; i++)
  191542. {
  191543. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191544. value >>= shift[i%channels];
  191545. *bp++ = (png_byte)(value >> 8);
  191546. *bp++ = (png_byte)(value & 0xff);
  191547. }
  191548. break;
  191549. }
  191550. }
  191551. }
  191552. }
  191553. #endif
  191554. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191555. /* chop rows of bit depth 16 down to 8 */
  191556. void /* PRIVATE */
  191557. png_do_chop(png_row_infop row_info, png_bytep row)
  191558. {
  191559. png_debug(1, "in png_do_chop\n");
  191560. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191561. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191562. #else
  191563. if (row_info->bit_depth == 16)
  191564. #endif
  191565. {
  191566. png_bytep sp = row;
  191567. png_bytep dp = row;
  191568. png_uint_32 i;
  191569. png_uint_32 istop = row_info->width * row_info->channels;
  191570. for (i = 0; i<istop; i++, sp += 2, dp++)
  191571. {
  191572. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191573. /* This does a more accurate scaling of the 16-bit color
  191574. * value, rather than a simple low-byte truncation.
  191575. *
  191576. * What the ideal calculation should be:
  191577. * *dp = (((((png_uint_32)(*sp) << 8) |
  191578. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191579. *
  191580. * GRR: no, I think this is what it really should be:
  191581. * *dp = (((((png_uint_32)(*sp) << 8) |
  191582. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191583. *
  191584. * GRR: here's the exact calculation with shifts:
  191585. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191586. * *dp = (temp - (temp >> 8)) >> 8;
  191587. *
  191588. * Approximate calculation with shift/add instead of multiply/divide:
  191589. * *dp = ((((png_uint_32)(*sp) << 8) |
  191590. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191591. *
  191592. * What we actually do to avoid extra shifting and conversion:
  191593. */
  191594. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191595. #else
  191596. /* Simply discard the low order byte */
  191597. *dp = *sp;
  191598. #endif
  191599. }
  191600. row_info->bit_depth = 8;
  191601. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191602. row_info->rowbytes = row_info->width * row_info->channels;
  191603. }
  191604. }
  191605. #endif
  191606. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191607. void /* PRIVATE */
  191608. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191609. {
  191610. png_debug(1, "in png_do_read_swap_alpha\n");
  191611. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191612. if (row != NULL && row_info != NULL)
  191613. #endif
  191614. {
  191615. png_uint_32 row_width = row_info->width;
  191616. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191617. {
  191618. /* This converts from RGBA to ARGB */
  191619. if (row_info->bit_depth == 8)
  191620. {
  191621. png_bytep sp = row + row_info->rowbytes;
  191622. png_bytep dp = sp;
  191623. png_byte save;
  191624. png_uint_32 i;
  191625. for (i = 0; i < row_width; i++)
  191626. {
  191627. save = *(--sp);
  191628. *(--dp) = *(--sp);
  191629. *(--dp) = *(--sp);
  191630. *(--dp) = *(--sp);
  191631. *(--dp) = save;
  191632. }
  191633. }
  191634. /* This converts from RRGGBBAA to AARRGGBB */
  191635. else
  191636. {
  191637. png_bytep sp = row + row_info->rowbytes;
  191638. png_bytep dp = sp;
  191639. png_byte save[2];
  191640. png_uint_32 i;
  191641. for (i = 0; i < row_width; i++)
  191642. {
  191643. save[0] = *(--sp);
  191644. save[1] = *(--sp);
  191645. *(--dp) = *(--sp);
  191646. *(--dp) = *(--sp);
  191647. *(--dp) = *(--sp);
  191648. *(--dp) = *(--sp);
  191649. *(--dp) = *(--sp);
  191650. *(--dp) = *(--sp);
  191651. *(--dp) = save[0];
  191652. *(--dp) = save[1];
  191653. }
  191654. }
  191655. }
  191656. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191657. {
  191658. /* This converts from GA to AG */
  191659. if (row_info->bit_depth == 8)
  191660. {
  191661. png_bytep sp = row + row_info->rowbytes;
  191662. png_bytep dp = sp;
  191663. png_byte save;
  191664. png_uint_32 i;
  191665. for (i = 0; i < row_width; i++)
  191666. {
  191667. save = *(--sp);
  191668. *(--dp) = *(--sp);
  191669. *(--dp) = save;
  191670. }
  191671. }
  191672. /* This converts from GGAA to AAGG */
  191673. else
  191674. {
  191675. png_bytep sp = row + row_info->rowbytes;
  191676. png_bytep dp = sp;
  191677. png_byte save[2];
  191678. png_uint_32 i;
  191679. for (i = 0; i < row_width; i++)
  191680. {
  191681. save[0] = *(--sp);
  191682. save[1] = *(--sp);
  191683. *(--dp) = *(--sp);
  191684. *(--dp) = *(--sp);
  191685. *(--dp) = save[0];
  191686. *(--dp) = save[1];
  191687. }
  191688. }
  191689. }
  191690. }
  191691. }
  191692. #endif
  191693. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191694. void /* PRIVATE */
  191695. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191696. {
  191697. png_debug(1, "in png_do_read_invert_alpha\n");
  191698. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191699. if (row != NULL && row_info != NULL)
  191700. #endif
  191701. {
  191702. png_uint_32 row_width = row_info->width;
  191703. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191704. {
  191705. /* This inverts the alpha channel in RGBA */
  191706. if (row_info->bit_depth == 8)
  191707. {
  191708. png_bytep sp = row + row_info->rowbytes;
  191709. png_bytep dp = sp;
  191710. png_uint_32 i;
  191711. for (i = 0; i < row_width; i++)
  191712. {
  191713. *(--dp) = (png_byte)(255 - *(--sp));
  191714. /* This does nothing:
  191715. *(--dp) = *(--sp);
  191716. *(--dp) = *(--sp);
  191717. *(--dp) = *(--sp);
  191718. We can replace it with:
  191719. */
  191720. sp-=3;
  191721. dp=sp;
  191722. }
  191723. }
  191724. /* This inverts the alpha channel in RRGGBBAA */
  191725. else
  191726. {
  191727. png_bytep sp = row + row_info->rowbytes;
  191728. png_bytep dp = sp;
  191729. png_uint_32 i;
  191730. for (i = 0; i < row_width; i++)
  191731. {
  191732. *(--dp) = (png_byte)(255 - *(--sp));
  191733. *(--dp) = (png_byte)(255 - *(--sp));
  191734. /* This does nothing:
  191735. *(--dp) = *(--sp);
  191736. *(--dp) = *(--sp);
  191737. *(--dp) = *(--sp);
  191738. *(--dp) = *(--sp);
  191739. *(--dp) = *(--sp);
  191740. *(--dp) = *(--sp);
  191741. We can replace it with:
  191742. */
  191743. sp-=6;
  191744. dp=sp;
  191745. }
  191746. }
  191747. }
  191748. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191749. {
  191750. /* This inverts the alpha channel in GA */
  191751. if (row_info->bit_depth == 8)
  191752. {
  191753. png_bytep sp = row + row_info->rowbytes;
  191754. png_bytep dp = sp;
  191755. png_uint_32 i;
  191756. for (i = 0; i < row_width; i++)
  191757. {
  191758. *(--dp) = (png_byte)(255 - *(--sp));
  191759. *(--dp) = *(--sp);
  191760. }
  191761. }
  191762. /* This inverts the alpha channel in GGAA */
  191763. else
  191764. {
  191765. png_bytep sp = row + row_info->rowbytes;
  191766. png_bytep dp = sp;
  191767. png_uint_32 i;
  191768. for (i = 0; i < row_width; i++)
  191769. {
  191770. *(--dp) = (png_byte)(255 - *(--sp));
  191771. *(--dp) = (png_byte)(255 - *(--sp));
  191772. /*
  191773. *(--dp) = *(--sp);
  191774. *(--dp) = *(--sp);
  191775. */
  191776. sp-=2;
  191777. dp=sp;
  191778. }
  191779. }
  191780. }
  191781. }
  191782. }
  191783. #endif
  191784. #if defined(PNG_READ_FILLER_SUPPORTED)
  191785. /* Add filler channel if we have RGB color */
  191786. void /* PRIVATE */
  191787. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191788. png_uint_32 filler, png_uint_32 flags)
  191789. {
  191790. png_uint_32 i;
  191791. png_uint_32 row_width = row_info->width;
  191792. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191793. png_byte lo_filler = (png_byte)(filler & 0xff);
  191794. png_debug(1, "in png_do_read_filler\n");
  191795. if (
  191796. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191797. row != NULL && row_info != NULL &&
  191798. #endif
  191799. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191800. {
  191801. if(row_info->bit_depth == 8)
  191802. {
  191803. /* This changes the data from G to GX */
  191804. if (flags & PNG_FLAG_FILLER_AFTER)
  191805. {
  191806. png_bytep sp = row + (png_size_t)row_width;
  191807. png_bytep dp = sp + (png_size_t)row_width;
  191808. for (i = 1; i < row_width; i++)
  191809. {
  191810. *(--dp) = lo_filler;
  191811. *(--dp) = *(--sp);
  191812. }
  191813. *(--dp) = lo_filler;
  191814. row_info->channels = 2;
  191815. row_info->pixel_depth = 16;
  191816. row_info->rowbytes = row_width * 2;
  191817. }
  191818. /* This changes the data from G to XG */
  191819. else
  191820. {
  191821. png_bytep sp = row + (png_size_t)row_width;
  191822. png_bytep dp = sp + (png_size_t)row_width;
  191823. for (i = 0; i < row_width; i++)
  191824. {
  191825. *(--dp) = *(--sp);
  191826. *(--dp) = lo_filler;
  191827. }
  191828. row_info->channels = 2;
  191829. row_info->pixel_depth = 16;
  191830. row_info->rowbytes = row_width * 2;
  191831. }
  191832. }
  191833. else if(row_info->bit_depth == 16)
  191834. {
  191835. /* This changes the data from GG to GGXX */
  191836. if (flags & PNG_FLAG_FILLER_AFTER)
  191837. {
  191838. png_bytep sp = row + (png_size_t)row_width * 2;
  191839. png_bytep dp = sp + (png_size_t)row_width * 2;
  191840. for (i = 1; i < row_width; i++)
  191841. {
  191842. *(--dp) = hi_filler;
  191843. *(--dp) = lo_filler;
  191844. *(--dp) = *(--sp);
  191845. *(--dp) = *(--sp);
  191846. }
  191847. *(--dp) = hi_filler;
  191848. *(--dp) = lo_filler;
  191849. row_info->channels = 2;
  191850. row_info->pixel_depth = 32;
  191851. row_info->rowbytes = row_width * 4;
  191852. }
  191853. /* This changes the data from GG to XXGG */
  191854. else
  191855. {
  191856. png_bytep sp = row + (png_size_t)row_width * 2;
  191857. png_bytep dp = sp + (png_size_t)row_width * 2;
  191858. for (i = 0; i < row_width; i++)
  191859. {
  191860. *(--dp) = *(--sp);
  191861. *(--dp) = *(--sp);
  191862. *(--dp) = hi_filler;
  191863. *(--dp) = lo_filler;
  191864. }
  191865. row_info->channels = 2;
  191866. row_info->pixel_depth = 32;
  191867. row_info->rowbytes = row_width * 4;
  191868. }
  191869. }
  191870. } /* COLOR_TYPE == GRAY */
  191871. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191872. {
  191873. if(row_info->bit_depth == 8)
  191874. {
  191875. /* This changes the data from RGB to RGBX */
  191876. if (flags & PNG_FLAG_FILLER_AFTER)
  191877. {
  191878. png_bytep sp = row + (png_size_t)row_width * 3;
  191879. png_bytep dp = sp + (png_size_t)row_width;
  191880. for (i = 1; i < row_width; i++)
  191881. {
  191882. *(--dp) = lo_filler;
  191883. *(--dp) = *(--sp);
  191884. *(--dp) = *(--sp);
  191885. *(--dp) = *(--sp);
  191886. }
  191887. *(--dp) = lo_filler;
  191888. row_info->channels = 4;
  191889. row_info->pixel_depth = 32;
  191890. row_info->rowbytes = row_width * 4;
  191891. }
  191892. /* This changes the data from RGB to XRGB */
  191893. else
  191894. {
  191895. png_bytep sp = row + (png_size_t)row_width * 3;
  191896. png_bytep dp = sp + (png_size_t)row_width;
  191897. for (i = 0; i < row_width; i++)
  191898. {
  191899. *(--dp) = *(--sp);
  191900. *(--dp) = *(--sp);
  191901. *(--dp) = *(--sp);
  191902. *(--dp) = lo_filler;
  191903. }
  191904. row_info->channels = 4;
  191905. row_info->pixel_depth = 32;
  191906. row_info->rowbytes = row_width * 4;
  191907. }
  191908. }
  191909. else if(row_info->bit_depth == 16)
  191910. {
  191911. /* This changes the data from RRGGBB to RRGGBBXX */
  191912. if (flags & PNG_FLAG_FILLER_AFTER)
  191913. {
  191914. png_bytep sp = row + (png_size_t)row_width * 6;
  191915. png_bytep dp = sp + (png_size_t)row_width * 2;
  191916. for (i = 1; i < row_width; i++)
  191917. {
  191918. *(--dp) = hi_filler;
  191919. *(--dp) = lo_filler;
  191920. *(--dp) = *(--sp);
  191921. *(--dp) = *(--sp);
  191922. *(--dp) = *(--sp);
  191923. *(--dp) = *(--sp);
  191924. *(--dp) = *(--sp);
  191925. *(--dp) = *(--sp);
  191926. }
  191927. *(--dp) = hi_filler;
  191928. *(--dp) = lo_filler;
  191929. row_info->channels = 4;
  191930. row_info->pixel_depth = 64;
  191931. row_info->rowbytes = row_width * 8;
  191932. }
  191933. /* This changes the data from RRGGBB to XXRRGGBB */
  191934. else
  191935. {
  191936. png_bytep sp = row + (png_size_t)row_width * 6;
  191937. png_bytep dp = sp + (png_size_t)row_width * 2;
  191938. for (i = 0; i < row_width; i++)
  191939. {
  191940. *(--dp) = *(--sp);
  191941. *(--dp) = *(--sp);
  191942. *(--dp) = *(--sp);
  191943. *(--dp) = *(--sp);
  191944. *(--dp) = *(--sp);
  191945. *(--dp) = *(--sp);
  191946. *(--dp) = hi_filler;
  191947. *(--dp) = lo_filler;
  191948. }
  191949. row_info->channels = 4;
  191950. row_info->pixel_depth = 64;
  191951. row_info->rowbytes = row_width * 8;
  191952. }
  191953. }
  191954. } /* COLOR_TYPE == RGB */
  191955. }
  191956. #endif
  191957. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191958. /* expand grayscale files to RGB, with or without alpha */
  191959. void /* PRIVATE */
  191960. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191961. {
  191962. png_uint_32 i;
  191963. png_uint_32 row_width = row_info->width;
  191964. png_debug(1, "in png_do_gray_to_rgb\n");
  191965. if (row_info->bit_depth >= 8 &&
  191966. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191967. row != NULL && row_info != NULL &&
  191968. #endif
  191969. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191970. {
  191971. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191972. {
  191973. if (row_info->bit_depth == 8)
  191974. {
  191975. png_bytep sp = row + (png_size_t)row_width - 1;
  191976. png_bytep dp = sp + (png_size_t)row_width * 2;
  191977. for (i = 0; i < row_width; i++)
  191978. {
  191979. *(dp--) = *sp;
  191980. *(dp--) = *sp;
  191981. *(dp--) = *(sp--);
  191982. }
  191983. }
  191984. else
  191985. {
  191986. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191987. png_bytep dp = sp + (png_size_t)row_width * 4;
  191988. for (i = 0; i < row_width; i++)
  191989. {
  191990. *(dp--) = *sp;
  191991. *(dp--) = *(sp - 1);
  191992. *(dp--) = *sp;
  191993. *(dp--) = *(sp - 1);
  191994. *(dp--) = *(sp--);
  191995. *(dp--) = *(sp--);
  191996. }
  191997. }
  191998. }
  191999. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192000. {
  192001. if (row_info->bit_depth == 8)
  192002. {
  192003. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192004. png_bytep dp = sp + (png_size_t)row_width * 2;
  192005. for (i = 0; i < row_width; i++)
  192006. {
  192007. *(dp--) = *(sp--);
  192008. *(dp--) = *sp;
  192009. *(dp--) = *sp;
  192010. *(dp--) = *(sp--);
  192011. }
  192012. }
  192013. else
  192014. {
  192015. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192016. png_bytep dp = sp + (png_size_t)row_width * 4;
  192017. for (i = 0; i < row_width; i++)
  192018. {
  192019. *(dp--) = *(sp--);
  192020. *(dp--) = *(sp--);
  192021. *(dp--) = *sp;
  192022. *(dp--) = *(sp - 1);
  192023. *(dp--) = *sp;
  192024. *(dp--) = *(sp - 1);
  192025. *(dp--) = *(sp--);
  192026. *(dp--) = *(sp--);
  192027. }
  192028. }
  192029. }
  192030. row_info->channels += (png_byte)2;
  192031. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192032. row_info->pixel_depth = (png_byte)(row_info->channels *
  192033. row_info->bit_depth);
  192034. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192035. }
  192036. }
  192037. #endif
  192038. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192039. /* reduce RGB files to grayscale, with or without alpha
  192040. * using the equation given in Poynton's ColorFAQ at
  192041. * <http://www.inforamp.net/~poynton/>
  192042. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192043. *
  192044. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192045. *
  192046. * We approximate this with
  192047. *
  192048. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192049. *
  192050. * which can be expressed with integers as
  192051. *
  192052. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192053. *
  192054. * The calculation is to be done in a linear colorspace.
  192055. *
  192056. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192057. */
  192058. int /* PRIVATE */
  192059. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192060. {
  192061. png_uint_32 i;
  192062. png_uint_32 row_width = row_info->width;
  192063. int rgb_error = 0;
  192064. png_debug(1, "in png_do_rgb_to_gray\n");
  192065. if (
  192066. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192067. row != NULL && row_info != NULL &&
  192068. #endif
  192069. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192070. {
  192071. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192072. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192073. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192074. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192075. {
  192076. if (row_info->bit_depth == 8)
  192077. {
  192078. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192079. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192080. {
  192081. png_bytep sp = row;
  192082. png_bytep dp = row;
  192083. for (i = 0; i < row_width; i++)
  192084. {
  192085. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192086. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192087. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192088. if(red != green || red != blue)
  192089. {
  192090. rgb_error |= 1;
  192091. *(dp++) = png_ptr->gamma_from_1[
  192092. (rc*red+gc*green+bc*blue)>>15];
  192093. }
  192094. else
  192095. *(dp++) = *(sp-1);
  192096. }
  192097. }
  192098. else
  192099. #endif
  192100. {
  192101. png_bytep sp = row;
  192102. png_bytep dp = row;
  192103. for (i = 0; i < row_width; i++)
  192104. {
  192105. png_byte red = *(sp++);
  192106. png_byte green = *(sp++);
  192107. png_byte blue = *(sp++);
  192108. if(red != green || red != blue)
  192109. {
  192110. rgb_error |= 1;
  192111. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192112. }
  192113. else
  192114. *(dp++) = *(sp-1);
  192115. }
  192116. }
  192117. }
  192118. else /* RGB bit_depth == 16 */
  192119. {
  192120. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192121. if (png_ptr->gamma_16_to_1 != NULL &&
  192122. png_ptr->gamma_16_from_1 != NULL)
  192123. {
  192124. png_bytep sp = row;
  192125. png_bytep dp = row;
  192126. for (i = 0; i < row_width; i++)
  192127. {
  192128. png_uint_16 red, green, blue, w;
  192129. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192130. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192131. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192132. if(red == green && red == blue)
  192133. w = red;
  192134. else
  192135. {
  192136. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192137. png_ptr->gamma_shift][red>>8];
  192138. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192139. png_ptr->gamma_shift][green>>8];
  192140. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192141. png_ptr->gamma_shift][blue>>8];
  192142. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192143. + bc*blue_1)>>15);
  192144. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192145. png_ptr->gamma_shift][gray16 >> 8];
  192146. rgb_error |= 1;
  192147. }
  192148. *(dp++) = (png_byte)((w>>8) & 0xff);
  192149. *(dp++) = (png_byte)(w & 0xff);
  192150. }
  192151. }
  192152. else
  192153. #endif
  192154. {
  192155. png_bytep sp = row;
  192156. png_bytep dp = row;
  192157. for (i = 0; i < row_width; i++)
  192158. {
  192159. png_uint_16 red, green, blue, gray16;
  192160. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192161. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192162. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192163. if(red != green || red != blue)
  192164. rgb_error |= 1;
  192165. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192166. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192167. *(dp++) = (png_byte)(gray16 & 0xff);
  192168. }
  192169. }
  192170. }
  192171. }
  192172. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192173. {
  192174. if (row_info->bit_depth == 8)
  192175. {
  192176. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192177. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192178. {
  192179. png_bytep sp = row;
  192180. png_bytep dp = row;
  192181. for (i = 0; i < row_width; i++)
  192182. {
  192183. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192184. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192185. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192186. if(red != green || red != blue)
  192187. rgb_error |= 1;
  192188. *(dp++) = png_ptr->gamma_from_1
  192189. [(rc*red + gc*green + bc*blue)>>15];
  192190. *(dp++) = *(sp++); /* alpha */
  192191. }
  192192. }
  192193. else
  192194. #endif
  192195. {
  192196. png_bytep sp = row;
  192197. png_bytep dp = row;
  192198. for (i = 0; i < row_width; i++)
  192199. {
  192200. png_byte red = *(sp++);
  192201. png_byte green = *(sp++);
  192202. png_byte blue = *(sp++);
  192203. if(red != green || red != blue)
  192204. rgb_error |= 1;
  192205. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192206. *(dp++) = *(sp++); /* alpha */
  192207. }
  192208. }
  192209. }
  192210. else /* RGBA bit_depth == 16 */
  192211. {
  192212. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192213. if (png_ptr->gamma_16_to_1 != NULL &&
  192214. png_ptr->gamma_16_from_1 != NULL)
  192215. {
  192216. png_bytep sp = row;
  192217. png_bytep dp = row;
  192218. for (i = 0; i < row_width; i++)
  192219. {
  192220. png_uint_16 red, green, blue, w;
  192221. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192222. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192223. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192224. if(red == green && red == blue)
  192225. w = red;
  192226. else
  192227. {
  192228. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192229. png_ptr->gamma_shift][red>>8];
  192230. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192231. png_ptr->gamma_shift][green>>8];
  192232. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192233. png_ptr->gamma_shift][blue>>8];
  192234. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192235. + gc * green_1 + bc * blue_1)>>15);
  192236. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192237. png_ptr->gamma_shift][gray16 >> 8];
  192238. rgb_error |= 1;
  192239. }
  192240. *(dp++) = (png_byte)((w>>8) & 0xff);
  192241. *(dp++) = (png_byte)(w & 0xff);
  192242. *(dp++) = *(sp++); /* alpha */
  192243. *(dp++) = *(sp++);
  192244. }
  192245. }
  192246. else
  192247. #endif
  192248. {
  192249. png_bytep sp = row;
  192250. png_bytep dp = row;
  192251. for (i = 0; i < row_width; i++)
  192252. {
  192253. png_uint_16 red, green, blue, gray16;
  192254. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192255. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192256. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192257. if(red != green || red != blue)
  192258. rgb_error |= 1;
  192259. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192260. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192261. *(dp++) = (png_byte)(gray16 & 0xff);
  192262. *(dp++) = *(sp++); /* alpha */
  192263. *(dp++) = *(sp++);
  192264. }
  192265. }
  192266. }
  192267. }
  192268. row_info->channels -= (png_byte)2;
  192269. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192270. row_info->pixel_depth = (png_byte)(row_info->channels *
  192271. row_info->bit_depth);
  192272. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192273. }
  192274. return rgb_error;
  192275. }
  192276. #endif
  192277. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192278. * large of png_color. This lets grayscale images be treated as
  192279. * paletted. Most useful for gamma correction and simplification
  192280. * of code.
  192281. */
  192282. void PNGAPI
  192283. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192284. {
  192285. int num_palette;
  192286. int color_inc;
  192287. int i;
  192288. int v;
  192289. png_debug(1, "in png_do_build_grayscale_palette\n");
  192290. if (palette == NULL)
  192291. return;
  192292. switch (bit_depth)
  192293. {
  192294. case 1:
  192295. num_palette = 2;
  192296. color_inc = 0xff;
  192297. break;
  192298. case 2:
  192299. num_palette = 4;
  192300. color_inc = 0x55;
  192301. break;
  192302. case 4:
  192303. num_palette = 16;
  192304. color_inc = 0x11;
  192305. break;
  192306. case 8:
  192307. num_palette = 256;
  192308. color_inc = 1;
  192309. break;
  192310. default:
  192311. num_palette = 0;
  192312. color_inc = 0;
  192313. break;
  192314. }
  192315. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192316. {
  192317. palette[i].red = (png_byte)v;
  192318. palette[i].green = (png_byte)v;
  192319. palette[i].blue = (png_byte)v;
  192320. }
  192321. }
  192322. /* This function is currently unused. Do we really need it? */
  192323. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192324. void /* PRIVATE */
  192325. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192326. int num_palette)
  192327. {
  192328. png_debug(1, "in png_correct_palette\n");
  192329. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192330. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192331. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192332. {
  192333. png_color back, back_1;
  192334. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192335. {
  192336. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192337. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192338. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192339. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192340. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192341. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192342. }
  192343. else
  192344. {
  192345. double g;
  192346. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192347. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192348. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192349. {
  192350. back.red = png_ptr->background.red;
  192351. back.green = png_ptr->background.green;
  192352. back.blue = png_ptr->background.blue;
  192353. }
  192354. else
  192355. {
  192356. back.red =
  192357. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192358. 255.0 + 0.5);
  192359. back.green =
  192360. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192361. 255.0 + 0.5);
  192362. back.blue =
  192363. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192364. 255.0 + 0.5);
  192365. }
  192366. g = 1.0 / png_ptr->background_gamma;
  192367. back_1.red =
  192368. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192369. 255.0 + 0.5);
  192370. back_1.green =
  192371. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192372. 255.0 + 0.5);
  192373. back_1.blue =
  192374. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192375. 255.0 + 0.5);
  192376. }
  192377. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192378. {
  192379. png_uint_32 i;
  192380. for (i = 0; i < (png_uint_32)num_palette; i++)
  192381. {
  192382. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192383. {
  192384. palette[i] = back;
  192385. }
  192386. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192387. {
  192388. png_byte v, w;
  192389. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192390. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192391. palette[i].red = png_ptr->gamma_from_1[w];
  192392. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192393. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192394. palette[i].green = png_ptr->gamma_from_1[w];
  192395. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192396. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192397. palette[i].blue = png_ptr->gamma_from_1[w];
  192398. }
  192399. else
  192400. {
  192401. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192402. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192403. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192404. }
  192405. }
  192406. }
  192407. else
  192408. {
  192409. int i;
  192410. for (i = 0; i < num_palette; i++)
  192411. {
  192412. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192413. {
  192414. palette[i] = back;
  192415. }
  192416. else
  192417. {
  192418. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192419. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192420. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192421. }
  192422. }
  192423. }
  192424. }
  192425. else
  192426. #endif
  192427. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192428. if (png_ptr->transformations & PNG_GAMMA)
  192429. {
  192430. int i;
  192431. for (i = 0; i < num_palette; i++)
  192432. {
  192433. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192434. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192435. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192436. }
  192437. }
  192438. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192439. else
  192440. #endif
  192441. #endif
  192442. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192443. if (png_ptr->transformations & PNG_BACKGROUND)
  192444. {
  192445. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192446. {
  192447. png_color back;
  192448. back.red = (png_byte)png_ptr->background.red;
  192449. back.green = (png_byte)png_ptr->background.green;
  192450. back.blue = (png_byte)png_ptr->background.blue;
  192451. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192452. {
  192453. if (png_ptr->trans[i] == 0)
  192454. {
  192455. palette[i].red = back.red;
  192456. palette[i].green = back.green;
  192457. palette[i].blue = back.blue;
  192458. }
  192459. else if (png_ptr->trans[i] != 0xff)
  192460. {
  192461. png_composite(palette[i].red, png_ptr->palette[i].red,
  192462. png_ptr->trans[i], back.red);
  192463. png_composite(palette[i].green, png_ptr->palette[i].green,
  192464. png_ptr->trans[i], back.green);
  192465. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192466. png_ptr->trans[i], back.blue);
  192467. }
  192468. }
  192469. }
  192470. else /* assume grayscale palette (what else could it be?) */
  192471. {
  192472. int i;
  192473. for (i = 0; i < num_palette; i++)
  192474. {
  192475. if (i == (png_byte)png_ptr->trans_values.gray)
  192476. {
  192477. palette[i].red = (png_byte)png_ptr->background.red;
  192478. palette[i].green = (png_byte)png_ptr->background.green;
  192479. palette[i].blue = (png_byte)png_ptr->background.blue;
  192480. }
  192481. }
  192482. }
  192483. }
  192484. #endif
  192485. }
  192486. #endif
  192487. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192488. /* Replace any alpha or transparency with the supplied background color.
  192489. * "background" is already in the screen gamma, while "background_1" is
  192490. * at a gamma of 1.0. Paletted files have already been taken care of.
  192491. */
  192492. void /* PRIVATE */
  192493. png_do_background(png_row_infop row_info, png_bytep row,
  192494. png_color_16p trans_values, png_color_16p background
  192495. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192496. , png_color_16p background_1,
  192497. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192498. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192499. png_uint_16pp gamma_16_to_1, int gamma_shift
  192500. #endif
  192501. )
  192502. {
  192503. png_bytep sp, dp;
  192504. png_uint_32 i;
  192505. png_uint_32 row_width=row_info->width;
  192506. int shift;
  192507. png_debug(1, "in png_do_background\n");
  192508. if (background != NULL &&
  192509. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192510. row != NULL && row_info != NULL &&
  192511. #endif
  192512. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192513. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192514. {
  192515. switch (row_info->color_type)
  192516. {
  192517. case PNG_COLOR_TYPE_GRAY:
  192518. {
  192519. switch (row_info->bit_depth)
  192520. {
  192521. case 1:
  192522. {
  192523. sp = row;
  192524. shift = 7;
  192525. for (i = 0; i < row_width; i++)
  192526. {
  192527. if ((png_uint_16)((*sp >> shift) & 0x01)
  192528. == trans_values->gray)
  192529. {
  192530. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192531. *sp |= (png_byte)(background->gray << shift);
  192532. }
  192533. if (!shift)
  192534. {
  192535. shift = 7;
  192536. sp++;
  192537. }
  192538. else
  192539. shift--;
  192540. }
  192541. break;
  192542. }
  192543. case 2:
  192544. {
  192545. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192546. if (gamma_table != NULL)
  192547. {
  192548. sp = row;
  192549. shift = 6;
  192550. for (i = 0; i < row_width; i++)
  192551. {
  192552. if ((png_uint_16)((*sp >> shift) & 0x03)
  192553. == trans_values->gray)
  192554. {
  192555. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192556. *sp |= (png_byte)(background->gray << shift);
  192557. }
  192558. else
  192559. {
  192560. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192561. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192562. (p << 4) | (p << 6)] >> 6) & 0x03);
  192563. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192564. *sp |= (png_byte)(g << shift);
  192565. }
  192566. if (!shift)
  192567. {
  192568. shift = 6;
  192569. sp++;
  192570. }
  192571. else
  192572. shift -= 2;
  192573. }
  192574. }
  192575. else
  192576. #endif
  192577. {
  192578. sp = row;
  192579. shift = 6;
  192580. for (i = 0; i < row_width; i++)
  192581. {
  192582. if ((png_uint_16)((*sp >> shift) & 0x03)
  192583. == trans_values->gray)
  192584. {
  192585. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192586. *sp |= (png_byte)(background->gray << shift);
  192587. }
  192588. if (!shift)
  192589. {
  192590. shift = 6;
  192591. sp++;
  192592. }
  192593. else
  192594. shift -= 2;
  192595. }
  192596. }
  192597. break;
  192598. }
  192599. case 4:
  192600. {
  192601. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192602. if (gamma_table != NULL)
  192603. {
  192604. sp = row;
  192605. shift = 4;
  192606. for (i = 0; i < row_width; i++)
  192607. {
  192608. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192609. == trans_values->gray)
  192610. {
  192611. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192612. *sp |= (png_byte)(background->gray << shift);
  192613. }
  192614. else
  192615. {
  192616. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192617. png_byte g = (png_byte)((gamma_table[p |
  192618. (p << 4)] >> 4) & 0x0f);
  192619. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192620. *sp |= (png_byte)(g << shift);
  192621. }
  192622. if (!shift)
  192623. {
  192624. shift = 4;
  192625. sp++;
  192626. }
  192627. else
  192628. shift -= 4;
  192629. }
  192630. }
  192631. else
  192632. #endif
  192633. {
  192634. sp = row;
  192635. shift = 4;
  192636. for (i = 0; i < row_width; i++)
  192637. {
  192638. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192639. == trans_values->gray)
  192640. {
  192641. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192642. *sp |= (png_byte)(background->gray << shift);
  192643. }
  192644. if (!shift)
  192645. {
  192646. shift = 4;
  192647. sp++;
  192648. }
  192649. else
  192650. shift -= 4;
  192651. }
  192652. }
  192653. break;
  192654. }
  192655. case 8:
  192656. {
  192657. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192658. if (gamma_table != NULL)
  192659. {
  192660. sp = row;
  192661. for (i = 0; i < row_width; i++, sp++)
  192662. {
  192663. if (*sp == trans_values->gray)
  192664. {
  192665. *sp = (png_byte)background->gray;
  192666. }
  192667. else
  192668. {
  192669. *sp = gamma_table[*sp];
  192670. }
  192671. }
  192672. }
  192673. else
  192674. #endif
  192675. {
  192676. sp = row;
  192677. for (i = 0; i < row_width; i++, sp++)
  192678. {
  192679. if (*sp == trans_values->gray)
  192680. {
  192681. *sp = (png_byte)background->gray;
  192682. }
  192683. }
  192684. }
  192685. break;
  192686. }
  192687. case 16:
  192688. {
  192689. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192690. if (gamma_16 != NULL)
  192691. {
  192692. sp = row;
  192693. for (i = 0; i < row_width; i++, sp += 2)
  192694. {
  192695. png_uint_16 v;
  192696. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192697. if (v == trans_values->gray)
  192698. {
  192699. /* background is already in screen gamma */
  192700. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192701. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192702. }
  192703. else
  192704. {
  192705. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192706. *sp = (png_byte)((v >> 8) & 0xff);
  192707. *(sp + 1) = (png_byte)(v & 0xff);
  192708. }
  192709. }
  192710. }
  192711. else
  192712. #endif
  192713. {
  192714. sp = row;
  192715. for (i = 0; i < row_width; i++, sp += 2)
  192716. {
  192717. png_uint_16 v;
  192718. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192719. if (v == trans_values->gray)
  192720. {
  192721. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192722. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192723. }
  192724. }
  192725. }
  192726. break;
  192727. }
  192728. }
  192729. break;
  192730. }
  192731. case PNG_COLOR_TYPE_RGB:
  192732. {
  192733. if (row_info->bit_depth == 8)
  192734. {
  192735. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192736. if (gamma_table != NULL)
  192737. {
  192738. sp = row;
  192739. for (i = 0; i < row_width; i++, sp += 3)
  192740. {
  192741. if (*sp == trans_values->red &&
  192742. *(sp + 1) == trans_values->green &&
  192743. *(sp + 2) == trans_values->blue)
  192744. {
  192745. *sp = (png_byte)background->red;
  192746. *(sp + 1) = (png_byte)background->green;
  192747. *(sp + 2) = (png_byte)background->blue;
  192748. }
  192749. else
  192750. {
  192751. *sp = gamma_table[*sp];
  192752. *(sp + 1) = gamma_table[*(sp + 1)];
  192753. *(sp + 2) = gamma_table[*(sp + 2)];
  192754. }
  192755. }
  192756. }
  192757. else
  192758. #endif
  192759. {
  192760. sp = row;
  192761. for (i = 0; i < row_width; i++, sp += 3)
  192762. {
  192763. if (*sp == trans_values->red &&
  192764. *(sp + 1) == trans_values->green &&
  192765. *(sp + 2) == trans_values->blue)
  192766. {
  192767. *sp = (png_byte)background->red;
  192768. *(sp + 1) = (png_byte)background->green;
  192769. *(sp + 2) = (png_byte)background->blue;
  192770. }
  192771. }
  192772. }
  192773. }
  192774. else /* if (row_info->bit_depth == 16) */
  192775. {
  192776. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192777. if (gamma_16 != NULL)
  192778. {
  192779. sp = row;
  192780. for (i = 0; i < row_width; i++, sp += 6)
  192781. {
  192782. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192783. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192784. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192785. if (r == trans_values->red && g == trans_values->green &&
  192786. b == trans_values->blue)
  192787. {
  192788. /* background is already in screen gamma */
  192789. *sp = (png_byte)((background->red >> 8) & 0xff);
  192790. *(sp + 1) = (png_byte)(background->red & 0xff);
  192791. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192792. *(sp + 3) = (png_byte)(background->green & 0xff);
  192793. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192794. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192795. }
  192796. else
  192797. {
  192798. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192799. *sp = (png_byte)((v >> 8) & 0xff);
  192800. *(sp + 1) = (png_byte)(v & 0xff);
  192801. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192802. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192803. *(sp + 3) = (png_byte)(v & 0xff);
  192804. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192805. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192806. *(sp + 5) = (png_byte)(v & 0xff);
  192807. }
  192808. }
  192809. }
  192810. else
  192811. #endif
  192812. {
  192813. sp = row;
  192814. for (i = 0; i < row_width; i++, sp += 6)
  192815. {
  192816. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192817. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192818. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192819. if (r == trans_values->red && g == trans_values->green &&
  192820. b == trans_values->blue)
  192821. {
  192822. *sp = (png_byte)((background->red >> 8) & 0xff);
  192823. *(sp + 1) = (png_byte)(background->red & 0xff);
  192824. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192825. *(sp + 3) = (png_byte)(background->green & 0xff);
  192826. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192827. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192828. }
  192829. }
  192830. }
  192831. }
  192832. break;
  192833. }
  192834. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192835. {
  192836. if (row_info->bit_depth == 8)
  192837. {
  192838. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192839. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192840. gamma_table != NULL)
  192841. {
  192842. sp = row;
  192843. dp = row;
  192844. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192845. {
  192846. png_uint_16 a = *(sp + 1);
  192847. if (a == 0xff)
  192848. {
  192849. *dp = gamma_table[*sp];
  192850. }
  192851. else if (a == 0)
  192852. {
  192853. /* background is already in screen gamma */
  192854. *dp = (png_byte)background->gray;
  192855. }
  192856. else
  192857. {
  192858. png_byte v, w;
  192859. v = gamma_to_1[*sp];
  192860. png_composite(w, v, a, background_1->gray);
  192861. *dp = gamma_from_1[w];
  192862. }
  192863. }
  192864. }
  192865. else
  192866. #endif
  192867. {
  192868. sp = row;
  192869. dp = row;
  192870. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192871. {
  192872. png_byte a = *(sp + 1);
  192873. if (a == 0xff)
  192874. {
  192875. *dp = *sp;
  192876. }
  192877. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192878. else if (a == 0)
  192879. {
  192880. *dp = (png_byte)background->gray;
  192881. }
  192882. else
  192883. {
  192884. png_composite(*dp, *sp, a, background_1->gray);
  192885. }
  192886. #else
  192887. *dp = (png_byte)background->gray;
  192888. #endif
  192889. }
  192890. }
  192891. }
  192892. else /* if (png_ptr->bit_depth == 16) */
  192893. {
  192894. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192895. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192896. gamma_16_to_1 != NULL)
  192897. {
  192898. sp = row;
  192899. dp = row;
  192900. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192901. {
  192902. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192903. if (a == (png_uint_16)0xffff)
  192904. {
  192905. png_uint_16 v;
  192906. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192907. *dp = (png_byte)((v >> 8) & 0xff);
  192908. *(dp + 1) = (png_byte)(v & 0xff);
  192909. }
  192910. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192911. else if (a == 0)
  192912. #else
  192913. else
  192914. #endif
  192915. {
  192916. /* background is already in screen gamma */
  192917. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192918. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192919. }
  192920. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192921. else
  192922. {
  192923. png_uint_16 g, v, w;
  192924. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192925. png_composite_16(v, g, a, background_1->gray);
  192926. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192927. *dp = (png_byte)((w >> 8) & 0xff);
  192928. *(dp + 1) = (png_byte)(w & 0xff);
  192929. }
  192930. #endif
  192931. }
  192932. }
  192933. else
  192934. #endif
  192935. {
  192936. sp = row;
  192937. dp = row;
  192938. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192939. {
  192940. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192941. if (a == (png_uint_16)0xffff)
  192942. {
  192943. png_memcpy(dp, sp, 2);
  192944. }
  192945. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192946. else if (a == 0)
  192947. #else
  192948. else
  192949. #endif
  192950. {
  192951. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192952. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192953. }
  192954. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192955. else
  192956. {
  192957. png_uint_16 g, v;
  192958. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192959. png_composite_16(v, g, a, background_1->gray);
  192960. *dp = (png_byte)((v >> 8) & 0xff);
  192961. *(dp + 1) = (png_byte)(v & 0xff);
  192962. }
  192963. #endif
  192964. }
  192965. }
  192966. }
  192967. break;
  192968. }
  192969. case PNG_COLOR_TYPE_RGB_ALPHA:
  192970. {
  192971. if (row_info->bit_depth == 8)
  192972. {
  192973. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192974. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192975. gamma_table != NULL)
  192976. {
  192977. sp = row;
  192978. dp = row;
  192979. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192980. {
  192981. png_byte a = *(sp + 3);
  192982. if (a == 0xff)
  192983. {
  192984. *dp = gamma_table[*sp];
  192985. *(dp + 1) = gamma_table[*(sp + 1)];
  192986. *(dp + 2) = gamma_table[*(sp + 2)];
  192987. }
  192988. else if (a == 0)
  192989. {
  192990. /* background is already in screen gamma */
  192991. *dp = (png_byte)background->red;
  192992. *(dp + 1) = (png_byte)background->green;
  192993. *(dp + 2) = (png_byte)background->blue;
  192994. }
  192995. else
  192996. {
  192997. png_byte v, w;
  192998. v = gamma_to_1[*sp];
  192999. png_composite(w, v, a, background_1->red);
  193000. *dp = gamma_from_1[w];
  193001. v = gamma_to_1[*(sp + 1)];
  193002. png_composite(w, v, a, background_1->green);
  193003. *(dp + 1) = gamma_from_1[w];
  193004. v = gamma_to_1[*(sp + 2)];
  193005. png_composite(w, v, a, background_1->blue);
  193006. *(dp + 2) = gamma_from_1[w];
  193007. }
  193008. }
  193009. }
  193010. else
  193011. #endif
  193012. {
  193013. sp = row;
  193014. dp = row;
  193015. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193016. {
  193017. png_byte a = *(sp + 3);
  193018. if (a == 0xff)
  193019. {
  193020. *dp = *sp;
  193021. *(dp + 1) = *(sp + 1);
  193022. *(dp + 2) = *(sp + 2);
  193023. }
  193024. else if (a == 0)
  193025. {
  193026. *dp = (png_byte)background->red;
  193027. *(dp + 1) = (png_byte)background->green;
  193028. *(dp + 2) = (png_byte)background->blue;
  193029. }
  193030. else
  193031. {
  193032. png_composite(*dp, *sp, a, background->red);
  193033. png_composite(*(dp + 1), *(sp + 1), a,
  193034. background->green);
  193035. png_composite(*(dp + 2), *(sp + 2), a,
  193036. background->blue);
  193037. }
  193038. }
  193039. }
  193040. }
  193041. else /* if (row_info->bit_depth == 16) */
  193042. {
  193043. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193044. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193045. gamma_16_to_1 != NULL)
  193046. {
  193047. sp = row;
  193048. dp = row;
  193049. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193050. {
  193051. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193052. << 8) + (png_uint_16)(*(sp + 7)));
  193053. if (a == (png_uint_16)0xffff)
  193054. {
  193055. png_uint_16 v;
  193056. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193057. *dp = (png_byte)((v >> 8) & 0xff);
  193058. *(dp + 1) = (png_byte)(v & 0xff);
  193059. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193060. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193061. *(dp + 3) = (png_byte)(v & 0xff);
  193062. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193063. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193064. *(dp + 5) = (png_byte)(v & 0xff);
  193065. }
  193066. else if (a == 0)
  193067. {
  193068. /* background is already in screen gamma */
  193069. *dp = (png_byte)((background->red >> 8) & 0xff);
  193070. *(dp + 1) = (png_byte)(background->red & 0xff);
  193071. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193072. *(dp + 3) = (png_byte)(background->green & 0xff);
  193073. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193074. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193075. }
  193076. else
  193077. {
  193078. png_uint_16 v, w, x;
  193079. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193080. png_composite_16(w, v, a, background_1->red);
  193081. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193082. *dp = (png_byte)((x >> 8) & 0xff);
  193083. *(dp + 1) = (png_byte)(x & 0xff);
  193084. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193085. png_composite_16(w, v, a, background_1->green);
  193086. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193087. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193088. *(dp + 3) = (png_byte)(x & 0xff);
  193089. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193090. png_composite_16(w, v, a, background_1->blue);
  193091. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193092. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193093. *(dp + 5) = (png_byte)(x & 0xff);
  193094. }
  193095. }
  193096. }
  193097. else
  193098. #endif
  193099. {
  193100. sp = row;
  193101. dp = row;
  193102. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193103. {
  193104. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193105. << 8) + (png_uint_16)(*(sp + 7)));
  193106. if (a == (png_uint_16)0xffff)
  193107. {
  193108. png_memcpy(dp, sp, 6);
  193109. }
  193110. else if (a == 0)
  193111. {
  193112. *dp = (png_byte)((background->red >> 8) & 0xff);
  193113. *(dp + 1) = (png_byte)(background->red & 0xff);
  193114. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193115. *(dp + 3) = (png_byte)(background->green & 0xff);
  193116. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193117. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193118. }
  193119. else
  193120. {
  193121. png_uint_16 v;
  193122. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193123. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193124. + *(sp + 3));
  193125. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193126. + *(sp + 5));
  193127. png_composite_16(v, r, a, background->red);
  193128. *dp = (png_byte)((v >> 8) & 0xff);
  193129. *(dp + 1) = (png_byte)(v & 0xff);
  193130. png_composite_16(v, g, a, background->green);
  193131. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193132. *(dp + 3) = (png_byte)(v & 0xff);
  193133. png_composite_16(v, b, a, background->blue);
  193134. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193135. *(dp + 5) = (png_byte)(v & 0xff);
  193136. }
  193137. }
  193138. }
  193139. }
  193140. break;
  193141. }
  193142. }
  193143. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193144. {
  193145. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193146. row_info->channels--;
  193147. row_info->pixel_depth = (png_byte)(row_info->channels *
  193148. row_info->bit_depth);
  193149. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193150. }
  193151. }
  193152. }
  193153. #endif
  193154. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193155. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193156. * you do this after you deal with the transparency issue on grayscale
  193157. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193158. * is 16, use gamma_16_table and gamma_shift. Build these with
  193159. * build_gamma_table().
  193160. */
  193161. void /* PRIVATE */
  193162. png_do_gamma(png_row_infop row_info, png_bytep row,
  193163. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193164. int gamma_shift)
  193165. {
  193166. png_bytep sp;
  193167. png_uint_32 i;
  193168. png_uint_32 row_width=row_info->width;
  193169. png_debug(1, "in png_do_gamma\n");
  193170. if (
  193171. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193172. row != NULL && row_info != NULL &&
  193173. #endif
  193174. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193175. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193176. {
  193177. switch (row_info->color_type)
  193178. {
  193179. case PNG_COLOR_TYPE_RGB:
  193180. {
  193181. if (row_info->bit_depth == 8)
  193182. {
  193183. sp = row;
  193184. for (i = 0; i < row_width; i++)
  193185. {
  193186. *sp = gamma_table[*sp];
  193187. sp++;
  193188. *sp = gamma_table[*sp];
  193189. sp++;
  193190. *sp = gamma_table[*sp];
  193191. sp++;
  193192. }
  193193. }
  193194. else /* if (row_info->bit_depth == 16) */
  193195. {
  193196. sp = row;
  193197. for (i = 0; i < row_width; i++)
  193198. {
  193199. png_uint_16 v;
  193200. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193201. *sp = (png_byte)((v >> 8) & 0xff);
  193202. *(sp + 1) = (png_byte)(v & 0xff);
  193203. sp += 2;
  193204. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193205. *sp = (png_byte)((v >> 8) & 0xff);
  193206. *(sp + 1) = (png_byte)(v & 0xff);
  193207. sp += 2;
  193208. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193209. *sp = (png_byte)((v >> 8) & 0xff);
  193210. *(sp + 1) = (png_byte)(v & 0xff);
  193211. sp += 2;
  193212. }
  193213. }
  193214. break;
  193215. }
  193216. case PNG_COLOR_TYPE_RGB_ALPHA:
  193217. {
  193218. if (row_info->bit_depth == 8)
  193219. {
  193220. sp = row;
  193221. for (i = 0; i < row_width; i++)
  193222. {
  193223. *sp = gamma_table[*sp];
  193224. sp++;
  193225. *sp = gamma_table[*sp];
  193226. sp++;
  193227. *sp = gamma_table[*sp];
  193228. sp++;
  193229. sp++;
  193230. }
  193231. }
  193232. else /* if (row_info->bit_depth == 16) */
  193233. {
  193234. sp = row;
  193235. for (i = 0; i < row_width; i++)
  193236. {
  193237. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193238. *sp = (png_byte)((v >> 8) & 0xff);
  193239. *(sp + 1) = (png_byte)(v & 0xff);
  193240. sp += 2;
  193241. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193242. *sp = (png_byte)((v >> 8) & 0xff);
  193243. *(sp + 1) = (png_byte)(v & 0xff);
  193244. sp += 2;
  193245. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193246. *sp = (png_byte)((v >> 8) & 0xff);
  193247. *(sp + 1) = (png_byte)(v & 0xff);
  193248. sp += 4;
  193249. }
  193250. }
  193251. break;
  193252. }
  193253. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193254. {
  193255. if (row_info->bit_depth == 8)
  193256. {
  193257. sp = row;
  193258. for (i = 0; i < row_width; i++)
  193259. {
  193260. *sp = gamma_table[*sp];
  193261. sp += 2;
  193262. }
  193263. }
  193264. else /* if (row_info->bit_depth == 16) */
  193265. {
  193266. sp = row;
  193267. for (i = 0; i < row_width; i++)
  193268. {
  193269. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193270. *sp = (png_byte)((v >> 8) & 0xff);
  193271. *(sp + 1) = (png_byte)(v & 0xff);
  193272. sp += 4;
  193273. }
  193274. }
  193275. break;
  193276. }
  193277. case PNG_COLOR_TYPE_GRAY:
  193278. {
  193279. if (row_info->bit_depth == 2)
  193280. {
  193281. sp = row;
  193282. for (i = 0; i < row_width; i += 4)
  193283. {
  193284. int a = *sp & 0xc0;
  193285. int b = *sp & 0x30;
  193286. int c = *sp & 0x0c;
  193287. int d = *sp & 0x03;
  193288. *sp = (png_byte)(
  193289. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193290. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193291. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193292. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193293. sp++;
  193294. }
  193295. }
  193296. if (row_info->bit_depth == 4)
  193297. {
  193298. sp = row;
  193299. for (i = 0; i < row_width; i += 2)
  193300. {
  193301. int msb = *sp & 0xf0;
  193302. int lsb = *sp & 0x0f;
  193303. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193304. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193305. sp++;
  193306. }
  193307. }
  193308. else if (row_info->bit_depth == 8)
  193309. {
  193310. sp = row;
  193311. for (i = 0; i < row_width; i++)
  193312. {
  193313. *sp = gamma_table[*sp];
  193314. sp++;
  193315. }
  193316. }
  193317. else if (row_info->bit_depth == 16)
  193318. {
  193319. sp = row;
  193320. for (i = 0; i < row_width; i++)
  193321. {
  193322. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193323. *sp = (png_byte)((v >> 8) & 0xff);
  193324. *(sp + 1) = (png_byte)(v & 0xff);
  193325. sp += 2;
  193326. }
  193327. }
  193328. break;
  193329. }
  193330. }
  193331. }
  193332. }
  193333. #endif
  193334. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193335. /* Expands a palette row to an RGB or RGBA row depending
  193336. * upon whether you supply trans and num_trans.
  193337. */
  193338. void /* PRIVATE */
  193339. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193340. png_colorp palette, png_bytep trans, int num_trans)
  193341. {
  193342. int shift, value;
  193343. png_bytep sp, dp;
  193344. png_uint_32 i;
  193345. png_uint_32 row_width=row_info->width;
  193346. png_debug(1, "in png_do_expand_palette\n");
  193347. if (
  193348. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193349. row != NULL && row_info != NULL &&
  193350. #endif
  193351. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193352. {
  193353. if (row_info->bit_depth < 8)
  193354. {
  193355. switch (row_info->bit_depth)
  193356. {
  193357. case 1:
  193358. {
  193359. sp = row + (png_size_t)((row_width - 1) >> 3);
  193360. dp = row + (png_size_t)row_width - 1;
  193361. shift = 7 - (int)((row_width + 7) & 0x07);
  193362. for (i = 0; i < row_width; i++)
  193363. {
  193364. if ((*sp >> shift) & 0x01)
  193365. *dp = 1;
  193366. else
  193367. *dp = 0;
  193368. if (shift == 7)
  193369. {
  193370. shift = 0;
  193371. sp--;
  193372. }
  193373. else
  193374. shift++;
  193375. dp--;
  193376. }
  193377. break;
  193378. }
  193379. case 2:
  193380. {
  193381. sp = row + (png_size_t)((row_width - 1) >> 2);
  193382. dp = row + (png_size_t)row_width - 1;
  193383. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193384. for (i = 0; i < row_width; i++)
  193385. {
  193386. value = (*sp >> shift) & 0x03;
  193387. *dp = (png_byte)value;
  193388. if (shift == 6)
  193389. {
  193390. shift = 0;
  193391. sp--;
  193392. }
  193393. else
  193394. shift += 2;
  193395. dp--;
  193396. }
  193397. break;
  193398. }
  193399. case 4:
  193400. {
  193401. sp = row + (png_size_t)((row_width - 1) >> 1);
  193402. dp = row + (png_size_t)row_width - 1;
  193403. shift = (int)((row_width & 0x01) << 2);
  193404. for (i = 0; i < row_width; i++)
  193405. {
  193406. value = (*sp >> shift) & 0x0f;
  193407. *dp = (png_byte)value;
  193408. if (shift == 4)
  193409. {
  193410. shift = 0;
  193411. sp--;
  193412. }
  193413. else
  193414. shift += 4;
  193415. dp--;
  193416. }
  193417. break;
  193418. }
  193419. }
  193420. row_info->bit_depth = 8;
  193421. row_info->pixel_depth = 8;
  193422. row_info->rowbytes = row_width;
  193423. }
  193424. switch (row_info->bit_depth)
  193425. {
  193426. case 8:
  193427. {
  193428. if (trans != NULL)
  193429. {
  193430. sp = row + (png_size_t)row_width - 1;
  193431. dp = row + (png_size_t)(row_width << 2) - 1;
  193432. for (i = 0; i < row_width; i++)
  193433. {
  193434. if ((int)(*sp) >= num_trans)
  193435. *dp-- = 0xff;
  193436. else
  193437. *dp-- = trans[*sp];
  193438. *dp-- = palette[*sp].blue;
  193439. *dp-- = palette[*sp].green;
  193440. *dp-- = palette[*sp].red;
  193441. sp--;
  193442. }
  193443. row_info->bit_depth = 8;
  193444. row_info->pixel_depth = 32;
  193445. row_info->rowbytes = row_width * 4;
  193446. row_info->color_type = 6;
  193447. row_info->channels = 4;
  193448. }
  193449. else
  193450. {
  193451. sp = row + (png_size_t)row_width - 1;
  193452. dp = row + (png_size_t)(row_width * 3) - 1;
  193453. for (i = 0; i < row_width; i++)
  193454. {
  193455. *dp-- = palette[*sp].blue;
  193456. *dp-- = palette[*sp].green;
  193457. *dp-- = palette[*sp].red;
  193458. sp--;
  193459. }
  193460. row_info->bit_depth = 8;
  193461. row_info->pixel_depth = 24;
  193462. row_info->rowbytes = row_width * 3;
  193463. row_info->color_type = 2;
  193464. row_info->channels = 3;
  193465. }
  193466. break;
  193467. }
  193468. }
  193469. }
  193470. }
  193471. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193472. * expanded transparency value is supplied, an alpha channel is built.
  193473. */
  193474. void /* PRIVATE */
  193475. png_do_expand(png_row_infop row_info, png_bytep row,
  193476. png_color_16p trans_value)
  193477. {
  193478. int shift, value;
  193479. png_bytep sp, dp;
  193480. png_uint_32 i;
  193481. png_uint_32 row_width=row_info->width;
  193482. png_debug(1, "in png_do_expand\n");
  193483. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193484. if (row != NULL && row_info != NULL)
  193485. #endif
  193486. {
  193487. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193488. {
  193489. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193490. if (row_info->bit_depth < 8)
  193491. {
  193492. switch (row_info->bit_depth)
  193493. {
  193494. case 1:
  193495. {
  193496. gray = (png_uint_16)((gray&0x01)*0xff);
  193497. sp = row + (png_size_t)((row_width - 1) >> 3);
  193498. dp = row + (png_size_t)row_width - 1;
  193499. shift = 7 - (int)((row_width + 7) & 0x07);
  193500. for (i = 0; i < row_width; i++)
  193501. {
  193502. if ((*sp >> shift) & 0x01)
  193503. *dp = 0xff;
  193504. else
  193505. *dp = 0;
  193506. if (shift == 7)
  193507. {
  193508. shift = 0;
  193509. sp--;
  193510. }
  193511. else
  193512. shift++;
  193513. dp--;
  193514. }
  193515. break;
  193516. }
  193517. case 2:
  193518. {
  193519. gray = (png_uint_16)((gray&0x03)*0x55);
  193520. sp = row + (png_size_t)((row_width - 1) >> 2);
  193521. dp = row + (png_size_t)row_width - 1;
  193522. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193523. for (i = 0; i < row_width; i++)
  193524. {
  193525. value = (*sp >> shift) & 0x03;
  193526. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193527. (value << 6));
  193528. if (shift == 6)
  193529. {
  193530. shift = 0;
  193531. sp--;
  193532. }
  193533. else
  193534. shift += 2;
  193535. dp--;
  193536. }
  193537. break;
  193538. }
  193539. case 4:
  193540. {
  193541. gray = (png_uint_16)((gray&0x0f)*0x11);
  193542. sp = row + (png_size_t)((row_width - 1) >> 1);
  193543. dp = row + (png_size_t)row_width - 1;
  193544. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193545. for (i = 0; i < row_width; i++)
  193546. {
  193547. value = (*sp >> shift) & 0x0f;
  193548. *dp = (png_byte)(value | (value << 4));
  193549. if (shift == 4)
  193550. {
  193551. shift = 0;
  193552. sp--;
  193553. }
  193554. else
  193555. shift = 4;
  193556. dp--;
  193557. }
  193558. break;
  193559. }
  193560. }
  193561. row_info->bit_depth = 8;
  193562. row_info->pixel_depth = 8;
  193563. row_info->rowbytes = row_width;
  193564. }
  193565. if (trans_value != NULL)
  193566. {
  193567. if (row_info->bit_depth == 8)
  193568. {
  193569. gray = gray & 0xff;
  193570. sp = row + (png_size_t)row_width - 1;
  193571. dp = row + (png_size_t)(row_width << 1) - 1;
  193572. for (i = 0; i < row_width; i++)
  193573. {
  193574. if (*sp == gray)
  193575. *dp-- = 0;
  193576. else
  193577. *dp-- = 0xff;
  193578. *dp-- = *sp--;
  193579. }
  193580. }
  193581. else if (row_info->bit_depth == 16)
  193582. {
  193583. png_byte gray_high = (gray >> 8) & 0xff;
  193584. png_byte gray_low = gray & 0xff;
  193585. sp = row + row_info->rowbytes - 1;
  193586. dp = row + (row_info->rowbytes << 1) - 1;
  193587. for (i = 0; i < row_width; i++)
  193588. {
  193589. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193590. {
  193591. *dp-- = 0;
  193592. *dp-- = 0;
  193593. }
  193594. else
  193595. {
  193596. *dp-- = 0xff;
  193597. *dp-- = 0xff;
  193598. }
  193599. *dp-- = *sp--;
  193600. *dp-- = *sp--;
  193601. }
  193602. }
  193603. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193604. row_info->channels = 2;
  193605. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193606. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193607. row_width);
  193608. }
  193609. }
  193610. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193611. {
  193612. if (row_info->bit_depth == 8)
  193613. {
  193614. png_byte red = trans_value->red & 0xff;
  193615. png_byte green = trans_value->green & 0xff;
  193616. png_byte blue = trans_value->blue & 0xff;
  193617. sp = row + (png_size_t)row_info->rowbytes - 1;
  193618. dp = row + (png_size_t)(row_width << 2) - 1;
  193619. for (i = 0; i < row_width; i++)
  193620. {
  193621. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193622. *dp-- = 0;
  193623. else
  193624. *dp-- = 0xff;
  193625. *dp-- = *sp--;
  193626. *dp-- = *sp--;
  193627. *dp-- = *sp--;
  193628. }
  193629. }
  193630. else if (row_info->bit_depth == 16)
  193631. {
  193632. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193633. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193634. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193635. png_byte red_low = trans_value->red & 0xff;
  193636. png_byte green_low = trans_value->green & 0xff;
  193637. png_byte blue_low = trans_value->blue & 0xff;
  193638. sp = row + row_info->rowbytes - 1;
  193639. dp = row + (png_size_t)(row_width << 3) - 1;
  193640. for (i = 0; i < row_width; i++)
  193641. {
  193642. if (*(sp - 5) == red_high &&
  193643. *(sp - 4) == red_low &&
  193644. *(sp - 3) == green_high &&
  193645. *(sp - 2) == green_low &&
  193646. *(sp - 1) == blue_high &&
  193647. *(sp ) == blue_low)
  193648. {
  193649. *dp-- = 0;
  193650. *dp-- = 0;
  193651. }
  193652. else
  193653. {
  193654. *dp-- = 0xff;
  193655. *dp-- = 0xff;
  193656. }
  193657. *dp-- = *sp--;
  193658. *dp-- = *sp--;
  193659. *dp-- = *sp--;
  193660. *dp-- = *sp--;
  193661. *dp-- = *sp--;
  193662. *dp-- = *sp--;
  193663. }
  193664. }
  193665. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193666. row_info->channels = 4;
  193667. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193668. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193669. }
  193670. }
  193671. }
  193672. #endif
  193673. #if defined(PNG_READ_DITHER_SUPPORTED)
  193674. void /* PRIVATE */
  193675. png_do_dither(png_row_infop row_info, png_bytep row,
  193676. png_bytep palette_lookup, png_bytep dither_lookup)
  193677. {
  193678. png_bytep sp, dp;
  193679. png_uint_32 i;
  193680. png_uint_32 row_width=row_info->width;
  193681. png_debug(1, "in png_do_dither\n");
  193682. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193683. if (row != NULL && row_info != NULL)
  193684. #endif
  193685. {
  193686. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193687. palette_lookup && row_info->bit_depth == 8)
  193688. {
  193689. int r, g, b, p;
  193690. sp = row;
  193691. dp = row;
  193692. for (i = 0; i < row_width; i++)
  193693. {
  193694. r = *sp++;
  193695. g = *sp++;
  193696. b = *sp++;
  193697. /* this looks real messy, but the compiler will reduce
  193698. it down to a reasonable formula. For example, with
  193699. 5 bits per color, we get:
  193700. p = (((r >> 3) & 0x1f) << 10) |
  193701. (((g >> 3) & 0x1f) << 5) |
  193702. ((b >> 3) & 0x1f);
  193703. */
  193704. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193705. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193706. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193707. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193708. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193709. (PNG_DITHER_BLUE_BITS)) |
  193710. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193711. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193712. *dp++ = palette_lookup[p];
  193713. }
  193714. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193715. row_info->channels = 1;
  193716. row_info->pixel_depth = row_info->bit_depth;
  193717. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193718. }
  193719. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193720. palette_lookup != NULL && row_info->bit_depth == 8)
  193721. {
  193722. int r, g, b, p;
  193723. sp = row;
  193724. dp = row;
  193725. for (i = 0; i < row_width; i++)
  193726. {
  193727. r = *sp++;
  193728. g = *sp++;
  193729. b = *sp++;
  193730. sp++;
  193731. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193732. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193733. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193734. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193735. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193736. (PNG_DITHER_BLUE_BITS)) |
  193737. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193738. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193739. *dp++ = palette_lookup[p];
  193740. }
  193741. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193742. row_info->channels = 1;
  193743. row_info->pixel_depth = row_info->bit_depth;
  193744. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193745. }
  193746. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193747. dither_lookup && row_info->bit_depth == 8)
  193748. {
  193749. sp = row;
  193750. for (i = 0; i < row_width; i++, sp++)
  193751. {
  193752. *sp = dither_lookup[*sp];
  193753. }
  193754. }
  193755. }
  193756. }
  193757. #endif
  193758. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193759. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193760. static PNG_CONST int png_gamma_shift[] =
  193761. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193762. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193763. * tables, we don't make a full table if we are reducing to 8-bit in
  193764. * the future. Note also how the gamma_16 tables are segmented so that
  193765. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193766. */
  193767. void /* PRIVATE */
  193768. png_build_gamma_table(png_structp png_ptr)
  193769. {
  193770. png_debug(1, "in png_build_gamma_table\n");
  193771. if (png_ptr->bit_depth <= 8)
  193772. {
  193773. int i;
  193774. double g;
  193775. if (png_ptr->screen_gamma > .000001)
  193776. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193777. else
  193778. g = 1.0;
  193779. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193780. (png_uint_32)256);
  193781. for (i = 0; i < 256; i++)
  193782. {
  193783. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193784. g) * 255.0 + .5);
  193785. }
  193786. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193787. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193788. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193789. {
  193790. g = 1.0 / (png_ptr->gamma);
  193791. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193792. (png_uint_32)256);
  193793. for (i = 0; i < 256; i++)
  193794. {
  193795. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193796. g) * 255.0 + .5);
  193797. }
  193798. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193799. (png_uint_32)256);
  193800. if(png_ptr->screen_gamma > 0.000001)
  193801. g = 1.0 / png_ptr->screen_gamma;
  193802. else
  193803. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193804. for (i = 0; i < 256; i++)
  193805. {
  193806. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193807. g) * 255.0 + .5);
  193808. }
  193809. }
  193810. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193811. }
  193812. else
  193813. {
  193814. double g;
  193815. int i, j, shift, num;
  193816. int sig_bit;
  193817. png_uint_32 ig;
  193818. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193819. {
  193820. sig_bit = (int)png_ptr->sig_bit.red;
  193821. if ((int)png_ptr->sig_bit.green > sig_bit)
  193822. sig_bit = png_ptr->sig_bit.green;
  193823. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193824. sig_bit = png_ptr->sig_bit.blue;
  193825. }
  193826. else
  193827. {
  193828. sig_bit = (int)png_ptr->sig_bit.gray;
  193829. }
  193830. if (sig_bit > 0)
  193831. shift = 16 - sig_bit;
  193832. else
  193833. shift = 0;
  193834. if (png_ptr->transformations & PNG_16_TO_8)
  193835. {
  193836. if (shift < (16 - PNG_MAX_GAMMA_8))
  193837. shift = (16 - PNG_MAX_GAMMA_8);
  193838. }
  193839. if (shift > 8)
  193840. shift = 8;
  193841. if (shift < 0)
  193842. shift = 0;
  193843. png_ptr->gamma_shift = (png_byte)shift;
  193844. num = (1 << (8 - shift));
  193845. if (png_ptr->screen_gamma > .000001)
  193846. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193847. else
  193848. g = 1.0;
  193849. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193850. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193851. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193852. {
  193853. double fin, fout;
  193854. png_uint_32 last, max;
  193855. for (i = 0; i < num; i++)
  193856. {
  193857. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193858. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193859. }
  193860. g = 1.0 / g;
  193861. last = 0;
  193862. for (i = 0; i < 256; i++)
  193863. {
  193864. fout = ((double)i + 0.5) / 256.0;
  193865. fin = pow(fout, g);
  193866. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193867. while (last <= max)
  193868. {
  193869. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193870. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193871. (png_uint_16)i | ((png_uint_16)i << 8));
  193872. last++;
  193873. }
  193874. }
  193875. while (last < ((png_uint_32)num << 8))
  193876. {
  193877. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193878. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193879. last++;
  193880. }
  193881. }
  193882. else
  193883. {
  193884. for (i = 0; i < num; i++)
  193885. {
  193886. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193887. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193888. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193889. for (j = 0; j < 256; j++)
  193890. {
  193891. png_ptr->gamma_16_table[i][j] =
  193892. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193893. 65535.0, g) * 65535.0 + .5);
  193894. }
  193895. }
  193896. }
  193897. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193898. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193899. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193900. {
  193901. g = 1.0 / (png_ptr->gamma);
  193902. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193903. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193904. for (i = 0; i < num; i++)
  193905. {
  193906. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193907. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193908. ig = (((png_uint_32)i *
  193909. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193910. for (j = 0; j < 256; j++)
  193911. {
  193912. png_ptr->gamma_16_to_1[i][j] =
  193913. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193914. 65535.0, g) * 65535.0 + .5);
  193915. }
  193916. }
  193917. if(png_ptr->screen_gamma > 0.000001)
  193918. g = 1.0 / png_ptr->screen_gamma;
  193919. else
  193920. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193921. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193922. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193923. for (i = 0; i < num; i++)
  193924. {
  193925. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193926. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193927. ig = (((png_uint_32)i *
  193928. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193929. for (j = 0; j < 256; j++)
  193930. {
  193931. png_ptr->gamma_16_from_1[i][j] =
  193932. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193933. 65535.0, g) * 65535.0 + .5);
  193934. }
  193935. }
  193936. }
  193937. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193938. }
  193939. }
  193940. #endif
  193941. /* To do: install integer version of png_build_gamma_table here */
  193942. #endif
  193943. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193944. /* undoes intrapixel differencing */
  193945. void /* PRIVATE */
  193946. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193947. {
  193948. png_debug(1, "in png_do_read_intrapixel\n");
  193949. if (
  193950. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193951. row != NULL && row_info != NULL &&
  193952. #endif
  193953. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193954. {
  193955. int bytes_per_pixel;
  193956. png_uint_32 row_width = row_info->width;
  193957. if (row_info->bit_depth == 8)
  193958. {
  193959. png_bytep rp;
  193960. png_uint_32 i;
  193961. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193962. bytes_per_pixel = 3;
  193963. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193964. bytes_per_pixel = 4;
  193965. else
  193966. return;
  193967. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193968. {
  193969. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193970. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193971. }
  193972. }
  193973. else if (row_info->bit_depth == 16)
  193974. {
  193975. png_bytep rp;
  193976. png_uint_32 i;
  193977. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193978. bytes_per_pixel = 6;
  193979. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193980. bytes_per_pixel = 8;
  193981. else
  193982. return;
  193983. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193984. {
  193985. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193986. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193987. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193988. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193989. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193990. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193991. *(rp+1) = (png_byte)(red & 0xff);
  193992. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193993. *(rp+5) = (png_byte)(blue & 0xff);
  193994. }
  193995. }
  193996. }
  193997. }
  193998. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193999. #endif /* PNG_READ_SUPPORTED */
  194000. /*** End of inlined file: pngrtran.c ***/
  194001. /*** Start of inlined file: pngrutil.c ***/
  194002. /* pngrutil.c - utilities to read a PNG file
  194003. *
  194004. * Last changed in libpng 1.2.21 [October 4, 2007]
  194005. * For conditions of distribution and use, see copyright notice in png.h
  194006. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194007. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194008. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194009. *
  194010. * This file contains routines that are only called from within
  194011. * libpng itself during the course of reading an image.
  194012. */
  194013. #define PNG_INTERNAL
  194014. #if defined(PNG_READ_SUPPORTED)
  194015. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194016. # define WIN32_WCE_OLD
  194017. #endif
  194018. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194019. # if defined(WIN32_WCE_OLD)
  194020. /* strtod() function is not supported on WindowsCE */
  194021. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194022. {
  194023. double result = 0;
  194024. int len;
  194025. wchar_t *str, *end;
  194026. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194027. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194028. if ( NULL != str )
  194029. {
  194030. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194031. result = wcstod(str, &end);
  194032. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194033. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194034. png_free(png_ptr, str);
  194035. }
  194036. return result;
  194037. }
  194038. # else
  194039. # define png_strtod(p,a,b) strtod(a,b)
  194040. # endif
  194041. #endif
  194042. png_uint_32 PNGAPI
  194043. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194044. {
  194045. png_uint_32 i = png_get_uint_32(buf);
  194046. if (i > PNG_UINT_31_MAX)
  194047. png_error(png_ptr, "PNG unsigned integer out of range.");
  194048. return (i);
  194049. }
  194050. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194051. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194052. png_uint_32 PNGAPI
  194053. png_get_uint_32(png_bytep buf)
  194054. {
  194055. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194056. ((png_uint_32)(*(buf + 1)) << 16) +
  194057. ((png_uint_32)(*(buf + 2)) << 8) +
  194058. (png_uint_32)(*(buf + 3));
  194059. return (i);
  194060. }
  194061. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194062. * data is stored in the PNG file in two's complement format, and it is
  194063. * assumed that the machine format for signed integers is the same. */
  194064. png_int_32 PNGAPI
  194065. png_get_int_32(png_bytep buf)
  194066. {
  194067. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194068. ((png_int_32)(*(buf + 1)) << 16) +
  194069. ((png_int_32)(*(buf + 2)) << 8) +
  194070. (png_int_32)(*(buf + 3));
  194071. return (i);
  194072. }
  194073. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194074. png_uint_16 PNGAPI
  194075. png_get_uint_16(png_bytep buf)
  194076. {
  194077. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194078. (png_uint_16)(*(buf + 1)));
  194079. return (i);
  194080. }
  194081. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194082. /* Read data, and (optionally) run it through the CRC. */
  194083. void /* PRIVATE */
  194084. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194085. {
  194086. if(png_ptr == NULL) return;
  194087. png_read_data(png_ptr, buf, length);
  194088. png_calculate_crc(png_ptr, buf, length);
  194089. }
  194090. /* Optionally skip data and then check the CRC. Depending on whether we
  194091. are reading a ancillary or critical chunk, and how the program has set
  194092. things up, we may calculate the CRC on the data and print a message.
  194093. Returns '1' if there was a CRC error, '0' otherwise. */
  194094. int /* PRIVATE */
  194095. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194096. {
  194097. png_size_t i;
  194098. png_size_t istop = png_ptr->zbuf_size;
  194099. for (i = (png_size_t)skip; i > istop; i -= istop)
  194100. {
  194101. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194102. }
  194103. if (i)
  194104. {
  194105. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194106. }
  194107. if (png_crc_error(png_ptr))
  194108. {
  194109. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194110. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194111. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194112. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194113. {
  194114. png_chunk_warning(png_ptr, "CRC error");
  194115. }
  194116. else
  194117. {
  194118. png_chunk_error(png_ptr, "CRC error");
  194119. }
  194120. return (1);
  194121. }
  194122. return (0);
  194123. }
  194124. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194125. the data it has read thus far. */
  194126. int /* PRIVATE */
  194127. png_crc_error(png_structp png_ptr)
  194128. {
  194129. png_byte crc_bytes[4];
  194130. png_uint_32 crc;
  194131. int need_crc = 1;
  194132. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194133. {
  194134. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194135. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194136. need_crc = 0;
  194137. }
  194138. else /* critical */
  194139. {
  194140. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194141. need_crc = 0;
  194142. }
  194143. png_read_data(png_ptr, crc_bytes, 4);
  194144. if (need_crc)
  194145. {
  194146. crc = png_get_uint_32(crc_bytes);
  194147. return ((int)(crc != png_ptr->crc));
  194148. }
  194149. else
  194150. return (0);
  194151. }
  194152. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194153. defined(PNG_READ_iCCP_SUPPORTED)
  194154. /*
  194155. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194156. * points at an allocated area holding the contents of a chunk with a
  194157. * trailing compressed part. What we get back is an allocated area
  194158. * holding the original prefix part and an uncompressed version of the
  194159. * trailing part (the malloc area passed in is freed).
  194160. */
  194161. png_charp /* PRIVATE */
  194162. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194163. png_charp chunkdata, png_size_t chunklength,
  194164. png_size_t prefix_size, png_size_t *newlength)
  194165. {
  194166. static PNG_CONST char msg[] = "Error decoding compressed text";
  194167. png_charp text;
  194168. png_size_t text_size;
  194169. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194170. {
  194171. int ret = Z_OK;
  194172. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194173. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194174. png_ptr->zstream.next_out = png_ptr->zbuf;
  194175. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194176. text_size = 0;
  194177. text = NULL;
  194178. while (png_ptr->zstream.avail_in)
  194179. {
  194180. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194181. if (ret != Z_OK && ret != Z_STREAM_END)
  194182. {
  194183. if (png_ptr->zstream.msg != NULL)
  194184. png_warning(png_ptr, png_ptr->zstream.msg);
  194185. else
  194186. png_warning(png_ptr, msg);
  194187. inflateReset(&png_ptr->zstream);
  194188. png_ptr->zstream.avail_in = 0;
  194189. if (text == NULL)
  194190. {
  194191. text_size = prefix_size + png_sizeof(msg) + 1;
  194192. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194193. if (text == NULL)
  194194. {
  194195. png_free(png_ptr,chunkdata);
  194196. png_error(png_ptr,"Not enough memory to decompress chunk");
  194197. }
  194198. png_memcpy(text, chunkdata, prefix_size);
  194199. }
  194200. text[text_size - 1] = 0x00;
  194201. /* Copy what we can of the error message into the text chunk */
  194202. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194203. text_size = png_sizeof(msg) > text_size ? text_size :
  194204. png_sizeof(msg);
  194205. png_memcpy(text + prefix_size, msg, text_size + 1);
  194206. break;
  194207. }
  194208. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194209. {
  194210. if (text == NULL)
  194211. {
  194212. text_size = prefix_size +
  194213. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194214. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194215. if (text == NULL)
  194216. {
  194217. png_free(png_ptr,chunkdata);
  194218. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194219. }
  194220. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194221. text_size - prefix_size);
  194222. png_memcpy(text, chunkdata, prefix_size);
  194223. *(text + text_size) = 0x00;
  194224. }
  194225. else
  194226. {
  194227. png_charp tmp;
  194228. tmp = text;
  194229. text = (png_charp)png_malloc_warn(png_ptr,
  194230. (png_uint_32)(text_size +
  194231. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194232. if (text == NULL)
  194233. {
  194234. png_free(png_ptr, tmp);
  194235. png_free(png_ptr, chunkdata);
  194236. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194237. }
  194238. png_memcpy(text, tmp, text_size);
  194239. png_free(png_ptr, tmp);
  194240. png_memcpy(text + text_size, png_ptr->zbuf,
  194241. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194242. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194243. *(text + text_size) = 0x00;
  194244. }
  194245. if (ret == Z_STREAM_END)
  194246. break;
  194247. else
  194248. {
  194249. png_ptr->zstream.next_out = png_ptr->zbuf;
  194250. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194251. }
  194252. }
  194253. }
  194254. if (ret != Z_STREAM_END)
  194255. {
  194256. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194257. char umsg[52];
  194258. if (ret == Z_BUF_ERROR)
  194259. png_snprintf(umsg, 52,
  194260. "Buffer error in compressed datastream in %s chunk",
  194261. png_ptr->chunk_name);
  194262. else if (ret == Z_DATA_ERROR)
  194263. png_snprintf(umsg, 52,
  194264. "Data error in compressed datastream in %s chunk",
  194265. png_ptr->chunk_name);
  194266. else
  194267. png_snprintf(umsg, 52,
  194268. "Incomplete compressed datastream in %s chunk",
  194269. png_ptr->chunk_name);
  194270. png_warning(png_ptr, umsg);
  194271. #else
  194272. png_warning(png_ptr,
  194273. "Incomplete compressed datastream in chunk other than IDAT");
  194274. #endif
  194275. text_size=prefix_size;
  194276. if (text == NULL)
  194277. {
  194278. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194279. if (text == NULL)
  194280. {
  194281. png_free(png_ptr, chunkdata);
  194282. png_error(png_ptr,"Not enough memory for text.");
  194283. }
  194284. png_memcpy(text, chunkdata, prefix_size);
  194285. }
  194286. *(text + text_size) = 0x00;
  194287. }
  194288. inflateReset(&png_ptr->zstream);
  194289. png_ptr->zstream.avail_in = 0;
  194290. png_free(png_ptr, chunkdata);
  194291. chunkdata = text;
  194292. *newlength=text_size;
  194293. }
  194294. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194295. {
  194296. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194297. char umsg[50];
  194298. png_snprintf(umsg, 50,
  194299. "Unknown zTXt compression type %d", comp_type);
  194300. png_warning(png_ptr, umsg);
  194301. #else
  194302. png_warning(png_ptr, "Unknown zTXt compression type");
  194303. #endif
  194304. *(chunkdata + prefix_size) = 0x00;
  194305. *newlength=prefix_size;
  194306. }
  194307. return chunkdata;
  194308. }
  194309. #endif
  194310. /* read and check the IDHR chunk */
  194311. void /* PRIVATE */
  194312. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194313. {
  194314. png_byte buf[13];
  194315. png_uint_32 width, height;
  194316. int bit_depth, color_type, compression_type, filter_type;
  194317. int interlace_type;
  194318. png_debug(1, "in png_handle_IHDR\n");
  194319. if (png_ptr->mode & PNG_HAVE_IHDR)
  194320. png_error(png_ptr, "Out of place IHDR");
  194321. /* check the length */
  194322. if (length != 13)
  194323. png_error(png_ptr, "Invalid IHDR chunk");
  194324. png_ptr->mode |= PNG_HAVE_IHDR;
  194325. png_crc_read(png_ptr, buf, 13);
  194326. png_crc_finish(png_ptr, 0);
  194327. width = png_get_uint_31(png_ptr, buf);
  194328. height = png_get_uint_31(png_ptr, buf + 4);
  194329. bit_depth = buf[8];
  194330. color_type = buf[9];
  194331. compression_type = buf[10];
  194332. filter_type = buf[11];
  194333. interlace_type = buf[12];
  194334. /* set internal variables */
  194335. png_ptr->width = width;
  194336. png_ptr->height = height;
  194337. png_ptr->bit_depth = (png_byte)bit_depth;
  194338. png_ptr->interlaced = (png_byte)interlace_type;
  194339. png_ptr->color_type = (png_byte)color_type;
  194340. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194341. png_ptr->filter_type = (png_byte)filter_type;
  194342. #endif
  194343. png_ptr->compression_type = (png_byte)compression_type;
  194344. /* find number of channels */
  194345. switch (png_ptr->color_type)
  194346. {
  194347. case PNG_COLOR_TYPE_GRAY:
  194348. case PNG_COLOR_TYPE_PALETTE:
  194349. png_ptr->channels = 1;
  194350. break;
  194351. case PNG_COLOR_TYPE_RGB:
  194352. png_ptr->channels = 3;
  194353. break;
  194354. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194355. png_ptr->channels = 2;
  194356. break;
  194357. case PNG_COLOR_TYPE_RGB_ALPHA:
  194358. png_ptr->channels = 4;
  194359. break;
  194360. }
  194361. /* set up other useful info */
  194362. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194363. png_ptr->channels);
  194364. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194365. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194366. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194367. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194368. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194369. color_type, interlace_type, compression_type, filter_type);
  194370. }
  194371. /* read and check the palette */
  194372. void /* PRIVATE */
  194373. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194374. {
  194375. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194376. int num, i;
  194377. #ifndef PNG_NO_POINTER_INDEXING
  194378. png_colorp pal_ptr;
  194379. #endif
  194380. png_debug(1, "in png_handle_PLTE\n");
  194381. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194382. png_error(png_ptr, "Missing IHDR before PLTE");
  194383. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194384. {
  194385. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194386. png_crc_finish(png_ptr, length);
  194387. return;
  194388. }
  194389. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194390. png_error(png_ptr, "Duplicate PLTE chunk");
  194391. png_ptr->mode |= PNG_HAVE_PLTE;
  194392. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194393. {
  194394. png_warning(png_ptr,
  194395. "Ignoring PLTE chunk in grayscale PNG");
  194396. png_crc_finish(png_ptr, length);
  194397. return;
  194398. }
  194399. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194400. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194401. {
  194402. png_crc_finish(png_ptr, length);
  194403. return;
  194404. }
  194405. #endif
  194406. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194407. {
  194408. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194409. {
  194410. png_warning(png_ptr, "Invalid palette chunk");
  194411. png_crc_finish(png_ptr, length);
  194412. return;
  194413. }
  194414. else
  194415. {
  194416. png_error(png_ptr, "Invalid palette chunk");
  194417. }
  194418. }
  194419. num = (int)length / 3;
  194420. #ifndef PNG_NO_POINTER_INDEXING
  194421. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194422. {
  194423. png_byte buf[3];
  194424. png_crc_read(png_ptr, buf, 3);
  194425. pal_ptr->red = buf[0];
  194426. pal_ptr->green = buf[1];
  194427. pal_ptr->blue = buf[2];
  194428. }
  194429. #else
  194430. for (i = 0; i < num; i++)
  194431. {
  194432. png_byte buf[3];
  194433. png_crc_read(png_ptr, buf, 3);
  194434. /* don't depend upon png_color being any order */
  194435. palette[i].red = buf[0];
  194436. palette[i].green = buf[1];
  194437. palette[i].blue = buf[2];
  194438. }
  194439. #endif
  194440. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194441. whatever the normal CRC configuration tells us. However, if we
  194442. have an RGB image, the PLTE can be considered ancillary, so
  194443. we will act as though it is. */
  194444. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194445. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194446. #endif
  194447. {
  194448. png_crc_finish(png_ptr, 0);
  194449. }
  194450. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194451. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194452. {
  194453. /* If we don't want to use the data from an ancillary chunk,
  194454. we have two options: an error abort, or a warning and we
  194455. ignore the data in this chunk (which should be OK, since
  194456. it's considered ancillary for a RGB or RGBA image). */
  194457. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194458. {
  194459. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194460. {
  194461. png_chunk_error(png_ptr, "CRC error");
  194462. }
  194463. else
  194464. {
  194465. png_chunk_warning(png_ptr, "CRC error");
  194466. return;
  194467. }
  194468. }
  194469. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194470. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194471. {
  194472. png_chunk_warning(png_ptr, "CRC error");
  194473. }
  194474. }
  194475. #endif
  194476. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194477. #if defined(PNG_READ_tRNS_SUPPORTED)
  194478. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194479. {
  194480. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194481. {
  194482. if (png_ptr->num_trans > (png_uint_16)num)
  194483. {
  194484. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194485. png_ptr->num_trans = (png_uint_16)num;
  194486. }
  194487. if (info_ptr->num_trans > (png_uint_16)num)
  194488. {
  194489. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194490. info_ptr->num_trans = (png_uint_16)num;
  194491. }
  194492. }
  194493. }
  194494. #endif
  194495. }
  194496. void /* PRIVATE */
  194497. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194498. {
  194499. png_debug(1, "in png_handle_IEND\n");
  194500. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194501. {
  194502. png_error(png_ptr, "No image in file");
  194503. }
  194504. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194505. if (length != 0)
  194506. {
  194507. png_warning(png_ptr, "Incorrect IEND chunk length");
  194508. }
  194509. png_crc_finish(png_ptr, length);
  194510. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194511. }
  194512. #if defined(PNG_READ_gAMA_SUPPORTED)
  194513. void /* PRIVATE */
  194514. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194515. {
  194516. png_fixed_point igamma;
  194517. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194518. float file_gamma;
  194519. #endif
  194520. png_byte buf[4];
  194521. png_debug(1, "in png_handle_gAMA\n");
  194522. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194523. png_error(png_ptr, "Missing IHDR before gAMA");
  194524. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194525. {
  194526. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194527. png_crc_finish(png_ptr, length);
  194528. return;
  194529. }
  194530. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194531. /* Should be an error, but we can cope with it */
  194532. png_warning(png_ptr, "Out of place gAMA chunk");
  194533. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194534. #if defined(PNG_READ_sRGB_SUPPORTED)
  194535. && !(info_ptr->valid & PNG_INFO_sRGB)
  194536. #endif
  194537. )
  194538. {
  194539. png_warning(png_ptr, "Duplicate gAMA chunk");
  194540. png_crc_finish(png_ptr, length);
  194541. return;
  194542. }
  194543. if (length != 4)
  194544. {
  194545. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194546. png_crc_finish(png_ptr, length);
  194547. return;
  194548. }
  194549. png_crc_read(png_ptr, buf, 4);
  194550. if (png_crc_finish(png_ptr, 0))
  194551. return;
  194552. igamma = (png_fixed_point)png_get_uint_32(buf);
  194553. /* check for zero gamma */
  194554. if (igamma == 0)
  194555. {
  194556. png_warning(png_ptr,
  194557. "Ignoring gAMA chunk with gamma=0");
  194558. return;
  194559. }
  194560. #if defined(PNG_READ_sRGB_SUPPORTED)
  194561. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194562. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194563. {
  194564. png_warning(png_ptr,
  194565. "Ignoring incorrect gAMA value when sRGB is also present");
  194566. #ifndef PNG_NO_CONSOLE_IO
  194567. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194568. #endif
  194569. return;
  194570. }
  194571. #endif /* PNG_READ_sRGB_SUPPORTED */
  194572. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194573. file_gamma = (float)igamma / (float)100000.0;
  194574. # ifdef PNG_READ_GAMMA_SUPPORTED
  194575. png_ptr->gamma = file_gamma;
  194576. # endif
  194577. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194578. #endif
  194579. #ifdef PNG_FIXED_POINT_SUPPORTED
  194580. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194581. #endif
  194582. }
  194583. #endif
  194584. #if defined(PNG_READ_sBIT_SUPPORTED)
  194585. void /* PRIVATE */
  194586. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194587. {
  194588. png_size_t truelen;
  194589. png_byte buf[4];
  194590. png_debug(1, "in png_handle_sBIT\n");
  194591. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194592. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194593. png_error(png_ptr, "Missing IHDR before sBIT");
  194594. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194595. {
  194596. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194597. png_crc_finish(png_ptr, length);
  194598. return;
  194599. }
  194600. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194601. {
  194602. /* Should be an error, but we can cope with it */
  194603. png_warning(png_ptr, "Out of place sBIT chunk");
  194604. }
  194605. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194606. {
  194607. png_warning(png_ptr, "Duplicate sBIT chunk");
  194608. png_crc_finish(png_ptr, length);
  194609. return;
  194610. }
  194611. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194612. truelen = 3;
  194613. else
  194614. truelen = (png_size_t)png_ptr->channels;
  194615. if (length != truelen || length > 4)
  194616. {
  194617. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194618. png_crc_finish(png_ptr, length);
  194619. return;
  194620. }
  194621. png_crc_read(png_ptr, buf, truelen);
  194622. if (png_crc_finish(png_ptr, 0))
  194623. return;
  194624. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194625. {
  194626. png_ptr->sig_bit.red = buf[0];
  194627. png_ptr->sig_bit.green = buf[1];
  194628. png_ptr->sig_bit.blue = buf[2];
  194629. png_ptr->sig_bit.alpha = buf[3];
  194630. }
  194631. else
  194632. {
  194633. png_ptr->sig_bit.gray = buf[0];
  194634. png_ptr->sig_bit.red = buf[0];
  194635. png_ptr->sig_bit.green = buf[0];
  194636. png_ptr->sig_bit.blue = buf[0];
  194637. png_ptr->sig_bit.alpha = buf[1];
  194638. }
  194639. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194640. }
  194641. #endif
  194642. #if defined(PNG_READ_cHRM_SUPPORTED)
  194643. void /* PRIVATE */
  194644. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194645. {
  194646. png_byte buf[4];
  194647. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194648. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194649. #endif
  194650. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194651. int_y_green, int_x_blue, int_y_blue;
  194652. png_uint_32 uint_x, uint_y;
  194653. png_debug(1, "in png_handle_cHRM\n");
  194654. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194655. png_error(png_ptr, "Missing IHDR before cHRM");
  194656. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194657. {
  194658. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194659. png_crc_finish(png_ptr, length);
  194660. return;
  194661. }
  194662. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194663. /* Should be an error, but we can cope with it */
  194664. png_warning(png_ptr, "Missing PLTE before cHRM");
  194665. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194666. #if defined(PNG_READ_sRGB_SUPPORTED)
  194667. && !(info_ptr->valid & PNG_INFO_sRGB)
  194668. #endif
  194669. )
  194670. {
  194671. png_warning(png_ptr, "Duplicate cHRM chunk");
  194672. png_crc_finish(png_ptr, length);
  194673. return;
  194674. }
  194675. if (length != 32)
  194676. {
  194677. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194678. png_crc_finish(png_ptr, length);
  194679. return;
  194680. }
  194681. png_crc_read(png_ptr, buf, 4);
  194682. uint_x = png_get_uint_32(buf);
  194683. png_crc_read(png_ptr, buf, 4);
  194684. uint_y = png_get_uint_32(buf);
  194685. if (uint_x > 80000L || uint_y > 80000L ||
  194686. uint_x + uint_y > 100000L)
  194687. {
  194688. png_warning(png_ptr, "Invalid cHRM white point");
  194689. png_crc_finish(png_ptr, 24);
  194690. return;
  194691. }
  194692. int_x_white = (png_fixed_point)uint_x;
  194693. int_y_white = (png_fixed_point)uint_y;
  194694. png_crc_read(png_ptr, buf, 4);
  194695. uint_x = png_get_uint_32(buf);
  194696. png_crc_read(png_ptr, buf, 4);
  194697. uint_y = png_get_uint_32(buf);
  194698. if (uint_x + uint_y > 100000L)
  194699. {
  194700. png_warning(png_ptr, "Invalid cHRM red point");
  194701. png_crc_finish(png_ptr, 16);
  194702. return;
  194703. }
  194704. int_x_red = (png_fixed_point)uint_x;
  194705. int_y_red = (png_fixed_point)uint_y;
  194706. png_crc_read(png_ptr, buf, 4);
  194707. uint_x = png_get_uint_32(buf);
  194708. png_crc_read(png_ptr, buf, 4);
  194709. uint_y = png_get_uint_32(buf);
  194710. if (uint_x + uint_y > 100000L)
  194711. {
  194712. png_warning(png_ptr, "Invalid cHRM green point");
  194713. png_crc_finish(png_ptr, 8);
  194714. return;
  194715. }
  194716. int_x_green = (png_fixed_point)uint_x;
  194717. int_y_green = (png_fixed_point)uint_y;
  194718. png_crc_read(png_ptr, buf, 4);
  194719. uint_x = png_get_uint_32(buf);
  194720. png_crc_read(png_ptr, buf, 4);
  194721. uint_y = png_get_uint_32(buf);
  194722. if (uint_x + uint_y > 100000L)
  194723. {
  194724. png_warning(png_ptr, "Invalid cHRM blue point");
  194725. png_crc_finish(png_ptr, 0);
  194726. return;
  194727. }
  194728. int_x_blue = (png_fixed_point)uint_x;
  194729. int_y_blue = (png_fixed_point)uint_y;
  194730. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194731. white_x = (float)int_x_white / (float)100000.0;
  194732. white_y = (float)int_y_white / (float)100000.0;
  194733. red_x = (float)int_x_red / (float)100000.0;
  194734. red_y = (float)int_y_red / (float)100000.0;
  194735. green_x = (float)int_x_green / (float)100000.0;
  194736. green_y = (float)int_y_green / (float)100000.0;
  194737. blue_x = (float)int_x_blue / (float)100000.0;
  194738. blue_y = (float)int_y_blue / (float)100000.0;
  194739. #endif
  194740. #if defined(PNG_READ_sRGB_SUPPORTED)
  194741. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194742. {
  194743. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194744. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194745. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194746. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194747. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194748. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194749. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194750. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194751. {
  194752. png_warning(png_ptr,
  194753. "Ignoring incorrect cHRM value when sRGB is also present");
  194754. #ifndef PNG_NO_CONSOLE_IO
  194755. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194756. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194757. white_x, white_y, red_x, red_y);
  194758. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194759. green_x, green_y, blue_x, blue_y);
  194760. #else
  194761. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194762. int_x_white, int_y_white, int_x_red, int_y_red);
  194763. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194764. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194765. #endif
  194766. #endif /* PNG_NO_CONSOLE_IO */
  194767. }
  194768. png_crc_finish(png_ptr, 0);
  194769. return;
  194770. }
  194771. #endif /* PNG_READ_sRGB_SUPPORTED */
  194772. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194773. png_set_cHRM(png_ptr, info_ptr,
  194774. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194775. #endif
  194776. #ifdef PNG_FIXED_POINT_SUPPORTED
  194777. png_set_cHRM_fixed(png_ptr, info_ptr,
  194778. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194779. int_y_green, int_x_blue, int_y_blue);
  194780. #endif
  194781. if (png_crc_finish(png_ptr, 0))
  194782. return;
  194783. }
  194784. #endif
  194785. #if defined(PNG_READ_sRGB_SUPPORTED)
  194786. void /* PRIVATE */
  194787. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194788. {
  194789. int intent;
  194790. png_byte buf[1];
  194791. png_debug(1, "in png_handle_sRGB\n");
  194792. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194793. png_error(png_ptr, "Missing IHDR before sRGB");
  194794. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194795. {
  194796. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194797. png_crc_finish(png_ptr, length);
  194798. return;
  194799. }
  194800. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194801. /* Should be an error, but we can cope with it */
  194802. png_warning(png_ptr, "Out of place sRGB chunk");
  194803. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194804. {
  194805. png_warning(png_ptr, "Duplicate sRGB chunk");
  194806. png_crc_finish(png_ptr, length);
  194807. return;
  194808. }
  194809. if (length != 1)
  194810. {
  194811. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194812. png_crc_finish(png_ptr, length);
  194813. return;
  194814. }
  194815. png_crc_read(png_ptr, buf, 1);
  194816. if (png_crc_finish(png_ptr, 0))
  194817. return;
  194818. intent = buf[0];
  194819. /* check for bad intent */
  194820. if (intent >= PNG_sRGB_INTENT_LAST)
  194821. {
  194822. png_warning(png_ptr, "Unknown sRGB intent");
  194823. return;
  194824. }
  194825. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194826. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194827. {
  194828. png_fixed_point igamma;
  194829. #ifdef PNG_FIXED_POINT_SUPPORTED
  194830. igamma=info_ptr->int_gamma;
  194831. #else
  194832. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194833. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194834. # endif
  194835. #endif
  194836. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194837. {
  194838. png_warning(png_ptr,
  194839. "Ignoring incorrect gAMA value when sRGB is also present");
  194840. #ifndef PNG_NO_CONSOLE_IO
  194841. # ifdef PNG_FIXED_POINT_SUPPORTED
  194842. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194843. # else
  194844. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194845. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194846. # endif
  194847. # endif
  194848. #endif
  194849. }
  194850. }
  194851. #endif /* PNG_READ_gAMA_SUPPORTED */
  194852. #ifdef PNG_READ_cHRM_SUPPORTED
  194853. #ifdef PNG_FIXED_POINT_SUPPORTED
  194854. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194855. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194856. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194857. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194858. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194859. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194860. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194861. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194862. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194863. {
  194864. png_warning(png_ptr,
  194865. "Ignoring incorrect cHRM value when sRGB is also present");
  194866. }
  194867. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194868. #endif /* PNG_READ_cHRM_SUPPORTED */
  194869. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194870. }
  194871. #endif /* PNG_READ_sRGB_SUPPORTED */
  194872. #if defined(PNG_READ_iCCP_SUPPORTED)
  194873. void /* PRIVATE */
  194874. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194875. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194876. {
  194877. png_charp chunkdata;
  194878. png_byte compression_type;
  194879. png_bytep pC;
  194880. png_charp profile;
  194881. png_uint_32 skip = 0;
  194882. png_uint_32 profile_size, profile_length;
  194883. png_size_t slength, prefix_length, data_length;
  194884. png_debug(1, "in png_handle_iCCP\n");
  194885. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194886. png_error(png_ptr, "Missing IHDR before iCCP");
  194887. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194888. {
  194889. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194890. png_crc_finish(png_ptr, length);
  194891. return;
  194892. }
  194893. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194894. /* Should be an error, but we can cope with it */
  194895. png_warning(png_ptr, "Out of place iCCP chunk");
  194896. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194897. {
  194898. png_warning(png_ptr, "Duplicate iCCP chunk");
  194899. png_crc_finish(png_ptr, length);
  194900. return;
  194901. }
  194902. #ifdef PNG_MAX_MALLOC_64K
  194903. if (length > (png_uint_32)65535L)
  194904. {
  194905. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194906. skip = length - (png_uint_32)65535L;
  194907. length = (png_uint_32)65535L;
  194908. }
  194909. #endif
  194910. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194911. slength = (png_size_t)length;
  194912. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194913. if (png_crc_finish(png_ptr, skip))
  194914. {
  194915. png_free(png_ptr, chunkdata);
  194916. return;
  194917. }
  194918. chunkdata[slength] = 0x00;
  194919. for (profile = chunkdata; *profile; profile++)
  194920. /* empty loop to find end of name */ ;
  194921. ++profile;
  194922. /* there should be at least one zero (the compression type byte)
  194923. following the separator, and we should be on it */
  194924. if ( profile >= chunkdata + slength - 1)
  194925. {
  194926. png_free(png_ptr, chunkdata);
  194927. png_warning(png_ptr, "Malformed iCCP chunk");
  194928. return;
  194929. }
  194930. /* compression_type should always be zero */
  194931. compression_type = *profile++;
  194932. if (compression_type)
  194933. {
  194934. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194935. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194936. wrote nonzero) */
  194937. }
  194938. prefix_length = profile - chunkdata;
  194939. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194940. slength, prefix_length, &data_length);
  194941. profile_length = data_length - prefix_length;
  194942. if ( prefix_length > data_length || profile_length < 4)
  194943. {
  194944. png_free(png_ptr, chunkdata);
  194945. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194946. return;
  194947. }
  194948. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194949. pC = (png_bytep)(chunkdata+prefix_length);
  194950. profile_size = ((*(pC ))<<24) |
  194951. ((*(pC+1))<<16) |
  194952. ((*(pC+2))<< 8) |
  194953. ((*(pC+3)) );
  194954. if(profile_size < profile_length)
  194955. profile_length = profile_size;
  194956. if(profile_size > profile_length)
  194957. {
  194958. png_free(png_ptr, chunkdata);
  194959. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194960. return;
  194961. }
  194962. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194963. chunkdata + prefix_length, profile_length);
  194964. png_free(png_ptr, chunkdata);
  194965. }
  194966. #endif /* PNG_READ_iCCP_SUPPORTED */
  194967. #if defined(PNG_READ_sPLT_SUPPORTED)
  194968. void /* PRIVATE */
  194969. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194970. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194971. {
  194972. png_bytep chunkdata;
  194973. png_bytep entry_start;
  194974. png_sPLT_t new_palette;
  194975. #ifdef PNG_NO_POINTER_INDEXING
  194976. png_sPLT_entryp pp;
  194977. #endif
  194978. int data_length, entry_size, i;
  194979. png_uint_32 skip = 0;
  194980. png_size_t slength;
  194981. png_debug(1, "in png_handle_sPLT\n");
  194982. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194983. png_error(png_ptr, "Missing IHDR before sPLT");
  194984. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194985. {
  194986. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194987. png_crc_finish(png_ptr, length);
  194988. return;
  194989. }
  194990. #ifdef PNG_MAX_MALLOC_64K
  194991. if (length > (png_uint_32)65535L)
  194992. {
  194993. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194994. skip = length - (png_uint_32)65535L;
  194995. length = (png_uint_32)65535L;
  194996. }
  194997. #endif
  194998. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194999. slength = (png_size_t)length;
  195000. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195001. if (png_crc_finish(png_ptr, skip))
  195002. {
  195003. png_free(png_ptr, chunkdata);
  195004. return;
  195005. }
  195006. chunkdata[slength] = 0x00;
  195007. for (entry_start = chunkdata; *entry_start; entry_start++)
  195008. /* empty loop to find end of name */ ;
  195009. ++entry_start;
  195010. /* a sample depth should follow the separator, and we should be on it */
  195011. if (entry_start > chunkdata + slength - 2)
  195012. {
  195013. png_free(png_ptr, chunkdata);
  195014. png_warning(png_ptr, "malformed sPLT chunk");
  195015. return;
  195016. }
  195017. new_palette.depth = *entry_start++;
  195018. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195019. data_length = (slength - (entry_start - chunkdata));
  195020. /* integrity-check the data length */
  195021. if (data_length % entry_size)
  195022. {
  195023. png_free(png_ptr, chunkdata);
  195024. png_warning(png_ptr, "sPLT chunk has bad length");
  195025. return;
  195026. }
  195027. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195028. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195029. png_sizeof(png_sPLT_entry)))
  195030. {
  195031. png_warning(png_ptr, "sPLT chunk too long");
  195032. return;
  195033. }
  195034. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195035. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195036. if (new_palette.entries == NULL)
  195037. {
  195038. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195039. return;
  195040. }
  195041. #ifndef PNG_NO_POINTER_INDEXING
  195042. for (i = 0; i < new_palette.nentries; i++)
  195043. {
  195044. png_sPLT_entryp pp = new_palette.entries + i;
  195045. if (new_palette.depth == 8)
  195046. {
  195047. pp->red = *entry_start++;
  195048. pp->green = *entry_start++;
  195049. pp->blue = *entry_start++;
  195050. pp->alpha = *entry_start++;
  195051. }
  195052. else
  195053. {
  195054. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195055. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195056. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195057. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195058. }
  195059. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195060. }
  195061. #else
  195062. pp = new_palette.entries;
  195063. for (i = 0; i < new_palette.nentries; i++)
  195064. {
  195065. if (new_palette.depth == 8)
  195066. {
  195067. pp[i].red = *entry_start++;
  195068. pp[i].green = *entry_start++;
  195069. pp[i].blue = *entry_start++;
  195070. pp[i].alpha = *entry_start++;
  195071. }
  195072. else
  195073. {
  195074. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195075. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195076. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195077. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195078. }
  195079. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195080. }
  195081. #endif
  195082. /* discard all chunk data except the name and stash that */
  195083. new_palette.name = (png_charp)chunkdata;
  195084. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195085. png_free(png_ptr, chunkdata);
  195086. png_free(png_ptr, new_palette.entries);
  195087. }
  195088. #endif /* PNG_READ_sPLT_SUPPORTED */
  195089. #if defined(PNG_READ_tRNS_SUPPORTED)
  195090. void /* PRIVATE */
  195091. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195092. {
  195093. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195094. int bit_mask;
  195095. png_debug(1, "in png_handle_tRNS\n");
  195096. /* For non-indexed color, mask off any bits in the tRNS value that
  195097. * exceed the bit depth. Some creators were writing extra bits there.
  195098. * This is not needed for indexed color. */
  195099. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195100. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195101. png_error(png_ptr, "Missing IHDR before tRNS");
  195102. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195103. {
  195104. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195105. png_crc_finish(png_ptr, length);
  195106. return;
  195107. }
  195108. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195109. {
  195110. png_warning(png_ptr, "Duplicate tRNS chunk");
  195111. png_crc_finish(png_ptr, length);
  195112. return;
  195113. }
  195114. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195115. {
  195116. png_byte buf[2];
  195117. if (length != 2)
  195118. {
  195119. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195120. png_crc_finish(png_ptr, length);
  195121. return;
  195122. }
  195123. png_crc_read(png_ptr, buf, 2);
  195124. png_ptr->num_trans = 1;
  195125. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195126. }
  195127. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195128. {
  195129. png_byte buf[6];
  195130. if (length != 6)
  195131. {
  195132. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195133. png_crc_finish(png_ptr, length);
  195134. return;
  195135. }
  195136. png_crc_read(png_ptr, buf, (png_size_t)length);
  195137. png_ptr->num_trans = 1;
  195138. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195139. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195140. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195141. }
  195142. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195143. {
  195144. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195145. {
  195146. /* Should be an error, but we can cope with it. */
  195147. png_warning(png_ptr, "Missing PLTE before tRNS");
  195148. }
  195149. if (length > (png_uint_32)png_ptr->num_palette ||
  195150. length > PNG_MAX_PALETTE_LENGTH)
  195151. {
  195152. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195153. png_crc_finish(png_ptr, length);
  195154. return;
  195155. }
  195156. if (length == 0)
  195157. {
  195158. png_warning(png_ptr, "Zero length tRNS chunk");
  195159. png_crc_finish(png_ptr, length);
  195160. return;
  195161. }
  195162. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195163. png_ptr->num_trans = (png_uint_16)length;
  195164. }
  195165. else
  195166. {
  195167. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195168. png_crc_finish(png_ptr, length);
  195169. return;
  195170. }
  195171. if (png_crc_finish(png_ptr, 0))
  195172. {
  195173. png_ptr->num_trans = 0;
  195174. return;
  195175. }
  195176. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195177. &(png_ptr->trans_values));
  195178. }
  195179. #endif
  195180. #if defined(PNG_READ_bKGD_SUPPORTED)
  195181. void /* PRIVATE */
  195182. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195183. {
  195184. png_size_t truelen;
  195185. png_byte buf[6];
  195186. png_debug(1, "in png_handle_bKGD\n");
  195187. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195188. png_error(png_ptr, "Missing IHDR before bKGD");
  195189. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195190. {
  195191. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195192. png_crc_finish(png_ptr, length);
  195193. return;
  195194. }
  195195. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195196. !(png_ptr->mode & PNG_HAVE_PLTE))
  195197. {
  195198. png_warning(png_ptr, "Missing PLTE before bKGD");
  195199. png_crc_finish(png_ptr, length);
  195200. return;
  195201. }
  195202. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195203. {
  195204. png_warning(png_ptr, "Duplicate bKGD chunk");
  195205. png_crc_finish(png_ptr, length);
  195206. return;
  195207. }
  195208. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195209. truelen = 1;
  195210. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195211. truelen = 6;
  195212. else
  195213. truelen = 2;
  195214. if (length != truelen)
  195215. {
  195216. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195217. png_crc_finish(png_ptr, length);
  195218. return;
  195219. }
  195220. png_crc_read(png_ptr, buf, truelen);
  195221. if (png_crc_finish(png_ptr, 0))
  195222. return;
  195223. /* We convert the index value into RGB components so that we can allow
  195224. * arbitrary RGB values for background when we have transparency, and
  195225. * so it is easy to determine the RGB values of the background color
  195226. * from the info_ptr struct. */
  195227. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195228. {
  195229. png_ptr->background.index = buf[0];
  195230. if(info_ptr->num_palette)
  195231. {
  195232. if(buf[0] > info_ptr->num_palette)
  195233. {
  195234. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195235. return;
  195236. }
  195237. png_ptr->background.red =
  195238. (png_uint_16)png_ptr->palette[buf[0]].red;
  195239. png_ptr->background.green =
  195240. (png_uint_16)png_ptr->palette[buf[0]].green;
  195241. png_ptr->background.blue =
  195242. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195243. }
  195244. }
  195245. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195246. {
  195247. png_ptr->background.red =
  195248. png_ptr->background.green =
  195249. png_ptr->background.blue =
  195250. png_ptr->background.gray = png_get_uint_16(buf);
  195251. }
  195252. else
  195253. {
  195254. png_ptr->background.red = png_get_uint_16(buf);
  195255. png_ptr->background.green = png_get_uint_16(buf + 2);
  195256. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195257. }
  195258. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195259. }
  195260. #endif
  195261. #if defined(PNG_READ_hIST_SUPPORTED)
  195262. void /* PRIVATE */
  195263. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195264. {
  195265. unsigned int num, i;
  195266. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195267. png_debug(1, "in png_handle_hIST\n");
  195268. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195269. png_error(png_ptr, "Missing IHDR before hIST");
  195270. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195271. {
  195272. png_warning(png_ptr, "Invalid hIST after IDAT");
  195273. png_crc_finish(png_ptr, length);
  195274. return;
  195275. }
  195276. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195277. {
  195278. png_warning(png_ptr, "Missing PLTE before hIST");
  195279. png_crc_finish(png_ptr, length);
  195280. return;
  195281. }
  195282. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195283. {
  195284. png_warning(png_ptr, "Duplicate hIST chunk");
  195285. png_crc_finish(png_ptr, length);
  195286. return;
  195287. }
  195288. num = length / 2 ;
  195289. if (num != (unsigned int) png_ptr->num_palette || num >
  195290. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195291. {
  195292. png_warning(png_ptr, "Incorrect hIST chunk length");
  195293. png_crc_finish(png_ptr, length);
  195294. return;
  195295. }
  195296. for (i = 0; i < num; i++)
  195297. {
  195298. png_byte buf[2];
  195299. png_crc_read(png_ptr, buf, 2);
  195300. readbuf[i] = png_get_uint_16(buf);
  195301. }
  195302. if (png_crc_finish(png_ptr, 0))
  195303. return;
  195304. png_set_hIST(png_ptr, info_ptr, readbuf);
  195305. }
  195306. #endif
  195307. #if defined(PNG_READ_pHYs_SUPPORTED)
  195308. void /* PRIVATE */
  195309. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195310. {
  195311. png_byte buf[9];
  195312. png_uint_32 res_x, res_y;
  195313. int unit_type;
  195314. png_debug(1, "in png_handle_pHYs\n");
  195315. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195316. png_error(png_ptr, "Missing IHDR before pHYs");
  195317. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195318. {
  195319. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195320. png_crc_finish(png_ptr, length);
  195321. return;
  195322. }
  195323. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195324. {
  195325. png_warning(png_ptr, "Duplicate pHYs chunk");
  195326. png_crc_finish(png_ptr, length);
  195327. return;
  195328. }
  195329. if (length != 9)
  195330. {
  195331. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195332. png_crc_finish(png_ptr, length);
  195333. return;
  195334. }
  195335. png_crc_read(png_ptr, buf, 9);
  195336. if (png_crc_finish(png_ptr, 0))
  195337. return;
  195338. res_x = png_get_uint_32(buf);
  195339. res_y = png_get_uint_32(buf + 4);
  195340. unit_type = buf[8];
  195341. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195342. }
  195343. #endif
  195344. #if defined(PNG_READ_oFFs_SUPPORTED)
  195345. void /* PRIVATE */
  195346. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195347. {
  195348. png_byte buf[9];
  195349. png_int_32 offset_x, offset_y;
  195350. int unit_type;
  195351. png_debug(1, "in png_handle_oFFs\n");
  195352. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195353. png_error(png_ptr, "Missing IHDR before oFFs");
  195354. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195355. {
  195356. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195357. png_crc_finish(png_ptr, length);
  195358. return;
  195359. }
  195360. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195361. {
  195362. png_warning(png_ptr, "Duplicate oFFs chunk");
  195363. png_crc_finish(png_ptr, length);
  195364. return;
  195365. }
  195366. if (length != 9)
  195367. {
  195368. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195369. png_crc_finish(png_ptr, length);
  195370. return;
  195371. }
  195372. png_crc_read(png_ptr, buf, 9);
  195373. if (png_crc_finish(png_ptr, 0))
  195374. return;
  195375. offset_x = png_get_int_32(buf);
  195376. offset_y = png_get_int_32(buf + 4);
  195377. unit_type = buf[8];
  195378. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195379. }
  195380. #endif
  195381. #if defined(PNG_READ_pCAL_SUPPORTED)
  195382. /* read the pCAL chunk (described in the PNG Extensions document) */
  195383. void /* PRIVATE */
  195384. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195385. {
  195386. png_charp purpose;
  195387. png_int_32 X0, X1;
  195388. png_byte type, nparams;
  195389. png_charp buf, units, endptr;
  195390. png_charpp params;
  195391. png_size_t slength;
  195392. int i;
  195393. png_debug(1, "in png_handle_pCAL\n");
  195394. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195395. png_error(png_ptr, "Missing IHDR before pCAL");
  195396. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195397. {
  195398. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195399. png_crc_finish(png_ptr, length);
  195400. return;
  195401. }
  195402. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195403. {
  195404. png_warning(png_ptr, "Duplicate pCAL chunk");
  195405. png_crc_finish(png_ptr, length);
  195406. return;
  195407. }
  195408. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195409. length + 1);
  195410. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195411. if (purpose == NULL)
  195412. {
  195413. png_warning(png_ptr, "No memory for pCAL purpose.");
  195414. return;
  195415. }
  195416. slength = (png_size_t)length;
  195417. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195418. if (png_crc_finish(png_ptr, 0))
  195419. {
  195420. png_free(png_ptr, purpose);
  195421. return;
  195422. }
  195423. purpose[slength] = 0x00; /* null terminate the last string */
  195424. png_debug(3, "Finding end of pCAL purpose string\n");
  195425. for (buf = purpose; *buf; buf++)
  195426. /* empty loop */ ;
  195427. endptr = purpose + slength;
  195428. /* We need to have at least 12 bytes after the purpose string
  195429. in order to get the parameter information. */
  195430. if (endptr <= buf + 12)
  195431. {
  195432. png_warning(png_ptr, "Invalid pCAL data");
  195433. png_free(png_ptr, purpose);
  195434. return;
  195435. }
  195436. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195437. X0 = png_get_int_32((png_bytep)buf+1);
  195438. X1 = png_get_int_32((png_bytep)buf+5);
  195439. type = buf[9];
  195440. nparams = buf[10];
  195441. units = buf + 11;
  195442. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195443. /* Check that we have the right number of parameters for known
  195444. equation types. */
  195445. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195446. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195447. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195448. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195449. {
  195450. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195451. png_free(png_ptr, purpose);
  195452. return;
  195453. }
  195454. else if (type >= PNG_EQUATION_LAST)
  195455. {
  195456. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195457. }
  195458. for (buf = units; *buf; buf++)
  195459. /* Empty loop to move past the units string. */ ;
  195460. png_debug(3, "Allocating pCAL parameters array\n");
  195461. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195462. *png_sizeof(png_charp))) ;
  195463. if (params == NULL)
  195464. {
  195465. png_free(png_ptr, purpose);
  195466. png_warning(png_ptr, "No memory for pCAL params.");
  195467. return;
  195468. }
  195469. /* Get pointers to the start of each parameter string. */
  195470. for (i = 0; i < (int)nparams; i++)
  195471. {
  195472. buf++; /* Skip the null string terminator from previous parameter. */
  195473. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195474. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195475. /* Empty loop to move past each parameter string */ ;
  195476. /* Make sure we haven't run out of data yet */
  195477. if (buf > endptr)
  195478. {
  195479. png_warning(png_ptr, "Invalid pCAL data");
  195480. png_free(png_ptr, purpose);
  195481. png_free(png_ptr, params);
  195482. return;
  195483. }
  195484. }
  195485. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195486. units, params);
  195487. png_free(png_ptr, purpose);
  195488. png_free(png_ptr, params);
  195489. }
  195490. #endif
  195491. #if defined(PNG_READ_sCAL_SUPPORTED)
  195492. /* read the sCAL chunk */
  195493. void /* PRIVATE */
  195494. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195495. {
  195496. png_charp buffer, ep;
  195497. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195498. double width, height;
  195499. png_charp vp;
  195500. #else
  195501. #ifdef PNG_FIXED_POINT_SUPPORTED
  195502. png_charp swidth, sheight;
  195503. #endif
  195504. #endif
  195505. png_size_t slength;
  195506. png_debug(1, "in png_handle_sCAL\n");
  195507. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195508. png_error(png_ptr, "Missing IHDR before sCAL");
  195509. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195510. {
  195511. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195512. png_crc_finish(png_ptr, length);
  195513. return;
  195514. }
  195515. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195516. {
  195517. png_warning(png_ptr, "Duplicate sCAL chunk");
  195518. png_crc_finish(png_ptr, length);
  195519. return;
  195520. }
  195521. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195522. length + 1);
  195523. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195524. if (buffer == NULL)
  195525. {
  195526. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195527. return;
  195528. }
  195529. slength = (png_size_t)length;
  195530. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195531. if (png_crc_finish(png_ptr, 0))
  195532. {
  195533. png_free(png_ptr, buffer);
  195534. return;
  195535. }
  195536. buffer[slength] = 0x00; /* null terminate the last string */
  195537. ep = buffer + 1; /* skip unit byte */
  195538. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195539. width = png_strtod(png_ptr, ep, &vp);
  195540. if (*vp)
  195541. {
  195542. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195543. return;
  195544. }
  195545. #else
  195546. #ifdef PNG_FIXED_POINT_SUPPORTED
  195547. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195548. if (swidth == NULL)
  195549. {
  195550. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195551. return;
  195552. }
  195553. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195554. #endif
  195555. #endif
  195556. for (ep = buffer; *ep; ep++)
  195557. /* empty loop */ ;
  195558. ep++;
  195559. if (buffer + slength < ep)
  195560. {
  195561. png_warning(png_ptr, "Truncated sCAL chunk");
  195562. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195563. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195564. png_free(png_ptr, swidth);
  195565. #endif
  195566. png_free(png_ptr, buffer);
  195567. return;
  195568. }
  195569. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195570. height = png_strtod(png_ptr, ep, &vp);
  195571. if (*vp)
  195572. {
  195573. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195574. return;
  195575. }
  195576. #else
  195577. #ifdef PNG_FIXED_POINT_SUPPORTED
  195578. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195579. if (swidth == NULL)
  195580. {
  195581. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195582. return;
  195583. }
  195584. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195585. #endif
  195586. #endif
  195587. if (buffer + slength < ep
  195588. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195589. || width <= 0. || height <= 0.
  195590. #endif
  195591. )
  195592. {
  195593. png_warning(png_ptr, "Invalid sCAL data");
  195594. png_free(png_ptr, buffer);
  195595. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195596. png_free(png_ptr, swidth);
  195597. png_free(png_ptr, sheight);
  195598. #endif
  195599. return;
  195600. }
  195601. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195602. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195603. #else
  195604. #ifdef PNG_FIXED_POINT_SUPPORTED
  195605. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195606. #endif
  195607. #endif
  195608. png_free(png_ptr, buffer);
  195609. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195610. png_free(png_ptr, swidth);
  195611. png_free(png_ptr, sheight);
  195612. #endif
  195613. }
  195614. #endif
  195615. #if defined(PNG_READ_tIME_SUPPORTED)
  195616. void /* PRIVATE */
  195617. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195618. {
  195619. png_byte buf[7];
  195620. png_time mod_time;
  195621. png_debug(1, "in png_handle_tIME\n");
  195622. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195623. png_error(png_ptr, "Out of place tIME chunk");
  195624. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195625. {
  195626. png_warning(png_ptr, "Duplicate tIME chunk");
  195627. png_crc_finish(png_ptr, length);
  195628. return;
  195629. }
  195630. if (png_ptr->mode & PNG_HAVE_IDAT)
  195631. png_ptr->mode |= PNG_AFTER_IDAT;
  195632. if (length != 7)
  195633. {
  195634. png_warning(png_ptr, "Incorrect tIME chunk length");
  195635. png_crc_finish(png_ptr, length);
  195636. return;
  195637. }
  195638. png_crc_read(png_ptr, buf, 7);
  195639. if (png_crc_finish(png_ptr, 0))
  195640. return;
  195641. mod_time.second = buf[6];
  195642. mod_time.minute = buf[5];
  195643. mod_time.hour = buf[4];
  195644. mod_time.day = buf[3];
  195645. mod_time.month = buf[2];
  195646. mod_time.year = png_get_uint_16(buf);
  195647. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195648. }
  195649. #endif
  195650. #if defined(PNG_READ_tEXt_SUPPORTED)
  195651. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195652. void /* PRIVATE */
  195653. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195654. {
  195655. png_textp text_ptr;
  195656. png_charp key;
  195657. png_charp text;
  195658. png_uint_32 skip = 0;
  195659. png_size_t slength;
  195660. int ret;
  195661. png_debug(1, "in png_handle_tEXt\n");
  195662. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195663. png_error(png_ptr, "Missing IHDR before tEXt");
  195664. if (png_ptr->mode & PNG_HAVE_IDAT)
  195665. png_ptr->mode |= PNG_AFTER_IDAT;
  195666. #ifdef PNG_MAX_MALLOC_64K
  195667. if (length > (png_uint_32)65535L)
  195668. {
  195669. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195670. skip = length - (png_uint_32)65535L;
  195671. length = (png_uint_32)65535L;
  195672. }
  195673. #endif
  195674. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195675. if (key == NULL)
  195676. {
  195677. png_warning(png_ptr, "No memory to process text chunk.");
  195678. return;
  195679. }
  195680. slength = (png_size_t)length;
  195681. png_crc_read(png_ptr, (png_bytep)key, slength);
  195682. if (png_crc_finish(png_ptr, skip))
  195683. {
  195684. png_free(png_ptr, key);
  195685. return;
  195686. }
  195687. key[slength] = 0x00;
  195688. for (text = key; *text; text++)
  195689. /* empty loop to find end of key */ ;
  195690. if (text != key + slength)
  195691. text++;
  195692. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195693. (png_uint_32)png_sizeof(png_text));
  195694. if (text_ptr == NULL)
  195695. {
  195696. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195697. png_free(png_ptr, key);
  195698. return;
  195699. }
  195700. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195701. text_ptr->key = key;
  195702. #ifdef PNG_iTXt_SUPPORTED
  195703. text_ptr->lang = NULL;
  195704. text_ptr->lang_key = NULL;
  195705. text_ptr->itxt_length = 0;
  195706. #endif
  195707. text_ptr->text = text;
  195708. text_ptr->text_length = png_strlen(text);
  195709. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195710. png_free(png_ptr, key);
  195711. png_free(png_ptr, text_ptr);
  195712. if (ret)
  195713. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195714. }
  195715. #endif
  195716. #if defined(PNG_READ_zTXt_SUPPORTED)
  195717. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195718. void /* PRIVATE */
  195719. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195720. {
  195721. png_textp text_ptr;
  195722. png_charp chunkdata;
  195723. png_charp text;
  195724. int comp_type;
  195725. int ret;
  195726. png_size_t slength, prefix_len, data_len;
  195727. png_debug(1, "in png_handle_zTXt\n");
  195728. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195729. png_error(png_ptr, "Missing IHDR before zTXt");
  195730. if (png_ptr->mode & PNG_HAVE_IDAT)
  195731. png_ptr->mode |= PNG_AFTER_IDAT;
  195732. #ifdef PNG_MAX_MALLOC_64K
  195733. /* We will no doubt have problems with chunks even half this size, but
  195734. there is no hard and fast rule to tell us where to stop. */
  195735. if (length > (png_uint_32)65535L)
  195736. {
  195737. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195738. png_crc_finish(png_ptr, length);
  195739. return;
  195740. }
  195741. #endif
  195742. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195743. if (chunkdata == NULL)
  195744. {
  195745. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195746. return;
  195747. }
  195748. slength = (png_size_t)length;
  195749. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195750. if (png_crc_finish(png_ptr, 0))
  195751. {
  195752. png_free(png_ptr, chunkdata);
  195753. return;
  195754. }
  195755. chunkdata[slength] = 0x00;
  195756. for (text = chunkdata; *text; text++)
  195757. /* empty loop */ ;
  195758. /* zTXt must have some text after the chunkdataword */
  195759. if (text >= chunkdata + slength - 2)
  195760. {
  195761. png_warning(png_ptr, "Truncated zTXt chunk");
  195762. png_free(png_ptr, chunkdata);
  195763. return;
  195764. }
  195765. else
  195766. {
  195767. comp_type = *(++text);
  195768. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195769. {
  195770. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195771. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195772. }
  195773. text++; /* skip the compression_method byte */
  195774. }
  195775. prefix_len = text - chunkdata;
  195776. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195777. (png_size_t)length, prefix_len, &data_len);
  195778. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195779. (png_uint_32)png_sizeof(png_text));
  195780. if (text_ptr == NULL)
  195781. {
  195782. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195783. png_free(png_ptr, chunkdata);
  195784. return;
  195785. }
  195786. text_ptr->compression = comp_type;
  195787. text_ptr->key = chunkdata;
  195788. #ifdef PNG_iTXt_SUPPORTED
  195789. text_ptr->lang = NULL;
  195790. text_ptr->lang_key = NULL;
  195791. text_ptr->itxt_length = 0;
  195792. #endif
  195793. text_ptr->text = chunkdata + prefix_len;
  195794. text_ptr->text_length = data_len;
  195795. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195796. png_free(png_ptr, text_ptr);
  195797. png_free(png_ptr, chunkdata);
  195798. if (ret)
  195799. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195800. }
  195801. #endif
  195802. #if defined(PNG_READ_iTXt_SUPPORTED)
  195803. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195804. void /* PRIVATE */
  195805. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195806. {
  195807. png_textp text_ptr;
  195808. png_charp chunkdata;
  195809. png_charp key, lang, text, lang_key;
  195810. int comp_flag;
  195811. int comp_type = 0;
  195812. int ret;
  195813. png_size_t slength, prefix_len, data_len;
  195814. png_debug(1, "in png_handle_iTXt\n");
  195815. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195816. png_error(png_ptr, "Missing IHDR before iTXt");
  195817. if (png_ptr->mode & PNG_HAVE_IDAT)
  195818. png_ptr->mode |= PNG_AFTER_IDAT;
  195819. #ifdef PNG_MAX_MALLOC_64K
  195820. /* We will no doubt have problems with chunks even half this size, but
  195821. there is no hard and fast rule to tell us where to stop. */
  195822. if (length > (png_uint_32)65535L)
  195823. {
  195824. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195825. png_crc_finish(png_ptr, length);
  195826. return;
  195827. }
  195828. #endif
  195829. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195830. if (chunkdata == NULL)
  195831. {
  195832. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195833. return;
  195834. }
  195835. slength = (png_size_t)length;
  195836. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195837. if (png_crc_finish(png_ptr, 0))
  195838. {
  195839. png_free(png_ptr, chunkdata);
  195840. return;
  195841. }
  195842. chunkdata[slength] = 0x00;
  195843. for (lang = chunkdata; *lang; lang++)
  195844. /* empty loop */ ;
  195845. lang++; /* skip NUL separator */
  195846. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195847. translated keyword (possibly empty), and possibly some text after the
  195848. keyword */
  195849. if (lang >= chunkdata + slength - 3)
  195850. {
  195851. png_warning(png_ptr, "Truncated iTXt chunk");
  195852. png_free(png_ptr, chunkdata);
  195853. return;
  195854. }
  195855. else
  195856. {
  195857. comp_flag = *lang++;
  195858. comp_type = *lang++;
  195859. }
  195860. for (lang_key = lang; *lang_key; lang_key++)
  195861. /* empty loop */ ;
  195862. lang_key++; /* skip NUL separator */
  195863. if (lang_key >= chunkdata + slength)
  195864. {
  195865. png_warning(png_ptr, "Truncated iTXt chunk");
  195866. png_free(png_ptr, chunkdata);
  195867. return;
  195868. }
  195869. for (text = lang_key; *text; text++)
  195870. /* empty loop */ ;
  195871. text++; /* skip NUL separator */
  195872. if (text >= chunkdata + slength)
  195873. {
  195874. png_warning(png_ptr, "Malformed iTXt chunk");
  195875. png_free(png_ptr, chunkdata);
  195876. return;
  195877. }
  195878. prefix_len = text - chunkdata;
  195879. key=chunkdata;
  195880. if (comp_flag)
  195881. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195882. (size_t)length, prefix_len, &data_len);
  195883. else
  195884. data_len=png_strlen(chunkdata + prefix_len);
  195885. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195886. (png_uint_32)png_sizeof(png_text));
  195887. if (text_ptr == NULL)
  195888. {
  195889. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195890. png_free(png_ptr, chunkdata);
  195891. return;
  195892. }
  195893. text_ptr->compression = (int)comp_flag + 1;
  195894. text_ptr->lang_key = chunkdata+(lang_key-key);
  195895. text_ptr->lang = chunkdata+(lang-key);
  195896. text_ptr->itxt_length = data_len;
  195897. text_ptr->text_length = 0;
  195898. text_ptr->key = chunkdata;
  195899. text_ptr->text = chunkdata + prefix_len;
  195900. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195901. png_free(png_ptr, text_ptr);
  195902. png_free(png_ptr, chunkdata);
  195903. if (ret)
  195904. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195905. }
  195906. #endif
  195907. /* This function is called when we haven't found a handler for a
  195908. chunk. If there isn't a problem with the chunk itself (ie bad
  195909. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195910. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195911. case it will be saved away to be written out later. */
  195912. void /* PRIVATE */
  195913. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195914. {
  195915. png_uint_32 skip = 0;
  195916. png_debug(1, "in png_handle_unknown\n");
  195917. if (png_ptr->mode & PNG_HAVE_IDAT)
  195918. {
  195919. #ifdef PNG_USE_LOCAL_ARRAYS
  195920. PNG_CONST PNG_IDAT;
  195921. #endif
  195922. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195923. png_ptr->mode |= PNG_AFTER_IDAT;
  195924. }
  195925. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195926. if (!(png_ptr->chunk_name[0] & 0x20))
  195927. {
  195928. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195929. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195930. PNG_HANDLE_CHUNK_ALWAYS
  195931. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195932. && png_ptr->read_user_chunk_fn == NULL
  195933. #endif
  195934. )
  195935. #endif
  195936. png_chunk_error(png_ptr, "unknown critical chunk");
  195937. }
  195938. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195939. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195940. (png_ptr->read_user_chunk_fn != NULL))
  195941. {
  195942. #ifdef PNG_MAX_MALLOC_64K
  195943. if (length > (png_uint_32)65535L)
  195944. {
  195945. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195946. skip = length - (png_uint_32)65535L;
  195947. length = (png_uint_32)65535L;
  195948. }
  195949. #endif
  195950. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195951. (png_charp)png_ptr->chunk_name, 5);
  195952. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195953. png_ptr->unknown_chunk.size = (png_size_t)length;
  195954. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195955. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195956. if(png_ptr->read_user_chunk_fn != NULL)
  195957. {
  195958. /* callback to user unknown chunk handler */
  195959. int ret;
  195960. ret = (*(png_ptr->read_user_chunk_fn))
  195961. (png_ptr, &png_ptr->unknown_chunk);
  195962. if (ret < 0)
  195963. png_chunk_error(png_ptr, "error in user chunk");
  195964. if (ret == 0)
  195965. {
  195966. if (!(png_ptr->chunk_name[0] & 0x20))
  195967. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195968. PNG_HANDLE_CHUNK_ALWAYS)
  195969. png_chunk_error(png_ptr, "unknown critical chunk");
  195970. png_set_unknown_chunks(png_ptr, info_ptr,
  195971. &png_ptr->unknown_chunk, 1);
  195972. }
  195973. }
  195974. #else
  195975. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195976. #endif
  195977. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195978. png_ptr->unknown_chunk.data = NULL;
  195979. }
  195980. else
  195981. #endif
  195982. skip = length;
  195983. png_crc_finish(png_ptr, skip);
  195984. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195985. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195986. #endif
  195987. }
  195988. /* This function is called to verify that a chunk name is valid.
  195989. This function can't have the "critical chunk check" incorporated
  195990. into it, since in the future we will need to be able to call user
  195991. functions to handle unknown critical chunks after we check that
  195992. the chunk name itself is valid. */
  195993. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195994. void /* PRIVATE */
  195995. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195996. {
  195997. png_debug(1, "in png_check_chunk_name\n");
  195998. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195999. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196000. {
  196001. png_chunk_error(png_ptr, "invalid chunk type");
  196002. }
  196003. }
  196004. /* Combines the row recently read in with the existing pixels in the
  196005. row. This routine takes care of alpha and transparency if requested.
  196006. This routine also handles the two methods of progressive display
  196007. of interlaced images, depending on the mask value.
  196008. The mask value describes which pixels are to be combined with
  196009. the row. The pattern always repeats every 8 pixels, so just 8
  196010. bits are needed. A one indicates the pixel is to be combined,
  196011. a zero indicates the pixel is to be skipped. This is in addition
  196012. to any alpha or transparency value associated with the pixel. If
  196013. you want all pixels to be combined, pass 0xff (255) in mask. */
  196014. void /* PRIVATE */
  196015. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196016. {
  196017. png_debug(1,"in png_combine_row\n");
  196018. if (mask == 0xff)
  196019. {
  196020. png_memcpy(row, png_ptr->row_buf + 1,
  196021. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196022. }
  196023. else
  196024. {
  196025. switch (png_ptr->row_info.pixel_depth)
  196026. {
  196027. case 1:
  196028. {
  196029. png_bytep sp = png_ptr->row_buf + 1;
  196030. png_bytep dp = row;
  196031. int s_inc, s_start, s_end;
  196032. int m = 0x80;
  196033. int shift;
  196034. png_uint_32 i;
  196035. png_uint_32 row_width = png_ptr->width;
  196036. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196037. if (png_ptr->transformations & PNG_PACKSWAP)
  196038. {
  196039. s_start = 0;
  196040. s_end = 7;
  196041. s_inc = 1;
  196042. }
  196043. else
  196044. #endif
  196045. {
  196046. s_start = 7;
  196047. s_end = 0;
  196048. s_inc = -1;
  196049. }
  196050. shift = s_start;
  196051. for (i = 0; i < row_width; i++)
  196052. {
  196053. if (m & mask)
  196054. {
  196055. int value;
  196056. value = (*sp >> shift) & 0x01;
  196057. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196058. *dp |= (png_byte)(value << shift);
  196059. }
  196060. if (shift == s_end)
  196061. {
  196062. shift = s_start;
  196063. sp++;
  196064. dp++;
  196065. }
  196066. else
  196067. shift += s_inc;
  196068. if (m == 1)
  196069. m = 0x80;
  196070. else
  196071. m >>= 1;
  196072. }
  196073. break;
  196074. }
  196075. case 2:
  196076. {
  196077. png_bytep sp = png_ptr->row_buf + 1;
  196078. png_bytep dp = row;
  196079. int s_start, s_end, s_inc;
  196080. int m = 0x80;
  196081. int shift;
  196082. png_uint_32 i;
  196083. png_uint_32 row_width = png_ptr->width;
  196084. int value;
  196085. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196086. if (png_ptr->transformations & PNG_PACKSWAP)
  196087. {
  196088. s_start = 0;
  196089. s_end = 6;
  196090. s_inc = 2;
  196091. }
  196092. else
  196093. #endif
  196094. {
  196095. s_start = 6;
  196096. s_end = 0;
  196097. s_inc = -2;
  196098. }
  196099. shift = s_start;
  196100. for (i = 0; i < row_width; i++)
  196101. {
  196102. if (m & mask)
  196103. {
  196104. value = (*sp >> shift) & 0x03;
  196105. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196106. *dp |= (png_byte)(value << shift);
  196107. }
  196108. if (shift == s_end)
  196109. {
  196110. shift = s_start;
  196111. sp++;
  196112. dp++;
  196113. }
  196114. else
  196115. shift += s_inc;
  196116. if (m == 1)
  196117. m = 0x80;
  196118. else
  196119. m >>= 1;
  196120. }
  196121. break;
  196122. }
  196123. case 4:
  196124. {
  196125. png_bytep sp = png_ptr->row_buf + 1;
  196126. png_bytep dp = row;
  196127. int s_start, s_end, s_inc;
  196128. int m = 0x80;
  196129. int shift;
  196130. png_uint_32 i;
  196131. png_uint_32 row_width = png_ptr->width;
  196132. int value;
  196133. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196134. if (png_ptr->transformations & PNG_PACKSWAP)
  196135. {
  196136. s_start = 0;
  196137. s_end = 4;
  196138. s_inc = 4;
  196139. }
  196140. else
  196141. #endif
  196142. {
  196143. s_start = 4;
  196144. s_end = 0;
  196145. s_inc = -4;
  196146. }
  196147. shift = s_start;
  196148. for (i = 0; i < row_width; i++)
  196149. {
  196150. if (m & mask)
  196151. {
  196152. value = (*sp >> shift) & 0xf;
  196153. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196154. *dp |= (png_byte)(value << shift);
  196155. }
  196156. if (shift == s_end)
  196157. {
  196158. shift = s_start;
  196159. sp++;
  196160. dp++;
  196161. }
  196162. else
  196163. shift += s_inc;
  196164. if (m == 1)
  196165. m = 0x80;
  196166. else
  196167. m >>= 1;
  196168. }
  196169. break;
  196170. }
  196171. default:
  196172. {
  196173. png_bytep sp = png_ptr->row_buf + 1;
  196174. png_bytep dp = row;
  196175. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196176. png_uint_32 i;
  196177. png_uint_32 row_width = png_ptr->width;
  196178. png_byte m = 0x80;
  196179. for (i = 0; i < row_width; i++)
  196180. {
  196181. if (m & mask)
  196182. {
  196183. png_memcpy(dp, sp, pixel_bytes);
  196184. }
  196185. sp += pixel_bytes;
  196186. dp += pixel_bytes;
  196187. if (m == 1)
  196188. m = 0x80;
  196189. else
  196190. m >>= 1;
  196191. }
  196192. break;
  196193. }
  196194. }
  196195. }
  196196. }
  196197. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196198. /* OLD pre-1.0.9 interface:
  196199. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196200. png_uint_32 transformations)
  196201. */
  196202. void /* PRIVATE */
  196203. png_do_read_interlace(png_structp png_ptr)
  196204. {
  196205. png_row_infop row_info = &(png_ptr->row_info);
  196206. png_bytep row = png_ptr->row_buf + 1;
  196207. int pass = png_ptr->pass;
  196208. png_uint_32 transformations = png_ptr->transformations;
  196209. #ifdef PNG_USE_LOCAL_ARRAYS
  196210. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196211. /* offset to next interlace block */
  196212. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196213. #endif
  196214. png_debug(1,"in png_do_read_interlace\n");
  196215. if (row != NULL && row_info != NULL)
  196216. {
  196217. png_uint_32 final_width;
  196218. final_width = row_info->width * png_pass_inc[pass];
  196219. switch (row_info->pixel_depth)
  196220. {
  196221. case 1:
  196222. {
  196223. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196224. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196225. int sshift, dshift;
  196226. int s_start, s_end, s_inc;
  196227. int jstop = png_pass_inc[pass];
  196228. png_byte v;
  196229. png_uint_32 i;
  196230. int j;
  196231. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196232. if (transformations & PNG_PACKSWAP)
  196233. {
  196234. sshift = (int)((row_info->width + 7) & 0x07);
  196235. dshift = (int)((final_width + 7) & 0x07);
  196236. s_start = 7;
  196237. s_end = 0;
  196238. s_inc = -1;
  196239. }
  196240. else
  196241. #endif
  196242. {
  196243. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196244. dshift = 7 - (int)((final_width + 7) & 0x07);
  196245. s_start = 0;
  196246. s_end = 7;
  196247. s_inc = 1;
  196248. }
  196249. for (i = 0; i < row_info->width; i++)
  196250. {
  196251. v = (png_byte)((*sp >> sshift) & 0x01);
  196252. for (j = 0; j < jstop; j++)
  196253. {
  196254. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196255. *dp |= (png_byte)(v << dshift);
  196256. if (dshift == s_end)
  196257. {
  196258. dshift = s_start;
  196259. dp--;
  196260. }
  196261. else
  196262. dshift += s_inc;
  196263. }
  196264. if (sshift == s_end)
  196265. {
  196266. sshift = s_start;
  196267. sp--;
  196268. }
  196269. else
  196270. sshift += s_inc;
  196271. }
  196272. break;
  196273. }
  196274. case 2:
  196275. {
  196276. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196277. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196278. int sshift, dshift;
  196279. int s_start, s_end, s_inc;
  196280. int jstop = png_pass_inc[pass];
  196281. png_uint_32 i;
  196282. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196283. if (transformations & PNG_PACKSWAP)
  196284. {
  196285. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196286. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196287. s_start = 6;
  196288. s_end = 0;
  196289. s_inc = -2;
  196290. }
  196291. else
  196292. #endif
  196293. {
  196294. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196295. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196296. s_start = 0;
  196297. s_end = 6;
  196298. s_inc = 2;
  196299. }
  196300. for (i = 0; i < row_info->width; i++)
  196301. {
  196302. png_byte v;
  196303. int j;
  196304. v = (png_byte)((*sp >> sshift) & 0x03);
  196305. for (j = 0; j < jstop; j++)
  196306. {
  196307. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196308. *dp |= (png_byte)(v << dshift);
  196309. if (dshift == s_end)
  196310. {
  196311. dshift = s_start;
  196312. dp--;
  196313. }
  196314. else
  196315. dshift += s_inc;
  196316. }
  196317. if (sshift == s_end)
  196318. {
  196319. sshift = s_start;
  196320. sp--;
  196321. }
  196322. else
  196323. sshift += s_inc;
  196324. }
  196325. break;
  196326. }
  196327. case 4:
  196328. {
  196329. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196330. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196331. int sshift, dshift;
  196332. int s_start, s_end, s_inc;
  196333. png_uint_32 i;
  196334. int jstop = png_pass_inc[pass];
  196335. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196336. if (transformations & PNG_PACKSWAP)
  196337. {
  196338. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196339. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196340. s_start = 4;
  196341. s_end = 0;
  196342. s_inc = -4;
  196343. }
  196344. else
  196345. #endif
  196346. {
  196347. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196348. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196349. s_start = 0;
  196350. s_end = 4;
  196351. s_inc = 4;
  196352. }
  196353. for (i = 0; i < row_info->width; i++)
  196354. {
  196355. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196356. int j;
  196357. for (j = 0; j < jstop; j++)
  196358. {
  196359. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196360. *dp |= (png_byte)(v << dshift);
  196361. if (dshift == s_end)
  196362. {
  196363. dshift = s_start;
  196364. dp--;
  196365. }
  196366. else
  196367. dshift += s_inc;
  196368. }
  196369. if (sshift == s_end)
  196370. {
  196371. sshift = s_start;
  196372. sp--;
  196373. }
  196374. else
  196375. sshift += s_inc;
  196376. }
  196377. break;
  196378. }
  196379. default:
  196380. {
  196381. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196382. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196383. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196384. int jstop = png_pass_inc[pass];
  196385. png_uint_32 i;
  196386. for (i = 0; i < row_info->width; i++)
  196387. {
  196388. png_byte v[8];
  196389. int j;
  196390. png_memcpy(v, sp, pixel_bytes);
  196391. for (j = 0; j < jstop; j++)
  196392. {
  196393. png_memcpy(dp, v, pixel_bytes);
  196394. dp -= pixel_bytes;
  196395. }
  196396. sp -= pixel_bytes;
  196397. }
  196398. break;
  196399. }
  196400. }
  196401. row_info->width = final_width;
  196402. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196403. }
  196404. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196405. transformations = transformations; /* silence compiler warning */
  196406. #endif
  196407. }
  196408. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196409. void /* PRIVATE */
  196410. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196411. png_bytep prev_row, int filter)
  196412. {
  196413. png_debug(1, "in png_read_filter_row\n");
  196414. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196415. switch (filter)
  196416. {
  196417. case PNG_FILTER_VALUE_NONE:
  196418. break;
  196419. case PNG_FILTER_VALUE_SUB:
  196420. {
  196421. png_uint_32 i;
  196422. png_uint_32 istop = row_info->rowbytes;
  196423. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196424. png_bytep rp = row + bpp;
  196425. png_bytep lp = row;
  196426. for (i = bpp; i < istop; i++)
  196427. {
  196428. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196429. rp++;
  196430. }
  196431. break;
  196432. }
  196433. case PNG_FILTER_VALUE_UP:
  196434. {
  196435. png_uint_32 i;
  196436. png_uint_32 istop = row_info->rowbytes;
  196437. png_bytep rp = row;
  196438. png_bytep pp = prev_row;
  196439. for (i = 0; i < istop; i++)
  196440. {
  196441. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196442. rp++;
  196443. }
  196444. break;
  196445. }
  196446. case PNG_FILTER_VALUE_AVG:
  196447. {
  196448. png_uint_32 i;
  196449. png_bytep rp = row;
  196450. png_bytep pp = prev_row;
  196451. png_bytep lp = row;
  196452. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196453. png_uint_32 istop = row_info->rowbytes - bpp;
  196454. for (i = 0; i < bpp; i++)
  196455. {
  196456. *rp = (png_byte)(((int)(*rp) +
  196457. ((int)(*pp++) / 2 )) & 0xff);
  196458. rp++;
  196459. }
  196460. for (i = 0; i < istop; i++)
  196461. {
  196462. *rp = (png_byte)(((int)(*rp) +
  196463. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196464. rp++;
  196465. }
  196466. break;
  196467. }
  196468. case PNG_FILTER_VALUE_PAETH:
  196469. {
  196470. png_uint_32 i;
  196471. png_bytep rp = row;
  196472. png_bytep pp = prev_row;
  196473. png_bytep lp = row;
  196474. png_bytep cp = prev_row;
  196475. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196476. png_uint_32 istop=row_info->rowbytes - bpp;
  196477. for (i = 0; i < bpp; i++)
  196478. {
  196479. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196480. rp++;
  196481. }
  196482. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196483. {
  196484. int a, b, c, pa, pb, pc, p;
  196485. a = *lp++;
  196486. b = *pp++;
  196487. c = *cp++;
  196488. p = b - c;
  196489. pc = a - c;
  196490. #ifdef PNG_USE_ABS
  196491. pa = abs(p);
  196492. pb = abs(pc);
  196493. pc = abs(p + pc);
  196494. #else
  196495. pa = p < 0 ? -p : p;
  196496. pb = pc < 0 ? -pc : pc;
  196497. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196498. #endif
  196499. /*
  196500. if (pa <= pb && pa <= pc)
  196501. p = a;
  196502. else if (pb <= pc)
  196503. p = b;
  196504. else
  196505. p = c;
  196506. */
  196507. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196508. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196509. rp++;
  196510. }
  196511. break;
  196512. }
  196513. default:
  196514. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196515. *row=0;
  196516. break;
  196517. }
  196518. }
  196519. void /* PRIVATE */
  196520. png_read_finish_row(png_structp png_ptr)
  196521. {
  196522. #ifdef PNG_USE_LOCAL_ARRAYS
  196523. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196524. /* start of interlace block */
  196525. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196526. /* offset to next interlace block */
  196527. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196528. /* start of interlace block in the y direction */
  196529. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196530. /* offset to next interlace block in the y direction */
  196531. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196532. #endif
  196533. png_debug(1, "in png_read_finish_row\n");
  196534. png_ptr->row_number++;
  196535. if (png_ptr->row_number < png_ptr->num_rows)
  196536. return;
  196537. if (png_ptr->interlaced)
  196538. {
  196539. png_ptr->row_number = 0;
  196540. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196541. png_ptr->rowbytes + 1);
  196542. do
  196543. {
  196544. png_ptr->pass++;
  196545. if (png_ptr->pass >= 7)
  196546. break;
  196547. png_ptr->iwidth = (png_ptr->width +
  196548. png_pass_inc[png_ptr->pass] - 1 -
  196549. png_pass_start[png_ptr->pass]) /
  196550. png_pass_inc[png_ptr->pass];
  196551. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196552. png_ptr->iwidth) + 1;
  196553. if (!(png_ptr->transformations & PNG_INTERLACE))
  196554. {
  196555. png_ptr->num_rows = (png_ptr->height +
  196556. png_pass_yinc[png_ptr->pass] - 1 -
  196557. png_pass_ystart[png_ptr->pass]) /
  196558. png_pass_yinc[png_ptr->pass];
  196559. if (!(png_ptr->num_rows))
  196560. continue;
  196561. }
  196562. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196563. break;
  196564. } while (png_ptr->iwidth == 0);
  196565. if (png_ptr->pass < 7)
  196566. return;
  196567. }
  196568. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196569. {
  196570. #ifdef PNG_USE_LOCAL_ARRAYS
  196571. PNG_CONST PNG_IDAT;
  196572. #endif
  196573. char extra;
  196574. int ret;
  196575. png_ptr->zstream.next_out = (Bytef *)&extra;
  196576. png_ptr->zstream.avail_out = (uInt)1;
  196577. for(;;)
  196578. {
  196579. if (!(png_ptr->zstream.avail_in))
  196580. {
  196581. while (!png_ptr->idat_size)
  196582. {
  196583. png_byte chunk_length[4];
  196584. png_crc_finish(png_ptr, 0);
  196585. png_read_data(png_ptr, chunk_length, 4);
  196586. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196587. png_reset_crc(png_ptr);
  196588. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196589. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196590. png_error(png_ptr, "Not enough image data");
  196591. }
  196592. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196593. png_ptr->zstream.next_in = png_ptr->zbuf;
  196594. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196595. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196596. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196597. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196598. }
  196599. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196600. if (ret == Z_STREAM_END)
  196601. {
  196602. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196603. png_ptr->idat_size)
  196604. png_warning(png_ptr, "Extra compressed data");
  196605. png_ptr->mode |= PNG_AFTER_IDAT;
  196606. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196607. break;
  196608. }
  196609. if (ret != Z_OK)
  196610. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196611. "Decompression Error");
  196612. if (!(png_ptr->zstream.avail_out))
  196613. {
  196614. png_warning(png_ptr, "Extra compressed data.");
  196615. png_ptr->mode |= PNG_AFTER_IDAT;
  196616. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196617. break;
  196618. }
  196619. }
  196620. png_ptr->zstream.avail_out = 0;
  196621. }
  196622. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196623. png_warning(png_ptr, "Extra compression data");
  196624. inflateReset(&png_ptr->zstream);
  196625. png_ptr->mode |= PNG_AFTER_IDAT;
  196626. }
  196627. void /* PRIVATE */
  196628. png_read_start_row(png_structp png_ptr)
  196629. {
  196630. #ifdef PNG_USE_LOCAL_ARRAYS
  196631. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196632. /* start of interlace block */
  196633. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196634. /* offset to next interlace block */
  196635. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196636. /* start of interlace block in the y direction */
  196637. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196638. /* offset to next interlace block in the y direction */
  196639. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196640. #endif
  196641. int max_pixel_depth;
  196642. png_uint_32 row_bytes;
  196643. png_debug(1, "in png_read_start_row\n");
  196644. png_ptr->zstream.avail_in = 0;
  196645. png_init_read_transformations(png_ptr);
  196646. if (png_ptr->interlaced)
  196647. {
  196648. if (!(png_ptr->transformations & PNG_INTERLACE))
  196649. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196650. png_pass_ystart[0]) / png_pass_yinc[0];
  196651. else
  196652. png_ptr->num_rows = png_ptr->height;
  196653. png_ptr->iwidth = (png_ptr->width +
  196654. png_pass_inc[png_ptr->pass] - 1 -
  196655. png_pass_start[png_ptr->pass]) /
  196656. png_pass_inc[png_ptr->pass];
  196657. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196658. png_ptr->irowbytes = (png_size_t)row_bytes;
  196659. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196660. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196661. }
  196662. else
  196663. {
  196664. png_ptr->num_rows = png_ptr->height;
  196665. png_ptr->iwidth = png_ptr->width;
  196666. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196667. }
  196668. max_pixel_depth = png_ptr->pixel_depth;
  196669. #if defined(PNG_READ_PACK_SUPPORTED)
  196670. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196671. max_pixel_depth = 8;
  196672. #endif
  196673. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196674. if (png_ptr->transformations & PNG_EXPAND)
  196675. {
  196676. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196677. {
  196678. if (png_ptr->num_trans)
  196679. max_pixel_depth = 32;
  196680. else
  196681. max_pixel_depth = 24;
  196682. }
  196683. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196684. {
  196685. if (max_pixel_depth < 8)
  196686. max_pixel_depth = 8;
  196687. if (png_ptr->num_trans)
  196688. max_pixel_depth *= 2;
  196689. }
  196690. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196691. {
  196692. if (png_ptr->num_trans)
  196693. {
  196694. max_pixel_depth *= 4;
  196695. max_pixel_depth /= 3;
  196696. }
  196697. }
  196698. }
  196699. #endif
  196700. #if defined(PNG_READ_FILLER_SUPPORTED)
  196701. if (png_ptr->transformations & (PNG_FILLER))
  196702. {
  196703. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196704. max_pixel_depth = 32;
  196705. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196706. {
  196707. if (max_pixel_depth <= 8)
  196708. max_pixel_depth = 16;
  196709. else
  196710. max_pixel_depth = 32;
  196711. }
  196712. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196713. {
  196714. if (max_pixel_depth <= 32)
  196715. max_pixel_depth = 32;
  196716. else
  196717. max_pixel_depth = 64;
  196718. }
  196719. }
  196720. #endif
  196721. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196722. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196723. {
  196724. if (
  196725. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196726. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196727. #endif
  196728. #if defined(PNG_READ_FILLER_SUPPORTED)
  196729. (png_ptr->transformations & (PNG_FILLER)) ||
  196730. #endif
  196731. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196732. {
  196733. if (max_pixel_depth <= 16)
  196734. max_pixel_depth = 32;
  196735. else
  196736. max_pixel_depth = 64;
  196737. }
  196738. else
  196739. {
  196740. if (max_pixel_depth <= 8)
  196741. {
  196742. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196743. max_pixel_depth = 32;
  196744. else
  196745. max_pixel_depth = 24;
  196746. }
  196747. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196748. max_pixel_depth = 64;
  196749. else
  196750. max_pixel_depth = 48;
  196751. }
  196752. }
  196753. #endif
  196754. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196755. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196756. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196757. {
  196758. int user_pixel_depth=png_ptr->user_transform_depth*
  196759. png_ptr->user_transform_channels;
  196760. if(user_pixel_depth > max_pixel_depth)
  196761. max_pixel_depth=user_pixel_depth;
  196762. }
  196763. #endif
  196764. /* align the width on the next larger 8 pixels. Mainly used
  196765. for interlacing */
  196766. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196767. /* calculate the maximum bytes needed, adding a byte and a pixel
  196768. for safety's sake */
  196769. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196770. 1 + ((max_pixel_depth + 7) >> 3);
  196771. #ifdef PNG_MAX_MALLOC_64K
  196772. if (row_bytes > (png_uint_32)65536L)
  196773. png_error(png_ptr, "This image requires a row greater than 64KB");
  196774. #endif
  196775. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196776. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196777. #ifdef PNG_MAX_MALLOC_64K
  196778. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196779. png_error(png_ptr, "This image requires a row greater than 64KB");
  196780. #endif
  196781. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196782. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196783. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196784. png_ptr->rowbytes + 1));
  196785. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196786. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196787. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196788. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196789. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196790. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196791. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196792. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196793. }
  196794. #endif /* PNG_READ_SUPPORTED */
  196795. /*** End of inlined file: pngrutil.c ***/
  196796. /*** Start of inlined file: pngset.c ***/
  196797. /* pngset.c - storage of image information into info struct
  196798. *
  196799. * Last changed in libpng 1.2.21 [October 4, 2007]
  196800. * For conditions of distribution and use, see copyright notice in png.h
  196801. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196802. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196803. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196804. *
  196805. * The functions here are used during reads to store data from the file
  196806. * into the info struct, and during writes to store application data
  196807. * into the info struct for writing into the file. This abstracts the
  196808. * info struct and allows us to change the structure in the future.
  196809. */
  196810. #define PNG_INTERNAL
  196811. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196812. #if defined(PNG_bKGD_SUPPORTED)
  196813. void PNGAPI
  196814. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196815. {
  196816. png_debug1(1, "in %s storage function\n", "bKGD");
  196817. if (png_ptr == NULL || info_ptr == NULL)
  196818. return;
  196819. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196820. info_ptr->valid |= PNG_INFO_bKGD;
  196821. }
  196822. #endif
  196823. #if defined(PNG_cHRM_SUPPORTED)
  196824. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196825. void PNGAPI
  196826. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196827. double white_x, double white_y, double red_x, double red_y,
  196828. double green_x, double green_y, double blue_x, double blue_y)
  196829. {
  196830. png_debug1(1, "in %s storage function\n", "cHRM");
  196831. if (png_ptr == NULL || info_ptr == NULL)
  196832. return;
  196833. if (white_x < 0.0 || white_y < 0.0 ||
  196834. red_x < 0.0 || red_y < 0.0 ||
  196835. green_x < 0.0 || green_y < 0.0 ||
  196836. blue_x < 0.0 || blue_y < 0.0)
  196837. {
  196838. png_warning(png_ptr,
  196839. "Ignoring attempt to set negative chromaticity value");
  196840. return;
  196841. }
  196842. if (white_x > 21474.83 || white_y > 21474.83 ||
  196843. red_x > 21474.83 || red_y > 21474.83 ||
  196844. green_x > 21474.83 || green_y > 21474.83 ||
  196845. blue_x > 21474.83 || blue_y > 21474.83)
  196846. {
  196847. png_warning(png_ptr,
  196848. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196849. return;
  196850. }
  196851. info_ptr->x_white = (float)white_x;
  196852. info_ptr->y_white = (float)white_y;
  196853. info_ptr->x_red = (float)red_x;
  196854. info_ptr->y_red = (float)red_y;
  196855. info_ptr->x_green = (float)green_x;
  196856. info_ptr->y_green = (float)green_y;
  196857. info_ptr->x_blue = (float)blue_x;
  196858. info_ptr->y_blue = (float)blue_y;
  196859. #ifdef PNG_FIXED_POINT_SUPPORTED
  196860. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196861. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196862. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196863. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196864. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196865. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196866. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196867. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196868. #endif
  196869. info_ptr->valid |= PNG_INFO_cHRM;
  196870. }
  196871. #endif
  196872. #ifdef PNG_FIXED_POINT_SUPPORTED
  196873. void PNGAPI
  196874. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196875. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196876. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196877. png_fixed_point blue_x, png_fixed_point blue_y)
  196878. {
  196879. png_debug1(1, "in %s storage function\n", "cHRM");
  196880. if (png_ptr == NULL || info_ptr == NULL)
  196881. return;
  196882. if (white_x < 0 || white_y < 0 ||
  196883. red_x < 0 || red_y < 0 ||
  196884. green_x < 0 || green_y < 0 ||
  196885. blue_x < 0 || blue_y < 0)
  196886. {
  196887. png_warning(png_ptr,
  196888. "Ignoring attempt to set negative chromaticity value");
  196889. return;
  196890. }
  196891. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196892. if (white_x > (double) PNG_UINT_31_MAX ||
  196893. white_y > (double) PNG_UINT_31_MAX ||
  196894. red_x > (double) PNG_UINT_31_MAX ||
  196895. red_y > (double) PNG_UINT_31_MAX ||
  196896. green_x > (double) PNG_UINT_31_MAX ||
  196897. green_y > (double) PNG_UINT_31_MAX ||
  196898. blue_x > (double) PNG_UINT_31_MAX ||
  196899. blue_y > (double) PNG_UINT_31_MAX)
  196900. #else
  196901. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196902. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196903. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196904. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196905. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196906. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196907. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196908. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196909. #endif
  196910. {
  196911. png_warning(png_ptr,
  196912. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196913. return;
  196914. }
  196915. info_ptr->int_x_white = white_x;
  196916. info_ptr->int_y_white = white_y;
  196917. info_ptr->int_x_red = red_x;
  196918. info_ptr->int_y_red = red_y;
  196919. info_ptr->int_x_green = green_x;
  196920. info_ptr->int_y_green = green_y;
  196921. info_ptr->int_x_blue = blue_x;
  196922. info_ptr->int_y_blue = blue_y;
  196923. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196924. info_ptr->x_white = (float)(white_x/100000.);
  196925. info_ptr->y_white = (float)(white_y/100000.);
  196926. info_ptr->x_red = (float)( red_x/100000.);
  196927. info_ptr->y_red = (float)( red_y/100000.);
  196928. info_ptr->x_green = (float)(green_x/100000.);
  196929. info_ptr->y_green = (float)(green_y/100000.);
  196930. info_ptr->x_blue = (float)( blue_x/100000.);
  196931. info_ptr->y_blue = (float)( blue_y/100000.);
  196932. #endif
  196933. info_ptr->valid |= PNG_INFO_cHRM;
  196934. }
  196935. #endif
  196936. #endif
  196937. #if defined(PNG_gAMA_SUPPORTED)
  196938. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196939. void PNGAPI
  196940. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196941. {
  196942. double gamma;
  196943. png_debug1(1, "in %s storage function\n", "gAMA");
  196944. if (png_ptr == NULL || info_ptr == NULL)
  196945. return;
  196946. /* Check for overflow */
  196947. if (file_gamma > 21474.83)
  196948. {
  196949. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196950. gamma=21474.83;
  196951. }
  196952. else
  196953. gamma=file_gamma;
  196954. info_ptr->gamma = (float)gamma;
  196955. #ifdef PNG_FIXED_POINT_SUPPORTED
  196956. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196957. #endif
  196958. info_ptr->valid |= PNG_INFO_gAMA;
  196959. if(gamma == 0.0)
  196960. png_warning(png_ptr, "Setting gamma=0");
  196961. }
  196962. #endif
  196963. void PNGAPI
  196964. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196965. int_gamma)
  196966. {
  196967. png_fixed_point gamma;
  196968. png_debug1(1, "in %s storage function\n", "gAMA");
  196969. if (png_ptr == NULL || info_ptr == NULL)
  196970. return;
  196971. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196972. {
  196973. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196974. gamma=PNG_UINT_31_MAX;
  196975. }
  196976. else
  196977. {
  196978. if (int_gamma < 0)
  196979. {
  196980. png_warning(png_ptr, "Setting negative gamma to zero");
  196981. gamma=0;
  196982. }
  196983. else
  196984. gamma=int_gamma;
  196985. }
  196986. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196987. info_ptr->gamma = (float)(gamma/100000.);
  196988. #endif
  196989. #ifdef PNG_FIXED_POINT_SUPPORTED
  196990. info_ptr->int_gamma = gamma;
  196991. #endif
  196992. info_ptr->valid |= PNG_INFO_gAMA;
  196993. if(gamma == 0)
  196994. png_warning(png_ptr, "Setting gamma=0");
  196995. }
  196996. #endif
  196997. #if defined(PNG_hIST_SUPPORTED)
  196998. void PNGAPI
  196999. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197000. {
  197001. int i;
  197002. png_debug1(1, "in %s storage function\n", "hIST");
  197003. if (png_ptr == NULL || info_ptr == NULL)
  197004. return;
  197005. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197006. > PNG_MAX_PALETTE_LENGTH)
  197007. {
  197008. png_warning(png_ptr,
  197009. "Invalid palette size, hIST allocation skipped.");
  197010. return;
  197011. }
  197012. #ifdef PNG_FREE_ME_SUPPORTED
  197013. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197014. #endif
  197015. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197016. 1.2.1 */
  197017. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197018. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197019. if (png_ptr->hist == NULL)
  197020. {
  197021. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197022. return;
  197023. }
  197024. for (i = 0; i < info_ptr->num_palette; i++)
  197025. png_ptr->hist[i] = hist[i];
  197026. info_ptr->hist = png_ptr->hist;
  197027. info_ptr->valid |= PNG_INFO_hIST;
  197028. #ifdef PNG_FREE_ME_SUPPORTED
  197029. info_ptr->free_me |= PNG_FREE_HIST;
  197030. #else
  197031. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197032. #endif
  197033. }
  197034. #endif
  197035. void PNGAPI
  197036. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197037. png_uint_32 width, png_uint_32 height, int bit_depth,
  197038. int color_type, int interlace_type, int compression_type,
  197039. int filter_type)
  197040. {
  197041. png_debug1(1, "in %s storage function\n", "IHDR");
  197042. if (png_ptr == NULL || info_ptr == NULL)
  197043. return;
  197044. /* check for width and height valid values */
  197045. if (width == 0 || height == 0)
  197046. png_error(png_ptr, "Image width or height is zero in IHDR");
  197047. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197048. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197049. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197050. #else
  197051. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197052. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197053. #endif
  197054. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197055. png_error(png_ptr, "Invalid image size in IHDR");
  197056. if ( width > (PNG_UINT_32_MAX
  197057. >> 3) /* 8-byte RGBA pixels */
  197058. - 64 /* bigrowbuf hack */
  197059. - 1 /* filter byte */
  197060. - 7*8 /* rounding of width to multiple of 8 pixels */
  197061. - 8) /* extra max_pixel_depth pad */
  197062. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197063. /* check other values */
  197064. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197065. bit_depth != 8 && bit_depth != 16)
  197066. png_error(png_ptr, "Invalid bit depth in IHDR");
  197067. if (color_type < 0 || color_type == 1 ||
  197068. color_type == 5 || color_type > 6)
  197069. png_error(png_ptr, "Invalid color type in IHDR");
  197070. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197071. ((color_type == PNG_COLOR_TYPE_RGB ||
  197072. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197073. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197074. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197075. if (interlace_type >= PNG_INTERLACE_LAST)
  197076. png_error(png_ptr, "Unknown interlace method in IHDR");
  197077. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197078. png_error(png_ptr, "Unknown compression method in IHDR");
  197079. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197080. /* Accept filter_method 64 (intrapixel differencing) only if
  197081. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197082. * 2. Libpng did not read a PNG signature (this filter_method is only
  197083. * used in PNG datastreams that are embedded in MNG datastreams) and
  197084. * 3. The application called png_permit_mng_features with a mask that
  197085. * included PNG_FLAG_MNG_FILTER_64 and
  197086. * 4. The filter_method is 64 and
  197087. * 5. The color_type is RGB or RGBA
  197088. */
  197089. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197090. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197091. if(filter_type != PNG_FILTER_TYPE_BASE)
  197092. {
  197093. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197094. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197095. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197096. (color_type == PNG_COLOR_TYPE_RGB ||
  197097. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197098. png_error(png_ptr, "Unknown filter method in IHDR");
  197099. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197100. png_warning(png_ptr, "Invalid filter method in IHDR");
  197101. }
  197102. #else
  197103. if(filter_type != PNG_FILTER_TYPE_BASE)
  197104. png_error(png_ptr, "Unknown filter method in IHDR");
  197105. #endif
  197106. info_ptr->width = width;
  197107. info_ptr->height = height;
  197108. info_ptr->bit_depth = (png_byte)bit_depth;
  197109. info_ptr->color_type =(png_byte) color_type;
  197110. info_ptr->compression_type = (png_byte)compression_type;
  197111. info_ptr->filter_type = (png_byte)filter_type;
  197112. info_ptr->interlace_type = (png_byte)interlace_type;
  197113. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197114. info_ptr->channels = 1;
  197115. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197116. info_ptr->channels = 3;
  197117. else
  197118. info_ptr->channels = 1;
  197119. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197120. info_ptr->channels++;
  197121. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197122. /* check for potential overflow */
  197123. if (width > (PNG_UINT_32_MAX
  197124. >> 3) /* 8-byte RGBA pixels */
  197125. - 64 /* bigrowbuf hack */
  197126. - 1 /* filter byte */
  197127. - 7*8 /* rounding of width to multiple of 8 pixels */
  197128. - 8) /* extra max_pixel_depth pad */
  197129. info_ptr->rowbytes = (png_size_t)0;
  197130. else
  197131. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197132. }
  197133. #if defined(PNG_oFFs_SUPPORTED)
  197134. void PNGAPI
  197135. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197136. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197137. {
  197138. png_debug1(1, "in %s storage function\n", "oFFs");
  197139. if (png_ptr == NULL || info_ptr == NULL)
  197140. return;
  197141. info_ptr->x_offset = offset_x;
  197142. info_ptr->y_offset = offset_y;
  197143. info_ptr->offset_unit_type = (png_byte)unit_type;
  197144. info_ptr->valid |= PNG_INFO_oFFs;
  197145. }
  197146. #endif
  197147. #if defined(PNG_pCAL_SUPPORTED)
  197148. void PNGAPI
  197149. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197150. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197151. png_charp units, png_charpp params)
  197152. {
  197153. png_uint_32 length;
  197154. int i;
  197155. png_debug1(1, "in %s storage function\n", "pCAL");
  197156. if (png_ptr == NULL || info_ptr == NULL)
  197157. return;
  197158. length = png_strlen(purpose) + 1;
  197159. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197160. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197161. if (info_ptr->pcal_purpose == NULL)
  197162. {
  197163. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197164. return;
  197165. }
  197166. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197167. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197168. info_ptr->pcal_X0 = X0;
  197169. info_ptr->pcal_X1 = X1;
  197170. info_ptr->pcal_type = (png_byte)type;
  197171. info_ptr->pcal_nparams = (png_byte)nparams;
  197172. length = png_strlen(units) + 1;
  197173. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197174. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197175. if (info_ptr->pcal_units == NULL)
  197176. {
  197177. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197178. return;
  197179. }
  197180. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197181. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197182. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197183. if (info_ptr->pcal_params == NULL)
  197184. {
  197185. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197186. return;
  197187. }
  197188. info_ptr->pcal_params[nparams] = NULL;
  197189. for (i = 0; i < nparams; i++)
  197190. {
  197191. length = png_strlen(params[i]) + 1;
  197192. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197193. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197194. if (info_ptr->pcal_params[i] == NULL)
  197195. {
  197196. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197197. return;
  197198. }
  197199. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197200. }
  197201. info_ptr->valid |= PNG_INFO_pCAL;
  197202. #ifdef PNG_FREE_ME_SUPPORTED
  197203. info_ptr->free_me |= PNG_FREE_PCAL;
  197204. #endif
  197205. }
  197206. #endif
  197207. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197208. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197209. void PNGAPI
  197210. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197211. int unit, double width, double height)
  197212. {
  197213. png_debug1(1, "in %s storage function\n", "sCAL");
  197214. if (png_ptr == NULL || info_ptr == NULL)
  197215. return;
  197216. info_ptr->scal_unit = (png_byte)unit;
  197217. info_ptr->scal_pixel_width = width;
  197218. info_ptr->scal_pixel_height = height;
  197219. info_ptr->valid |= PNG_INFO_sCAL;
  197220. }
  197221. #else
  197222. #ifdef PNG_FIXED_POINT_SUPPORTED
  197223. void PNGAPI
  197224. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197225. int unit, png_charp swidth, png_charp sheight)
  197226. {
  197227. png_uint_32 length;
  197228. png_debug1(1, "in %s storage function\n", "sCAL");
  197229. if (png_ptr == NULL || info_ptr == NULL)
  197230. return;
  197231. info_ptr->scal_unit = (png_byte)unit;
  197232. length = png_strlen(swidth) + 1;
  197233. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197234. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197235. if (info_ptr->scal_s_width == NULL)
  197236. {
  197237. png_warning(png_ptr,
  197238. "Memory allocation failed while processing sCAL.");
  197239. }
  197240. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197241. length = png_strlen(sheight) + 1;
  197242. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197243. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197244. if (info_ptr->scal_s_height == NULL)
  197245. {
  197246. png_free (png_ptr, info_ptr->scal_s_width);
  197247. png_warning(png_ptr,
  197248. "Memory allocation failed while processing sCAL.");
  197249. }
  197250. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197251. info_ptr->valid |= PNG_INFO_sCAL;
  197252. #ifdef PNG_FREE_ME_SUPPORTED
  197253. info_ptr->free_me |= PNG_FREE_SCAL;
  197254. #endif
  197255. }
  197256. #endif
  197257. #endif
  197258. #endif
  197259. #if defined(PNG_pHYs_SUPPORTED)
  197260. void PNGAPI
  197261. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197262. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197263. {
  197264. png_debug1(1, "in %s storage function\n", "pHYs");
  197265. if (png_ptr == NULL || info_ptr == NULL)
  197266. return;
  197267. info_ptr->x_pixels_per_unit = res_x;
  197268. info_ptr->y_pixels_per_unit = res_y;
  197269. info_ptr->phys_unit_type = (png_byte)unit_type;
  197270. info_ptr->valid |= PNG_INFO_pHYs;
  197271. }
  197272. #endif
  197273. void PNGAPI
  197274. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197275. png_colorp palette, int num_palette)
  197276. {
  197277. png_debug1(1, "in %s storage function\n", "PLTE");
  197278. if (png_ptr == NULL || info_ptr == NULL)
  197279. return;
  197280. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197281. {
  197282. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197283. png_error(png_ptr, "Invalid palette length");
  197284. else
  197285. {
  197286. png_warning(png_ptr, "Invalid palette length");
  197287. return;
  197288. }
  197289. }
  197290. /*
  197291. * It may not actually be necessary to set png_ptr->palette here;
  197292. * we do it for backward compatibility with the way the png_handle_tRNS
  197293. * function used to do the allocation.
  197294. */
  197295. #ifdef PNG_FREE_ME_SUPPORTED
  197296. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197297. #endif
  197298. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197299. of num_palette entries,
  197300. in case of an invalid PNG file that has too-large sample values. */
  197301. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197302. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197303. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197304. png_sizeof(png_color));
  197305. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197306. info_ptr->palette = png_ptr->palette;
  197307. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197308. #ifdef PNG_FREE_ME_SUPPORTED
  197309. info_ptr->free_me |= PNG_FREE_PLTE;
  197310. #else
  197311. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197312. #endif
  197313. info_ptr->valid |= PNG_INFO_PLTE;
  197314. }
  197315. #if defined(PNG_sBIT_SUPPORTED)
  197316. void PNGAPI
  197317. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197318. png_color_8p sig_bit)
  197319. {
  197320. png_debug1(1, "in %s storage function\n", "sBIT");
  197321. if (png_ptr == NULL || info_ptr == NULL)
  197322. return;
  197323. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197324. info_ptr->valid |= PNG_INFO_sBIT;
  197325. }
  197326. #endif
  197327. #if defined(PNG_sRGB_SUPPORTED)
  197328. void PNGAPI
  197329. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197330. {
  197331. png_debug1(1, "in %s storage function\n", "sRGB");
  197332. if (png_ptr == NULL || info_ptr == NULL)
  197333. return;
  197334. info_ptr->srgb_intent = (png_byte)intent;
  197335. info_ptr->valid |= PNG_INFO_sRGB;
  197336. }
  197337. void PNGAPI
  197338. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197339. int intent)
  197340. {
  197341. #if defined(PNG_gAMA_SUPPORTED)
  197342. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197343. float file_gamma;
  197344. #endif
  197345. #ifdef PNG_FIXED_POINT_SUPPORTED
  197346. png_fixed_point int_file_gamma;
  197347. #endif
  197348. #endif
  197349. #if defined(PNG_cHRM_SUPPORTED)
  197350. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197351. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197352. #endif
  197353. #ifdef PNG_FIXED_POINT_SUPPORTED
  197354. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197355. int_green_y, int_blue_x, int_blue_y;
  197356. #endif
  197357. #endif
  197358. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197359. if (png_ptr == NULL || info_ptr == NULL)
  197360. return;
  197361. png_set_sRGB(png_ptr, info_ptr, intent);
  197362. #if defined(PNG_gAMA_SUPPORTED)
  197363. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197364. file_gamma = (float).45455;
  197365. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197366. #endif
  197367. #ifdef PNG_FIXED_POINT_SUPPORTED
  197368. int_file_gamma = 45455L;
  197369. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197370. #endif
  197371. #endif
  197372. #if defined(PNG_cHRM_SUPPORTED)
  197373. #ifdef PNG_FIXED_POINT_SUPPORTED
  197374. int_white_x = 31270L;
  197375. int_white_y = 32900L;
  197376. int_red_x = 64000L;
  197377. int_red_y = 33000L;
  197378. int_green_x = 30000L;
  197379. int_green_y = 60000L;
  197380. int_blue_x = 15000L;
  197381. int_blue_y = 6000L;
  197382. png_set_cHRM_fixed(png_ptr, info_ptr,
  197383. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197384. int_blue_x, int_blue_y);
  197385. #endif
  197386. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197387. white_x = (float).3127;
  197388. white_y = (float).3290;
  197389. red_x = (float).64;
  197390. red_y = (float).33;
  197391. green_x = (float).30;
  197392. green_y = (float).60;
  197393. blue_x = (float).15;
  197394. blue_y = (float).06;
  197395. png_set_cHRM(png_ptr, info_ptr,
  197396. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197397. #endif
  197398. #endif
  197399. }
  197400. #endif
  197401. #if defined(PNG_iCCP_SUPPORTED)
  197402. void PNGAPI
  197403. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197404. png_charp name, int compression_type,
  197405. png_charp profile, png_uint_32 proflen)
  197406. {
  197407. png_charp new_iccp_name;
  197408. png_charp new_iccp_profile;
  197409. png_debug1(1, "in %s storage function\n", "iCCP");
  197410. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197411. return;
  197412. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197413. if (new_iccp_name == NULL)
  197414. {
  197415. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197416. return;
  197417. }
  197418. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197419. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197420. if (new_iccp_profile == NULL)
  197421. {
  197422. png_free (png_ptr, new_iccp_name);
  197423. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197424. return;
  197425. }
  197426. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197427. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197428. info_ptr->iccp_proflen = proflen;
  197429. info_ptr->iccp_name = new_iccp_name;
  197430. info_ptr->iccp_profile = new_iccp_profile;
  197431. /* Compression is always zero but is here so the API and info structure
  197432. * does not have to change if we introduce multiple compression types */
  197433. info_ptr->iccp_compression = (png_byte)compression_type;
  197434. #ifdef PNG_FREE_ME_SUPPORTED
  197435. info_ptr->free_me |= PNG_FREE_ICCP;
  197436. #endif
  197437. info_ptr->valid |= PNG_INFO_iCCP;
  197438. }
  197439. #endif
  197440. #if defined(PNG_TEXT_SUPPORTED)
  197441. void PNGAPI
  197442. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197443. int num_text)
  197444. {
  197445. int ret;
  197446. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197447. if (ret)
  197448. png_error(png_ptr, "Insufficient memory to store text");
  197449. }
  197450. int /* PRIVATE */
  197451. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197452. int num_text)
  197453. {
  197454. int i;
  197455. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197456. "text" : (png_const_charp)png_ptr->chunk_name));
  197457. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197458. return(0);
  197459. /* Make sure we have enough space in the "text" array in info_struct
  197460. * to hold all of the incoming text_ptr objects.
  197461. */
  197462. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197463. {
  197464. if (info_ptr->text != NULL)
  197465. {
  197466. png_textp old_text;
  197467. int old_max;
  197468. old_max = info_ptr->max_text;
  197469. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197470. old_text = info_ptr->text;
  197471. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197472. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197473. if (info_ptr->text == NULL)
  197474. {
  197475. png_free(png_ptr, old_text);
  197476. return(1);
  197477. }
  197478. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197479. png_sizeof(png_text)));
  197480. png_free(png_ptr, old_text);
  197481. }
  197482. else
  197483. {
  197484. info_ptr->max_text = num_text + 8;
  197485. info_ptr->num_text = 0;
  197486. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197487. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197488. if (info_ptr->text == NULL)
  197489. return(1);
  197490. #ifdef PNG_FREE_ME_SUPPORTED
  197491. info_ptr->free_me |= PNG_FREE_TEXT;
  197492. #endif
  197493. }
  197494. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197495. info_ptr->max_text);
  197496. }
  197497. for (i = 0; i < num_text; i++)
  197498. {
  197499. png_size_t text_length,key_len;
  197500. png_size_t lang_len,lang_key_len;
  197501. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197502. if (text_ptr[i].key == NULL)
  197503. continue;
  197504. key_len = png_strlen(text_ptr[i].key);
  197505. if(text_ptr[i].compression <= 0)
  197506. {
  197507. lang_len = 0;
  197508. lang_key_len = 0;
  197509. }
  197510. else
  197511. #ifdef PNG_iTXt_SUPPORTED
  197512. {
  197513. /* set iTXt data */
  197514. if (text_ptr[i].lang != NULL)
  197515. lang_len = png_strlen(text_ptr[i].lang);
  197516. else
  197517. lang_len = 0;
  197518. if (text_ptr[i].lang_key != NULL)
  197519. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197520. else
  197521. lang_key_len = 0;
  197522. }
  197523. #else
  197524. {
  197525. png_warning(png_ptr, "iTXt chunk not supported.");
  197526. continue;
  197527. }
  197528. #endif
  197529. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197530. {
  197531. text_length = 0;
  197532. #ifdef PNG_iTXt_SUPPORTED
  197533. if(text_ptr[i].compression > 0)
  197534. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197535. else
  197536. #endif
  197537. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197538. }
  197539. else
  197540. {
  197541. text_length = png_strlen(text_ptr[i].text);
  197542. textp->compression = text_ptr[i].compression;
  197543. }
  197544. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197545. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197546. if (textp->key == NULL)
  197547. return(1);
  197548. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197549. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197550. (int)textp->key);
  197551. png_memcpy(textp->key, text_ptr[i].key,
  197552. (png_size_t)(key_len));
  197553. *(textp->key+key_len) = '\0';
  197554. #ifdef PNG_iTXt_SUPPORTED
  197555. if (text_ptr[i].compression > 0)
  197556. {
  197557. textp->lang=textp->key + key_len + 1;
  197558. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197559. *(textp->lang+lang_len) = '\0';
  197560. textp->lang_key=textp->lang + lang_len + 1;
  197561. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197562. *(textp->lang_key+lang_key_len) = '\0';
  197563. textp->text=textp->lang_key + lang_key_len + 1;
  197564. }
  197565. else
  197566. #endif
  197567. {
  197568. #ifdef PNG_iTXt_SUPPORTED
  197569. textp->lang=NULL;
  197570. textp->lang_key=NULL;
  197571. #endif
  197572. textp->text=textp->key + key_len + 1;
  197573. }
  197574. if(text_length)
  197575. png_memcpy(textp->text, text_ptr[i].text,
  197576. (png_size_t)(text_length));
  197577. *(textp->text+text_length) = '\0';
  197578. #ifdef PNG_iTXt_SUPPORTED
  197579. if(textp->compression > 0)
  197580. {
  197581. textp->text_length = 0;
  197582. textp->itxt_length = text_length;
  197583. }
  197584. else
  197585. #endif
  197586. {
  197587. textp->text_length = text_length;
  197588. #ifdef PNG_iTXt_SUPPORTED
  197589. textp->itxt_length = 0;
  197590. #endif
  197591. }
  197592. info_ptr->num_text++;
  197593. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197594. }
  197595. return(0);
  197596. }
  197597. #endif
  197598. #if defined(PNG_tIME_SUPPORTED)
  197599. void PNGAPI
  197600. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197601. {
  197602. png_debug1(1, "in %s storage function\n", "tIME");
  197603. if (png_ptr == NULL || info_ptr == NULL ||
  197604. (png_ptr->mode & PNG_WROTE_tIME))
  197605. return;
  197606. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197607. info_ptr->valid |= PNG_INFO_tIME;
  197608. }
  197609. #endif
  197610. #if defined(PNG_tRNS_SUPPORTED)
  197611. void PNGAPI
  197612. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197613. png_bytep trans, int num_trans, png_color_16p trans_values)
  197614. {
  197615. png_debug1(1, "in %s storage function\n", "tRNS");
  197616. if (png_ptr == NULL || info_ptr == NULL)
  197617. return;
  197618. if (trans != NULL)
  197619. {
  197620. /*
  197621. * It may not actually be necessary to set png_ptr->trans here;
  197622. * we do it for backward compatibility with the way the png_handle_tRNS
  197623. * function used to do the allocation.
  197624. */
  197625. #ifdef PNG_FREE_ME_SUPPORTED
  197626. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197627. #endif
  197628. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197629. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197630. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197631. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197632. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197633. #ifdef PNG_FREE_ME_SUPPORTED
  197634. info_ptr->free_me |= PNG_FREE_TRNS;
  197635. #else
  197636. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197637. #endif
  197638. }
  197639. if (trans_values != NULL)
  197640. {
  197641. png_memcpy(&(info_ptr->trans_values), trans_values,
  197642. png_sizeof(png_color_16));
  197643. if (num_trans == 0)
  197644. num_trans = 1;
  197645. }
  197646. info_ptr->num_trans = (png_uint_16)num_trans;
  197647. info_ptr->valid |= PNG_INFO_tRNS;
  197648. }
  197649. #endif
  197650. #if defined(PNG_sPLT_SUPPORTED)
  197651. void PNGAPI
  197652. png_set_sPLT(png_structp png_ptr,
  197653. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197654. {
  197655. png_sPLT_tp np;
  197656. int i;
  197657. if (png_ptr == NULL || info_ptr == NULL)
  197658. return;
  197659. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197660. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197661. if (np == NULL)
  197662. {
  197663. png_warning(png_ptr, "No memory for sPLT palettes.");
  197664. return;
  197665. }
  197666. png_memcpy(np, info_ptr->splt_palettes,
  197667. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197668. png_free(png_ptr, info_ptr->splt_palettes);
  197669. info_ptr->splt_palettes=NULL;
  197670. for (i = 0; i < nentries; i++)
  197671. {
  197672. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197673. png_sPLT_tp from = entries + i;
  197674. to->name = (png_charp)png_malloc_warn(png_ptr,
  197675. png_strlen(from->name) + 1);
  197676. if (to->name == NULL)
  197677. {
  197678. png_warning(png_ptr,
  197679. "Out of memory while processing sPLT chunk");
  197680. }
  197681. /* TODO: use png_malloc_warn */
  197682. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197683. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197684. from->nentries * png_sizeof(png_sPLT_entry));
  197685. /* TODO: use png_malloc_warn */
  197686. png_memcpy(to->entries, from->entries,
  197687. from->nentries * png_sizeof(png_sPLT_entry));
  197688. if (to->entries == NULL)
  197689. {
  197690. png_warning(png_ptr,
  197691. "Out of memory while processing sPLT chunk");
  197692. png_free(png_ptr,to->name);
  197693. to->name = NULL;
  197694. }
  197695. to->nentries = from->nentries;
  197696. to->depth = from->depth;
  197697. }
  197698. info_ptr->splt_palettes = np;
  197699. info_ptr->splt_palettes_num += nentries;
  197700. info_ptr->valid |= PNG_INFO_sPLT;
  197701. #ifdef PNG_FREE_ME_SUPPORTED
  197702. info_ptr->free_me |= PNG_FREE_SPLT;
  197703. #endif
  197704. }
  197705. #endif /* PNG_sPLT_SUPPORTED */
  197706. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197707. void PNGAPI
  197708. png_set_unknown_chunks(png_structp png_ptr,
  197709. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197710. {
  197711. png_unknown_chunkp np;
  197712. int i;
  197713. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197714. return;
  197715. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197716. (info_ptr->unknown_chunks_num + num_unknowns) *
  197717. png_sizeof(png_unknown_chunk));
  197718. if (np == NULL)
  197719. {
  197720. png_warning(png_ptr,
  197721. "Out of memory while processing unknown chunk.");
  197722. return;
  197723. }
  197724. png_memcpy(np, info_ptr->unknown_chunks,
  197725. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197726. png_free(png_ptr, info_ptr->unknown_chunks);
  197727. info_ptr->unknown_chunks=NULL;
  197728. for (i = 0; i < num_unknowns; i++)
  197729. {
  197730. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197731. png_unknown_chunkp from = unknowns + i;
  197732. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197733. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197734. if (to->data == NULL)
  197735. {
  197736. png_warning(png_ptr,
  197737. "Out of memory while processing unknown chunk.");
  197738. }
  197739. else
  197740. {
  197741. png_memcpy(to->data, from->data, from->size);
  197742. to->size = from->size;
  197743. /* note our location in the read or write sequence */
  197744. to->location = (png_byte)(png_ptr->mode & 0xff);
  197745. }
  197746. }
  197747. info_ptr->unknown_chunks = np;
  197748. info_ptr->unknown_chunks_num += num_unknowns;
  197749. #ifdef PNG_FREE_ME_SUPPORTED
  197750. info_ptr->free_me |= PNG_FREE_UNKN;
  197751. #endif
  197752. }
  197753. void PNGAPI
  197754. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197755. int chunk, int location)
  197756. {
  197757. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197758. (int)info_ptr->unknown_chunks_num)
  197759. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197760. }
  197761. #endif
  197762. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197763. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197764. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197765. void PNGAPI
  197766. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197767. {
  197768. /* This function is deprecated in favor of png_permit_mng_features()
  197769. and will be removed from libpng-1.3.0 */
  197770. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197771. if (png_ptr == NULL)
  197772. return;
  197773. png_ptr->mng_features_permitted = (png_byte)
  197774. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197775. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197776. }
  197777. #endif
  197778. #endif
  197779. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197780. png_uint_32 PNGAPI
  197781. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197782. {
  197783. png_debug(1, "in png_permit_mng_features\n");
  197784. if (png_ptr == NULL)
  197785. return (png_uint_32)0;
  197786. png_ptr->mng_features_permitted =
  197787. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197788. return (png_uint_32)png_ptr->mng_features_permitted;
  197789. }
  197790. #endif
  197791. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197792. void PNGAPI
  197793. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197794. chunk_list, int num_chunks)
  197795. {
  197796. png_bytep new_list, p;
  197797. int i, old_num_chunks;
  197798. if (png_ptr == NULL)
  197799. return;
  197800. if (num_chunks == 0)
  197801. {
  197802. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197803. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197804. else
  197805. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197806. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197807. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197808. else
  197809. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197810. return;
  197811. }
  197812. if (chunk_list == NULL)
  197813. return;
  197814. old_num_chunks=png_ptr->num_chunk_list;
  197815. new_list=(png_bytep)png_malloc(png_ptr,
  197816. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197817. if(png_ptr->chunk_list != NULL)
  197818. {
  197819. png_memcpy(new_list, png_ptr->chunk_list,
  197820. (png_size_t)(5*old_num_chunks));
  197821. png_free(png_ptr, png_ptr->chunk_list);
  197822. png_ptr->chunk_list=NULL;
  197823. }
  197824. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197825. (png_size_t)(5*num_chunks));
  197826. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197827. *p=(png_byte)keep;
  197828. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197829. png_ptr->chunk_list=new_list;
  197830. #ifdef PNG_FREE_ME_SUPPORTED
  197831. png_ptr->free_me |= PNG_FREE_LIST;
  197832. #endif
  197833. }
  197834. #endif
  197835. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197836. void PNGAPI
  197837. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197838. png_user_chunk_ptr read_user_chunk_fn)
  197839. {
  197840. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197841. if (png_ptr == NULL)
  197842. return;
  197843. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197844. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197845. }
  197846. #endif
  197847. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197848. void PNGAPI
  197849. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197850. {
  197851. png_debug1(1, "in %s storage function\n", "rows");
  197852. if (png_ptr == NULL || info_ptr == NULL)
  197853. return;
  197854. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197855. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197856. info_ptr->row_pointers = row_pointers;
  197857. if(row_pointers)
  197858. info_ptr->valid |= PNG_INFO_IDAT;
  197859. }
  197860. #endif
  197861. #ifdef PNG_WRITE_SUPPORTED
  197862. void PNGAPI
  197863. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197864. {
  197865. if (png_ptr == NULL)
  197866. return;
  197867. if(png_ptr->zbuf)
  197868. png_free(png_ptr, png_ptr->zbuf);
  197869. png_ptr->zbuf_size = (png_size_t)size;
  197870. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197871. png_ptr->zstream.next_out = png_ptr->zbuf;
  197872. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197873. }
  197874. #endif
  197875. void PNGAPI
  197876. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197877. {
  197878. if (png_ptr && info_ptr)
  197879. info_ptr->valid &= ~(mask);
  197880. }
  197881. #ifndef PNG_1_0_X
  197882. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197883. /* function was added to libpng 1.2.0 and should always exist by default */
  197884. void PNGAPI
  197885. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197886. {
  197887. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197888. if (png_ptr != NULL)
  197889. png_ptr->asm_flags = 0;
  197890. }
  197891. /* this function was added to libpng 1.2.0 */
  197892. void PNGAPI
  197893. png_set_mmx_thresholds (png_structp png_ptr,
  197894. png_byte,
  197895. png_uint_32)
  197896. {
  197897. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197898. if (png_ptr == NULL)
  197899. return;
  197900. }
  197901. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197902. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197903. /* this function was added to libpng 1.2.6 */
  197904. void PNGAPI
  197905. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197906. png_uint_32 user_height_max)
  197907. {
  197908. /* Images with dimensions larger than these limits will be
  197909. * rejected by png_set_IHDR(). To accept any PNG datastream
  197910. * regardless of dimensions, set both limits to 0x7ffffffL.
  197911. */
  197912. if(png_ptr == NULL) return;
  197913. png_ptr->user_width_max = user_width_max;
  197914. png_ptr->user_height_max = user_height_max;
  197915. }
  197916. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197917. #endif /* ?PNG_1_0_X */
  197918. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197919. /*** End of inlined file: pngset.c ***/
  197920. /*** Start of inlined file: pngtrans.c ***/
  197921. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197922. *
  197923. * Last changed in libpng 1.2.17 May 15, 2007
  197924. * For conditions of distribution and use, see copyright notice in png.h
  197925. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197926. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197927. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197928. */
  197929. #define PNG_INTERNAL
  197930. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197931. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197932. /* turn on BGR-to-RGB mapping */
  197933. void PNGAPI
  197934. png_set_bgr(png_structp png_ptr)
  197935. {
  197936. png_debug(1, "in png_set_bgr\n");
  197937. if(png_ptr == NULL) return;
  197938. png_ptr->transformations |= PNG_BGR;
  197939. }
  197940. #endif
  197941. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197942. /* turn on 16 bit byte swapping */
  197943. void PNGAPI
  197944. png_set_swap(png_structp png_ptr)
  197945. {
  197946. png_debug(1, "in png_set_swap\n");
  197947. if(png_ptr == NULL) return;
  197948. if (png_ptr->bit_depth == 16)
  197949. png_ptr->transformations |= PNG_SWAP_BYTES;
  197950. }
  197951. #endif
  197952. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197953. /* turn on pixel packing */
  197954. void PNGAPI
  197955. png_set_packing(png_structp png_ptr)
  197956. {
  197957. png_debug(1, "in png_set_packing\n");
  197958. if(png_ptr == NULL) return;
  197959. if (png_ptr->bit_depth < 8)
  197960. {
  197961. png_ptr->transformations |= PNG_PACK;
  197962. png_ptr->usr_bit_depth = 8;
  197963. }
  197964. }
  197965. #endif
  197966. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197967. /* turn on packed pixel swapping */
  197968. void PNGAPI
  197969. png_set_packswap(png_structp png_ptr)
  197970. {
  197971. png_debug(1, "in png_set_packswap\n");
  197972. if(png_ptr == NULL) return;
  197973. if (png_ptr->bit_depth < 8)
  197974. png_ptr->transformations |= PNG_PACKSWAP;
  197975. }
  197976. #endif
  197977. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197978. void PNGAPI
  197979. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197980. {
  197981. png_debug(1, "in png_set_shift\n");
  197982. if(png_ptr == NULL) return;
  197983. png_ptr->transformations |= PNG_SHIFT;
  197984. png_ptr->shift = *true_bits;
  197985. }
  197986. #endif
  197987. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197988. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197989. int PNGAPI
  197990. png_set_interlace_handling(png_structp png_ptr)
  197991. {
  197992. png_debug(1, "in png_set_interlace handling\n");
  197993. if (png_ptr && png_ptr->interlaced)
  197994. {
  197995. png_ptr->transformations |= PNG_INTERLACE;
  197996. return (7);
  197997. }
  197998. return (1);
  197999. }
  198000. #endif
  198001. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198002. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198003. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198004. * for 48-bit input data, as well as to avoid problems with some compilers
  198005. * that don't like bytes as parameters.
  198006. */
  198007. void PNGAPI
  198008. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198009. {
  198010. png_debug(1, "in png_set_filler\n");
  198011. if(png_ptr == NULL) return;
  198012. png_ptr->transformations |= PNG_FILLER;
  198013. png_ptr->filler = (png_byte)filler;
  198014. if (filler_loc == PNG_FILLER_AFTER)
  198015. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198016. else
  198017. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198018. /* This should probably go in the "do_read_filler" routine.
  198019. * I attempted to do that in libpng-1.0.1a but that caused problems
  198020. * so I restored it in libpng-1.0.2a
  198021. */
  198022. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198023. {
  198024. png_ptr->usr_channels = 4;
  198025. }
  198026. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198027. * a less-than-8-bit grayscale to GA? */
  198028. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198029. {
  198030. png_ptr->usr_channels = 2;
  198031. }
  198032. }
  198033. #if !defined(PNG_1_0_X)
  198034. /* Added to libpng-1.2.7 */
  198035. void PNGAPI
  198036. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198037. {
  198038. png_debug(1, "in png_set_add_alpha\n");
  198039. if(png_ptr == NULL) return;
  198040. png_set_filler(png_ptr, filler, filler_loc);
  198041. png_ptr->transformations |= PNG_ADD_ALPHA;
  198042. }
  198043. #endif
  198044. #endif
  198045. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198046. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198047. void PNGAPI
  198048. png_set_swap_alpha(png_structp png_ptr)
  198049. {
  198050. png_debug(1, "in png_set_swap_alpha\n");
  198051. if(png_ptr == NULL) return;
  198052. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198053. }
  198054. #endif
  198055. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198056. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198057. void PNGAPI
  198058. png_set_invert_alpha(png_structp png_ptr)
  198059. {
  198060. png_debug(1, "in png_set_invert_alpha\n");
  198061. if(png_ptr == NULL) return;
  198062. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198063. }
  198064. #endif
  198065. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198066. void PNGAPI
  198067. png_set_invert_mono(png_structp png_ptr)
  198068. {
  198069. png_debug(1, "in png_set_invert_mono\n");
  198070. if(png_ptr == NULL) return;
  198071. png_ptr->transformations |= PNG_INVERT_MONO;
  198072. }
  198073. /* invert monochrome grayscale data */
  198074. void /* PRIVATE */
  198075. png_do_invert(png_row_infop row_info, png_bytep row)
  198076. {
  198077. png_debug(1, "in png_do_invert\n");
  198078. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198079. * if (row_info->bit_depth == 1 &&
  198080. */
  198081. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198082. if (row == NULL || row_info == NULL)
  198083. return;
  198084. #endif
  198085. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198086. {
  198087. png_bytep rp = row;
  198088. png_uint_32 i;
  198089. png_uint_32 istop = row_info->rowbytes;
  198090. for (i = 0; i < istop; i++)
  198091. {
  198092. *rp = (png_byte)(~(*rp));
  198093. rp++;
  198094. }
  198095. }
  198096. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198097. row_info->bit_depth == 8)
  198098. {
  198099. png_bytep rp = row;
  198100. png_uint_32 i;
  198101. png_uint_32 istop = row_info->rowbytes;
  198102. for (i = 0; i < istop; i+=2)
  198103. {
  198104. *rp = (png_byte)(~(*rp));
  198105. rp+=2;
  198106. }
  198107. }
  198108. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198109. row_info->bit_depth == 16)
  198110. {
  198111. png_bytep rp = row;
  198112. png_uint_32 i;
  198113. png_uint_32 istop = row_info->rowbytes;
  198114. for (i = 0; i < istop; i+=4)
  198115. {
  198116. *rp = (png_byte)(~(*rp));
  198117. *(rp+1) = (png_byte)(~(*(rp+1)));
  198118. rp+=4;
  198119. }
  198120. }
  198121. }
  198122. #endif
  198123. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198124. /* swaps byte order on 16 bit depth images */
  198125. void /* PRIVATE */
  198126. png_do_swap(png_row_infop row_info, png_bytep row)
  198127. {
  198128. png_debug(1, "in png_do_swap\n");
  198129. if (
  198130. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198131. row != NULL && row_info != NULL &&
  198132. #endif
  198133. row_info->bit_depth == 16)
  198134. {
  198135. png_bytep rp = row;
  198136. png_uint_32 i;
  198137. png_uint_32 istop= row_info->width * row_info->channels;
  198138. for (i = 0; i < istop; i++, rp += 2)
  198139. {
  198140. png_byte t = *rp;
  198141. *rp = *(rp + 1);
  198142. *(rp + 1) = t;
  198143. }
  198144. }
  198145. }
  198146. #endif
  198147. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198148. static PNG_CONST png_byte onebppswaptable[256] = {
  198149. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198150. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198151. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198152. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198153. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198154. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198155. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198156. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198157. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198158. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198159. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198160. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198161. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198162. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198163. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198164. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198165. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198166. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198167. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198168. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198169. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198170. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198171. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198172. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198173. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198174. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198175. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198176. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198177. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198178. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198179. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198180. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198181. };
  198182. static PNG_CONST png_byte twobppswaptable[256] = {
  198183. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198184. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198185. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198186. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198187. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198188. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198189. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198190. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198191. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198192. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198193. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198194. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198195. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198196. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198197. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198198. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198199. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198200. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198201. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198202. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198203. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198204. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198205. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198206. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198207. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198208. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198209. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198210. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198211. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198212. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198213. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198214. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198215. };
  198216. static PNG_CONST png_byte fourbppswaptable[256] = {
  198217. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198218. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198219. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198220. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198221. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198222. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198223. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198224. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198225. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198226. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198227. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198228. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198229. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198230. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198231. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198232. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198233. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198234. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198235. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198236. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198237. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198238. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198239. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198240. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198241. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198242. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198243. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198244. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198245. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198246. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198247. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198248. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198249. };
  198250. /* swaps pixel packing order within bytes */
  198251. void /* PRIVATE */
  198252. png_do_packswap(png_row_infop row_info, png_bytep row)
  198253. {
  198254. png_debug(1, "in png_do_packswap\n");
  198255. if (
  198256. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198257. row != NULL && row_info != NULL &&
  198258. #endif
  198259. row_info->bit_depth < 8)
  198260. {
  198261. png_bytep rp, end, table;
  198262. end = row + row_info->rowbytes;
  198263. if (row_info->bit_depth == 1)
  198264. table = (png_bytep)onebppswaptable;
  198265. else if (row_info->bit_depth == 2)
  198266. table = (png_bytep)twobppswaptable;
  198267. else if (row_info->bit_depth == 4)
  198268. table = (png_bytep)fourbppswaptable;
  198269. else
  198270. return;
  198271. for (rp = row; rp < end; rp++)
  198272. *rp = table[*rp];
  198273. }
  198274. }
  198275. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198276. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198277. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198278. /* remove filler or alpha byte(s) */
  198279. void /* PRIVATE */
  198280. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198281. {
  198282. png_debug(1, "in png_do_strip_filler\n");
  198283. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198284. if (row != NULL && row_info != NULL)
  198285. #endif
  198286. {
  198287. png_bytep sp=row;
  198288. png_bytep dp=row;
  198289. png_uint_32 row_width=row_info->width;
  198290. png_uint_32 i;
  198291. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198292. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198293. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198294. row_info->channels == 4)
  198295. {
  198296. if (row_info->bit_depth == 8)
  198297. {
  198298. /* This converts from RGBX or RGBA to RGB */
  198299. if (flags & PNG_FLAG_FILLER_AFTER)
  198300. {
  198301. dp+=3; sp+=4;
  198302. for (i = 1; i < row_width; i++)
  198303. {
  198304. *dp++ = *sp++;
  198305. *dp++ = *sp++;
  198306. *dp++ = *sp++;
  198307. sp++;
  198308. }
  198309. }
  198310. /* This converts from XRGB or ARGB to RGB */
  198311. else
  198312. {
  198313. for (i = 0; i < row_width; i++)
  198314. {
  198315. sp++;
  198316. *dp++ = *sp++;
  198317. *dp++ = *sp++;
  198318. *dp++ = *sp++;
  198319. }
  198320. }
  198321. row_info->pixel_depth = 24;
  198322. row_info->rowbytes = row_width * 3;
  198323. }
  198324. else /* if (row_info->bit_depth == 16) */
  198325. {
  198326. if (flags & PNG_FLAG_FILLER_AFTER)
  198327. {
  198328. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198329. sp += 8; dp += 6;
  198330. for (i = 1; i < row_width; i++)
  198331. {
  198332. /* This could be (although png_memcpy is probably slower):
  198333. png_memcpy(dp, sp, 6);
  198334. sp += 8;
  198335. dp += 6;
  198336. */
  198337. *dp++ = *sp++;
  198338. *dp++ = *sp++;
  198339. *dp++ = *sp++;
  198340. *dp++ = *sp++;
  198341. *dp++ = *sp++;
  198342. *dp++ = *sp++;
  198343. sp += 2;
  198344. }
  198345. }
  198346. else
  198347. {
  198348. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198349. for (i = 0; i < row_width; i++)
  198350. {
  198351. /* This could be (although png_memcpy is probably slower):
  198352. png_memcpy(dp, sp, 6);
  198353. sp += 8;
  198354. dp += 6;
  198355. */
  198356. sp+=2;
  198357. *dp++ = *sp++;
  198358. *dp++ = *sp++;
  198359. *dp++ = *sp++;
  198360. *dp++ = *sp++;
  198361. *dp++ = *sp++;
  198362. *dp++ = *sp++;
  198363. }
  198364. }
  198365. row_info->pixel_depth = 48;
  198366. row_info->rowbytes = row_width * 6;
  198367. }
  198368. row_info->channels = 3;
  198369. }
  198370. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198371. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198372. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198373. row_info->channels == 2)
  198374. {
  198375. if (row_info->bit_depth == 8)
  198376. {
  198377. /* This converts from GX or GA to G */
  198378. if (flags & PNG_FLAG_FILLER_AFTER)
  198379. {
  198380. for (i = 0; i < row_width; i++)
  198381. {
  198382. *dp++ = *sp++;
  198383. sp++;
  198384. }
  198385. }
  198386. /* This converts from XG or AG to G */
  198387. else
  198388. {
  198389. for (i = 0; i < row_width; i++)
  198390. {
  198391. sp++;
  198392. *dp++ = *sp++;
  198393. }
  198394. }
  198395. row_info->pixel_depth = 8;
  198396. row_info->rowbytes = row_width;
  198397. }
  198398. else /* if (row_info->bit_depth == 16) */
  198399. {
  198400. if (flags & PNG_FLAG_FILLER_AFTER)
  198401. {
  198402. /* This converts from GGXX or GGAA to GG */
  198403. sp += 4; dp += 2;
  198404. for (i = 1; i < row_width; i++)
  198405. {
  198406. *dp++ = *sp++;
  198407. *dp++ = *sp++;
  198408. sp += 2;
  198409. }
  198410. }
  198411. else
  198412. {
  198413. /* This converts from XXGG or AAGG to GG */
  198414. for (i = 0; i < row_width; i++)
  198415. {
  198416. sp += 2;
  198417. *dp++ = *sp++;
  198418. *dp++ = *sp++;
  198419. }
  198420. }
  198421. row_info->pixel_depth = 16;
  198422. row_info->rowbytes = row_width * 2;
  198423. }
  198424. row_info->channels = 1;
  198425. }
  198426. if (flags & PNG_FLAG_STRIP_ALPHA)
  198427. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198428. }
  198429. }
  198430. #endif
  198431. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198432. /* swaps red and blue bytes within a pixel */
  198433. void /* PRIVATE */
  198434. png_do_bgr(png_row_infop row_info, png_bytep row)
  198435. {
  198436. png_debug(1, "in png_do_bgr\n");
  198437. if (
  198438. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198439. row != NULL && row_info != NULL &&
  198440. #endif
  198441. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198442. {
  198443. png_uint_32 row_width = row_info->width;
  198444. if (row_info->bit_depth == 8)
  198445. {
  198446. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198447. {
  198448. png_bytep rp;
  198449. png_uint_32 i;
  198450. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198451. {
  198452. png_byte save = *rp;
  198453. *rp = *(rp + 2);
  198454. *(rp + 2) = save;
  198455. }
  198456. }
  198457. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198458. {
  198459. png_bytep rp;
  198460. png_uint_32 i;
  198461. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198462. {
  198463. png_byte save = *rp;
  198464. *rp = *(rp + 2);
  198465. *(rp + 2) = save;
  198466. }
  198467. }
  198468. }
  198469. else if (row_info->bit_depth == 16)
  198470. {
  198471. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198472. {
  198473. png_bytep rp;
  198474. png_uint_32 i;
  198475. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198476. {
  198477. png_byte save = *rp;
  198478. *rp = *(rp + 4);
  198479. *(rp + 4) = save;
  198480. save = *(rp + 1);
  198481. *(rp + 1) = *(rp + 5);
  198482. *(rp + 5) = save;
  198483. }
  198484. }
  198485. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198486. {
  198487. png_bytep rp;
  198488. png_uint_32 i;
  198489. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198490. {
  198491. png_byte save = *rp;
  198492. *rp = *(rp + 4);
  198493. *(rp + 4) = save;
  198494. save = *(rp + 1);
  198495. *(rp + 1) = *(rp + 5);
  198496. *(rp + 5) = save;
  198497. }
  198498. }
  198499. }
  198500. }
  198501. }
  198502. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198503. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198504. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198505. defined(PNG_LEGACY_SUPPORTED)
  198506. void PNGAPI
  198507. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198508. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198509. {
  198510. png_debug(1, "in png_set_user_transform_info\n");
  198511. if(png_ptr == NULL) return;
  198512. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198513. png_ptr->user_transform_ptr = user_transform_ptr;
  198514. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198515. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198516. #else
  198517. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198518. png_warning(png_ptr,
  198519. "This version of libpng does not support user transform info");
  198520. #endif
  198521. }
  198522. #endif
  198523. /* This function returns a pointer to the user_transform_ptr associated with
  198524. * the user transform functions. The application should free any memory
  198525. * associated with this pointer before png_write_destroy and png_read_destroy
  198526. * are called.
  198527. */
  198528. png_voidp PNGAPI
  198529. png_get_user_transform_ptr(png_structp png_ptr)
  198530. {
  198531. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198532. if (png_ptr == NULL) return (NULL);
  198533. return ((png_voidp)png_ptr->user_transform_ptr);
  198534. #else
  198535. return (NULL);
  198536. #endif
  198537. }
  198538. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198539. /*** End of inlined file: pngtrans.c ***/
  198540. /*** Start of inlined file: pngwio.c ***/
  198541. /* pngwio.c - functions for data output
  198542. *
  198543. * Last changed in libpng 1.2.13 November 13, 2006
  198544. * For conditions of distribution and use, see copyright notice in png.h
  198545. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198546. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198547. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198548. *
  198549. * This file provides a location for all output. Users who need
  198550. * special handling are expected to write functions that have the same
  198551. * arguments as these and perform similar functions, but that possibly
  198552. * use different output methods. Note that you shouldn't change these
  198553. * functions, but rather write replacement functions and then change
  198554. * them at run time with png_set_write_fn(...).
  198555. */
  198556. #define PNG_INTERNAL
  198557. #ifdef PNG_WRITE_SUPPORTED
  198558. /* Write the data to whatever output you are using. The default routine
  198559. writes to a file pointer. Note that this routine sometimes gets called
  198560. with very small lengths, so you should implement some kind of simple
  198561. buffering if you are using unbuffered writes. This should never be asked
  198562. to write more than 64K on a 16 bit machine. */
  198563. void /* PRIVATE */
  198564. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198565. {
  198566. if (png_ptr->write_data_fn != NULL )
  198567. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198568. else
  198569. png_error(png_ptr, "Call to NULL write function");
  198570. }
  198571. #if !defined(PNG_NO_STDIO)
  198572. /* This is the function that does the actual writing of data. If you are
  198573. not writing to a standard C stream, you should create a replacement
  198574. write_data function and use it at run time with png_set_write_fn(), rather
  198575. than changing the library. */
  198576. #ifndef USE_FAR_KEYWORD
  198577. void PNGAPI
  198578. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198579. {
  198580. png_uint_32 check;
  198581. if(png_ptr == NULL) return;
  198582. #if defined(_WIN32_WCE)
  198583. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198584. check = 0;
  198585. #else
  198586. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198587. #endif
  198588. if (check != length)
  198589. png_error(png_ptr, "Write Error");
  198590. }
  198591. #else
  198592. /* this is the model-independent version. Since the standard I/O library
  198593. can't handle far buffers in the medium and small models, we have to copy
  198594. the data.
  198595. */
  198596. #define NEAR_BUF_SIZE 1024
  198597. #define MIN(a,b) (a <= b ? a : b)
  198598. void PNGAPI
  198599. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198600. {
  198601. png_uint_32 check;
  198602. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198603. png_FILE_p io_ptr;
  198604. if(png_ptr == NULL) return;
  198605. /* Check if data really is near. If so, use usual code. */
  198606. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198607. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198608. if ((png_bytep)near_data == data)
  198609. {
  198610. #if defined(_WIN32_WCE)
  198611. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198612. check = 0;
  198613. #else
  198614. check = fwrite(near_data, 1, length, io_ptr);
  198615. #endif
  198616. }
  198617. else
  198618. {
  198619. png_byte buf[NEAR_BUF_SIZE];
  198620. png_size_t written, remaining, err;
  198621. check = 0;
  198622. remaining = length;
  198623. do
  198624. {
  198625. written = MIN(NEAR_BUF_SIZE, remaining);
  198626. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198627. #if defined(_WIN32_WCE)
  198628. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198629. err = 0;
  198630. #else
  198631. err = fwrite(buf, 1, written, io_ptr);
  198632. #endif
  198633. if (err != written)
  198634. break;
  198635. else
  198636. check += err;
  198637. data += written;
  198638. remaining -= written;
  198639. }
  198640. while (remaining != 0);
  198641. }
  198642. if (check != length)
  198643. png_error(png_ptr, "Write Error");
  198644. }
  198645. #endif
  198646. #endif
  198647. /* This function is called to output any data pending writing (normally
  198648. to disk). After png_flush is called, there should be no data pending
  198649. writing in any buffers. */
  198650. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198651. void /* PRIVATE */
  198652. png_flush(png_structp png_ptr)
  198653. {
  198654. if (png_ptr->output_flush_fn != NULL)
  198655. (*(png_ptr->output_flush_fn))(png_ptr);
  198656. }
  198657. #if !defined(PNG_NO_STDIO)
  198658. void PNGAPI
  198659. png_default_flush(png_structp png_ptr)
  198660. {
  198661. #if !defined(_WIN32_WCE)
  198662. png_FILE_p io_ptr;
  198663. #endif
  198664. if(png_ptr == NULL) return;
  198665. #if !defined(_WIN32_WCE)
  198666. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198667. if (io_ptr != NULL)
  198668. fflush(io_ptr);
  198669. #endif
  198670. }
  198671. #endif
  198672. #endif
  198673. /* This function allows the application to supply new output functions for
  198674. libpng if standard C streams aren't being used.
  198675. This function takes as its arguments:
  198676. png_ptr - pointer to a png output data structure
  198677. io_ptr - pointer to user supplied structure containing info about
  198678. the output functions. May be NULL.
  198679. write_data_fn - pointer to a new output function that takes as its
  198680. arguments a pointer to a png_struct, a pointer to
  198681. data to be written, and a 32-bit unsigned int that is
  198682. the number of bytes to be written. The new write
  198683. function should call png_error(png_ptr, "Error msg")
  198684. to exit and output any fatal error messages.
  198685. flush_data_fn - pointer to a new flush function that takes as its
  198686. arguments a pointer to a png_struct. After a call to
  198687. the flush function, there should be no data in any buffers
  198688. or pending transmission. If the output method doesn't do
  198689. any buffering of ouput, a function prototype must still be
  198690. supplied although it doesn't have to do anything. If
  198691. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198692. time, output_flush_fn will be ignored, although it must be
  198693. supplied for compatibility. */
  198694. void PNGAPI
  198695. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198696. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198697. {
  198698. if(png_ptr == NULL) return;
  198699. png_ptr->io_ptr = io_ptr;
  198700. #if !defined(PNG_NO_STDIO)
  198701. if (write_data_fn != NULL)
  198702. png_ptr->write_data_fn = write_data_fn;
  198703. else
  198704. png_ptr->write_data_fn = png_default_write_data;
  198705. #else
  198706. png_ptr->write_data_fn = write_data_fn;
  198707. #endif
  198708. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198709. #if !defined(PNG_NO_STDIO)
  198710. if (output_flush_fn != NULL)
  198711. png_ptr->output_flush_fn = output_flush_fn;
  198712. else
  198713. png_ptr->output_flush_fn = png_default_flush;
  198714. #else
  198715. png_ptr->output_flush_fn = output_flush_fn;
  198716. #endif
  198717. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198718. /* It is an error to read while writing a png file */
  198719. if (png_ptr->read_data_fn != NULL)
  198720. {
  198721. png_ptr->read_data_fn = NULL;
  198722. png_warning(png_ptr,
  198723. "Attempted to set both read_data_fn and write_data_fn in");
  198724. png_warning(png_ptr,
  198725. "the same structure. Resetting read_data_fn to NULL.");
  198726. }
  198727. }
  198728. #if defined(USE_FAR_KEYWORD)
  198729. #if defined(_MSC_VER)
  198730. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198731. {
  198732. void *near_ptr;
  198733. void FAR *far_ptr;
  198734. FP_OFF(near_ptr) = FP_OFF(ptr);
  198735. far_ptr = (void FAR *)near_ptr;
  198736. if(check != 0)
  198737. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198738. png_error(png_ptr,"segment lost in conversion");
  198739. return(near_ptr);
  198740. }
  198741. # else
  198742. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198743. {
  198744. void *near_ptr;
  198745. void FAR *far_ptr;
  198746. near_ptr = (void FAR *)ptr;
  198747. far_ptr = (void FAR *)near_ptr;
  198748. if(check != 0)
  198749. if(far_ptr != ptr)
  198750. png_error(png_ptr,"segment lost in conversion");
  198751. return(near_ptr);
  198752. }
  198753. # endif
  198754. # endif
  198755. #endif /* PNG_WRITE_SUPPORTED */
  198756. /*** End of inlined file: pngwio.c ***/
  198757. /*** Start of inlined file: pngwrite.c ***/
  198758. /* pngwrite.c - general routines to write a PNG file
  198759. *
  198760. * Last changed in libpng 1.2.15 January 5, 2007
  198761. * For conditions of distribution and use, see copyright notice in png.h
  198762. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198763. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198764. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198765. */
  198766. /* get internal access to png.h */
  198767. #define PNG_INTERNAL
  198768. #ifdef PNG_WRITE_SUPPORTED
  198769. /* Writes all the PNG information. This is the suggested way to use the
  198770. * library. If you have a new chunk to add, make a function to write it,
  198771. * and put it in the correct location here. If you want the chunk written
  198772. * after the image data, put it in png_write_end(). I strongly encourage
  198773. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198774. * the chunk, as that will keep the code from breaking if you want to just
  198775. * write a plain PNG file. If you have long comments, I suggest writing
  198776. * them in png_write_end(), and compressing them.
  198777. */
  198778. void PNGAPI
  198779. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198780. {
  198781. png_debug(1, "in png_write_info_before_PLTE\n");
  198782. if (png_ptr == NULL || info_ptr == NULL)
  198783. return;
  198784. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198785. {
  198786. png_write_sig(png_ptr); /* write PNG signature */
  198787. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198788. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198789. {
  198790. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198791. png_ptr->mng_features_permitted=0;
  198792. }
  198793. #endif
  198794. /* write IHDR information. */
  198795. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198796. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198797. info_ptr->filter_type,
  198798. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198799. info_ptr->interlace_type);
  198800. #else
  198801. 0);
  198802. #endif
  198803. /* the rest of these check to see if the valid field has the appropriate
  198804. flag set, and if it does, writes the chunk. */
  198805. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198806. if (info_ptr->valid & PNG_INFO_gAMA)
  198807. {
  198808. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198809. png_write_gAMA(png_ptr, info_ptr->gamma);
  198810. #else
  198811. #ifdef PNG_FIXED_POINT_SUPPORTED
  198812. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198813. # endif
  198814. #endif
  198815. }
  198816. #endif
  198817. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198818. if (info_ptr->valid & PNG_INFO_sRGB)
  198819. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198820. #endif
  198821. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198822. if (info_ptr->valid & PNG_INFO_iCCP)
  198823. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198824. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198825. #endif
  198826. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198827. if (info_ptr->valid & PNG_INFO_sBIT)
  198828. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198829. #endif
  198830. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198831. if (info_ptr->valid & PNG_INFO_cHRM)
  198832. {
  198833. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198834. png_write_cHRM(png_ptr,
  198835. info_ptr->x_white, info_ptr->y_white,
  198836. info_ptr->x_red, info_ptr->y_red,
  198837. info_ptr->x_green, info_ptr->y_green,
  198838. info_ptr->x_blue, info_ptr->y_blue);
  198839. #else
  198840. # ifdef PNG_FIXED_POINT_SUPPORTED
  198841. png_write_cHRM_fixed(png_ptr,
  198842. info_ptr->int_x_white, info_ptr->int_y_white,
  198843. info_ptr->int_x_red, info_ptr->int_y_red,
  198844. info_ptr->int_x_green, info_ptr->int_y_green,
  198845. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198846. # endif
  198847. #endif
  198848. }
  198849. #endif
  198850. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198851. if (info_ptr->unknown_chunks_num)
  198852. {
  198853. png_unknown_chunk *up;
  198854. png_debug(5, "writing extra chunks\n");
  198855. for (up = info_ptr->unknown_chunks;
  198856. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198857. up++)
  198858. {
  198859. int keep=png_handle_as_unknown(png_ptr, up->name);
  198860. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198861. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198862. !(up->location & PNG_HAVE_IDAT) &&
  198863. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198864. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198865. {
  198866. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198867. }
  198868. }
  198869. }
  198870. #endif
  198871. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198872. }
  198873. }
  198874. void PNGAPI
  198875. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198876. {
  198877. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198878. int i;
  198879. #endif
  198880. png_debug(1, "in png_write_info\n");
  198881. if (png_ptr == NULL || info_ptr == NULL)
  198882. return;
  198883. png_write_info_before_PLTE(png_ptr, info_ptr);
  198884. if (info_ptr->valid & PNG_INFO_PLTE)
  198885. png_write_PLTE(png_ptr, info_ptr->palette,
  198886. (png_uint_32)info_ptr->num_palette);
  198887. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198888. png_error(png_ptr, "Valid palette required for paletted images");
  198889. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198890. if (info_ptr->valid & PNG_INFO_tRNS)
  198891. {
  198892. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198893. /* invert the alpha channel (in tRNS) */
  198894. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198895. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198896. {
  198897. int j;
  198898. for (j=0; j<(int)info_ptr->num_trans; j++)
  198899. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198900. }
  198901. #endif
  198902. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198903. info_ptr->num_trans, info_ptr->color_type);
  198904. }
  198905. #endif
  198906. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198907. if (info_ptr->valid & PNG_INFO_bKGD)
  198908. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198909. #endif
  198910. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198911. if (info_ptr->valid & PNG_INFO_hIST)
  198912. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198913. #endif
  198914. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198915. if (info_ptr->valid & PNG_INFO_oFFs)
  198916. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198917. info_ptr->offset_unit_type);
  198918. #endif
  198919. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198920. if (info_ptr->valid & PNG_INFO_pCAL)
  198921. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198922. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198923. info_ptr->pcal_units, info_ptr->pcal_params);
  198924. #endif
  198925. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198926. if (info_ptr->valid & PNG_INFO_sCAL)
  198927. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198928. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198929. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198930. #else
  198931. #ifdef PNG_FIXED_POINT_SUPPORTED
  198932. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198933. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198934. #else
  198935. png_warning(png_ptr,
  198936. "png_write_sCAL not supported; sCAL chunk not written.");
  198937. #endif
  198938. #endif
  198939. #endif
  198940. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198941. if (info_ptr->valid & PNG_INFO_pHYs)
  198942. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198943. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198944. #endif
  198945. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198946. if (info_ptr->valid & PNG_INFO_tIME)
  198947. {
  198948. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198949. png_ptr->mode |= PNG_WROTE_tIME;
  198950. }
  198951. #endif
  198952. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198953. if (info_ptr->valid & PNG_INFO_sPLT)
  198954. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198955. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198956. #endif
  198957. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198958. /* Check to see if we need to write text chunks */
  198959. for (i = 0; i < info_ptr->num_text; i++)
  198960. {
  198961. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198962. info_ptr->text[i].compression);
  198963. /* an internationalized chunk? */
  198964. if (info_ptr->text[i].compression > 0)
  198965. {
  198966. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198967. /* write international chunk */
  198968. png_write_iTXt(png_ptr,
  198969. info_ptr->text[i].compression,
  198970. info_ptr->text[i].key,
  198971. info_ptr->text[i].lang,
  198972. info_ptr->text[i].lang_key,
  198973. info_ptr->text[i].text);
  198974. #else
  198975. png_warning(png_ptr, "Unable to write international text");
  198976. #endif
  198977. /* Mark this chunk as written */
  198978. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198979. }
  198980. /* If we want a compressed text chunk */
  198981. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198982. {
  198983. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198984. /* write compressed chunk */
  198985. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198986. info_ptr->text[i].text, 0,
  198987. info_ptr->text[i].compression);
  198988. #else
  198989. png_warning(png_ptr, "Unable to write compressed text");
  198990. #endif
  198991. /* Mark this chunk as written */
  198992. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198993. }
  198994. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198995. {
  198996. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198997. /* write uncompressed chunk */
  198998. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198999. info_ptr->text[i].text,
  199000. 0);
  199001. #else
  199002. png_warning(png_ptr, "Unable to write uncompressed text");
  199003. #endif
  199004. /* Mark this chunk as written */
  199005. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199006. }
  199007. }
  199008. #endif
  199009. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199010. if (info_ptr->unknown_chunks_num)
  199011. {
  199012. png_unknown_chunk *up;
  199013. png_debug(5, "writing extra chunks\n");
  199014. for (up = info_ptr->unknown_chunks;
  199015. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199016. up++)
  199017. {
  199018. int keep=png_handle_as_unknown(png_ptr, up->name);
  199019. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199020. up->location && (up->location & PNG_HAVE_PLTE) &&
  199021. !(up->location & PNG_HAVE_IDAT) &&
  199022. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199023. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199024. {
  199025. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199026. }
  199027. }
  199028. }
  199029. #endif
  199030. }
  199031. /* Writes the end of the PNG file. If you don't want to write comments or
  199032. * time information, you can pass NULL for info. If you already wrote these
  199033. * in png_write_info(), do not write them again here. If you have long
  199034. * comments, I suggest writing them here, and compressing them.
  199035. */
  199036. void PNGAPI
  199037. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199038. {
  199039. png_debug(1, "in png_write_end\n");
  199040. if (png_ptr == NULL)
  199041. return;
  199042. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199043. png_error(png_ptr, "No IDATs written into file");
  199044. /* see if user wants us to write information chunks */
  199045. if (info_ptr != NULL)
  199046. {
  199047. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199048. int i; /* local index variable */
  199049. #endif
  199050. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199051. /* check to see if user has supplied a time chunk */
  199052. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199053. !(png_ptr->mode & PNG_WROTE_tIME))
  199054. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199055. #endif
  199056. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199057. /* loop through comment chunks */
  199058. for (i = 0; i < info_ptr->num_text; i++)
  199059. {
  199060. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199061. info_ptr->text[i].compression);
  199062. /* an internationalized chunk? */
  199063. if (info_ptr->text[i].compression > 0)
  199064. {
  199065. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199066. /* write international chunk */
  199067. png_write_iTXt(png_ptr,
  199068. info_ptr->text[i].compression,
  199069. info_ptr->text[i].key,
  199070. info_ptr->text[i].lang,
  199071. info_ptr->text[i].lang_key,
  199072. info_ptr->text[i].text);
  199073. #else
  199074. png_warning(png_ptr, "Unable to write international text");
  199075. #endif
  199076. /* Mark this chunk as written */
  199077. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199078. }
  199079. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199080. {
  199081. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199082. /* write compressed chunk */
  199083. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199084. info_ptr->text[i].text, 0,
  199085. info_ptr->text[i].compression);
  199086. #else
  199087. png_warning(png_ptr, "Unable to write compressed text");
  199088. #endif
  199089. /* Mark this chunk as written */
  199090. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199091. }
  199092. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199093. {
  199094. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199095. /* write uncompressed chunk */
  199096. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199097. info_ptr->text[i].text, 0);
  199098. #else
  199099. png_warning(png_ptr, "Unable to write uncompressed text");
  199100. #endif
  199101. /* Mark this chunk as written */
  199102. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199103. }
  199104. }
  199105. #endif
  199106. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199107. if (info_ptr->unknown_chunks_num)
  199108. {
  199109. png_unknown_chunk *up;
  199110. png_debug(5, "writing extra chunks\n");
  199111. for (up = info_ptr->unknown_chunks;
  199112. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199113. up++)
  199114. {
  199115. int keep=png_handle_as_unknown(png_ptr, up->name);
  199116. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199117. up->location && (up->location & PNG_AFTER_IDAT) &&
  199118. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199119. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199120. {
  199121. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199122. }
  199123. }
  199124. }
  199125. #endif
  199126. }
  199127. png_ptr->mode |= PNG_AFTER_IDAT;
  199128. /* write end of PNG file */
  199129. png_write_IEND(png_ptr);
  199130. }
  199131. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199132. #if !defined(_WIN32_WCE)
  199133. /* "time.h" functions are not supported on WindowsCE */
  199134. void PNGAPI
  199135. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199136. {
  199137. png_debug(1, "in png_convert_from_struct_tm\n");
  199138. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199139. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199140. ptime->day = (png_byte)ttime->tm_mday;
  199141. ptime->hour = (png_byte)ttime->tm_hour;
  199142. ptime->minute = (png_byte)ttime->tm_min;
  199143. ptime->second = (png_byte)ttime->tm_sec;
  199144. }
  199145. void PNGAPI
  199146. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199147. {
  199148. struct tm *tbuf;
  199149. png_debug(1, "in png_convert_from_time_t\n");
  199150. tbuf = gmtime(&ttime);
  199151. png_convert_from_struct_tm(ptime, tbuf);
  199152. }
  199153. #endif
  199154. #endif
  199155. /* Initialize png_ptr structure, and allocate any memory needed */
  199156. png_structp PNGAPI
  199157. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199158. png_error_ptr error_fn, png_error_ptr warn_fn)
  199159. {
  199160. #ifdef PNG_USER_MEM_SUPPORTED
  199161. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199162. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199163. }
  199164. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199165. png_structp PNGAPI
  199166. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199167. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199168. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199169. {
  199170. #endif /* PNG_USER_MEM_SUPPORTED */
  199171. png_structp png_ptr;
  199172. #ifdef PNG_SETJMP_SUPPORTED
  199173. #ifdef USE_FAR_KEYWORD
  199174. jmp_buf jmpbuf;
  199175. #endif
  199176. #endif
  199177. int i;
  199178. png_debug(1, "in png_create_write_struct\n");
  199179. #ifdef PNG_USER_MEM_SUPPORTED
  199180. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199181. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199182. #else
  199183. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199184. #endif /* PNG_USER_MEM_SUPPORTED */
  199185. if (png_ptr == NULL)
  199186. return (NULL);
  199187. /* added at libpng-1.2.6 */
  199188. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199189. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199190. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199191. #endif
  199192. #ifdef PNG_SETJMP_SUPPORTED
  199193. #ifdef USE_FAR_KEYWORD
  199194. if (setjmp(jmpbuf))
  199195. #else
  199196. if (setjmp(png_ptr->jmpbuf))
  199197. #endif
  199198. {
  199199. png_free(png_ptr, png_ptr->zbuf);
  199200. png_ptr->zbuf=NULL;
  199201. png_destroy_struct(png_ptr);
  199202. return (NULL);
  199203. }
  199204. #ifdef USE_FAR_KEYWORD
  199205. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199206. #endif
  199207. #endif
  199208. #ifdef PNG_USER_MEM_SUPPORTED
  199209. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199210. #endif /* PNG_USER_MEM_SUPPORTED */
  199211. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199212. i=0;
  199213. do
  199214. {
  199215. if(user_png_ver[i] != png_libpng_ver[i])
  199216. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199217. } while (png_libpng_ver[i++]);
  199218. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199219. {
  199220. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199221. * we must recompile any applications that use any older library version.
  199222. * For versions after libpng 1.0, we will be compatible, so we need
  199223. * only check the first digit.
  199224. */
  199225. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199226. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199227. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199228. {
  199229. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199230. char msg[80];
  199231. if (user_png_ver)
  199232. {
  199233. png_snprintf(msg, 80,
  199234. "Application was compiled with png.h from libpng-%.20s",
  199235. user_png_ver);
  199236. png_warning(png_ptr, msg);
  199237. }
  199238. png_snprintf(msg, 80,
  199239. "Application is running with png.c from libpng-%.20s",
  199240. png_libpng_ver);
  199241. png_warning(png_ptr, msg);
  199242. #endif
  199243. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199244. png_ptr->flags=0;
  199245. #endif
  199246. png_error(png_ptr,
  199247. "Incompatible libpng version in application and library");
  199248. }
  199249. }
  199250. /* initialize zbuf - compression buffer */
  199251. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199252. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199253. (png_uint_32)png_ptr->zbuf_size);
  199254. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199255. png_flush_ptr_NULL);
  199256. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199257. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199258. 1, png_doublep_NULL, png_doublep_NULL);
  199259. #endif
  199260. #ifdef PNG_SETJMP_SUPPORTED
  199261. /* Applications that neglect to set up their own setjmp() and then encounter
  199262. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199263. abort instead of returning. */
  199264. #ifdef USE_FAR_KEYWORD
  199265. if (setjmp(jmpbuf))
  199266. PNG_ABORT();
  199267. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199268. #else
  199269. if (setjmp(png_ptr->jmpbuf))
  199270. PNG_ABORT();
  199271. #endif
  199272. #endif
  199273. return (png_ptr);
  199274. }
  199275. /* Initialize png_ptr structure, and allocate any memory needed */
  199276. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199277. /* Deprecated. */
  199278. #undef png_write_init
  199279. void PNGAPI
  199280. png_write_init(png_structp png_ptr)
  199281. {
  199282. /* We only come here via pre-1.0.7-compiled applications */
  199283. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199284. }
  199285. void PNGAPI
  199286. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199287. png_size_t png_struct_size, png_size_t png_info_size)
  199288. {
  199289. /* We only come here via pre-1.0.12-compiled applications */
  199290. if(png_ptr == NULL) return;
  199291. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199292. if(png_sizeof(png_struct) > png_struct_size ||
  199293. png_sizeof(png_info) > png_info_size)
  199294. {
  199295. char msg[80];
  199296. png_ptr->warning_fn=NULL;
  199297. if (user_png_ver)
  199298. {
  199299. png_snprintf(msg, 80,
  199300. "Application was compiled with png.h from libpng-%.20s",
  199301. user_png_ver);
  199302. png_warning(png_ptr, msg);
  199303. }
  199304. png_snprintf(msg, 80,
  199305. "Application is running with png.c from libpng-%.20s",
  199306. png_libpng_ver);
  199307. png_warning(png_ptr, msg);
  199308. }
  199309. #endif
  199310. if(png_sizeof(png_struct) > png_struct_size)
  199311. {
  199312. png_ptr->error_fn=NULL;
  199313. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199314. png_ptr->flags=0;
  199315. #endif
  199316. png_error(png_ptr,
  199317. "The png struct allocated by the application for writing is too small.");
  199318. }
  199319. if(png_sizeof(png_info) > png_info_size)
  199320. {
  199321. png_ptr->error_fn=NULL;
  199322. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199323. png_ptr->flags=0;
  199324. #endif
  199325. png_error(png_ptr,
  199326. "The info struct allocated by the application for writing is too small.");
  199327. }
  199328. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199329. }
  199330. #endif /* PNG_1_0_X || PNG_1_2_X */
  199331. void PNGAPI
  199332. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199333. png_size_t png_struct_size)
  199334. {
  199335. png_structp png_ptr=*ptr_ptr;
  199336. #ifdef PNG_SETJMP_SUPPORTED
  199337. jmp_buf tmp_jmp; /* to save current jump buffer */
  199338. #endif
  199339. int i = 0;
  199340. if (png_ptr == NULL)
  199341. return;
  199342. do
  199343. {
  199344. if (user_png_ver[i] != png_libpng_ver[i])
  199345. {
  199346. #ifdef PNG_LEGACY_SUPPORTED
  199347. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199348. #else
  199349. png_ptr->warning_fn=NULL;
  199350. png_warning(png_ptr,
  199351. "Application uses deprecated png_write_init() and should be recompiled.");
  199352. break;
  199353. #endif
  199354. }
  199355. } while (png_libpng_ver[i++]);
  199356. png_debug(1, "in png_write_init_3\n");
  199357. #ifdef PNG_SETJMP_SUPPORTED
  199358. /* save jump buffer and error functions */
  199359. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199360. #endif
  199361. if (png_sizeof(png_struct) > png_struct_size)
  199362. {
  199363. png_destroy_struct(png_ptr);
  199364. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199365. *ptr_ptr = png_ptr;
  199366. }
  199367. /* reset all variables to 0 */
  199368. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199369. /* added at libpng-1.2.6 */
  199370. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199371. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199372. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199373. #endif
  199374. #ifdef PNG_SETJMP_SUPPORTED
  199375. /* restore jump buffer */
  199376. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199377. #endif
  199378. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199379. png_flush_ptr_NULL);
  199380. /* initialize zbuf - compression buffer */
  199381. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199382. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199383. (png_uint_32)png_ptr->zbuf_size);
  199384. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199385. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199386. 1, png_doublep_NULL, png_doublep_NULL);
  199387. #endif
  199388. }
  199389. /* Write a few rows of image data. If the image is interlaced,
  199390. * either you will have to write the 7 sub images, or, if you
  199391. * have called png_set_interlace_handling(), you will have to
  199392. * "write" the image seven times.
  199393. */
  199394. void PNGAPI
  199395. png_write_rows(png_structp png_ptr, png_bytepp row,
  199396. png_uint_32 num_rows)
  199397. {
  199398. png_uint_32 i; /* row counter */
  199399. png_bytepp rp; /* row pointer */
  199400. png_debug(1, "in png_write_rows\n");
  199401. if (png_ptr == NULL)
  199402. return;
  199403. /* loop through the rows */
  199404. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199405. {
  199406. png_write_row(png_ptr, *rp);
  199407. }
  199408. }
  199409. /* Write the image. You only need to call this function once, even
  199410. * if you are writing an interlaced image.
  199411. */
  199412. void PNGAPI
  199413. png_write_image(png_structp png_ptr, png_bytepp image)
  199414. {
  199415. png_uint_32 i; /* row index */
  199416. int pass, num_pass; /* pass variables */
  199417. png_bytepp rp; /* points to current row */
  199418. if (png_ptr == NULL)
  199419. return;
  199420. png_debug(1, "in png_write_image\n");
  199421. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199422. /* intialize interlace handling. If image is not interlaced,
  199423. this will set pass to 1 */
  199424. num_pass = png_set_interlace_handling(png_ptr);
  199425. #else
  199426. num_pass = 1;
  199427. #endif
  199428. /* loop through passes */
  199429. for (pass = 0; pass < num_pass; pass++)
  199430. {
  199431. /* loop through image */
  199432. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199433. {
  199434. png_write_row(png_ptr, *rp);
  199435. }
  199436. }
  199437. }
  199438. /* called by user to write a row of image data */
  199439. void PNGAPI
  199440. png_write_row(png_structp png_ptr, png_bytep row)
  199441. {
  199442. if (png_ptr == NULL)
  199443. return;
  199444. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199445. png_ptr->row_number, png_ptr->pass);
  199446. /* initialize transformations and other stuff if first time */
  199447. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199448. {
  199449. /* make sure we wrote the header info */
  199450. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199451. png_error(png_ptr,
  199452. "png_write_info was never called before png_write_row.");
  199453. /* check for transforms that have been set but were defined out */
  199454. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199455. if (png_ptr->transformations & PNG_INVERT_MONO)
  199456. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199457. #endif
  199458. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199459. if (png_ptr->transformations & PNG_FILLER)
  199460. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199461. #endif
  199462. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199463. if (png_ptr->transformations & PNG_PACKSWAP)
  199464. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199465. #endif
  199466. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199467. if (png_ptr->transformations & PNG_PACK)
  199468. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199469. #endif
  199470. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199471. if (png_ptr->transformations & PNG_SHIFT)
  199472. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199473. #endif
  199474. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199475. if (png_ptr->transformations & PNG_BGR)
  199476. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199477. #endif
  199478. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199479. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199480. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199481. #endif
  199482. png_write_start_row(png_ptr);
  199483. }
  199484. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199485. /* if interlaced and not interested in row, return */
  199486. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199487. {
  199488. switch (png_ptr->pass)
  199489. {
  199490. case 0:
  199491. if (png_ptr->row_number & 0x07)
  199492. {
  199493. png_write_finish_row(png_ptr);
  199494. return;
  199495. }
  199496. break;
  199497. case 1:
  199498. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199499. {
  199500. png_write_finish_row(png_ptr);
  199501. return;
  199502. }
  199503. break;
  199504. case 2:
  199505. if ((png_ptr->row_number & 0x07) != 4)
  199506. {
  199507. png_write_finish_row(png_ptr);
  199508. return;
  199509. }
  199510. break;
  199511. case 3:
  199512. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199513. {
  199514. png_write_finish_row(png_ptr);
  199515. return;
  199516. }
  199517. break;
  199518. case 4:
  199519. if ((png_ptr->row_number & 0x03) != 2)
  199520. {
  199521. png_write_finish_row(png_ptr);
  199522. return;
  199523. }
  199524. break;
  199525. case 5:
  199526. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199527. {
  199528. png_write_finish_row(png_ptr);
  199529. return;
  199530. }
  199531. break;
  199532. case 6:
  199533. if (!(png_ptr->row_number & 0x01))
  199534. {
  199535. png_write_finish_row(png_ptr);
  199536. return;
  199537. }
  199538. break;
  199539. }
  199540. }
  199541. #endif
  199542. /* set up row info for transformations */
  199543. png_ptr->row_info.color_type = png_ptr->color_type;
  199544. png_ptr->row_info.width = png_ptr->usr_width;
  199545. png_ptr->row_info.channels = png_ptr->usr_channels;
  199546. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199547. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199548. png_ptr->row_info.channels);
  199549. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199550. png_ptr->row_info.width);
  199551. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199552. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199553. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199554. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199555. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199556. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199557. /* Copy user's row into buffer, leaving room for filter byte. */
  199558. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199559. png_ptr->row_info.rowbytes);
  199560. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199561. /* handle interlacing */
  199562. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199563. (png_ptr->transformations & PNG_INTERLACE))
  199564. {
  199565. png_do_write_interlace(&(png_ptr->row_info),
  199566. png_ptr->row_buf + 1, png_ptr->pass);
  199567. /* this should always get caught above, but still ... */
  199568. if (!(png_ptr->row_info.width))
  199569. {
  199570. png_write_finish_row(png_ptr);
  199571. return;
  199572. }
  199573. }
  199574. #endif
  199575. /* handle other transformations */
  199576. if (png_ptr->transformations)
  199577. png_do_write_transformations(png_ptr);
  199578. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199579. /* Write filter_method 64 (intrapixel differencing) only if
  199580. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199581. * 2. Libpng did not write a PNG signature (this filter_method is only
  199582. * used in PNG datastreams that are embedded in MNG datastreams) and
  199583. * 3. The application called png_permit_mng_features with a mask that
  199584. * included PNG_FLAG_MNG_FILTER_64 and
  199585. * 4. The filter_method is 64 and
  199586. * 5. The color_type is RGB or RGBA
  199587. */
  199588. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199589. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199590. {
  199591. /* Intrapixel differencing */
  199592. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199593. }
  199594. #endif
  199595. /* Find a filter if necessary, filter the row and write it out. */
  199596. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199597. if (png_ptr->write_row_fn != NULL)
  199598. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199599. }
  199600. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199601. /* Set the automatic flush interval or 0 to turn flushing off */
  199602. void PNGAPI
  199603. png_set_flush(png_structp png_ptr, int nrows)
  199604. {
  199605. png_debug(1, "in png_set_flush\n");
  199606. if (png_ptr == NULL)
  199607. return;
  199608. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199609. }
  199610. /* flush the current output buffers now */
  199611. void PNGAPI
  199612. png_write_flush(png_structp png_ptr)
  199613. {
  199614. int wrote_IDAT;
  199615. png_debug(1, "in png_write_flush\n");
  199616. if (png_ptr == NULL)
  199617. return;
  199618. /* We have already written out all of the data */
  199619. if (png_ptr->row_number >= png_ptr->num_rows)
  199620. return;
  199621. do
  199622. {
  199623. int ret;
  199624. /* compress the data */
  199625. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199626. wrote_IDAT = 0;
  199627. /* check for compression errors */
  199628. if (ret != Z_OK)
  199629. {
  199630. if (png_ptr->zstream.msg != NULL)
  199631. png_error(png_ptr, png_ptr->zstream.msg);
  199632. else
  199633. png_error(png_ptr, "zlib error");
  199634. }
  199635. if (!(png_ptr->zstream.avail_out))
  199636. {
  199637. /* write the IDAT and reset the zlib output buffer */
  199638. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199639. png_ptr->zbuf_size);
  199640. png_ptr->zstream.next_out = png_ptr->zbuf;
  199641. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199642. wrote_IDAT = 1;
  199643. }
  199644. } while(wrote_IDAT == 1);
  199645. /* If there is any data left to be output, write it into a new IDAT */
  199646. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199647. {
  199648. /* write the IDAT and reset the zlib output buffer */
  199649. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199650. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199651. png_ptr->zstream.next_out = png_ptr->zbuf;
  199652. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199653. }
  199654. png_ptr->flush_rows = 0;
  199655. png_flush(png_ptr);
  199656. }
  199657. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199658. /* free all memory used by the write */
  199659. void PNGAPI
  199660. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199661. {
  199662. png_structp png_ptr = NULL;
  199663. png_infop info_ptr = NULL;
  199664. #ifdef PNG_USER_MEM_SUPPORTED
  199665. png_free_ptr free_fn = NULL;
  199666. png_voidp mem_ptr = NULL;
  199667. #endif
  199668. png_debug(1, "in png_destroy_write_struct\n");
  199669. if (png_ptr_ptr != NULL)
  199670. {
  199671. png_ptr = *png_ptr_ptr;
  199672. #ifdef PNG_USER_MEM_SUPPORTED
  199673. free_fn = png_ptr->free_fn;
  199674. mem_ptr = png_ptr->mem_ptr;
  199675. #endif
  199676. }
  199677. if (info_ptr_ptr != NULL)
  199678. info_ptr = *info_ptr_ptr;
  199679. if (info_ptr != NULL)
  199680. {
  199681. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199682. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199683. if (png_ptr->num_chunk_list)
  199684. {
  199685. png_free(png_ptr, png_ptr->chunk_list);
  199686. png_ptr->chunk_list=NULL;
  199687. png_ptr->num_chunk_list=0;
  199688. }
  199689. #endif
  199690. #ifdef PNG_USER_MEM_SUPPORTED
  199691. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199692. (png_voidp)mem_ptr);
  199693. #else
  199694. png_destroy_struct((png_voidp)info_ptr);
  199695. #endif
  199696. *info_ptr_ptr = NULL;
  199697. }
  199698. if (png_ptr != NULL)
  199699. {
  199700. png_write_destroy(png_ptr);
  199701. #ifdef PNG_USER_MEM_SUPPORTED
  199702. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199703. (png_voidp)mem_ptr);
  199704. #else
  199705. png_destroy_struct((png_voidp)png_ptr);
  199706. #endif
  199707. *png_ptr_ptr = NULL;
  199708. }
  199709. }
  199710. /* Free any memory used in png_ptr struct (old method) */
  199711. void /* PRIVATE */
  199712. png_write_destroy(png_structp png_ptr)
  199713. {
  199714. #ifdef PNG_SETJMP_SUPPORTED
  199715. jmp_buf tmp_jmp; /* save jump buffer */
  199716. #endif
  199717. png_error_ptr error_fn;
  199718. png_error_ptr warning_fn;
  199719. png_voidp error_ptr;
  199720. #ifdef PNG_USER_MEM_SUPPORTED
  199721. png_free_ptr free_fn;
  199722. #endif
  199723. png_debug(1, "in png_write_destroy\n");
  199724. /* free any memory zlib uses */
  199725. deflateEnd(&png_ptr->zstream);
  199726. /* free our memory. png_free checks NULL for us. */
  199727. png_free(png_ptr, png_ptr->zbuf);
  199728. png_free(png_ptr, png_ptr->row_buf);
  199729. png_free(png_ptr, png_ptr->prev_row);
  199730. png_free(png_ptr, png_ptr->sub_row);
  199731. png_free(png_ptr, png_ptr->up_row);
  199732. png_free(png_ptr, png_ptr->avg_row);
  199733. png_free(png_ptr, png_ptr->paeth_row);
  199734. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199735. png_free(png_ptr, png_ptr->time_buffer);
  199736. #endif
  199737. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199738. png_free(png_ptr, png_ptr->prev_filters);
  199739. png_free(png_ptr, png_ptr->filter_weights);
  199740. png_free(png_ptr, png_ptr->inv_filter_weights);
  199741. png_free(png_ptr, png_ptr->filter_costs);
  199742. png_free(png_ptr, png_ptr->inv_filter_costs);
  199743. #endif
  199744. #ifdef PNG_SETJMP_SUPPORTED
  199745. /* reset structure */
  199746. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199747. #endif
  199748. error_fn = png_ptr->error_fn;
  199749. warning_fn = png_ptr->warning_fn;
  199750. error_ptr = png_ptr->error_ptr;
  199751. #ifdef PNG_USER_MEM_SUPPORTED
  199752. free_fn = png_ptr->free_fn;
  199753. #endif
  199754. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199755. png_ptr->error_fn = error_fn;
  199756. png_ptr->warning_fn = warning_fn;
  199757. png_ptr->error_ptr = error_ptr;
  199758. #ifdef PNG_USER_MEM_SUPPORTED
  199759. png_ptr->free_fn = free_fn;
  199760. #endif
  199761. #ifdef PNG_SETJMP_SUPPORTED
  199762. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199763. #endif
  199764. }
  199765. /* Allow the application to select one or more row filters to use. */
  199766. void PNGAPI
  199767. png_set_filter(png_structp png_ptr, int method, int filters)
  199768. {
  199769. png_debug(1, "in png_set_filter\n");
  199770. if (png_ptr == NULL)
  199771. return;
  199772. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199773. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199774. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199775. method = PNG_FILTER_TYPE_BASE;
  199776. #endif
  199777. if (method == PNG_FILTER_TYPE_BASE)
  199778. {
  199779. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199780. {
  199781. #ifndef PNG_NO_WRITE_FILTER
  199782. case 5:
  199783. case 6:
  199784. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199785. #endif /* PNG_NO_WRITE_FILTER */
  199786. case PNG_FILTER_VALUE_NONE:
  199787. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199788. #ifndef PNG_NO_WRITE_FILTER
  199789. case PNG_FILTER_VALUE_SUB:
  199790. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199791. case PNG_FILTER_VALUE_UP:
  199792. png_ptr->do_filter=PNG_FILTER_UP; break;
  199793. case PNG_FILTER_VALUE_AVG:
  199794. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199795. case PNG_FILTER_VALUE_PAETH:
  199796. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199797. default: png_ptr->do_filter = (png_byte)filters; break;
  199798. #else
  199799. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199800. #endif /* PNG_NO_WRITE_FILTER */
  199801. }
  199802. /* If we have allocated the row_buf, this means we have already started
  199803. * with the image and we should have allocated all of the filter buffers
  199804. * that have been selected. If prev_row isn't already allocated, then
  199805. * it is too late to start using the filters that need it, since we
  199806. * will be missing the data in the previous row. If an application
  199807. * wants to start and stop using particular filters during compression,
  199808. * it should start out with all of the filters, and then add and
  199809. * remove them after the start of compression.
  199810. */
  199811. if (png_ptr->row_buf != NULL)
  199812. {
  199813. #ifndef PNG_NO_WRITE_FILTER
  199814. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199815. {
  199816. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199817. (png_ptr->rowbytes + 1));
  199818. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199819. }
  199820. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199821. {
  199822. if (png_ptr->prev_row == NULL)
  199823. {
  199824. png_warning(png_ptr, "Can't add Up filter after starting");
  199825. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199826. }
  199827. else
  199828. {
  199829. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199830. (png_ptr->rowbytes + 1));
  199831. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199832. }
  199833. }
  199834. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199835. {
  199836. if (png_ptr->prev_row == NULL)
  199837. {
  199838. png_warning(png_ptr, "Can't add Average filter after starting");
  199839. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199840. }
  199841. else
  199842. {
  199843. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199844. (png_ptr->rowbytes + 1));
  199845. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199846. }
  199847. }
  199848. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199849. png_ptr->paeth_row == NULL)
  199850. {
  199851. if (png_ptr->prev_row == NULL)
  199852. {
  199853. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199854. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199855. }
  199856. else
  199857. {
  199858. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199859. (png_ptr->rowbytes + 1));
  199860. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199861. }
  199862. }
  199863. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199864. #endif /* PNG_NO_WRITE_FILTER */
  199865. png_ptr->do_filter = PNG_FILTER_NONE;
  199866. }
  199867. }
  199868. else
  199869. png_error(png_ptr, "Unknown custom filter method");
  199870. }
  199871. /* This allows us to influence the way in which libpng chooses the "best"
  199872. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199873. * differences metric is relatively fast and effective, there is some
  199874. * question as to whether it can be improved upon by trying to keep the
  199875. * filtered data going to zlib more consistent, hopefully resulting in
  199876. * better compression.
  199877. */
  199878. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199879. void PNGAPI
  199880. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199881. int num_weights, png_doublep filter_weights,
  199882. png_doublep filter_costs)
  199883. {
  199884. int i;
  199885. png_debug(1, "in png_set_filter_heuristics\n");
  199886. if (png_ptr == NULL)
  199887. return;
  199888. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199889. {
  199890. png_warning(png_ptr, "Unknown filter heuristic method");
  199891. return;
  199892. }
  199893. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199894. {
  199895. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199896. }
  199897. if (num_weights < 0 || filter_weights == NULL ||
  199898. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199899. {
  199900. num_weights = 0;
  199901. }
  199902. png_ptr->num_prev_filters = (png_byte)num_weights;
  199903. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199904. if (num_weights > 0)
  199905. {
  199906. if (png_ptr->prev_filters == NULL)
  199907. {
  199908. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199909. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199910. /* To make sure that the weighting starts out fairly */
  199911. for (i = 0; i < num_weights; i++)
  199912. {
  199913. png_ptr->prev_filters[i] = 255;
  199914. }
  199915. }
  199916. if (png_ptr->filter_weights == NULL)
  199917. {
  199918. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199919. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199920. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199921. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199922. for (i = 0; i < num_weights; i++)
  199923. {
  199924. png_ptr->inv_filter_weights[i] =
  199925. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199926. }
  199927. }
  199928. for (i = 0; i < num_weights; i++)
  199929. {
  199930. if (filter_weights[i] < 0.0)
  199931. {
  199932. png_ptr->inv_filter_weights[i] =
  199933. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199934. }
  199935. else
  199936. {
  199937. png_ptr->inv_filter_weights[i] =
  199938. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199939. png_ptr->filter_weights[i] =
  199940. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199941. }
  199942. }
  199943. }
  199944. /* If, in the future, there are other filter methods, this would
  199945. * need to be based on png_ptr->filter.
  199946. */
  199947. if (png_ptr->filter_costs == NULL)
  199948. {
  199949. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199950. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199951. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199952. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199953. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199954. {
  199955. png_ptr->inv_filter_costs[i] =
  199956. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199957. }
  199958. }
  199959. /* Here is where we set the relative costs of the different filters. We
  199960. * should take the desired compression level into account when setting
  199961. * the costs, so that Paeth, for instance, has a high relative cost at low
  199962. * compression levels, while it has a lower relative cost at higher
  199963. * compression settings. The filter types are in order of increasing
  199964. * relative cost, so it would be possible to do this with an algorithm.
  199965. */
  199966. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199967. {
  199968. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199969. {
  199970. png_ptr->inv_filter_costs[i] =
  199971. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199972. }
  199973. else if (filter_costs[i] >= 1.0)
  199974. {
  199975. png_ptr->inv_filter_costs[i] =
  199976. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199977. png_ptr->filter_costs[i] =
  199978. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199979. }
  199980. }
  199981. }
  199982. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199983. void PNGAPI
  199984. png_set_compression_level(png_structp png_ptr, int level)
  199985. {
  199986. png_debug(1, "in png_set_compression_level\n");
  199987. if (png_ptr == NULL)
  199988. return;
  199989. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199990. png_ptr->zlib_level = level;
  199991. }
  199992. void PNGAPI
  199993. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199994. {
  199995. png_debug(1, "in png_set_compression_mem_level\n");
  199996. if (png_ptr == NULL)
  199997. return;
  199998. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199999. png_ptr->zlib_mem_level = mem_level;
  200000. }
  200001. void PNGAPI
  200002. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200003. {
  200004. png_debug(1, "in png_set_compression_strategy\n");
  200005. if (png_ptr == NULL)
  200006. return;
  200007. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200008. png_ptr->zlib_strategy = strategy;
  200009. }
  200010. void PNGAPI
  200011. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200012. {
  200013. if (png_ptr == NULL)
  200014. return;
  200015. if (window_bits > 15)
  200016. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200017. else if (window_bits < 8)
  200018. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200019. #ifndef WBITS_8_OK
  200020. /* avoid libpng bug with 256-byte windows */
  200021. if (window_bits == 8)
  200022. {
  200023. png_warning(png_ptr, "Compression window is being reset to 512");
  200024. window_bits=9;
  200025. }
  200026. #endif
  200027. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200028. png_ptr->zlib_window_bits = window_bits;
  200029. }
  200030. void PNGAPI
  200031. png_set_compression_method(png_structp png_ptr, int method)
  200032. {
  200033. png_debug(1, "in png_set_compression_method\n");
  200034. if (png_ptr == NULL)
  200035. return;
  200036. if (method != 8)
  200037. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200038. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200039. png_ptr->zlib_method = method;
  200040. }
  200041. void PNGAPI
  200042. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200043. {
  200044. if (png_ptr == NULL)
  200045. return;
  200046. png_ptr->write_row_fn = write_row_fn;
  200047. }
  200048. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200049. void PNGAPI
  200050. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200051. write_user_transform_fn)
  200052. {
  200053. png_debug(1, "in png_set_write_user_transform_fn\n");
  200054. if (png_ptr == NULL)
  200055. return;
  200056. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200057. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200058. }
  200059. #endif
  200060. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200061. void PNGAPI
  200062. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200063. int transforms, voidp params)
  200064. {
  200065. if (png_ptr == NULL || info_ptr == NULL)
  200066. return;
  200067. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200068. /* invert the alpha channel from opacity to transparency */
  200069. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200070. png_set_invert_alpha(png_ptr);
  200071. #endif
  200072. /* Write the file header information. */
  200073. png_write_info(png_ptr, info_ptr);
  200074. /* ------ these transformations don't touch the info structure ------- */
  200075. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200076. /* invert monochrome pixels */
  200077. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200078. png_set_invert_mono(png_ptr);
  200079. #endif
  200080. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200081. /* Shift the pixels up to a legal bit depth and fill in
  200082. * as appropriate to correctly scale the image.
  200083. */
  200084. if ((transforms & PNG_TRANSFORM_SHIFT)
  200085. && (info_ptr->valid & PNG_INFO_sBIT))
  200086. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200087. #endif
  200088. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200089. /* pack pixels into bytes */
  200090. if (transforms & PNG_TRANSFORM_PACKING)
  200091. png_set_packing(png_ptr);
  200092. #endif
  200093. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200094. /* swap location of alpha bytes from ARGB to RGBA */
  200095. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200096. png_set_swap_alpha(png_ptr);
  200097. #endif
  200098. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200099. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200100. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200101. */
  200102. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200103. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200104. #endif
  200105. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200106. /* flip BGR pixels to RGB */
  200107. if (transforms & PNG_TRANSFORM_BGR)
  200108. png_set_bgr(png_ptr);
  200109. #endif
  200110. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200111. /* swap bytes of 16-bit files to most significant byte first */
  200112. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200113. png_set_swap(png_ptr);
  200114. #endif
  200115. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200116. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200117. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200118. png_set_packswap(png_ptr);
  200119. #endif
  200120. /* ----------------------- end of transformations ------------------- */
  200121. /* write the bits */
  200122. if (info_ptr->valid & PNG_INFO_IDAT)
  200123. png_write_image(png_ptr, info_ptr->row_pointers);
  200124. /* It is REQUIRED to call this to finish writing the rest of the file */
  200125. png_write_end(png_ptr, info_ptr);
  200126. transforms = transforms; /* quiet compiler warnings */
  200127. params = params;
  200128. }
  200129. #endif
  200130. #endif /* PNG_WRITE_SUPPORTED */
  200131. /*** End of inlined file: pngwrite.c ***/
  200132. /*** Start of inlined file: pngwtran.c ***/
  200133. /* pngwtran.c - transforms the data in a row for PNG writers
  200134. *
  200135. * Last changed in libpng 1.2.9 April 14, 2006
  200136. * For conditions of distribution and use, see copyright notice in png.h
  200137. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200138. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200139. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200140. */
  200141. #define PNG_INTERNAL
  200142. #ifdef PNG_WRITE_SUPPORTED
  200143. /* Transform the data according to the user's wishes. The order of
  200144. * transformations is significant.
  200145. */
  200146. void /* PRIVATE */
  200147. png_do_write_transformations(png_structp png_ptr)
  200148. {
  200149. png_debug(1, "in png_do_write_transformations\n");
  200150. if (png_ptr == NULL)
  200151. return;
  200152. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200153. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200154. if(png_ptr->write_user_transform_fn != NULL)
  200155. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200156. (png_ptr, /* png_ptr */
  200157. &(png_ptr->row_info), /* row_info: */
  200158. /* png_uint_32 width; width of row */
  200159. /* png_uint_32 rowbytes; number of bytes in row */
  200160. /* png_byte color_type; color type of pixels */
  200161. /* png_byte bit_depth; bit depth of samples */
  200162. /* png_byte channels; number of channels (1-4) */
  200163. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200164. png_ptr->row_buf + 1); /* start of pixel data for row */
  200165. #endif
  200166. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200167. if (png_ptr->transformations & PNG_FILLER)
  200168. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200169. png_ptr->flags);
  200170. #endif
  200171. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200172. if (png_ptr->transformations & PNG_PACKSWAP)
  200173. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200174. #endif
  200175. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200176. if (png_ptr->transformations & PNG_PACK)
  200177. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200178. (png_uint_32)png_ptr->bit_depth);
  200179. #endif
  200180. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200181. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200182. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200183. #endif
  200184. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200185. if (png_ptr->transformations & PNG_SHIFT)
  200186. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200187. &(png_ptr->shift));
  200188. #endif
  200189. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200190. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200191. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200192. #endif
  200193. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200194. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200195. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200196. #endif
  200197. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200198. if (png_ptr->transformations & PNG_BGR)
  200199. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200200. #endif
  200201. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200202. if (png_ptr->transformations & PNG_INVERT_MONO)
  200203. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200204. #endif
  200205. }
  200206. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200207. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200208. * row_info bit depth should be 8 (one pixel per byte). The channels
  200209. * should be 1 (this only happens on grayscale and paletted images).
  200210. */
  200211. void /* PRIVATE */
  200212. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200213. {
  200214. png_debug(1, "in png_do_pack\n");
  200215. if (row_info->bit_depth == 8 &&
  200216. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200217. row != NULL && row_info != NULL &&
  200218. #endif
  200219. row_info->channels == 1)
  200220. {
  200221. switch ((int)bit_depth)
  200222. {
  200223. case 1:
  200224. {
  200225. png_bytep sp, dp;
  200226. int mask, v;
  200227. png_uint_32 i;
  200228. png_uint_32 row_width = row_info->width;
  200229. sp = row;
  200230. dp = row;
  200231. mask = 0x80;
  200232. v = 0;
  200233. for (i = 0; i < row_width; i++)
  200234. {
  200235. if (*sp != 0)
  200236. v |= mask;
  200237. sp++;
  200238. if (mask > 1)
  200239. mask >>= 1;
  200240. else
  200241. {
  200242. mask = 0x80;
  200243. *dp = (png_byte)v;
  200244. dp++;
  200245. v = 0;
  200246. }
  200247. }
  200248. if (mask != 0x80)
  200249. *dp = (png_byte)v;
  200250. break;
  200251. }
  200252. case 2:
  200253. {
  200254. png_bytep sp, dp;
  200255. int shift, v;
  200256. png_uint_32 i;
  200257. png_uint_32 row_width = row_info->width;
  200258. sp = row;
  200259. dp = row;
  200260. shift = 6;
  200261. v = 0;
  200262. for (i = 0; i < row_width; i++)
  200263. {
  200264. png_byte value;
  200265. value = (png_byte)(*sp & 0x03);
  200266. v |= (value << shift);
  200267. if (shift == 0)
  200268. {
  200269. shift = 6;
  200270. *dp = (png_byte)v;
  200271. dp++;
  200272. v = 0;
  200273. }
  200274. else
  200275. shift -= 2;
  200276. sp++;
  200277. }
  200278. if (shift != 6)
  200279. *dp = (png_byte)v;
  200280. break;
  200281. }
  200282. case 4:
  200283. {
  200284. png_bytep sp, dp;
  200285. int shift, v;
  200286. png_uint_32 i;
  200287. png_uint_32 row_width = row_info->width;
  200288. sp = row;
  200289. dp = row;
  200290. shift = 4;
  200291. v = 0;
  200292. for (i = 0; i < row_width; i++)
  200293. {
  200294. png_byte value;
  200295. value = (png_byte)(*sp & 0x0f);
  200296. v |= (value << shift);
  200297. if (shift == 0)
  200298. {
  200299. shift = 4;
  200300. *dp = (png_byte)v;
  200301. dp++;
  200302. v = 0;
  200303. }
  200304. else
  200305. shift -= 4;
  200306. sp++;
  200307. }
  200308. if (shift != 4)
  200309. *dp = (png_byte)v;
  200310. break;
  200311. }
  200312. }
  200313. row_info->bit_depth = (png_byte)bit_depth;
  200314. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200315. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200316. row_info->width);
  200317. }
  200318. }
  200319. #endif
  200320. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200321. /* Shift pixel values to take advantage of whole range. Pass the
  200322. * true number of bits in bit_depth. The row should be packed
  200323. * according to row_info->bit_depth. Thus, if you had a row of
  200324. * bit depth 4, but the pixels only had values from 0 to 7, you
  200325. * would pass 3 as bit_depth, and this routine would translate the
  200326. * data to 0 to 15.
  200327. */
  200328. void /* PRIVATE */
  200329. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200330. {
  200331. png_debug(1, "in png_do_shift\n");
  200332. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200333. if (row != NULL && row_info != NULL &&
  200334. #else
  200335. if (
  200336. #endif
  200337. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200338. {
  200339. int shift_start[4], shift_dec[4];
  200340. int channels = 0;
  200341. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200342. {
  200343. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200344. shift_dec[channels] = bit_depth->red;
  200345. channels++;
  200346. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200347. shift_dec[channels] = bit_depth->green;
  200348. channels++;
  200349. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200350. shift_dec[channels] = bit_depth->blue;
  200351. channels++;
  200352. }
  200353. else
  200354. {
  200355. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200356. shift_dec[channels] = bit_depth->gray;
  200357. channels++;
  200358. }
  200359. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200360. {
  200361. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200362. shift_dec[channels] = bit_depth->alpha;
  200363. channels++;
  200364. }
  200365. /* with low row depths, could only be grayscale, so one channel */
  200366. if (row_info->bit_depth < 8)
  200367. {
  200368. png_bytep bp = row;
  200369. png_uint_32 i;
  200370. png_byte mask;
  200371. png_uint_32 row_bytes = row_info->rowbytes;
  200372. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200373. mask = 0x55;
  200374. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200375. mask = 0x11;
  200376. else
  200377. mask = 0xff;
  200378. for (i = 0; i < row_bytes; i++, bp++)
  200379. {
  200380. png_uint_16 v;
  200381. int j;
  200382. v = *bp;
  200383. *bp = 0;
  200384. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200385. {
  200386. if (j > 0)
  200387. *bp |= (png_byte)((v << j) & 0xff);
  200388. else
  200389. *bp |= (png_byte)((v >> (-j)) & mask);
  200390. }
  200391. }
  200392. }
  200393. else if (row_info->bit_depth == 8)
  200394. {
  200395. png_bytep bp = row;
  200396. png_uint_32 i;
  200397. png_uint_32 istop = channels * row_info->width;
  200398. for (i = 0; i < istop; i++, bp++)
  200399. {
  200400. png_uint_16 v;
  200401. int j;
  200402. int c = (int)(i%channels);
  200403. v = *bp;
  200404. *bp = 0;
  200405. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200406. {
  200407. if (j > 0)
  200408. *bp |= (png_byte)((v << j) & 0xff);
  200409. else
  200410. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200411. }
  200412. }
  200413. }
  200414. else
  200415. {
  200416. png_bytep bp;
  200417. png_uint_32 i;
  200418. png_uint_32 istop = channels * row_info->width;
  200419. for (bp = row, i = 0; i < istop; i++)
  200420. {
  200421. int c = (int)(i%channels);
  200422. png_uint_16 value, v;
  200423. int j;
  200424. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200425. value = 0;
  200426. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200427. {
  200428. if (j > 0)
  200429. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200430. else
  200431. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200432. }
  200433. *bp++ = (png_byte)(value >> 8);
  200434. *bp++ = (png_byte)(value & 0xff);
  200435. }
  200436. }
  200437. }
  200438. }
  200439. #endif
  200440. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200441. void /* PRIVATE */
  200442. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200443. {
  200444. png_debug(1, "in png_do_write_swap_alpha\n");
  200445. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200446. if (row != NULL && row_info != NULL)
  200447. #endif
  200448. {
  200449. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200450. {
  200451. /* This converts from ARGB to RGBA */
  200452. if (row_info->bit_depth == 8)
  200453. {
  200454. png_bytep sp, dp;
  200455. png_uint_32 i;
  200456. png_uint_32 row_width = row_info->width;
  200457. for (i = 0, sp = dp = row; i < row_width; i++)
  200458. {
  200459. png_byte save = *(sp++);
  200460. *(dp++) = *(sp++);
  200461. *(dp++) = *(sp++);
  200462. *(dp++) = *(sp++);
  200463. *(dp++) = save;
  200464. }
  200465. }
  200466. /* This converts from AARRGGBB to RRGGBBAA */
  200467. else
  200468. {
  200469. png_bytep sp, dp;
  200470. png_uint_32 i;
  200471. png_uint_32 row_width = row_info->width;
  200472. for (i = 0, sp = dp = row; i < row_width; i++)
  200473. {
  200474. png_byte save[2];
  200475. save[0] = *(sp++);
  200476. save[1] = *(sp++);
  200477. *(dp++) = *(sp++);
  200478. *(dp++) = *(sp++);
  200479. *(dp++) = *(sp++);
  200480. *(dp++) = *(sp++);
  200481. *(dp++) = *(sp++);
  200482. *(dp++) = *(sp++);
  200483. *(dp++) = save[0];
  200484. *(dp++) = save[1];
  200485. }
  200486. }
  200487. }
  200488. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200489. {
  200490. /* This converts from AG to GA */
  200491. if (row_info->bit_depth == 8)
  200492. {
  200493. png_bytep sp, dp;
  200494. png_uint_32 i;
  200495. png_uint_32 row_width = row_info->width;
  200496. for (i = 0, sp = dp = row; i < row_width; i++)
  200497. {
  200498. png_byte save = *(sp++);
  200499. *(dp++) = *(sp++);
  200500. *(dp++) = save;
  200501. }
  200502. }
  200503. /* This converts from AAGG to GGAA */
  200504. else
  200505. {
  200506. png_bytep sp, dp;
  200507. png_uint_32 i;
  200508. png_uint_32 row_width = row_info->width;
  200509. for (i = 0, sp = dp = row; i < row_width; i++)
  200510. {
  200511. png_byte save[2];
  200512. save[0] = *(sp++);
  200513. save[1] = *(sp++);
  200514. *(dp++) = *(sp++);
  200515. *(dp++) = *(sp++);
  200516. *(dp++) = save[0];
  200517. *(dp++) = save[1];
  200518. }
  200519. }
  200520. }
  200521. }
  200522. }
  200523. #endif
  200524. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200525. void /* PRIVATE */
  200526. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200527. {
  200528. png_debug(1, "in png_do_write_invert_alpha\n");
  200529. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200530. if (row != NULL && row_info != NULL)
  200531. #endif
  200532. {
  200533. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200534. {
  200535. /* This inverts the alpha channel in RGBA */
  200536. if (row_info->bit_depth == 8)
  200537. {
  200538. png_bytep sp, dp;
  200539. png_uint_32 i;
  200540. png_uint_32 row_width = row_info->width;
  200541. for (i = 0, sp = dp = row; i < row_width; i++)
  200542. {
  200543. /* does nothing
  200544. *(dp++) = *(sp++);
  200545. *(dp++) = *(sp++);
  200546. *(dp++) = *(sp++);
  200547. */
  200548. sp+=3; dp = sp;
  200549. *(dp++) = (png_byte)(255 - *(sp++));
  200550. }
  200551. }
  200552. /* This inverts the alpha channel in RRGGBBAA */
  200553. else
  200554. {
  200555. png_bytep sp, dp;
  200556. png_uint_32 i;
  200557. png_uint_32 row_width = row_info->width;
  200558. for (i = 0, sp = dp = row; i < row_width; i++)
  200559. {
  200560. /* does nothing
  200561. *(dp++) = *(sp++);
  200562. *(dp++) = *(sp++);
  200563. *(dp++) = *(sp++);
  200564. *(dp++) = *(sp++);
  200565. *(dp++) = *(sp++);
  200566. *(dp++) = *(sp++);
  200567. */
  200568. sp+=6; dp = sp;
  200569. *(dp++) = (png_byte)(255 - *(sp++));
  200570. *(dp++) = (png_byte)(255 - *(sp++));
  200571. }
  200572. }
  200573. }
  200574. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200575. {
  200576. /* This inverts the alpha channel in GA */
  200577. if (row_info->bit_depth == 8)
  200578. {
  200579. png_bytep sp, dp;
  200580. png_uint_32 i;
  200581. png_uint_32 row_width = row_info->width;
  200582. for (i = 0, sp = dp = row; i < row_width; i++)
  200583. {
  200584. *(dp++) = *(sp++);
  200585. *(dp++) = (png_byte)(255 - *(sp++));
  200586. }
  200587. }
  200588. /* This inverts the alpha channel in GGAA */
  200589. else
  200590. {
  200591. png_bytep sp, dp;
  200592. png_uint_32 i;
  200593. png_uint_32 row_width = row_info->width;
  200594. for (i = 0, sp = dp = row; i < row_width; i++)
  200595. {
  200596. /* does nothing
  200597. *(dp++) = *(sp++);
  200598. *(dp++) = *(sp++);
  200599. */
  200600. sp+=2; dp = sp;
  200601. *(dp++) = (png_byte)(255 - *(sp++));
  200602. *(dp++) = (png_byte)(255 - *(sp++));
  200603. }
  200604. }
  200605. }
  200606. }
  200607. }
  200608. #endif
  200609. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200610. /* undoes intrapixel differencing */
  200611. void /* PRIVATE */
  200612. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200613. {
  200614. png_debug(1, "in png_do_write_intrapixel\n");
  200615. if (
  200616. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200617. row != NULL && row_info != NULL &&
  200618. #endif
  200619. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200620. {
  200621. int bytes_per_pixel;
  200622. png_uint_32 row_width = row_info->width;
  200623. if (row_info->bit_depth == 8)
  200624. {
  200625. png_bytep rp;
  200626. png_uint_32 i;
  200627. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200628. bytes_per_pixel = 3;
  200629. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200630. bytes_per_pixel = 4;
  200631. else
  200632. return;
  200633. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200634. {
  200635. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200636. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200637. }
  200638. }
  200639. else if (row_info->bit_depth == 16)
  200640. {
  200641. png_bytep rp;
  200642. png_uint_32 i;
  200643. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200644. bytes_per_pixel = 6;
  200645. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200646. bytes_per_pixel = 8;
  200647. else
  200648. return;
  200649. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200650. {
  200651. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200652. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200653. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200654. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200655. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200656. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200657. *(rp+1) = (png_byte)(red & 0xff);
  200658. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200659. *(rp+5) = (png_byte)(blue & 0xff);
  200660. }
  200661. }
  200662. }
  200663. }
  200664. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200665. #endif /* PNG_WRITE_SUPPORTED */
  200666. /*** End of inlined file: pngwtran.c ***/
  200667. /*** Start of inlined file: pngwutil.c ***/
  200668. /* pngwutil.c - utilities to write a PNG file
  200669. *
  200670. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200671. * For conditions of distribution and use, see copyright notice in png.h
  200672. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200673. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200674. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200675. */
  200676. #define PNG_INTERNAL
  200677. #ifdef PNG_WRITE_SUPPORTED
  200678. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200679. * with unsigned numbers for convenience, although one supported
  200680. * ancillary chunk uses signed (two's complement) numbers.
  200681. */
  200682. void PNGAPI
  200683. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200684. {
  200685. buf[0] = (png_byte)((i >> 24) & 0xff);
  200686. buf[1] = (png_byte)((i >> 16) & 0xff);
  200687. buf[2] = (png_byte)((i >> 8) & 0xff);
  200688. buf[3] = (png_byte)(i & 0xff);
  200689. }
  200690. /* The png_save_int_32 function assumes integers are stored in two's
  200691. * complement format. If this isn't the case, then this routine needs to
  200692. * be modified to write data in two's complement format.
  200693. */
  200694. void PNGAPI
  200695. png_save_int_32(png_bytep buf, png_int_32 i)
  200696. {
  200697. buf[0] = (png_byte)((i >> 24) & 0xff);
  200698. buf[1] = (png_byte)((i >> 16) & 0xff);
  200699. buf[2] = (png_byte)((i >> 8) & 0xff);
  200700. buf[3] = (png_byte)(i & 0xff);
  200701. }
  200702. /* Place a 16-bit number into a buffer in PNG byte order.
  200703. * The parameter is declared unsigned int, not png_uint_16,
  200704. * just to avoid potential problems on pre-ANSI C compilers.
  200705. */
  200706. void PNGAPI
  200707. png_save_uint_16(png_bytep buf, unsigned int i)
  200708. {
  200709. buf[0] = (png_byte)((i >> 8) & 0xff);
  200710. buf[1] = (png_byte)(i & 0xff);
  200711. }
  200712. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200713. * representing the chunk name. The array must be at least 4 bytes in
  200714. * length, and does not need to be null terminated. To be safe, pass the
  200715. * pre-defined chunk names here, and if you need a new one, define it
  200716. * where the others are defined. The length is the length of the data.
  200717. * All the data must be present. If that is not possible, use the
  200718. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200719. * functions instead.
  200720. */
  200721. void PNGAPI
  200722. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200723. png_bytep data, png_size_t length)
  200724. {
  200725. if(png_ptr == NULL) return;
  200726. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200727. png_write_chunk_data(png_ptr, data, length);
  200728. png_write_chunk_end(png_ptr);
  200729. }
  200730. /* Write the start of a PNG chunk. The type is the chunk type.
  200731. * The total_length is the sum of the lengths of all the data you will be
  200732. * passing in png_write_chunk_data().
  200733. */
  200734. void PNGAPI
  200735. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200736. png_uint_32 length)
  200737. {
  200738. png_byte buf[4];
  200739. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200740. if(png_ptr == NULL) return;
  200741. /* write the length */
  200742. png_save_uint_32(buf, length);
  200743. png_write_data(png_ptr, buf, (png_size_t)4);
  200744. /* write the chunk name */
  200745. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200746. /* reset the crc and run it over the chunk name */
  200747. png_reset_crc(png_ptr);
  200748. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200749. }
  200750. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200751. * Note that multiple calls to this function are allowed, and that the
  200752. * sum of the lengths from these calls *must* add up to the total_length
  200753. * given to png_write_chunk_start().
  200754. */
  200755. void PNGAPI
  200756. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200757. {
  200758. /* write the data, and run the CRC over it */
  200759. if(png_ptr == NULL) return;
  200760. if (data != NULL && length > 0)
  200761. {
  200762. png_calculate_crc(png_ptr, data, length);
  200763. png_write_data(png_ptr, data, length);
  200764. }
  200765. }
  200766. /* Finish a chunk started with png_write_chunk_start(). */
  200767. void PNGAPI
  200768. png_write_chunk_end(png_structp png_ptr)
  200769. {
  200770. png_byte buf[4];
  200771. if(png_ptr == NULL) return;
  200772. /* write the crc */
  200773. png_save_uint_32(buf, png_ptr->crc);
  200774. png_write_data(png_ptr, buf, (png_size_t)4);
  200775. }
  200776. /* Simple function to write the signature. If we have already written
  200777. * the magic bytes of the signature, or more likely, the PNG stream is
  200778. * being embedded into another stream and doesn't need its own signature,
  200779. * we should call png_set_sig_bytes() to tell libpng how many of the
  200780. * bytes have already been written.
  200781. */
  200782. void /* PRIVATE */
  200783. png_write_sig(png_structp png_ptr)
  200784. {
  200785. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200786. /* write the rest of the 8 byte signature */
  200787. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200788. (png_size_t)8 - png_ptr->sig_bytes);
  200789. if(png_ptr->sig_bytes < 3)
  200790. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200791. }
  200792. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200793. /*
  200794. * This pair of functions encapsulates the operation of (a) compressing a
  200795. * text string, and (b) issuing it later as a series of chunk data writes.
  200796. * The compression_state structure is shared context for these functions
  200797. * set up by the caller in order to make the whole mess thread-safe.
  200798. */
  200799. typedef struct
  200800. {
  200801. char *input; /* the uncompressed input data */
  200802. int input_len; /* its length */
  200803. int num_output_ptr; /* number of output pointers used */
  200804. int max_output_ptr; /* size of output_ptr */
  200805. png_charpp output_ptr; /* array of pointers to output */
  200806. } compression_state;
  200807. /* compress given text into storage in the png_ptr structure */
  200808. static int /* PRIVATE */
  200809. png_text_compress(png_structp png_ptr,
  200810. png_charp text, png_size_t text_len, int compression,
  200811. compression_state *comp)
  200812. {
  200813. int ret;
  200814. comp->num_output_ptr = 0;
  200815. comp->max_output_ptr = 0;
  200816. comp->output_ptr = NULL;
  200817. comp->input = NULL;
  200818. comp->input_len = 0;
  200819. /* we may just want to pass the text right through */
  200820. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200821. {
  200822. comp->input = text;
  200823. comp->input_len = text_len;
  200824. return((int)text_len);
  200825. }
  200826. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200827. {
  200828. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200829. char msg[50];
  200830. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200831. png_warning(png_ptr, msg);
  200832. #else
  200833. png_warning(png_ptr, "Unknown compression type");
  200834. #endif
  200835. }
  200836. /* We can't write the chunk until we find out how much data we have,
  200837. * which means we need to run the compressor first and save the
  200838. * output. This shouldn't be a problem, as the vast majority of
  200839. * comments should be reasonable, but we will set up an array of
  200840. * malloc'd pointers to be sure.
  200841. *
  200842. * If we knew the application was well behaved, we could simplify this
  200843. * greatly by assuming we can always malloc an output buffer large
  200844. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200845. * and malloc this directly. The only time this would be a bad idea is
  200846. * if we can't malloc more than 64K and we have 64K of random input
  200847. * data, or if the input string is incredibly large (although this
  200848. * wouldn't cause a failure, just a slowdown due to swapping).
  200849. */
  200850. /* set up the compression buffers */
  200851. png_ptr->zstream.avail_in = (uInt)text_len;
  200852. png_ptr->zstream.next_in = (Bytef *)text;
  200853. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200854. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200855. /* this is the same compression loop as in png_write_row() */
  200856. do
  200857. {
  200858. /* compress the data */
  200859. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200860. if (ret != Z_OK)
  200861. {
  200862. /* error */
  200863. if (png_ptr->zstream.msg != NULL)
  200864. png_error(png_ptr, png_ptr->zstream.msg);
  200865. else
  200866. png_error(png_ptr, "zlib error");
  200867. }
  200868. /* check to see if we need more room */
  200869. if (!(png_ptr->zstream.avail_out))
  200870. {
  200871. /* make sure the output array has room */
  200872. if (comp->num_output_ptr >= comp->max_output_ptr)
  200873. {
  200874. int old_max;
  200875. old_max = comp->max_output_ptr;
  200876. comp->max_output_ptr = comp->num_output_ptr + 4;
  200877. if (comp->output_ptr != NULL)
  200878. {
  200879. png_charpp old_ptr;
  200880. old_ptr = comp->output_ptr;
  200881. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200882. (png_uint_32)(comp->max_output_ptr *
  200883. png_sizeof (png_charpp)));
  200884. png_memcpy(comp->output_ptr, old_ptr, old_max
  200885. * png_sizeof (png_charp));
  200886. png_free(png_ptr, old_ptr);
  200887. }
  200888. else
  200889. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200890. (png_uint_32)(comp->max_output_ptr *
  200891. png_sizeof (png_charp)));
  200892. }
  200893. /* save the data */
  200894. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200895. (png_uint_32)png_ptr->zbuf_size);
  200896. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200897. png_ptr->zbuf_size);
  200898. comp->num_output_ptr++;
  200899. /* and reset the buffer */
  200900. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200901. png_ptr->zstream.next_out = png_ptr->zbuf;
  200902. }
  200903. /* continue until we don't have any more to compress */
  200904. } while (png_ptr->zstream.avail_in);
  200905. /* finish the compression */
  200906. do
  200907. {
  200908. /* tell zlib we are finished */
  200909. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200910. if (ret == Z_OK)
  200911. {
  200912. /* check to see if we need more room */
  200913. if (!(png_ptr->zstream.avail_out))
  200914. {
  200915. /* check to make sure our output array has room */
  200916. if (comp->num_output_ptr >= comp->max_output_ptr)
  200917. {
  200918. int old_max;
  200919. old_max = comp->max_output_ptr;
  200920. comp->max_output_ptr = comp->num_output_ptr + 4;
  200921. if (comp->output_ptr != NULL)
  200922. {
  200923. png_charpp old_ptr;
  200924. old_ptr = comp->output_ptr;
  200925. /* This could be optimized to realloc() */
  200926. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200927. (png_uint_32)(comp->max_output_ptr *
  200928. png_sizeof (png_charpp)));
  200929. png_memcpy(comp->output_ptr, old_ptr,
  200930. old_max * png_sizeof (png_charp));
  200931. png_free(png_ptr, old_ptr);
  200932. }
  200933. else
  200934. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200935. (png_uint_32)(comp->max_output_ptr *
  200936. png_sizeof (png_charp)));
  200937. }
  200938. /* save off the data */
  200939. comp->output_ptr[comp->num_output_ptr] =
  200940. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200941. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200942. png_ptr->zbuf_size);
  200943. comp->num_output_ptr++;
  200944. /* and reset the buffer pointers */
  200945. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200946. png_ptr->zstream.next_out = png_ptr->zbuf;
  200947. }
  200948. }
  200949. else if (ret != Z_STREAM_END)
  200950. {
  200951. /* we got an error */
  200952. if (png_ptr->zstream.msg != NULL)
  200953. png_error(png_ptr, png_ptr->zstream.msg);
  200954. else
  200955. png_error(png_ptr, "zlib error");
  200956. }
  200957. } while (ret != Z_STREAM_END);
  200958. /* text length is number of buffers plus last buffer */
  200959. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200960. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200961. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200962. return((int)text_len);
  200963. }
  200964. /* ship the compressed text out via chunk writes */
  200965. static void /* PRIVATE */
  200966. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200967. {
  200968. int i;
  200969. /* handle the no-compression case */
  200970. if (comp->input)
  200971. {
  200972. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200973. (png_size_t)comp->input_len);
  200974. return;
  200975. }
  200976. /* write saved output buffers, if any */
  200977. for (i = 0; i < comp->num_output_ptr; i++)
  200978. {
  200979. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200980. png_ptr->zbuf_size);
  200981. png_free(png_ptr, comp->output_ptr[i]);
  200982. comp->output_ptr[i]=NULL;
  200983. }
  200984. if (comp->max_output_ptr != 0)
  200985. png_free(png_ptr, comp->output_ptr);
  200986. comp->output_ptr=NULL;
  200987. /* write anything left in zbuf */
  200988. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200989. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200990. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200991. /* reset zlib for another zTXt/iTXt or image data */
  200992. deflateReset(&png_ptr->zstream);
  200993. png_ptr->zstream.data_type = Z_BINARY;
  200994. }
  200995. #endif
  200996. /* Write the IHDR chunk, and update the png_struct with the necessary
  200997. * information. Note that the rest of this code depends upon this
  200998. * information being correct.
  200999. */
  201000. void /* PRIVATE */
  201001. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201002. int bit_depth, int color_type, int compression_type, int filter_type,
  201003. int interlace_type)
  201004. {
  201005. #ifdef PNG_USE_LOCAL_ARRAYS
  201006. PNG_IHDR;
  201007. #endif
  201008. png_byte buf[13]; /* buffer to store the IHDR info */
  201009. png_debug(1, "in png_write_IHDR\n");
  201010. /* Check that we have valid input data from the application info */
  201011. switch (color_type)
  201012. {
  201013. case PNG_COLOR_TYPE_GRAY:
  201014. switch (bit_depth)
  201015. {
  201016. case 1:
  201017. case 2:
  201018. case 4:
  201019. case 8:
  201020. case 16: png_ptr->channels = 1; break;
  201021. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201022. }
  201023. break;
  201024. case PNG_COLOR_TYPE_RGB:
  201025. if (bit_depth != 8 && bit_depth != 16)
  201026. png_error(png_ptr, "Invalid bit depth for RGB image");
  201027. png_ptr->channels = 3;
  201028. break;
  201029. case PNG_COLOR_TYPE_PALETTE:
  201030. switch (bit_depth)
  201031. {
  201032. case 1:
  201033. case 2:
  201034. case 4:
  201035. case 8: png_ptr->channels = 1; break;
  201036. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201037. }
  201038. break;
  201039. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201040. if (bit_depth != 8 && bit_depth != 16)
  201041. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201042. png_ptr->channels = 2;
  201043. break;
  201044. case PNG_COLOR_TYPE_RGB_ALPHA:
  201045. if (bit_depth != 8 && bit_depth != 16)
  201046. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201047. png_ptr->channels = 4;
  201048. break;
  201049. default:
  201050. png_error(png_ptr, "Invalid image color type specified");
  201051. }
  201052. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201053. {
  201054. png_warning(png_ptr, "Invalid compression type specified");
  201055. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201056. }
  201057. /* Write filter_method 64 (intrapixel differencing) only if
  201058. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201059. * 2. Libpng did not write a PNG signature (this filter_method is only
  201060. * used in PNG datastreams that are embedded in MNG datastreams) and
  201061. * 3. The application called png_permit_mng_features with a mask that
  201062. * included PNG_FLAG_MNG_FILTER_64 and
  201063. * 4. The filter_method is 64 and
  201064. * 5. The color_type is RGB or RGBA
  201065. */
  201066. if (
  201067. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201068. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201069. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201070. (color_type == PNG_COLOR_TYPE_RGB ||
  201071. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201072. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201073. #endif
  201074. filter_type != PNG_FILTER_TYPE_BASE)
  201075. {
  201076. png_warning(png_ptr, "Invalid filter type specified");
  201077. filter_type = PNG_FILTER_TYPE_BASE;
  201078. }
  201079. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201080. if (interlace_type != PNG_INTERLACE_NONE &&
  201081. interlace_type != PNG_INTERLACE_ADAM7)
  201082. {
  201083. png_warning(png_ptr, "Invalid interlace type specified");
  201084. interlace_type = PNG_INTERLACE_ADAM7;
  201085. }
  201086. #else
  201087. interlace_type=PNG_INTERLACE_NONE;
  201088. #endif
  201089. /* save off the relevent information */
  201090. png_ptr->bit_depth = (png_byte)bit_depth;
  201091. png_ptr->color_type = (png_byte)color_type;
  201092. png_ptr->interlaced = (png_byte)interlace_type;
  201093. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201094. png_ptr->filter_type = (png_byte)filter_type;
  201095. #endif
  201096. png_ptr->compression_type = (png_byte)compression_type;
  201097. png_ptr->width = width;
  201098. png_ptr->height = height;
  201099. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201100. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201101. /* set the usr info, so any transformations can modify it */
  201102. png_ptr->usr_width = png_ptr->width;
  201103. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201104. png_ptr->usr_channels = png_ptr->channels;
  201105. /* pack the header information into the buffer */
  201106. png_save_uint_32(buf, width);
  201107. png_save_uint_32(buf + 4, height);
  201108. buf[8] = (png_byte)bit_depth;
  201109. buf[9] = (png_byte)color_type;
  201110. buf[10] = (png_byte)compression_type;
  201111. buf[11] = (png_byte)filter_type;
  201112. buf[12] = (png_byte)interlace_type;
  201113. /* write the chunk */
  201114. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201115. /* initialize zlib with PNG info */
  201116. png_ptr->zstream.zalloc = png_zalloc;
  201117. png_ptr->zstream.zfree = png_zfree;
  201118. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201119. if (!(png_ptr->do_filter))
  201120. {
  201121. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201122. png_ptr->bit_depth < 8)
  201123. png_ptr->do_filter = PNG_FILTER_NONE;
  201124. else
  201125. png_ptr->do_filter = PNG_ALL_FILTERS;
  201126. }
  201127. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201128. {
  201129. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201130. png_ptr->zlib_strategy = Z_FILTERED;
  201131. else
  201132. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201133. }
  201134. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201135. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201136. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201137. png_ptr->zlib_mem_level = 8;
  201138. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201139. png_ptr->zlib_window_bits = 15;
  201140. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201141. png_ptr->zlib_method = 8;
  201142. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201143. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201144. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201145. png_error(png_ptr, "zlib failed to initialize compressor");
  201146. png_ptr->zstream.next_out = png_ptr->zbuf;
  201147. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201148. /* libpng is not interested in zstream.data_type */
  201149. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201150. png_ptr->zstream.data_type = Z_BINARY;
  201151. png_ptr->mode = PNG_HAVE_IHDR;
  201152. }
  201153. /* write the palette. We are careful not to trust png_color to be in the
  201154. * correct order for PNG, so people can redefine it to any convenient
  201155. * structure.
  201156. */
  201157. void /* PRIVATE */
  201158. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201159. {
  201160. #ifdef PNG_USE_LOCAL_ARRAYS
  201161. PNG_PLTE;
  201162. #endif
  201163. png_uint_32 i;
  201164. png_colorp pal_ptr;
  201165. png_byte buf[3];
  201166. png_debug(1, "in png_write_PLTE\n");
  201167. if ((
  201168. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201169. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201170. #endif
  201171. num_pal == 0) || num_pal > 256)
  201172. {
  201173. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201174. {
  201175. png_error(png_ptr, "Invalid number of colors in palette");
  201176. }
  201177. else
  201178. {
  201179. png_warning(png_ptr, "Invalid number of colors in palette");
  201180. return;
  201181. }
  201182. }
  201183. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201184. {
  201185. png_warning(png_ptr,
  201186. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201187. return;
  201188. }
  201189. png_ptr->num_palette = (png_uint_16)num_pal;
  201190. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201191. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201192. #ifndef PNG_NO_POINTER_INDEXING
  201193. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201194. {
  201195. buf[0] = pal_ptr->red;
  201196. buf[1] = pal_ptr->green;
  201197. buf[2] = pal_ptr->blue;
  201198. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201199. }
  201200. #else
  201201. /* This is a little slower but some buggy compilers need to do this instead */
  201202. pal_ptr=palette;
  201203. for (i = 0; i < num_pal; i++)
  201204. {
  201205. buf[0] = pal_ptr[i].red;
  201206. buf[1] = pal_ptr[i].green;
  201207. buf[2] = pal_ptr[i].blue;
  201208. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201209. }
  201210. #endif
  201211. png_write_chunk_end(png_ptr);
  201212. png_ptr->mode |= PNG_HAVE_PLTE;
  201213. }
  201214. /* write an IDAT chunk */
  201215. void /* PRIVATE */
  201216. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201217. {
  201218. #ifdef PNG_USE_LOCAL_ARRAYS
  201219. PNG_IDAT;
  201220. #endif
  201221. png_debug(1, "in png_write_IDAT\n");
  201222. /* Optimize the CMF field in the zlib stream. */
  201223. /* This hack of the zlib stream is compliant to the stream specification. */
  201224. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201225. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201226. {
  201227. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201228. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201229. {
  201230. /* Avoid memory underflows and multiplication overflows. */
  201231. /* The conditions below are practically always satisfied;
  201232. however, they still must be checked. */
  201233. if (length >= 2 &&
  201234. png_ptr->height < 16384 && png_ptr->width < 16384)
  201235. {
  201236. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201237. ((png_ptr->width *
  201238. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201239. unsigned int z_cinfo = z_cmf >> 4;
  201240. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201241. while (uncompressed_idat_size <= half_z_window_size &&
  201242. half_z_window_size >= 256)
  201243. {
  201244. z_cinfo--;
  201245. half_z_window_size >>= 1;
  201246. }
  201247. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201248. if (data[0] != (png_byte)z_cmf)
  201249. {
  201250. data[0] = (png_byte)z_cmf;
  201251. data[1] &= 0xe0;
  201252. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201253. }
  201254. }
  201255. }
  201256. else
  201257. png_error(png_ptr,
  201258. "Invalid zlib compression method or flags in IDAT");
  201259. }
  201260. png_write_chunk(png_ptr, png_IDAT, data, length);
  201261. png_ptr->mode |= PNG_HAVE_IDAT;
  201262. }
  201263. /* write an IEND chunk */
  201264. void /* PRIVATE */
  201265. png_write_IEND(png_structp png_ptr)
  201266. {
  201267. #ifdef PNG_USE_LOCAL_ARRAYS
  201268. PNG_IEND;
  201269. #endif
  201270. png_debug(1, "in png_write_IEND\n");
  201271. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201272. (png_size_t)0);
  201273. png_ptr->mode |= PNG_HAVE_IEND;
  201274. }
  201275. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201276. /* write a gAMA chunk */
  201277. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201278. void /* PRIVATE */
  201279. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201280. {
  201281. #ifdef PNG_USE_LOCAL_ARRAYS
  201282. PNG_gAMA;
  201283. #endif
  201284. png_uint_32 igamma;
  201285. png_byte buf[4];
  201286. png_debug(1, "in png_write_gAMA\n");
  201287. /* file_gamma is saved in 1/100,000ths */
  201288. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201289. png_save_uint_32(buf, igamma);
  201290. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201291. }
  201292. #endif
  201293. #ifdef PNG_FIXED_POINT_SUPPORTED
  201294. void /* PRIVATE */
  201295. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201296. {
  201297. #ifdef PNG_USE_LOCAL_ARRAYS
  201298. PNG_gAMA;
  201299. #endif
  201300. png_byte buf[4];
  201301. png_debug(1, "in png_write_gAMA\n");
  201302. /* file_gamma is saved in 1/100,000ths */
  201303. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201304. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201305. }
  201306. #endif
  201307. #endif
  201308. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201309. /* write a sRGB chunk */
  201310. void /* PRIVATE */
  201311. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201312. {
  201313. #ifdef PNG_USE_LOCAL_ARRAYS
  201314. PNG_sRGB;
  201315. #endif
  201316. png_byte buf[1];
  201317. png_debug(1, "in png_write_sRGB\n");
  201318. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201319. png_warning(png_ptr,
  201320. "Invalid sRGB rendering intent specified");
  201321. buf[0]=(png_byte)srgb_intent;
  201322. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201323. }
  201324. #endif
  201325. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201326. /* write an iCCP chunk */
  201327. void /* PRIVATE */
  201328. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201329. png_charp profile, int profile_len)
  201330. {
  201331. #ifdef PNG_USE_LOCAL_ARRAYS
  201332. PNG_iCCP;
  201333. #endif
  201334. png_size_t name_len;
  201335. png_charp new_name;
  201336. compression_state comp;
  201337. int embedded_profile_len = 0;
  201338. png_debug(1, "in png_write_iCCP\n");
  201339. comp.num_output_ptr = 0;
  201340. comp.max_output_ptr = 0;
  201341. comp.output_ptr = NULL;
  201342. comp.input = NULL;
  201343. comp.input_len = 0;
  201344. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201345. &new_name)) == 0)
  201346. {
  201347. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201348. return;
  201349. }
  201350. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201351. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201352. if (profile == NULL)
  201353. profile_len = 0;
  201354. if (profile_len > 3)
  201355. embedded_profile_len =
  201356. ((*( (png_bytep)profile ))<<24) |
  201357. ((*( (png_bytep)profile+1))<<16) |
  201358. ((*( (png_bytep)profile+2))<< 8) |
  201359. ((*( (png_bytep)profile+3)) );
  201360. if (profile_len < embedded_profile_len)
  201361. {
  201362. png_warning(png_ptr,
  201363. "Embedded profile length too large in iCCP chunk");
  201364. return;
  201365. }
  201366. if (profile_len > embedded_profile_len)
  201367. {
  201368. png_warning(png_ptr,
  201369. "Truncating profile to actual length in iCCP chunk");
  201370. profile_len = embedded_profile_len;
  201371. }
  201372. if (profile_len)
  201373. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201374. PNG_COMPRESSION_TYPE_BASE, &comp);
  201375. /* make sure we include the NULL after the name and the compression type */
  201376. png_write_chunk_start(png_ptr, png_iCCP,
  201377. (png_uint_32)name_len+profile_len+2);
  201378. new_name[name_len+1]=0x00;
  201379. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201380. if (profile_len)
  201381. png_write_compressed_data_out(png_ptr, &comp);
  201382. png_write_chunk_end(png_ptr);
  201383. png_free(png_ptr, new_name);
  201384. }
  201385. #endif
  201386. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201387. /* write a sPLT chunk */
  201388. void /* PRIVATE */
  201389. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201390. {
  201391. #ifdef PNG_USE_LOCAL_ARRAYS
  201392. PNG_sPLT;
  201393. #endif
  201394. png_size_t name_len;
  201395. png_charp new_name;
  201396. png_byte entrybuf[10];
  201397. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201398. int palette_size = entry_size * spalette->nentries;
  201399. png_sPLT_entryp ep;
  201400. #ifdef PNG_NO_POINTER_INDEXING
  201401. int i;
  201402. #endif
  201403. png_debug(1, "in png_write_sPLT\n");
  201404. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201405. spalette->name, &new_name))==0)
  201406. {
  201407. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201408. return;
  201409. }
  201410. /* make sure we include the NULL after the name */
  201411. png_write_chunk_start(png_ptr, png_sPLT,
  201412. (png_uint_32)(name_len + 2 + palette_size));
  201413. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201414. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201415. /* loop through each palette entry, writing appropriately */
  201416. #ifndef PNG_NO_POINTER_INDEXING
  201417. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201418. {
  201419. if (spalette->depth == 8)
  201420. {
  201421. entrybuf[0] = (png_byte)ep->red;
  201422. entrybuf[1] = (png_byte)ep->green;
  201423. entrybuf[2] = (png_byte)ep->blue;
  201424. entrybuf[3] = (png_byte)ep->alpha;
  201425. png_save_uint_16(entrybuf + 4, ep->frequency);
  201426. }
  201427. else
  201428. {
  201429. png_save_uint_16(entrybuf + 0, ep->red);
  201430. png_save_uint_16(entrybuf + 2, ep->green);
  201431. png_save_uint_16(entrybuf + 4, ep->blue);
  201432. png_save_uint_16(entrybuf + 6, ep->alpha);
  201433. png_save_uint_16(entrybuf + 8, ep->frequency);
  201434. }
  201435. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201436. }
  201437. #else
  201438. ep=spalette->entries;
  201439. for (i=0; i>spalette->nentries; i++)
  201440. {
  201441. if (spalette->depth == 8)
  201442. {
  201443. entrybuf[0] = (png_byte)ep[i].red;
  201444. entrybuf[1] = (png_byte)ep[i].green;
  201445. entrybuf[2] = (png_byte)ep[i].blue;
  201446. entrybuf[3] = (png_byte)ep[i].alpha;
  201447. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201448. }
  201449. else
  201450. {
  201451. png_save_uint_16(entrybuf + 0, ep[i].red);
  201452. png_save_uint_16(entrybuf + 2, ep[i].green);
  201453. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201454. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201455. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201456. }
  201457. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201458. }
  201459. #endif
  201460. png_write_chunk_end(png_ptr);
  201461. png_free(png_ptr, new_name);
  201462. }
  201463. #endif
  201464. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201465. /* write the sBIT chunk */
  201466. void /* PRIVATE */
  201467. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201468. {
  201469. #ifdef PNG_USE_LOCAL_ARRAYS
  201470. PNG_sBIT;
  201471. #endif
  201472. png_byte buf[4];
  201473. png_size_t size;
  201474. png_debug(1, "in png_write_sBIT\n");
  201475. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201476. if (color_type & PNG_COLOR_MASK_COLOR)
  201477. {
  201478. png_byte maxbits;
  201479. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201480. png_ptr->usr_bit_depth);
  201481. if (sbit->red == 0 || sbit->red > maxbits ||
  201482. sbit->green == 0 || sbit->green > maxbits ||
  201483. sbit->blue == 0 || sbit->blue > maxbits)
  201484. {
  201485. png_warning(png_ptr, "Invalid sBIT depth specified");
  201486. return;
  201487. }
  201488. buf[0] = sbit->red;
  201489. buf[1] = sbit->green;
  201490. buf[2] = sbit->blue;
  201491. size = 3;
  201492. }
  201493. else
  201494. {
  201495. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201496. {
  201497. png_warning(png_ptr, "Invalid sBIT depth specified");
  201498. return;
  201499. }
  201500. buf[0] = sbit->gray;
  201501. size = 1;
  201502. }
  201503. if (color_type & PNG_COLOR_MASK_ALPHA)
  201504. {
  201505. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201506. {
  201507. png_warning(png_ptr, "Invalid sBIT depth specified");
  201508. return;
  201509. }
  201510. buf[size++] = sbit->alpha;
  201511. }
  201512. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201513. }
  201514. #endif
  201515. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201516. /* write the cHRM chunk */
  201517. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201518. void /* PRIVATE */
  201519. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201520. double red_x, double red_y, double green_x, double green_y,
  201521. double blue_x, double blue_y)
  201522. {
  201523. #ifdef PNG_USE_LOCAL_ARRAYS
  201524. PNG_cHRM;
  201525. #endif
  201526. png_byte buf[32];
  201527. png_uint_32 itemp;
  201528. png_debug(1, "in png_write_cHRM\n");
  201529. /* each value is saved in 1/100,000ths */
  201530. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201531. white_x + white_y > 1.0)
  201532. {
  201533. png_warning(png_ptr, "Invalid cHRM white point specified");
  201534. #if !defined(PNG_NO_CONSOLE_IO)
  201535. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201536. #endif
  201537. return;
  201538. }
  201539. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201540. png_save_uint_32(buf, itemp);
  201541. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201542. png_save_uint_32(buf + 4, itemp);
  201543. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201544. {
  201545. png_warning(png_ptr, "Invalid cHRM red point specified");
  201546. return;
  201547. }
  201548. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201549. png_save_uint_32(buf + 8, itemp);
  201550. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201551. png_save_uint_32(buf + 12, itemp);
  201552. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201553. {
  201554. png_warning(png_ptr, "Invalid cHRM green point specified");
  201555. return;
  201556. }
  201557. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201558. png_save_uint_32(buf + 16, itemp);
  201559. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201560. png_save_uint_32(buf + 20, itemp);
  201561. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201562. {
  201563. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201564. return;
  201565. }
  201566. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201567. png_save_uint_32(buf + 24, itemp);
  201568. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201569. png_save_uint_32(buf + 28, itemp);
  201570. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201571. }
  201572. #endif
  201573. #ifdef PNG_FIXED_POINT_SUPPORTED
  201574. void /* PRIVATE */
  201575. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201576. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201577. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201578. png_fixed_point blue_y)
  201579. {
  201580. #ifdef PNG_USE_LOCAL_ARRAYS
  201581. PNG_cHRM;
  201582. #endif
  201583. png_byte buf[32];
  201584. png_debug(1, "in png_write_cHRM\n");
  201585. /* each value is saved in 1/100,000ths */
  201586. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201587. {
  201588. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201589. #if !defined(PNG_NO_CONSOLE_IO)
  201590. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201591. #endif
  201592. return;
  201593. }
  201594. png_save_uint_32(buf, (png_uint_32)white_x);
  201595. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201596. if (red_x + red_y > 100000L)
  201597. {
  201598. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201599. return;
  201600. }
  201601. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201602. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201603. if (green_x + green_y > 100000L)
  201604. {
  201605. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201606. return;
  201607. }
  201608. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201609. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201610. if (blue_x + blue_y > 100000L)
  201611. {
  201612. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201613. return;
  201614. }
  201615. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201616. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201617. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201618. }
  201619. #endif
  201620. #endif
  201621. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201622. /* write the tRNS chunk */
  201623. void /* PRIVATE */
  201624. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201625. int num_trans, int color_type)
  201626. {
  201627. #ifdef PNG_USE_LOCAL_ARRAYS
  201628. PNG_tRNS;
  201629. #endif
  201630. png_byte buf[6];
  201631. png_debug(1, "in png_write_tRNS\n");
  201632. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201633. {
  201634. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201635. {
  201636. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201637. return;
  201638. }
  201639. /* write the chunk out as it is */
  201640. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201641. }
  201642. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201643. {
  201644. /* one 16 bit value */
  201645. if(tran->gray >= (1 << png_ptr->bit_depth))
  201646. {
  201647. png_warning(png_ptr,
  201648. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201649. return;
  201650. }
  201651. png_save_uint_16(buf, tran->gray);
  201652. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201653. }
  201654. else if (color_type == PNG_COLOR_TYPE_RGB)
  201655. {
  201656. /* three 16 bit values */
  201657. png_save_uint_16(buf, tran->red);
  201658. png_save_uint_16(buf + 2, tran->green);
  201659. png_save_uint_16(buf + 4, tran->blue);
  201660. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201661. {
  201662. png_warning(png_ptr,
  201663. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201664. return;
  201665. }
  201666. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201667. }
  201668. else
  201669. {
  201670. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201671. }
  201672. }
  201673. #endif
  201674. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201675. /* write the background chunk */
  201676. void /* PRIVATE */
  201677. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201678. {
  201679. #ifdef PNG_USE_LOCAL_ARRAYS
  201680. PNG_bKGD;
  201681. #endif
  201682. png_byte buf[6];
  201683. png_debug(1, "in png_write_bKGD\n");
  201684. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201685. {
  201686. if (
  201687. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201688. (png_ptr->num_palette ||
  201689. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201690. #endif
  201691. back->index > png_ptr->num_palette)
  201692. {
  201693. png_warning(png_ptr, "Invalid background palette index");
  201694. return;
  201695. }
  201696. buf[0] = back->index;
  201697. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201698. }
  201699. else if (color_type & PNG_COLOR_MASK_COLOR)
  201700. {
  201701. png_save_uint_16(buf, back->red);
  201702. png_save_uint_16(buf + 2, back->green);
  201703. png_save_uint_16(buf + 4, back->blue);
  201704. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201705. {
  201706. png_warning(png_ptr,
  201707. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201708. return;
  201709. }
  201710. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201711. }
  201712. else
  201713. {
  201714. if(back->gray >= (1 << png_ptr->bit_depth))
  201715. {
  201716. png_warning(png_ptr,
  201717. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201718. return;
  201719. }
  201720. png_save_uint_16(buf, back->gray);
  201721. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201722. }
  201723. }
  201724. #endif
  201725. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201726. /* write the histogram */
  201727. void /* PRIVATE */
  201728. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201729. {
  201730. #ifdef PNG_USE_LOCAL_ARRAYS
  201731. PNG_hIST;
  201732. #endif
  201733. int i;
  201734. png_byte buf[3];
  201735. png_debug(1, "in png_write_hIST\n");
  201736. if (num_hist > (int)png_ptr->num_palette)
  201737. {
  201738. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201739. png_ptr->num_palette);
  201740. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201741. return;
  201742. }
  201743. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201744. for (i = 0; i < num_hist; i++)
  201745. {
  201746. png_save_uint_16(buf, hist[i]);
  201747. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201748. }
  201749. png_write_chunk_end(png_ptr);
  201750. }
  201751. #endif
  201752. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201753. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201754. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201755. * and if invalid, correct the keyword rather than discarding the entire
  201756. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201757. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201758. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201759. *
  201760. * The new_key is allocated to hold the corrected keyword and must be freed
  201761. * by the calling routine. This avoids problems with trying to write to
  201762. * static keywords without having to have duplicate copies of the strings.
  201763. */
  201764. png_size_t /* PRIVATE */
  201765. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201766. {
  201767. png_size_t key_len;
  201768. png_charp kp, dp;
  201769. int kflag;
  201770. int kwarn=0;
  201771. png_debug(1, "in png_check_keyword\n");
  201772. *new_key = NULL;
  201773. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201774. {
  201775. png_warning(png_ptr, "zero length keyword");
  201776. return ((png_size_t)0);
  201777. }
  201778. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201779. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201780. if (*new_key == NULL)
  201781. {
  201782. png_warning(png_ptr, "Out of memory while procesing keyword");
  201783. return ((png_size_t)0);
  201784. }
  201785. /* Replace non-printing characters with a blank and print a warning */
  201786. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201787. {
  201788. if ((png_byte)*kp < 0x20 ||
  201789. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201790. {
  201791. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201792. char msg[40];
  201793. png_snprintf(msg, 40,
  201794. "invalid keyword character 0x%02X", (png_byte)*kp);
  201795. png_warning(png_ptr, msg);
  201796. #else
  201797. png_warning(png_ptr, "invalid character in keyword");
  201798. #endif
  201799. *dp = ' ';
  201800. }
  201801. else
  201802. {
  201803. *dp = *kp;
  201804. }
  201805. }
  201806. *dp = '\0';
  201807. /* Remove any trailing white space. */
  201808. kp = *new_key + key_len - 1;
  201809. if (*kp == ' ')
  201810. {
  201811. png_warning(png_ptr, "trailing spaces removed from keyword");
  201812. while (*kp == ' ')
  201813. {
  201814. *(kp--) = '\0';
  201815. key_len--;
  201816. }
  201817. }
  201818. /* Remove any leading white space. */
  201819. kp = *new_key;
  201820. if (*kp == ' ')
  201821. {
  201822. png_warning(png_ptr, "leading spaces removed from keyword");
  201823. while (*kp == ' ')
  201824. {
  201825. kp++;
  201826. key_len--;
  201827. }
  201828. }
  201829. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201830. /* Remove multiple internal spaces. */
  201831. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201832. {
  201833. if (*kp == ' ' && kflag == 0)
  201834. {
  201835. *(dp++) = *kp;
  201836. kflag = 1;
  201837. }
  201838. else if (*kp == ' ')
  201839. {
  201840. key_len--;
  201841. kwarn=1;
  201842. }
  201843. else
  201844. {
  201845. *(dp++) = *kp;
  201846. kflag = 0;
  201847. }
  201848. }
  201849. *dp = '\0';
  201850. if(kwarn)
  201851. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201852. if (key_len == 0)
  201853. {
  201854. png_free(png_ptr, *new_key);
  201855. *new_key=NULL;
  201856. png_warning(png_ptr, "Zero length keyword");
  201857. }
  201858. if (key_len > 79)
  201859. {
  201860. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201861. new_key[79] = '\0';
  201862. key_len = 79;
  201863. }
  201864. return (key_len);
  201865. }
  201866. #endif
  201867. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201868. /* write a tEXt chunk */
  201869. void /* PRIVATE */
  201870. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201871. png_size_t text_len)
  201872. {
  201873. #ifdef PNG_USE_LOCAL_ARRAYS
  201874. PNG_tEXt;
  201875. #endif
  201876. png_size_t key_len;
  201877. png_charp new_key;
  201878. png_debug(1, "in png_write_tEXt\n");
  201879. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201880. {
  201881. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201882. return;
  201883. }
  201884. if (text == NULL || *text == '\0')
  201885. text_len = 0;
  201886. else
  201887. text_len = png_strlen(text);
  201888. /* make sure we include the 0 after the key */
  201889. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201890. /*
  201891. * We leave it to the application to meet PNG-1.0 requirements on the
  201892. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201893. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201894. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201895. */
  201896. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201897. if (text_len)
  201898. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201899. png_write_chunk_end(png_ptr);
  201900. png_free(png_ptr, new_key);
  201901. }
  201902. #endif
  201903. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201904. /* write a compressed text chunk */
  201905. void /* PRIVATE */
  201906. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201907. png_size_t text_len, int compression)
  201908. {
  201909. #ifdef PNG_USE_LOCAL_ARRAYS
  201910. PNG_zTXt;
  201911. #endif
  201912. png_size_t key_len;
  201913. char buf[1];
  201914. png_charp new_key;
  201915. compression_state comp;
  201916. png_debug(1, "in png_write_zTXt\n");
  201917. comp.num_output_ptr = 0;
  201918. comp.max_output_ptr = 0;
  201919. comp.output_ptr = NULL;
  201920. comp.input = NULL;
  201921. comp.input_len = 0;
  201922. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201923. {
  201924. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201925. return;
  201926. }
  201927. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201928. {
  201929. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201930. png_free(png_ptr, new_key);
  201931. return;
  201932. }
  201933. text_len = png_strlen(text);
  201934. /* compute the compressed data; do it now for the length */
  201935. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201936. &comp);
  201937. /* write start of chunk */
  201938. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201939. (key_len+text_len+2));
  201940. /* write key */
  201941. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201942. png_free(png_ptr, new_key);
  201943. buf[0] = (png_byte)compression;
  201944. /* write compression */
  201945. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201946. /* write the compressed data */
  201947. png_write_compressed_data_out(png_ptr, &comp);
  201948. /* close the chunk */
  201949. png_write_chunk_end(png_ptr);
  201950. }
  201951. #endif
  201952. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201953. /* write an iTXt chunk */
  201954. void /* PRIVATE */
  201955. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201956. png_charp lang, png_charp lang_key, png_charp text)
  201957. {
  201958. #ifdef PNG_USE_LOCAL_ARRAYS
  201959. PNG_iTXt;
  201960. #endif
  201961. png_size_t lang_len, key_len, lang_key_len, text_len;
  201962. png_charp new_lang, new_key;
  201963. png_byte cbuf[2];
  201964. compression_state comp;
  201965. png_debug(1, "in png_write_iTXt\n");
  201966. comp.num_output_ptr = 0;
  201967. comp.max_output_ptr = 0;
  201968. comp.output_ptr = NULL;
  201969. comp.input = NULL;
  201970. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201971. {
  201972. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201973. return;
  201974. }
  201975. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201976. {
  201977. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201978. new_lang = NULL;
  201979. lang_len = 0;
  201980. }
  201981. if (lang_key == NULL)
  201982. lang_key_len = 0;
  201983. else
  201984. lang_key_len = png_strlen(lang_key);
  201985. if (text == NULL)
  201986. text_len = 0;
  201987. else
  201988. text_len = png_strlen(text);
  201989. /* compute the compressed data; do it now for the length */
  201990. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201991. &comp);
  201992. /* make sure we include the compression flag, the compression byte,
  201993. * and the NULs after the key, lang, and lang_key parts */
  201994. png_write_chunk_start(png_ptr, png_iTXt,
  201995. (png_uint_32)(
  201996. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201997. + key_len
  201998. + lang_len
  201999. + lang_key_len
  202000. + text_len));
  202001. /*
  202002. * We leave it to the application to meet PNG-1.0 requirements on the
  202003. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202004. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202005. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202006. */
  202007. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202008. /* set the compression flag */
  202009. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202010. compression == PNG_TEXT_COMPRESSION_NONE)
  202011. cbuf[0] = 0;
  202012. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202013. cbuf[0] = 1;
  202014. /* set the compression method */
  202015. cbuf[1] = 0;
  202016. png_write_chunk_data(png_ptr, cbuf, 2);
  202017. cbuf[0] = 0;
  202018. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202019. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202020. png_write_compressed_data_out(png_ptr, &comp);
  202021. png_write_chunk_end(png_ptr);
  202022. png_free(png_ptr, new_key);
  202023. if (new_lang)
  202024. png_free(png_ptr, new_lang);
  202025. }
  202026. #endif
  202027. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202028. /* write the oFFs chunk */
  202029. void /* PRIVATE */
  202030. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202031. int unit_type)
  202032. {
  202033. #ifdef PNG_USE_LOCAL_ARRAYS
  202034. PNG_oFFs;
  202035. #endif
  202036. png_byte buf[9];
  202037. png_debug(1, "in png_write_oFFs\n");
  202038. if (unit_type >= PNG_OFFSET_LAST)
  202039. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202040. png_save_int_32(buf, x_offset);
  202041. png_save_int_32(buf + 4, y_offset);
  202042. buf[8] = (png_byte)unit_type;
  202043. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202044. }
  202045. #endif
  202046. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202047. /* write the pCAL chunk (described in the PNG extensions document) */
  202048. void /* PRIVATE */
  202049. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202050. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202051. {
  202052. #ifdef PNG_USE_LOCAL_ARRAYS
  202053. PNG_pCAL;
  202054. #endif
  202055. png_size_t purpose_len, units_len, total_len;
  202056. png_uint_32p params_len;
  202057. png_byte buf[10];
  202058. png_charp new_purpose;
  202059. int i;
  202060. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202061. if (type >= PNG_EQUATION_LAST)
  202062. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202063. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202064. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202065. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202066. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202067. total_len = purpose_len + units_len + 10;
  202068. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202069. *png_sizeof(png_uint_32)));
  202070. /* Find the length of each parameter, making sure we don't count the
  202071. null terminator for the last parameter. */
  202072. for (i = 0; i < nparams; i++)
  202073. {
  202074. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202075. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202076. total_len += (png_size_t)params_len[i];
  202077. }
  202078. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202079. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202080. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202081. png_save_int_32(buf, X0);
  202082. png_save_int_32(buf + 4, X1);
  202083. buf[8] = (png_byte)type;
  202084. buf[9] = (png_byte)nparams;
  202085. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202086. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202087. png_free(png_ptr, new_purpose);
  202088. for (i = 0; i < nparams; i++)
  202089. {
  202090. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202091. (png_size_t)params_len[i]);
  202092. }
  202093. png_free(png_ptr, params_len);
  202094. png_write_chunk_end(png_ptr);
  202095. }
  202096. #endif
  202097. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202098. /* write the sCAL chunk */
  202099. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202100. void /* PRIVATE */
  202101. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202102. {
  202103. #ifdef PNG_USE_LOCAL_ARRAYS
  202104. PNG_sCAL;
  202105. #endif
  202106. char buf[64];
  202107. png_size_t total_len;
  202108. png_debug(1, "in png_write_sCAL\n");
  202109. buf[0] = (char)unit;
  202110. #if defined(_WIN32_WCE)
  202111. /* sprintf() function is not supported on WindowsCE */
  202112. {
  202113. wchar_t wc_buf[32];
  202114. size_t wc_len;
  202115. swprintf(wc_buf, TEXT("%12.12e"), width);
  202116. wc_len = wcslen(wc_buf);
  202117. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202118. total_len = wc_len + 2;
  202119. swprintf(wc_buf, TEXT("%12.12e"), height);
  202120. wc_len = wcslen(wc_buf);
  202121. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202122. NULL, NULL);
  202123. total_len += wc_len;
  202124. }
  202125. #else
  202126. png_snprintf(buf + 1, 63, "%12.12e", width);
  202127. total_len = 1 + png_strlen(buf + 1) + 1;
  202128. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202129. total_len += png_strlen(buf + total_len);
  202130. #endif
  202131. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202132. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202133. }
  202134. #else
  202135. #ifdef PNG_FIXED_POINT_SUPPORTED
  202136. void /* PRIVATE */
  202137. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202138. png_charp height)
  202139. {
  202140. #ifdef PNG_USE_LOCAL_ARRAYS
  202141. PNG_sCAL;
  202142. #endif
  202143. png_byte buf[64];
  202144. png_size_t wlen, hlen, total_len;
  202145. png_debug(1, "in png_write_sCAL_s\n");
  202146. wlen = png_strlen(width);
  202147. hlen = png_strlen(height);
  202148. total_len = wlen + hlen + 2;
  202149. if (total_len > 64)
  202150. {
  202151. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202152. return;
  202153. }
  202154. buf[0] = (png_byte)unit;
  202155. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202156. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202157. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202158. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202159. }
  202160. #endif
  202161. #endif
  202162. #endif
  202163. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202164. /* write the pHYs chunk */
  202165. void /* PRIVATE */
  202166. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202167. png_uint_32 y_pixels_per_unit,
  202168. int unit_type)
  202169. {
  202170. #ifdef PNG_USE_LOCAL_ARRAYS
  202171. PNG_pHYs;
  202172. #endif
  202173. png_byte buf[9];
  202174. png_debug(1, "in png_write_pHYs\n");
  202175. if (unit_type >= PNG_RESOLUTION_LAST)
  202176. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202177. png_save_uint_32(buf, x_pixels_per_unit);
  202178. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202179. buf[8] = (png_byte)unit_type;
  202180. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202181. }
  202182. #endif
  202183. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202184. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202185. * or png_convert_from_time_t(), or fill in the structure yourself.
  202186. */
  202187. void /* PRIVATE */
  202188. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202189. {
  202190. #ifdef PNG_USE_LOCAL_ARRAYS
  202191. PNG_tIME;
  202192. #endif
  202193. png_byte buf[7];
  202194. png_debug(1, "in png_write_tIME\n");
  202195. if (mod_time->month > 12 || mod_time->month < 1 ||
  202196. mod_time->day > 31 || mod_time->day < 1 ||
  202197. mod_time->hour > 23 || mod_time->second > 60)
  202198. {
  202199. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202200. return;
  202201. }
  202202. png_save_uint_16(buf, mod_time->year);
  202203. buf[2] = mod_time->month;
  202204. buf[3] = mod_time->day;
  202205. buf[4] = mod_time->hour;
  202206. buf[5] = mod_time->minute;
  202207. buf[6] = mod_time->second;
  202208. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202209. }
  202210. #endif
  202211. /* initializes the row writing capability of libpng */
  202212. void /* PRIVATE */
  202213. png_write_start_row(png_structp png_ptr)
  202214. {
  202215. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202216. #ifdef PNG_USE_LOCAL_ARRAYS
  202217. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202218. /* start of interlace block */
  202219. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202220. /* offset to next interlace block */
  202221. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202222. /* start of interlace block in the y direction */
  202223. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202224. /* offset to next interlace block in the y direction */
  202225. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202226. #endif
  202227. #endif
  202228. png_size_t buf_size;
  202229. png_debug(1, "in png_write_start_row\n");
  202230. buf_size = (png_size_t)(PNG_ROWBYTES(
  202231. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202232. /* set up row buffer */
  202233. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202234. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202235. #ifndef PNG_NO_WRITE_FILTERING
  202236. /* set up filtering buffer, if using this filter */
  202237. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202238. {
  202239. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202240. (png_ptr->rowbytes + 1));
  202241. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202242. }
  202243. /* We only need to keep the previous row if we are using one of these. */
  202244. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202245. {
  202246. /* set up previous row buffer */
  202247. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202248. png_memset(png_ptr->prev_row, 0, buf_size);
  202249. if (png_ptr->do_filter & PNG_FILTER_UP)
  202250. {
  202251. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202252. (png_ptr->rowbytes + 1));
  202253. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202254. }
  202255. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202256. {
  202257. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202258. (png_ptr->rowbytes + 1));
  202259. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202260. }
  202261. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202262. {
  202263. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202264. (png_ptr->rowbytes + 1));
  202265. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202266. }
  202267. #endif /* PNG_NO_WRITE_FILTERING */
  202268. }
  202269. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202270. /* if interlaced, we need to set up width and height of pass */
  202271. if (png_ptr->interlaced)
  202272. {
  202273. if (!(png_ptr->transformations & PNG_INTERLACE))
  202274. {
  202275. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202276. png_pass_ystart[0]) / png_pass_yinc[0];
  202277. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202278. png_pass_start[0]) / png_pass_inc[0];
  202279. }
  202280. else
  202281. {
  202282. png_ptr->num_rows = png_ptr->height;
  202283. png_ptr->usr_width = png_ptr->width;
  202284. }
  202285. }
  202286. else
  202287. #endif
  202288. {
  202289. png_ptr->num_rows = png_ptr->height;
  202290. png_ptr->usr_width = png_ptr->width;
  202291. }
  202292. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202293. png_ptr->zstream.next_out = png_ptr->zbuf;
  202294. }
  202295. /* Internal use only. Called when finished processing a row of data. */
  202296. void /* PRIVATE */
  202297. png_write_finish_row(png_structp png_ptr)
  202298. {
  202299. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202300. #ifdef PNG_USE_LOCAL_ARRAYS
  202301. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202302. /* start of interlace block */
  202303. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202304. /* offset to next interlace block */
  202305. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202306. /* start of interlace block in the y direction */
  202307. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202308. /* offset to next interlace block in the y direction */
  202309. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202310. #endif
  202311. #endif
  202312. int ret;
  202313. png_debug(1, "in png_write_finish_row\n");
  202314. /* next row */
  202315. png_ptr->row_number++;
  202316. /* see if we are done */
  202317. if (png_ptr->row_number < png_ptr->num_rows)
  202318. return;
  202319. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202320. /* if interlaced, go to next pass */
  202321. if (png_ptr->interlaced)
  202322. {
  202323. png_ptr->row_number = 0;
  202324. if (png_ptr->transformations & PNG_INTERLACE)
  202325. {
  202326. png_ptr->pass++;
  202327. }
  202328. else
  202329. {
  202330. /* loop until we find a non-zero width or height pass */
  202331. do
  202332. {
  202333. png_ptr->pass++;
  202334. if (png_ptr->pass >= 7)
  202335. break;
  202336. png_ptr->usr_width = (png_ptr->width +
  202337. png_pass_inc[png_ptr->pass] - 1 -
  202338. png_pass_start[png_ptr->pass]) /
  202339. png_pass_inc[png_ptr->pass];
  202340. png_ptr->num_rows = (png_ptr->height +
  202341. png_pass_yinc[png_ptr->pass] - 1 -
  202342. png_pass_ystart[png_ptr->pass]) /
  202343. png_pass_yinc[png_ptr->pass];
  202344. if (png_ptr->transformations & PNG_INTERLACE)
  202345. break;
  202346. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202347. }
  202348. /* reset the row above the image for the next pass */
  202349. if (png_ptr->pass < 7)
  202350. {
  202351. if (png_ptr->prev_row != NULL)
  202352. png_memset(png_ptr->prev_row, 0,
  202353. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202354. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202355. return;
  202356. }
  202357. }
  202358. #endif
  202359. /* if we get here, we've just written the last row, so we need
  202360. to flush the compressor */
  202361. do
  202362. {
  202363. /* tell the compressor we are done */
  202364. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202365. /* check for an error */
  202366. if (ret == Z_OK)
  202367. {
  202368. /* check to see if we need more room */
  202369. if (!(png_ptr->zstream.avail_out))
  202370. {
  202371. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202372. png_ptr->zstream.next_out = png_ptr->zbuf;
  202373. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202374. }
  202375. }
  202376. else if (ret != Z_STREAM_END)
  202377. {
  202378. if (png_ptr->zstream.msg != NULL)
  202379. png_error(png_ptr, png_ptr->zstream.msg);
  202380. else
  202381. png_error(png_ptr, "zlib error");
  202382. }
  202383. } while (ret != Z_STREAM_END);
  202384. /* write any extra space */
  202385. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202386. {
  202387. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202388. png_ptr->zstream.avail_out);
  202389. }
  202390. deflateReset(&png_ptr->zstream);
  202391. png_ptr->zstream.data_type = Z_BINARY;
  202392. }
  202393. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202394. /* Pick out the correct pixels for the interlace pass.
  202395. * The basic idea here is to go through the row with a source
  202396. * pointer and a destination pointer (sp and dp), and copy the
  202397. * correct pixels for the pass. As the row gets compacted,
  202398. * sp will always be >= dp, so we should never overwrite anything.
  202399. * See the default: case for the easiest code to understand.
  202400. */
  202401. void /* PRIVATE */
  202402. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202403. {
  202404. #ifdef PNG_USE_LOCAL_ARRAYS
  202405. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202406. /* start of interlace block */
  202407. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202408. /* offset to next interlace block */
  202409. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202410. #endif
  202411. png_debug(1, "in png_do_write_interlace\n");
  202412. /* we don't have to do anything on the last pass (6) */
  202413. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202414. if (row != NULL && row_info != NULL && pass < 6)
  202415. #else
  202416. if (pass < 6)
  202417. #endif
  202418. {
  202419. /* each pixel depth is handled separately */
  202420. switch (row_info->pixel_depth)
  202421. {
  202422. case 1:
  202423. {
  202424. png_bytep sp;
  202425. png_bytep dp;
  202426. int shift;
  202427. int d;
  202428. int value;
  202429. png_uint_32 i;
  202430. png_uint_32 row_width = row_info->width;
  202431. dp = row;
  202432. d = 0;
  202433. shift = 7;
  202434. for (i = png_pass_start[pass]; i < row_width;
  202435. i += png_pass_inc[pass])
  202436. {
  202437. sp = row + (png_size_t)(i >> 3);
  202438. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202439. d |= (value << shift);
  202440. if (shift == 0)
  202441. {
  202442. shift = 7;
  202443. *dp++ = (png_byte)d;
  202444. d = 0;
  202445. }
  202446. else
  202447. shift--;
  202448. }
  202449. if (shift != 7)
  202450. *dp = (png_byte)d;
  202451. break;
  202452. }
  202453. case 2:
  202454. {
  202455. png_bytep sp;
  202456. png_bytep dp;
  202457. int shift;
  202458. int d;
  202459. int value;
  202460. png_uint_32 i;
  202461. png_uint_32 row_width = row_info->width;
  202462. dp = row;
  202463. shift = 6;
  202464. d = 0;
  202465. for (i = png_pass_start[pass]; i < row_width;
  202466. i += png_pass_inc[pass])
  202467. {
  202468. sp = row + (png_size_t)(i >> 2);
  202469. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202470. d |= (value << shift);
  202471. if (shift == 0)
  202472. {
  202473. shift = 6;
  202474. *dp++ = (png_byte)d;
  202475. d = 0;
  202476. }
  202477. else
  202478. shift -= 2;
  202479. }
  202480. if (shift != 6)
  202481. *dp = (png_byte)d;
  202482. break;
  202483. }
  202484. case 4:
  202485. {
  202486. png_bytep sp;
  202487. png_bytep dp;
  202488. int shift;
  202489. int d;
  202490. int value;
  202491. png_uint_32 i;
  202492. png_uint_32 row_width = row_info->width;
  202493. dp = row;
  202494. shift = 4;
  202495. d = 0;
  202496. for (i = png_pass_start[pass]; i < row_width;
  202497. i += png_pass_inc[pass])
  202498. {
  202499. sp = row + (png_size_t)(i >> 1);
  202500. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202501. d |= (value << shift);
  202502. if (shift == 0)
  202503. {
  202504. shift = 4;
  202505. *dp++ = (png_byte)d;
  202506. d = 0;
  202507. }
  202508. else
  202509. shift -= 4;
  202510. }
  202511. if (shift != 4)
  202512. *dp = (png_byte)d;
  202513. break;
  202514. }
  202515. default:
  202516. {
  202517. png_bytep sp;
  202518. png_bytep dp;
  202519. png_uint_32 i;
  202520. png_uint_32 row_width = row_info->width;
  202521. png_size_t pixel_bytes;
  202522. /* start at the beginning */
  202523. dp = row;
  202524. /* find out how many bytes each pixel takes up */
  202525. pixel_bytes = (row_info->pixel_depth >> 3);
  202526. /* loop through the row, only looking at the pixels that
  202527. matter */
  202528. for (i = png_pass_start[pass]; i < row_width;
  202529. i += png_pass_inc[pass])
  202530. {
  202531. /* find out where the original pixel is */
  202532. sp = row + (png_size_t)i * pixel_bytes;
  202533. /* move the pixel */
  202534. if (dp != sp)
  202535. png_memcpy(dp, sp, pixel_bytes);
  202536. /* next pixel */
  202537. dp += pixel_bytes;
  202538. }
  202539. break;
  202540. }
  202541. }
  202542. /* set new row width */
  202543. row_info->width = (row_info->width +
  202544. png_pass_inc[pass] - 1 -
  202545. png_pass_start[pass]) /
  202546. png_pass_inc[pass];
  202547. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202548. row_info->width);
  202549. }
  202550. }
  202551. #endif
  202552. /* This filters the row, chooses which filter to use, if it has not already
  202553. * been specified by the application, and then writes the row out with the
  202554. * chosen filter.
  202555. */
  202556. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202557. #define PNG_HISHIFT 10
  202558. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202559. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202560. void /* PRIVATE */
  202561. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202562. {
  202563. png_bytep best_row;
  202564. #ifndef PNG_NO_WRITE_FILTER
  202565. png_bytep prev_row, row_buf;
  202566. png_uint_32 mins, bpp;
  202567. png_byte filter_to_do = png_ptr->do_filter;
  202568. png_uint_32 row_bytes = row_info->rowbytes;
  202569. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202570. int num_p_filters = (int)png_ptr->num_prev_filters;
  202571. #endif
  202572. png_debug(1, "in png_write_find_filter\n");
  202573. /* find out how many bytes offset each pixel is */
  202574. bpp = (row_info->pixel_depth + 7) >> 3;
  202575. prev_row = png_ptr->prev_row;
  202576. #endif
  202577. best_row = png_ptr->row_buf;
  202578. #ifndef PNG_NO_WRITE_FILTER
  202579. row_buf = best_row;
  202580. mins = PNG_MAXSUM;
  202581. /* The prediction method we use is to find which method provides the
  202582. * smallest value when summing the absolute values of the distances
  202583. * from zero, using anything >= 128 as negative numbers. This is known
  202584. * as the "minimum sum of absolute differences" heuristic. Other
  202585. * heuristics are the "weighted minimum sum of absolute differences"
  202586. * (experimental and can in theory improve compression), and the "zlib
  202587. * predictive" method (not implemented yet), which does test compressions
  202588. * of lines using different filter methods, and then chooses the
  202589. * (series of) filter(s) that give minimum compressed data size (VERY
  202590. * computationally expensive).
  202591. *
  202592. * GRR 980525: consider also
  202593. * (1) minimum sum of absolute differences from running average (i.e.,
  202594. * keep running sum of non-absolute differences & count of bytes)
  202595. * [track dispersion, too? restart average if dispersion too large?]
  202596. * (1b) minimum sum of absolute differences from sliding average, probably
  202597. * with window size <= deflate window (usually 32K)
  202598. * (2) minimum sum of squared differences from zero or running average
  202599. * (i.e., ~ root-mean-square approach)
  202600. */
  202601. /* We don't need to test the 'no filter' case if this is the only filter
  202602. * that has been chosen, as it doesn't actually do anything to the data.
  202603. */
  202604. if ((filter_to_do & PNG_FILTER_NONE) &&
  202605. filter_to_do != PNG_FILTER_NONE)
  202606. {
  202607. png_bytep rp;
  202608. png_uint_32 sum = 0;
  202609. png_uint_32 i;
  202610. int v;
  202611. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202612. {
  202613. v = *rp;
  202614. sum += (v < 128) ? v : 256 - v;
  202615. }
  202616. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202617. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202618. {
  202619. png_uint_32 sumhi, sumlo;
  202620. int j;
  202621. sumlo = sum & PNG_LOMASK;
  202622. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202623. /* Reduce the sum if we match any of the previous rows */
  202624. for (j = 0; j < num_p_filters; j++)
  202625. {
  202626. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202627. {
  202628. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202629. PNG_WEIGHT_SHIFT;
  202630. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202631. PNG_WEIGHT_SHIFT;
  202632. }
  202633. }
  202634. /* Factor in the cost of this filter (this is here for completeness,
  202635. * but it makes no sense to have a "cost" for the NONE filter, as
  202636. * it has the minimum possible computational cost - none).
  202637. */
  202638. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202639. PNG_COST_SHIFT;
  202640. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202641. PNG_COST_SHIFT;
  202642. if (sumhi > PNG_HIMASK)
  202643. sum = PNG_MAXSUM;
  202644. else
  202645. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202646. }
  202647. #endif
  202648. mins = sum;
  202649. }
  202650. /* sub filter */
  202651. if (filter_to_do == PNG_FILTER_SUB)
  202652. /* it's the only filter so no testing is needed */
  202653. {
  202654. png_bytep rp, lp, dp;
  202655. png_uint_32 i;
  202656. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202657. i++, rp++, dp++)
  202658. {
  202659. *dp = *rp;
  202660. }
  202661. for (lp = row_buf + 1; i < row_bytes;
  202662. i++, rp++, lp++, dp++)
  202663. {
  202664. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202665. }
  202666. best_row = png_ptr->sub_row;
  202667. }
  202668. else if (filter_to_do & PNG_FILTER_SUB)
  202669. {
  202670. png_bytep rp, dp, lp;
  202671. png_uint_32 sum = 0, lmins = mins;
  202672. png_uint_32 i;
  202673. int v;
  202674. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202675. /* We temporarily increase the "minimum sum" by the factor we
  202676. * would reduce the sum of this filter, so that we can do the
  202677. * early exit comparison without scaling the sum each time.
  202678. */
  202679. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202680. {
  202681. int j;
  202682. png_uint_32 lmhi, lmlo;
  202683. lmlo = lmins & PNG_LOMASK;
  202684. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202685. for (j = 0; j < num_p_filters; j++)
  202686. {
  202687. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202688. {
  202689. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202690. PNG_WEIGHT_SHIFT;
  202691. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202692. PNG_WEIGHT_SHIFT;
  202693. }
  202694. }
  202695. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202696. PNG_COST_SHIFT;
  202697. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202698. PNG_COST_SHIFT;
  202699. if (lmhi > PNG_HIMASK)
  202700. lmins = PNG_MAXSUM;
  202701. else
  202702. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202703. }
  202704. #endif
  202705. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202706. i++, rp++, dp++)
  202707. {
  202708. v = *dp = *rp;
  202709. sum += (v < 128) ? v : 256 - v;
  202710. }
  202711. for (lp = row_buf + 1; i < row_bytes;
  202712. i++, rp++, lp++, dp++)
  202713. {
  202714. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202715. sum += (v < 128) ? v : 256 - v;
  202716. if (sum > lmins) /* We are already worse, don't continue. */
  202717. break;
  202718. }
  202719. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202720. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202721. {
  202722. int j;
  202723. png_uint_32 sumhi, sumlo;
  202724. sumlo = sum & PNG_LOMASK;
  202725. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202726. for (j = 0; j < num_p_filters; j++)
  202727. {
  202728. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202729. {
  202730. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202731. PNG_WEIGHT_SHIFT;
  202732. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202733. PNG_WEIGHT_SHIFT;
  202734. }
  202735. }
  202736. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202737. PNG_COST_SHIFT;
  202738. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202739. PNG_COST_SHIFT;
  202740. if (sumhi > PNG_HIMASK)
  202741. sum = PNG_MAXSUM;
  202742. else
  202743. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202744. }
  202745. #endif
  202746. if (sum < mins)
  202747. {
  202748. mins = sum;
  202749. best_row = png_ptr->sub_row;
  202750. }
  202751. }
  202752. /* up filter */
  202753. if (filter_to_do == PNG_FILTER_UP)
  202754. {
  202755. png_bytep rp, dp, pp;
  202756. png_uint_32 i;
  202757. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202758. pp = prev_row + 1; i < row_bytes;
  202759. i++, rp++, pp++, dp++)
  202760. {
  202761. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202762. }
  202763. best_row = png_ptr->up_row;
  202764. }
  202765. else if (filter_to_do & PNG_FILTER_UP)
  202766. {
  202767. png_bytep rp, dp, pp;
  202768. png_uint_32 sum = 0, lmins = mins;
  202769. png_uint_32 i;
  202770. int v;
  202771. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202772. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202773. {
  202774. int j;
  202775. png_uint_32 lmhi, lmlo;
  202776. lmlo = lmins & PNG_LOMASK;
  202777. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202778. for (j = 0; j < num_p_filters; j++)
  202779. {
  202780. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202781. {
  202782. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202783. PNG_WEIGHT_SHIFT;
  202784. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202785. PNG_WEIGHT_SHIFT;
  202786. }
  202787. }
  202788. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202789. PNG_COST_SHIFT;
  202790. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202791. PNG_COST_SHIFT;
  202792. if (lmhi > PNG_HIMASK)
  202793. lmins = PNG_MAXSUM;
  202794. else
  202795. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202796. }
  202797. #endif
  202798. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202799. pp = prev_row + 1; i < row_bytes; i++)
  202800. {
  202801. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202802. sum += (v < 128) ? v : 256 - v;
  202803. if (sum > lmins) /* We are already worse, don't continue. */
  202804. break;
  202805. }
  202806. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202807. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202808. {
  202809. int j;
  202810. png_uint_32 sumhi, sumlo;
  202811. sumlo = sum & PNG_LOMASK;
  202812. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202813. for (j = 0; j < num_p_filters; j++)
  202814. {
  202815. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202816. {
  202817. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202818. PNG_WEIGHT_SHIFT;
  202819. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202820. PNG_WEIGHT_SHIFT;
  202821. }
  202822. }
  202823. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202824. PNG_COST_SHIFT;
  202825. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202826. PNG_COST_SHIFT;
  202827. if (sumhi > PNG_HIMASK)
  202828. sum = PNG_MAXSUM;
  202829. else
  202830. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202831. }
  202832. #endif
  202833. if (sum < mins)
  202834. {
  202835. mins = sum;
  202836. best_row = png_ptr->up_row;
  202837. }
  202838. }
  202839. /* avg filter */
  202840. if (filter_to_do == PNG_FILTER_AVG)
  202841. {
  202842. png_bytep rp, dp, pp, lp;
  202843. png_uint_32 i;
  202844. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202845. pp = prev_row + 1; i < bpp; i++)
  202846. {
  202847. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202848. }
  202849. for (lp = row_buf + 1; i < row_bytes; i++)
  202850. {
  202851. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202852. & 0xff);
  202853. }
  202854. best_row = png_ptr->avg_row;
  202855. }
  202856. else if (filter_to_do & PNG_FILTER_AVG)
  202857. {
  202858. png_bytep rp, dp, pp, lp;
  202859. png_uint_32 sum = 0, lmins = mins;
  202860. png_uint_32 i;
  202861. int v;
  202862. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202863. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202864. {
  202865. int j;
  202866. png_uint_32 lmhi, lmlo;
  202867. lmlo = lmins & PNG_LOMASK;
  202868. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202869. for (j = 0; j < num_p_filters; j++)
  202870. {
  202871. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202872. {
  202873. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202874. PNG_WEIGHT_SHIFT;
  202875. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202876. PNG_WEIGHT_SHIFT;
  202877. }
  202878. }
  202879. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202880. PNG_COST_SHIFT;
  202881. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202882. PNG_COST_SHIFT;
  202883. if (lmhi > PNG_HIMASK)
  202884. lmins = PNG_MAXSUM;
  202885. else
  202886. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202887. }
  202888. #endif
  202889. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202890. pp = prev_row + 1; i < bpp; i++)
  202891. {
  202892. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202893. sum += (v < 128) ? v : 256 - v;
  202894. }
  202895. for (lp = row_buf + 1; i < row_bytes; i++)
  202896. {
  202897. v = *dp++ =
  202898. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202899. sum += (v < 128) ? v : 256 - v;
  202900. if (sum > lmins) /* We are already worse, don't continue. */
  202901. break;
  202902. }
  202903. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202904. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202905. {
  202906. int j;
  202907. png_uint_32 sumhi, sumlo;
  202908. sumlo = sum & PNG_LOMASK;
  202909. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202910. for (j = 0; j < num_p_filters; j++)
  202911. {
  202912. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202913. {
  202914. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202915. PNG_WEIGHT_SHIFT;
  202916. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202917. PNG_WEIGHT_SHIFT;
  202918. }
  202919. }
  202920. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202921. PNG_COST_SHIFT;
  202922. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202923. PNG_COST_SHIFT;
  202924. if (sumhi > PNG_HIMASK)
  202925. sum = PNG_MAXSUM;
  202926. else
  202927. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202928. }
  202929. #endif
  202930. if (sum < mins)
  202931. {
  202932. mins = sum;
  202933. best_row = png_ptr->avg_row;
  202934. }
  202935. }
  202936. /* Paeth filter */
  202937. if (filter_to_do == PNG_FILTER_PAETH)
  202938. {
  202939. png_bytep rp, dp, pp, cp, lp;
  202940. png_uint_32 i;
  202941. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202942. pp = prev_row + 1; i < bpp; i++)
  202943. {
  202944. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202945. }
  202946. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202947. {
  202948. int a, b, c, pa, pb, pc, p;
  202949. b = *pp++;
  202950. c = *cp++;
  202951. a = *lp++;
  202952. p = b - c;
  202953. pc = a - c;
  202954. #ifdef PNG_USE_ABS
  202955. pa = abs(p);
  202956. pb = abs(pc);
  202957. pc = abs(p + pc);
  202958. #else
  202959. pa = p < 0 ? -p : p;
  202960. pb = pc < 0 ? -pc : pc;
  202961. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202962. #endif
  202963. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202964. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202965. }
  202966. best_row = png_ptr->paeth_row;
  202967. }
  202968. else if (filter_to_do & PNG_FILTER_PAETH)
  202969. {
  202970. png_bytep rp, dp, pp, cp, lp;
  202971. png_uint_32 sum = 0, lmins = mins;
  202972. png_uint_32 i;
  202973. int v;
  202974. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202975. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202976. {
  202977. int j;
  202978. png_uint_32 lmhi, lmlo;
  202979. lmlo = lmins & PNG_LOMASK;
  202980. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202981. for (j = 0; j < num_p_filters; j++)
  202982. {
  202983. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202984. {
  202985. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202986. PNG_WEIGHT_SHIFT;
  202987. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202988. PNG_WEIGHT_SHIFT;
  202989. }
  202990. }
  202991. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202992. PNG_COST_SHIFT;
  202993. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202994. PNG_COST_SHIFT;
  202995. if (lmhi > PNG_HIMASK)
  202996. lmins = PNG_MAXSUM;
  202997. else
  202998. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202999. }
  203000. #endif
  203001. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203002. pp = prev_row + 1; i < bpp; i++)
  203003. {
  203004. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203005. sum += (v < 128) ? v : 256 - v;
  203006. }
  203007. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203008. {
  203009. int a, b, c, pa, pb, pc, p;
  203010. b = *pp++;
  203011. c = *cp++;
  203012. a = *lp++;
  203013. #ifndef PNG_SLOW_PAETH
  203014. p = b - c;
  203015. pc = a - c;
  203016. #ifdef PNG_USE_ABS
  203017. pa = abs(p);
  203018. pb = abs(pc);
  203019. pc = abs(p + pc);
  203020. #else
  203021. pa = p < 0 ? -p : p;
  203022. pb = pc < 0 ? -pc : pc;
  203023. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203024. #endif
  203025. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203026. #else /* PNG_SLOW_PAETH */
  203027. p = a + b - c;
  203028. pa = abs(p - a);
  203029. pb = abs(p - b);
  203030. pc = abs(p - c);
  203031. if (pa <= pb && pa <= pc)
  203032. p = a;
  203033. else if (pb <= pc)
  203034. p = b;
  203035. else
  203036. p = c;
  203037. #endif /* PNG_SLOW_PAETH */
  203038. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203039. sum += (v < 128) ? v : 256 - v;
  203040. if (sum > lmins) /* We are already worse, don't continue. */
  203041. break;
  203042. }
  203043. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203044. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203045. {
  203046. int j;
  203047. png_uint_32 sumhi, sumlo;
  203048. sumlo = sum & PNG_LOMASK;
  203049. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203050. for (j = 0; j < num_p_filters; j++)
  203051. {
  203052. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203053. {
  203054. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203055. PNG_WEIGHT_SHIFT;
  203056. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203057. PNG_WEIGHT_SHIFT;
  203058. }
  203059. }
  203060. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203061. PNG_COST_SHIFT;
  203062. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203063. PNG_COST_SHIFT;
  203064. if (sumhi > PNG_HIMASK)
  203065. sum = PNG_MAXSUM;
  203066. else
  203067. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203068. }
  203069. #endif
  203070. if (sum < mins)
  203071. {
  203072. best_row = png_ptr->paeth_row;
  203073. }
  203074. }
  203075. #endif /* PNG_NO_WRITE_FILTER */
  203076. /* Do the actual writing of the filtered row data from the chosen filter. */
  203077. png_write_filtered_row(png_ptr, best_row);
  203078. #ifndef PNG_NO_WRITE_FILTER
  203079. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203080. /* Save the type of filter we picked this time for future calculations */
  203081. if (png_ptr->num_prev_filters > 0)
  203082. {
  203083. int j;
  203084. for (j = 1; j < num_p_filters; j++)
  203085. {
  203086. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203087. }
  203088. png_ptr->prev_filters[j] = best_row[0];
  203089. }
  203090. #endif
  203091. #endif /* PNG_NO_WRITE_FILTER */
  203092. }
  203093. /* Do the actual writing of a previously filtered row. */
  203094. void /* PRIVATE */
  203095. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203096. {
  203097. png_debug(1, "in png_write_filtered_row\n");
  203098. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203099. /* set up the zlib input buffer */
  203100. png_ptr->zstream.next_in = filtered_row;
  203101. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203102. /* repeat until we have compressed all the data */
  203103. do
  203104. {
  203105. int ret; /* return of zlib */
  203106. /* compress the data */
  203107. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203108. /* check for compression errors */
  203109. if (ret != Z_OK)
  203110. {
  203111. if (png_ptr->zstream.msg != NULL)
  203112. png_error(png_ptr, png_ptr->zstream.msg);
  203113. else
  203114. png_error(png_ptr, "zlib error");
  203115. }
  203116. /* see if it is time to write another IDAT */
  203117. if (!(png_ptr->zstream.avail_out))
  203118. {
  203119. /* write the IDAT and reset the zlib output buffer */
  203120. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203121. png_ptr->zstream.next_out = png_ptr->zbuf;
  203122. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203123. }
  203124. /* repeat until all data has been compressed */
  203125. } while (png_ptr->zstream.avail_in);
  203126. /* swap the current and previous rows */
  203127. if (png_ptr->prev_row != NULL)
  203128. {
  203129. png_bytep tptr;
  203130. tptr = png_ptr->prev_row;
  203131. png_ptr->prev_row = png_ptr->row_buf;
  203132. png_ptr->row_buf = tptr;
  203133. }
  203134. /* finish row - updates counters and flushes zlib if last row */
  203135. png_write_finish_row(png_ptr);
  203136. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203137. png_ptr->flush_rows++;
  203138. if (png_ptr->flush_dist > 0 &&
  203139. png_ptr->flush_rows >= png_ptr->flush_dist)
  203140. {
  203141. png_write_flush(png_ptr);
  203142. }
  203143. #endif
  203144. }
  203145. #endif /* PNG_WRITE_SUPPORTED */
  203146. /*** End of inlined file: pngwutil.c ***/
  203147. #else
  203148. extern "C"
  203149. {
  203150. #include <png.h>
  203151. #include <pngconf.h>
  203152. }
  203153. #endif
  203154. }
  203155. #undef max
  203156. #undef min
  203157. #if JUCE_MSVC
  203158. #pragma warning (pop)
  203159. #endif
  203160. BEGIN_JUCE_NAMESPACE
  203161. using ::calloc;
  203162. using ::malloc;
  203163. using ::free;
  203164. namespace PNGHelpers
  203165. {
  203166. using namespace pnglibNamespace;
  203167. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  203168. {
  203169. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203170. }
  203171. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203172. {
  203173. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203174. }
  203175. struct PNGErrorStruct {};
  203176. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203177. {
  203178. throw PNGErrorStruct();
  203179. }
  203180. }
  203181. PNGImageFormat::PNGImageFormat() {}
  203182. PNGImageFormat::~PNGImageFormat() {}
  203183. const String PNGImageFormat::getFormatName()
  203184. {
  203185. return "PNG";
  203186. }
  203187. bool PNGImageFormat::canUnderstand (InputStream& in)
  203188. {
  203189. const int bytesNeeded = 4;
  203190. char header [bytesNeeded];
  203191. return in.read (header, bytesNeeded) == bytesNeeded
  203192. && header[1] == 'P'
  203193. && header[2] == 'N'
  203194. && header[3] == 'G';
  203195. }
  203196. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203197. const Image juce_loadWithCoreImage (InputStream& input);
  203198. #endif
  203199. const Image PNGImageFormat::decodeImage (InputStream& in)
  203200. {
  203201. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203202. return juce_loadWithCoreImage (in);
  203203. #else
  203204. using namespace pnglibNamespace;
  203205. Image image;
  203206. png_structp pngReadStruct;
  203207. png_infop pngInfoStruct;
  203208. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203209. if (pngReadStruct != 0)
  203210. {
  203211. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203212. if (pngInfoStruct == 0)
  203213. {
  203214. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203215. return Image::null;
  203216. }
  203217. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203218. // read the header..
  203219. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203220. png_uint_32 width, height;
  203221. int bitDepth, colorType, interlaceType;
  203222. png_read_info (pngReadStruct, pngInfoStruct);
  203223. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203224. &width, &height,
  203225. &bitDepth, &colorType,
  203226. &interlaceType, 0, 0);
  203227. if (bitDepth == 16)
  203228. png_set_strip_16 (pngReadStruct);
  203229. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203230. png_set_expand (pngReadStruct);
  203231. if (bitDepth < 8)
  203232. png_set_expand (pngReadStruct);
  203233. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203234. png_set_expand (pngReadStruct);
  203235. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203236. png_set_gray_to_rgb (pngReadStruct);
  203237. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203238. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203239. || pngInfoStruct->num_trans > 0;
  203240. // Load the image into a temp buffer in the pnglib format..
  203241. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203242. {
  203243. HeapBlock <png_bytep> rows (height);
  203244. for (int y = (int) height; --y >= 0;)
  203245. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203246. png_read_image (pngReadStruct, rows);
  203247. png_read_end (pngReadStruct, pngInfoStruct);
  203248. }
  203249. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203250. // now convert the data to a juce image format..
  203251. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203252. (int) width, (int) height, hasAlphaChan);
  203253. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  203254. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203255. const Image::BitmapData destData (image, true);
  203256. uint8* srcRow = tempBuffer;
  203257. uint8* destRow = destData.data;
  203258. for (int y = 0; y < (int) height; ++y)
  203259. {
  203260. const uint8* src = srcRow;
  203261. srcRow += (width << 2);
  203262. uint8* dest = destRow;
  203263. destRow += destData.lineStride;
  203264. if (hasAlphaChan)
  203265. {
  203266. for (int i = (int) width; --i >= 0;)
  203267. {
  203268. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203269. ((PixelARGB*) dest)->premultiply();
  203270. dest += destData.pixelStride;
  203271. src += 4;
  203272. }
  203273. }
  203274. else
  203275. {
  203276. for (int i = (int) width; --i >= 0;)
  203277. {
  203278. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203279. dest += destData.pixelStride;
  203280. src += 4;
  203281. }
  203282. }
  203283. }
  203284. }
  203285. return image;
  203286. #endif
  203287. }
  203288. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203289. {
  203290. using namespace pnglibNamespace;
  203291. const int width = image.getWidth();
  203292. const int height = image.getHeight();
  203293. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203294. if (pngWriteStruct == 0)
  203295. return false;
  203296. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203297. if (pngInfoStruct == 0)
  203298. {
  203299. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203300. return false;
  203301. }
  203302. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203303. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203304. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203305. : PNG_COLOR_TYPE_RGB,
  203306. PNG_INTERLACE_NONE,
  203307. PNG_COMPRESSION_TYPE_BASE,
  203308. PNG_FILTER_TYPE_BASE);
  203309. HeapBlock <uint8> rowData (width * 4);
  203310. png_color_8 sig_bit;
  203311. sig_bit.red = 8;
  203312. sig_bit.green = 8;
  203313. sig_bit.blue = 8;
  203314. sig_bit.alpha = 8;
  203315. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203316. png_write_info (pngWriteStruct, pngInfoStruct);
  203317. png_set_shift (pngWriteStruct, &sig_bit);
  203318. png_set_packing (pngWriteStruct);
  203319. const Image::BitmapData srcData (image, false);
  203320. for (int y = 0; y < height; ++y)
  203321. {
  203322. uint8* dst = rowData;
  203323. const uint8* src = srcData.getLinePointer (y);
  203324. if (image.hasAlphaChannel())
  203325. {
  203326. for (int i = width; --i >= 0;)
  203327. {
  203328. PixelARGB p (*(const PixelARGB*) src);
  203329. p.unpremultiply();
  203330. *dst++ = p.getRed();
  203331. *dst++ = p.getGreen();
  203332. *dst++ = p.getBlue();
  203333. *dst++ = p.getAlpha();
  203334. src += srcData.pixelStride;
  203335. }
  203336. }
  203337. else
  203338. {
  203339. for (int i = width; --i >= 0;)
  203340. {
  203341. *dst++ = ((const PixelRGB*) src)->getRed();
  203342. *dst++ = ((const PixelRGB*) src)->getGreen();
  203343. *dst++ = ((const PixelRGB*) src)->getBlue();
  203344. src += srcData.pixelStride;
  203345. }
  203346. }
  203347. png_bytep rowPtr = rowData;
  203348. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203349. }
  203350. png_write_end (pngWriteStruct, pngInfoStruct);
  203351. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203352. out.flush();
  203353. return true;
  203354. }
  203355. END_JUCE_NAMESPACE
  203356. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203357. #endif
  203358. //==============================================================================
  203359. #if JUCE_BUILD_NATIVE
  203360. // Non-public headers that are needed by more than one platform must be included
  203361. // before the platform-specific sections..
  203362. BEGIN_JUCE_NAMESPACE
  203363. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203364. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203365. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203366. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203367. /**
  203368. Helper class that takes chunks of incoming midi bytes, packages them into
  203369. messages, and dispatches them to a midi callback.
  203370. */
  203371. class MidiDataConcatenator
  203372. {
  203373. public:
  203374. MidiDataConcatenator (const int initialBufferSize)
  203375. : pendingData (initialBufferSize),
  203376. pendingBytes (0), pendingDataTime (0)
  203377. {
  203378. }
  203379. void reset()
  203380. {
  203381. pendingBytes = 0;
  203382. pendingDataTime = 0;
  203383. }
  203384. void pushMidiData (const void* data, int numBytes, double time,
  203385. MidiInput* input, MidiInputCallback& callback)
  203386. {
  203387. const uint8* d = static_cast <const uint8*> (data);
  203388. while (numBytes > 0)
  203389. {
  203390. if (pendingBytes > 0 || d[0] == 0xf0)
  203391. {
  203392. processSysex (d, numBytes, time, input, callback);
  203393. }
  203394. else
  203395. {
  203396. int used = 0;
  203397. const MidiMessage m (d, numBytes, used, 0, time);
  203398. if (used <= 0)
  203399. break; // malformed message..
  203400. callback.handleIncomingMidiMessage (input, m);
  203401. numBytes -= used;
  203402. d += used;
  203403. }
  203404. }
  203405. }
  203406. private:
  203407. void processSysex (const uint8*& d, int& numBytes, double time,
  203408. MidiInput* input, MidiInputCallback& callback)
  203409. {
  203410. if (*d == 0xf0)
  203411. {
  203412. pendingBytes = 0;
  203413. pendingDataTime = time;
  203414. }
  203415. pendingData.ensureSize (pendingBytes + numBytes, false);
  203416. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203417. uint8* dest = totalMessage + pendingBytes;
  203418. do
  203419. {
  203420. if (pendingBytes > 0 && *d >= 0x80)
  203421. {
  203422. if (*d >= 0xfa || *d == 0xf8)
  203423. {
  203424. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203425. ++d;
  203426. --numBytes;
  203427. }
  203428. else
  203429. {
  203430. if (*d == 0xf7)
  203431. {
  203432. *dest++ = *d++;
  203433. pendingBytes++;
  203434. --numBytes;
  203435. }
  203436. break;
  203437. }
  203438. }
  203439. else
  203440. {
  203441. *dest++ = *d++;
  203442. pendingBytes++;
  203443. --numBytes;
  203444. }
  203445. }
  203446. while (numBytes > 0);
  203447. if (pendingBytes > 0)
  203448. {
  203449. if (totalMessage [pendingBytes - 1] == 0xf7)
  203450. {
  203451. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203452. pendingBytes = 0;
  203453. }
  203454. else
  203455. {
  203456. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203457. }
  203458. }
  203459. }
  203460. MemoryBlock pendingData;
  203461. int pendingBytes;
  203462. double pendingDataTime;
  203463. MidiDataConcatenator (const MidiDataConcatenator&);
  203464. MidiDataConcatenator& operator= (const MidiDataConcatenator&);
  203465. };
  203466. #endif
  203467. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203468. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203469. END_JUCE_NAMESPACE
  203470. #if JUCE_WINDOWS
  203471. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203472. /*
  203473. This file wraps together all the win32-specific code, so that
  203474. we can include all the native headers just once, and compile all our
  203475. platform-specific stuff in one big lump, keeping it out of the way of
  203476. the rest of the codebase.
  203477. */
  203478. #if JUCE_WINDOWS
  203479. BEGIN_JUCE_NAMESPACE
  203480. #define JUCE_INCLUDED_FILE 1
  203481. // Now include the actual code files..
  203482. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203483. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203484. // compiled on its own).
  203485. #if JUCE_INCLUDED_FILE
  203486. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203487. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203488. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203489. #ifndef DOXYGEN
  203490. // use with DynamicLibraryLoader to simplify importing functions
  203491. //
  203492. // functionName: function to import
  203493. // localFunctionName: name you want to use to actually call it (must be different)
  203494. // returnType: the return type
  203495. // object: the DynamicLibraryLoader to use
  203496. // params: list of params (bracketed)
  203497. //
  203498. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203499. typedef returnType (WINAPI *type##localFunctionName) params; \
  203500. type##localFunctionName localFunctionName \
  203501. = (type##localFunctionName)object.findProcAddress (#functionName);
  203502. // loads and unloads a DLL automatically
  203503. class JUCE_API DynamicLibraryLoader
  203504. {
  203505. public:
  203506. DynamicLibraryLoader (const String& name);
  203507. ~DynamicLibraryLoader();
  203508. void* findProcAddress (const String& functionName);
  203509. private:
  203510. void* libHandle;
  203511. };
  203512. #endif
  203513. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203514. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203515. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203516. {
  203517. libHandle = LoadLibrary (name);
  203518. }
  203519. DynamicLibraryLoader::~DynamicLibraryLoader()
  203520. {
  203521. FreeLibrary ((HMODULE) libHandle);
  203522. }
  203523. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203524. {
  203525. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203526. }
  203527. #endif
  203528. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203529. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203530. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203531. // compiled on its own).
  203532. #if JUCE_INCLUDED_FILE
  203533. extern void juce_initialiseThreadEvents();
  203534. void Logger::outputDebugString (const String& text)
  203535. {
  203536. OutputDebugString (text + "\n");
  203537. }
  203538. static int64 hiResTicksPerSecond;
  203539. static double hiResTicksScaleFactor;
  203540. #if JUCE_USE_INTRINSICS
  203541. // CPU info functions using intrinsics...
  203542. #pragma intrinsic (__cpuid)
  203543. #pragma intrinsic (__rdtsc)
  203544. const String SystemStats::getCpuVendor()
  203545. {
  203546. int info [4];
  203547. __cpuid (info, 0);
  203548. char v [12];
  203549. memcpy (v, info + 1, 4);
  203550. memcpy (v + 4, info + 3, 4);
  203551. memcpy (v + 8, info + 2, 4);
  203552. return String (v, 12);
  203553. }
  203554. #else
  203555. // CPU info functions using old fashioned inline asm...
  203556. static void juce_getCpuVendor (char* const v)
  203557. {
  203558. int vendor[4];
  203559. zeromem (vendor, 16);
  203560. #ifdef JUCE_64BIT
  203561. #else
  203562. #ifndef __MINGW32__
  203563. __try
  203564. #endif
  203565. {
  203566. #if JUCE_GCC
  203567. unsigned int dummy = 0;
  203568. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203569. #else
  203570. __asm
  203571. {
  203572. mov eax, 0
  203573. cpuid
  203574. mov [vendor], ebx
  203575. mov [vendor + 4], edx
  203576. mov [vendor + 8], ecx
  203577. }
  203578. #endif
  203579. }
  203580. #ifndef __MINGW32__
  203581. __except (EXCEPTION_EXECUTE_HANDLER)
  203582. {
  203583. *v = 0;
  203584. }
  203585. #endif
  203586. #endif
  203587. memcpy (v, vendor, 16);
  203588. }
  203589. const String SystemStats::getCpuVendor()
  203590. {
  203591. char v [16];
  203592. juce_getCpuVendor (v);
  203593. return String (v, 16);
  203594. }
  203595. #endif
  203596. void SystemStats::initialiseStats()
  203597. {
  203598. juce_initialiseThreadEvents();
  203599. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203600. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203601. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203602. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203603. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203604. #else
  203605. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203606. #endif
  203607. {
  203608. SYSTEM_INFO systemInfo;
  203609. GetSystemInfo (&systemInfo);
  203610. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203611. }
  203612. LARGE_INTEGER f;
  203613. QueryPerformanceFrequency (&f);
  203614. hiResTicksPerSecond = f.QuadPart;
  203615. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203616. String s (SystemStats::getJUCEVersion());
  203617. const MMRESULT res = timeBeginPeriod (1);
  203618. (void) res;
  203619. jassert (res == TIMERR_NOERROR);
  203620. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203621. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203622. #endif
  203623. }
  203624. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203625. {
  203626. OSVERSIONINFO info;
  203627. info.dwOSVersionInfoSize = sizeof (info);
  203628. GetVersionEx (&info);
  203629. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203630. {
  203631. switch (info.dwMajorVersion)
  203632. {
  203633. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203634. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203635. default: jassertfalse; break; // !! not a supported OS!
  203636. }
  203637. }
  203638. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203639. {
  203640. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203641. return Win98;
  203642. }
  203643. return UnknownOS;
  203644. }
  203645. const String SystemStats::getOperatingSystemName()
  203646. {
  203647. const char* name = "Unknown OS";
  203648. switch (getOperatingSystemType())
  203649. {
  203650. case Windows7: name = "Windows 7"; break;
  203651. case WinVista: name = "Windows Vista"; break;
  203652. case WinXP: name = "Windows XP"; break;
  203653. case Win2000: name = "Windows 2000"; break;
  203654. case Win98: name = "Windows 98"; break;
  203655. default: jassertfalse; break; // !! new type of OS?
  203656. }
  203657. return name;
  203658. }
  203659. bool SystemStats::isOperatingSystem64Bit()
  203660. {
  203661. #ifdef _WIN64
  203662. return true;
  203663. #else
  203664. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203665. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203666. BOOL isWow64 = FALSE;
  203667. return (fnIsWow64Process != 0)
  203668. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203669. && (isWow64 != FALSE);
  203670. #endif
  203671. }
  203672. int SystemStats::getMemorySizeInMegabytes()
  203673. {
  203674. MEMORYSTATUSEX mem;
  203675. mem.dwLength = sizeof (mem);
  203676. GlobalMemoryStatusEx (&mem);
  203677. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203678. }
  203679. uint32 juce_millisecondsSinceStartup() throw()
  203680. {
  203681. return (uint32) timeGetTime();
  203682. }
  203683. int64 Time::getHighResolutionTicks() throw()
  203684. {
  203685. LARGE_INTEGER ticks;
  203686. QueryPerformanceCounter (&ticks);
  203687. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203688. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203689. // fix for a very obscure PCI hardware bug that can make the counter
  203690. // sometimes jump forwards by a few seconds..
  203691. static int64 hiResTicksOffset = 0;
  203692. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203693. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203694. hiResTicksOffset = newOffset;
  203695. return ticks.QuadPart + hiResTicksOffset;
  203696. }
  203697. double Time::getMillisecondCounterHiRes() throw()
  203698. {
  203699. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203700. }
  203701. int64 Time::getHighResolutionTicksPerSecond() throw()
  203702. {
  203703. return hiResTicksPerSecond;
  203704. }
  203705. static int64 juce_getClockCycleCounter() throw()
  203706. {
  203707. #if JUCE_USE_INTRINSICS
  203708. // MS intrinsics version...
  203709. return __rdtsc();
  203710. #elif JUCE_GCC
  203711. // GNU inline asm version...
  203712. unsigned int hi = 0, lo = 0;
  203713. __asm__ __volatile__ (
  203714. "xor %%eax, %%eax \n\
  203715. xor %%edx, %%edx \n\
  203716. rdtsc \n\
  203717. movl %%eax, %[lo] \n\
  203718. movl %%edx, %[hi]"
  203719. :
  203720. : [hi] "m" (hi),
  203721. [lo] "m" (lo)
  203722. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203723. return (int64) ((((uint64) hi) << 32) | lo);
  203724. #else
  203725. // MSVC inline asm version...
  203726. unsigned int hi = 0, lo = 0;
  203727. __asm
  203728. {
  203729. xor eax, eax
  203730. xor edx, edx
  203731. rdtsc
  203732. mov lo, eax
  203733. mov hi, edx
  203734. }
  203735. return (int64) ((((uint64) hi) << 32) | lo);
  203736. #endif
  203737. }
  203738. int SystemStats::getCpuSpeedInMegaherz()
  203739. {
  203740. const int64 cycles = juce_getClockCycleCounter();
  203741. const uint32 millis = Time::getMillisecondCounter();
  203742. int lastResult = 0;
  203743. for (;;)
  203744. {
  203745. int n = 1000000;
  203746. while (--n > 0) {}
  203747. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203748. const int64 cyclesNow = juce_getClockCycleCounter();
  203749. if (millisElapsed > 80)
  203750. {
  203751. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203752. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203753. return newResult;
  203754. lastResult = newResult;
  203755. }
  203756. }
  203757. }
  203758. bool Time::setSystemTimeToThisTime() const
  203759. {
  203760. SYSTEMTIME st;
  203761. st.wDayOfWeek = 0;
  203762. st.wYear = (WORD) getYear();
  203763. st.wMonth = (WORD) (getMonth() + 1);
  203764. st.wDay = (WORD) getDayOfMonth();
  203765. st.wHour = (WORD) getHours();
  203766. st.wMinute = (WORD) getMinutes();
  203767. st.wSecond = (WORD) getSeconds();
  203768. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203769. // do this twice because of daylight saving conversion problems - the
  203770. // first one sets it up, the second one kicks it in.
  203771. return SetLocalTime (&st) != 0
  203772. && SetLocalTime (&st) != 0;
  203773. }
  203774. int SystemStats::getPageSize()
  203775. {
  203776. SYSTEM_INFO systemInfo;
  203777. GetSystemInfo (&systemInfo);
  203778. return systemInfo.dwPageSize;
  203779. }
  203780. const String SystemStats::getLogonName()
  203781. {
  203782. TCHAR text [256];
  203783. DWORD len = numElementsInArray (text) - 2;
  203784. zerostruct (text);
  203785. GetUserName (text, &len);
  203786. return String (text, len);
  203787. }
  203788. const String SystemStats::getFullUserName()
  203789. {
  203790. return getLogonName();
  203791. }
  203792. #endif
  203793. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203794. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203795. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203796. // compiled on its own).
  203797. #if JUCE_INCLUDED_FILE
  203798. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203799. extern HWND juce_messageWindowHandle;
  203800. #endif
  203801. #if ! JUCE_USE_INTRINSICS
  203802. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203803. // older ones we have to actually call the ops as win32 functions..
  203804. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203805. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203806. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203807. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203808. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203809. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203810. {
  203811. jassertfalse; // This operation isn't available in old MS compiler versions!
  203812. __int64 oldValue = *value;
  203813. if (oldValue == valueToCompare)
  203814. *value = newValue;
  203815. return oldValue;
  203816. }
  203817. #endif
  203818. CriticalSection::CriticalSection() throw()
  203819. {
  203820. // (just to check the MS haven't changed this structure and broken things...)
  203821. #if JUCE_VC7_OR_EARLIER
  203822. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203823. #else
  203824. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203825. #endif
  203826. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203827. }
  203828. CriticalSection::~CriticalSection() throw()
  203829. {
  203830. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203831. }
  203832. void CriticalSection::enter() const throw()
  203833. {
  203834. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203835. }
  203836. bool CriticalSection::tryEnter() const throw()
  203837. {
  203838. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203839. }
  203840. void CriticalSection::exit() const throw()
  203841. {
  203842. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203843. }
  203844. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203845. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203846. {
  203847. }
  203848. WaitableEvent::~WaitableEvent() throw()
  203849. {
  203850. CloseHandle (internal);
  203851. }
  203852. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203853. {
  203854. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203855. }
  203856. void WaitableEvent::signal() const throw()
  203857. {
  203858. SetEvent (internal);
  203859. }
  203860. void WaitableEvent::reset() const throw()
  203861. {
  203862. ResetEvent (internal);
  203863. }
  203864. void JUCE_API juce_threadEntryPoint (void*);
  203865. static unsigned int __stdcall threadEntryProc (void* userData)
  203866. {
  203867. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203868. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203869. GetCurrentThreadId(), TRUE);
  203870. #endif
  203871. juce_threadEntryPoint (userData);
  203872. _endthreadex (0);
  203873. return 0;
  203874. }
  203875. void juce_CloseThreadHandle (void* handle)
  203876. {
  203877. CloseHandle ((HANDLE) handle);
  203878. }
  203879. void* juce_createThread (void* userData)
  203880. {
  203881. unsigned int threadId;
  203882. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203883. }
  203884. void juce_killThread (void* handle)
  203885. {
  203886. if (handle != 0)
  203887. {
  203888. #if JUCE_DEBUG
  203889. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203890. #endif
  203891. TerminateThread (handle, 0);
  203892. }
  203893. }
  203894. void juce_setCurrentThreadName (const String& name)
  203895. {
  203896. #if JUCE_DEBUG && JUCE_MSVC
  203897. struct
  203898. {
  203899. DWORD dwType;
  203900. LPCSTR szName;
  203901. DWORD dwThreadID;
  203902. DWORD dwFlags;
  203903. } info;
  203904. info.dwType = 0x1000;
  203905. info.szName = name.toCString();
  203906. info.dwThreadID = GetCurrentThreadId();
  203907. info.dwFlags = 0;
  203908. __try
  203909. {
  203910. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203911. }
  203912. __except (EXCEPTION_CONTINUE_EXECUTION)
  203913. {}
  203914. #else
  203915. (void) name;
  203916. #endif
  203917. }
  203918. Thread::ThreadID Thread::getCurrentThreadId()
  203919. {
  203920. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203921. }
  203922. // priority 1 to 10 where 5=normal, 1=low
  203923. bool juce_setThreadPriority (void* threadHandle, int priority)
  203924. {
  203925. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203926. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203927. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203928. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203929. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203930. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203931. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203932. if (threadHandle == 0)
  203933. threadHandle = GetCurrentThread();
  203934. return SetThreadPriority (threadHandle, pri) != FALSE;
  203935. }
  203936. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203937. {
  203938. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203939. }
  203940. static HANDLE sleepEvent = 0;
  203941. void juce_initialiseThreadEvents()
  203942. {
  203943. if (sleepEvent == 0)
  203944. #if JUCE_DEBUG
  203945. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203946. #else
  203947. sleepEvent = CreateEvent (0, 0, 0, 0);
  203948. #endif
  203949. }
  203950. void Thread::yield()
  203951. {
  203952. Sleep (0);
  203953. }
  203954. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203955. {
  203956. if (millisecs >= 10)
  203957. {
  203958. Sleep (millisecs);
  203959. }
  203960. else
  203961. {
  203962. jassert (sleepEvent != 0);
  203963. // unlike Sleep() this is guaranteed to return to the current thread after
  203964. // the time expires, so we'll use this for short waits, which are more likely
  203965. // to need to be accurate
  203966. WaitForSingleObject (sleepEvent, millisecs);
  203967. }
  203968. }
  203969. static int lastProcessPriority = -1;
  203970. // called by WindowDriver because Windows does wierd things to process priority
  203971. // when you swap apps, and this forces an update when the app is brought to the front.
  203972. void juce_repeatLastProcessPriority()
  203973. {
  203974. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203975. {
  203976. DWORD p;
  203977. switch (lastProcessPriority)
  203978. {
  203979. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203980. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203981. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203982. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203983. default: jassertfalse; return; // bad priority value
  203984. }
  203985. SetPriorityClass (GetCurrentProcess(), p);
  203986. }
  203987. }
  203988. void Process::setPriority (ProcessPriority prior)
  203989. {
  203990. if (lastProcessPriority != (int) prior)
  203991. {
  203992. lastProcessPriority = (int) prior;
  203993. juce_repeatLastProcessPriority();
  203994. }
  203995. }
  203996. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  203997. {
  203998. return IsDebuggerPresent() != FALSE;
  203999. }
  204000. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  204001. {
  204002. return juce_isRunningUnderDebugger();
  204003. }
  204004. void Process::raisePrivilege()
  204005. {
  204006. jassertfalse; // xxx not implemented
  204007. }
  204008. void Process::lowerPrivilege()
  204009. {
  204010. jassertfalse; // xxx not implemented
  204011. }
  204012. void Process::terminate()
  204013. {
  204014. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204015. _CrtDumpMemoryLeaks();
  204016. #endif
  204017. // bullet in the head in case there's a problem shutting down..
  204018. ExitProcess (0);
  204019. }
  204020. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204021. {
  204022. void* result = 0;
  204023. JUCE_TRY
  204024. {
  204025. result = LoadLibrary (name);
  204026. }
  204027. JUCE_CATCH_ALL
  204028. return result;
  204029. }
  204030. void PlatformUtilities::freeDynamicLibrary (void* h)
  204031. {
  204032. JUCE_TRY
  204033. {
  204034. if (h != 0)
  204035. FreeLibrary ((HMODULE) h);
  204036. }
  204037. JUCE_CATCH_ALL
  204038. }
  204039. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204040. {
  204041. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  204042. }
  204043. class InterProcessLock::Pimpl
  204044. {
  204045. public:
  204046. Pimpl (const String& name, const int timeOutMillisecs)
  204047. : handle (0), refCount (1)
  204048. {
  204049. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  204050. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204051. {
  204052. if (timeOutMillisecs == 0)
  204053. {
  204054. close();
  204055. return;
  204056. }
  204057. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204058. {
  204059. case WAIT_OBJECT_0:
  204060. case WAIT_ABANDONED:
  204061. break;
  204062. case WAIT_TIMEOUT:
  204063. default:
  204064. close();
  204065. break;
  204066. }
  204067. }
  204068. }
  204069. ~Pimpl()
  204070. {
  204071. close();
  204072. }
  204073. void close()
  204074. {
  204075. if (handle != 0)
  204076. {
  204077. ReleaseMutex (handle);
  204078. CloseHandle (handle);
  204079. handle = 0;
  204080. }
  204081. }
  204082. HANDLE handle;
  204083. int refCount;
  204084. };
  204085. InterProcessLock::InterProcessLock (const String& name_)
  204086. : name (name_)
  204087. {
  204088. }
  204089. InterProcessLock::~InterProcessLock()
  204090. {
  204091. }
  204092. bool InterProcessLock::enter (const int timeOutMillisecs)
  204093. {
  204094. const ScopedLock sl (lock);
  204095. if (pimpl == 0)
  204096. {
  204097. pimpl = new Pimpl (name, timeOutMillisecs);
  204098. if (pimpl->handle == 0)
  204099. pimpl = 0;
  204100. }
  204101. else
  204102. {
  204103. pimpl->refCount++;
  204104. }
  204105. return pimpl != 0;
  204106. }
  204107. void InterProcessLock::exit()
  204108. {
  204109. const ScopedLock sl (lock);
  204110. // Trying to release the lock too many times!
  204111. jassert (pimpl != 0);
  204112. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204113. pimpl = 0;
  204114. }
  204115. #endif
  204116. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204117. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204118. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204119. // compiled on its own).
  204120. #if JUCE_INCLUDED_FILE
  204121. #ifndef CSIDL_MYMUSIC
  204122. #define CSIDL_MYMUSIC 0x000d
  204123. #endif
  204124. #ifndef CSIDL_MYVIDEO
  204125. #define CSIDL_MYVIDEO 0x000e
  204126. #endif
  204127. #ifndef INVALID_FILE_ATTRIBUTES
  204128. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204129. #endif
  204130. namespace WindowsFileHelpers
  204131. {
  204132. int64 fileTimeToTime (const FILETIME* const ft)
  204133. {
  204134. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204135. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204136. }
  204137. void timeToFileTime (const int64 time, FILETIME* const ft)
  204138. {
  204139. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204140. }
  204141. const String getDriveFromPath (const String& path)
  204142. {
  204143. if (path.isNotEmpty() && path[1] == ':')
  204144. return path.substring (0, 2) + '\\';
  204145. return path;
  204146. }
  204147. int64 getDiskSpaceInfo (const String& path, const bool total)
  204148. {
  204149. ULARGE_INTEGER spc, tot, totFree;
  204150. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204151. return total ? (int64) tot.QuadPart
  204152. : (int64) spc.QuadPart;
  204153. return 0;
  204154. }
  204155. unsigned int getWindowsDriveType (const String& path)
  204156. {
  204157. return GetDriveType (getDriveFromPath (path));
  204158. }
  204159. const File getSpecialFolderPath (int type)
  204160. {
  204161. WCHAR path [MAX_PATH + 256];
  204162. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204163. return File (String (path));
  204164. return File::nonexistent;
  204165. }
  204166. }
  204167. const juce_wchar File::separator = '\\';
  204168. const String File::separatorString ("\\");
  204169. bool File::exists() const
  204170. {
  204171. return fullPath.isNotEmpty()
  204172. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204173. }
  204174. bool File::existsAsFile() const
  204175. {
  204176. return fullPath.isNotEmpty()
  204177. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204178. }
  204179. bool File::isDirectory() const
  204180. {
  204181. const DWORD attr = GetFileAttributes (fullPath);
  204182. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204183. }
  204184. bool File::hasWriteAccess() const
  204185. {
  204186. if (exists())
  204187. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204188. // on windows, it seems that even read-only directories can still be written into,
  204189. // so checking the parent directory's permissions would return the wrong result..
  204190. return true;
  204191. }
  204192. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204193. {
  204194. DWORD attr = GetFileAttributes (fullPath);
  204195. if (attr == INVALID_FILE_ATTRIBUTES)
  204196. return false;
  204197. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204198. return true;
  204199. if (shouldBeReadOnly)
  204200. attr |= FILE_ATTRIBUTE_READONLY;
  204201. else
  204202. attr &= ~FILE_ATTRIBUTE_READONLY;
  204203. return SetFileAttributes (fullPath, attr) != FALSE;
  204204. }
  204205. bool File::isHidden() const
  204206. {
  204207. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204208. }
  204209. bool File::deleteFile() const
  204210. {
  204211. if (! exists())
  204212. return true;
  204213. else if (isDirectory())
  204214. return RemoveDirectory (fullPath) != 0;
  204215. else
  204216. return DeleteFile (fullPath) != 0;
  204217. }
  204218. bool File::moveToTrash() const
  204219. {
  204220. if (! exists())
  204221. return true;
  204222. SHFILEOPSTRUCT fos;
  204223. zerostruct (fos);
  204224. // The string we pass in must be double null terminated..
  204225. String doubleNullTermPath (getFullPathName() + " ");
  204226. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204227. p [getFullPathName().length()] = 0;
  204228. fos.wFunc = FO_DELETE;
  204229. fos.pFrom = p;
  204230. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204231. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204232. return SHFileOperation (&fos) == 0;
  204233. }
  204234. bool File::copyInternal (const File& dest) const
  204235. {
  204236. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204237. }
  204238. bool File::moveInternal (const File& dest) const
  204239. {
  204240. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204241. }
  204242. void File::createDirectoryInternal (const String& fileName) const
  204243. {
  204244. CreateDirectory (fileName, 0);
  204245. }
  204246. int64 juce_fileSetPosition (void* handle, int64 pos)
  204247. {
  204248. LARGE_INTEGER li;
  204249. li.QuadPart = pos;
  204250. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204251. return li.QuadPart;
  204252. }
  204253. void FileInputStream::openHandle()
  204254. {
  204255. totalSize = file.getSize();
  204256. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204257. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204258. if (h != INVALID_HANDLE_VALUE)
  204259. fileHandle = (void*) h;
  204260. }
  204261. void FileInputStream::closeHandle()
  204262. {
  204263. CloseHandle ((HANDLE) fileHandle);
  204264. }
  204265. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204266. {
  204267. if (fileHandle != 0)
  204268. {
  204269. DWORD actualNum = 0;
  204270. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204271. return (size_t) actualNum;
  204272. }
  204273. return 0;
  204274. }
  204275. void FileOutputStream::openHandle()
  204276. {
  204277. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204278. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204279. if (h != INVALID_HANDLE_VALUE)
  204280. {
  204281. LARGE_INTEGER li;
  204282. li.QuadPart = 0;
  204283. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204284. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204285. {
  204286. fileHandle = (void*) h;
  204287. currentPosition = li.QuadPart;
  204288. }
  204289. }
  204290. }
  204291. void FileOutputStream::closeHandle()
  204292. {
  204293. CloseHandle ((HANDLE) fileHandle);
  204294. }
  204295. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204296. {
  204297. if (fileHandle != 0)
  204298. {
  204299. DWORD actualNum = 0;
  204300. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204301. return (int) actualNum;
  204302. }
  204303. return 0;
  204304. }
  204305. void FileOutputStream::flushInternal()
  204306. {
  204307. if (fileHandle != 0)
  204308. FlushFileBuffers ((HANDLE) fileHandle);
  204309. }
  204310. int64 File::getSize() const
  204311. {
  204312. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204313. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204314. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204315. return 0;
  204316. }
  204317. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204318. {
  204319. using namespace WindowsFileHelpers;
  204320. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204321. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204322. {
  204323. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204324. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204325. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204326. }
  204327. else
  204328. {
  204329. creationTime = accessTime = modificationTime = 0;
  204330. }
  204331. }
  204332. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204333. {
  204334. using namespace WindowsFileHelpers;
  204335. bool ok = false;
  204336. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204337. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204338. if (h != INVALID_HANDLE_VALUE)
  204339. {
  204340. FILETIME m, a, c;
  204341. timeToFileTime (modificationTime, &m);
  204342. timeToFileTime (accessTime, &a);
  204343. timeToFileTime (creationTime, &c);
  204344. ok = SetFileTime (h,
  204345. creationTime > 0 ? &c : 0,
  204346. accessTime > 0 ? &a : 0,
  204347. modificationTime > 0 ? &m : 0) != 0;
  204348. CloseHandle (h);
  204349. }
  204350. return ok;
  204351. }
  204352. void File::findFileSystemRoots (Array<File>& destArray)
  204353. {
  204354. TCHAR buffer [2048];
  204355. buffer[0] = 0;
  204356. buffer[1] = 0;
  204357. GetLogicalDriveStrings (2048, buffer);
  204358. const TCHAR* n = buffer;
  204359. StringArray roots;
  204360. while (*n != 0)
  204361. {
  204362. roots.add (String (n));
  204363. while (*n++ != 0)
  204364. {}
  204365. }
  204366. roots.sort (true);
  204367. for (int i = 0; i < roots.size(); ++i)
  204368. destArray.add (roots [i]);
  204369. }
  204370. const String File::getVolumeLabel() const
  204371. {
  204372. TCHAR dest[64];
  204373. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204374. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204375. dest[0] = 0;
  204376. return dest;
  204377. }
  204378. int File::getVolumeSerialNumber() const
  204379. {
  204380. TCHAR dest[64];
  204381. DWORD serialNum;
  204382. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204383. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204384. return 0;
  204385. return (int) serialNum;
  204386. }
  204387. int64 File::getBytesFreeOnVolume() const
  204388. {
  204389. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204390. }
  204391. int64 File::getVolumeTotalSize() const
  204392. {
  204393. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204394. }
  204395. bool File::isOnCDRomDrive() const
  204396. {
  204397. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204398. }
  204399. bool File::isOnHardDisk() const
  204400. {
  204401. if (fullPath.isEmpty())
  204402. return false;
  204403. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204404. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204405. return n != DRIVE_REMOVABLE;
  204406. else
  204407. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204408. }
  204409. bool File::isOnRemovableDrive() const
  204410. {
  204411. if (fullPath.isEmpty())
  204412. return false;
  204413. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204414. return n == DRIVE_CDROM
  204415. || n == DRIVE_REMOTE
  204416. || n == DRIVE_REMOVABLE
  204417. || n == DRIVE_RAMDISK;
  204418. }
  204419. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204420. {
  204421. int csidlType = 0;
  204422. switch (type)
  204423. {
  204424. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204425. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204426. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204427. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204428. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204429. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204430. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204431. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204432. case tempDirectory:
  204433. {
  204434. WCHAR dest [2048];
  204435. dest[0] = 0;
  204436. GetTempPath (numElementsInArray (dest), dest);
  204437. return File (String (dest));
  204438. }
  204439. case invokedExecutableFile:
  204440. case currentExecutableFile:
  204441. case currentApplicationFile:
  204442. {
  204443. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204444. WCHAR dest [MAX_PATH + 256];
  204445. dest[0] = 0;
  204446. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204447. return File (String (dest));
  204448. }
  204449. case hostApplicationPath:
  204450. {
  204451. WCHAR dest [MAX_PATH + 256];
  204452. dest[0] = 0;
  204453. GetModuleFileName (0, dest, numElementsInArray (dest));
  204454. return File (String (dest));
  204455. }
  204456. default:
  204457. jassertfalse; // unknown type?
  204458. return File::nonexistent;
  204459. }
  204460. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204461. }
  204462. const File File::getCurrentWorkingDirectory()
  204463. {
  204464. WCHAR dest [MAX_PATH + 256];
  204465. dest[0] = 0;
  204466. GetCurrentDirectory (numElementsInArray (dest), dest);
  204467. return File (String (dest));
  204468. }
  204469. bool File::setAsCurrentWorkingDirectory() const
  204470. {
  204471. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204472. }
  204473. const String File::getVersion() const
  204474. {
  204475. String result;
  204476. DWORD handle = 0;
  204477. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204478. HeapBlock<char> buffer;
  204479. buffer.calloc (bufferSize);
  204480. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204481. {
  204482. VS_FIXEDFILEINFO* vffi;
  204483. UINT len = 0;
  204484. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204485. {
  204486. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204487. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204488. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204489. << (int) LOWORD (vffi->dwFileVersionLS);
  204490. }
  204491. }
  204492. return result;
  204493. }
  204494. const File File::getLinkedTarget() const
  204495. {
  204496. File result (*this);
  204497. String p (getFullPathName());
  204498. if (! exists())
  204499. p += ".lnk";
  204500. else if (getFileExtension() != ".lnk")
  204501. return result;
  204502. ComSmartPtr <IShellLink> shellLink;
  204503. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204504. {
  204505. ComSmartPtr <IPersistFile> persistFile;
  204506. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204507. {
  204508. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204509. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204510. {
  204511. WIN32_FIND_DATA winFindData;
  204512. WCHAR resolvedPath [MAX_PATH];
  204513. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204514. result = File (resolvedPath);
  204515. }
  204516. }
  204517. }
  204518. return result;
  204519. }
  204520. class DirectoryIterator::NativeIterator::Pimpl
  204521. {
  204522. public:
  204523. Pimpl (const File& directory, const String& wildCard)
  204524. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204525. handle (INVALID_HANDLE_VALUE)
  204526. {
  204527. }
  204528. ~Pimpl()
  204529. {
  204530. if (handle != INVALID_HANDLE_VALUE)
  204531. FindClose (handle);
  204532. }
  204533. bool next (String& filenameFound,
  204534. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204535. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204536. {
  204537. using namespace WindowsFileHelpers;
  204538. WIN32_FIND_DATA findData;
  204539. if (handle == INVALID_HANDLE_VALUE)
  204540. {
  204541. handle = FindFirstFile (directoryWithWildCard, &findData);
  204542. if (handle == INVALID_HANDLE_VALUE)
  204543. return false;
  204544. }
  204545. else
  204546. {
  204547. if (FindNextFile (handle, &findData) == 0)
  204548. return false;
  204549. }
  204550. filenameFound = findData.cFileName;
  204551. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204552. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204553. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204554. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204555. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204556. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204557. return true;
  204558. }
  204559. juce_UseDebuggingNewOperator
  204560. private:
  204561. const String directoryWithWildCard;
  204562. HANDLE handle;
  204563. Pimpl (const Pimpl&);
  204564. Pimpl& operator= (const Pimpl&);
  204565. };
  204566. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204567. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204568. {
  204569. }
  204570. DirectoryIterator::NativeIterator::~NativeIterator()
  204571. {
  204572. }
  204573. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204574. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204575. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204576. {
  204577. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204578. }
  204579. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204580. {
  204581. HINSTANCE hInstance = 0;
  204582. JUCE_TRY
  204583. {
  204584. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204585. }
  204586. JUCE_CATCH_ALL
  204587. return hInstance > (HINSTANCE) 32;
  204588. }
  204589. void File::revealToUser() const
  204590. {
  204591. if (isDirectory())
  204592. startAsProcess();
  204593. else if (getParentDirectory().exists())
  204594. getParentDirectory().startAsProcess();
  204595. }
  204596. class NamedPipeInternal
  204597. {
  204598. public:
  204599. NamedPipeInternal (const String& file, const bool isPipe_)
  204600. : pipeH (0),
  204601. cancelEvent (0),
  204602. connected (false),
  204603. isPipe (isPipe_)
  204604. {
  204605. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204606. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204607. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204608. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204609. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204610. }
  204611. ~NamedPipeInternal()
  204612. {
  204613. disconnectPipe();
  204614. if (pipeH != 0)
  204615. CloseHandle (pipeH);
  204616. CloseHandle (cancelEvent);
  204617. }
  204618. bool connect (const int timeOutMs)
  204619. {
  204620. if (! isPipe)
  204621. return true;
  204622. if (! connected)
  204623. {
  204624. OVERLAPPED over;
  204625. zerostruct (over);
  204626. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204627. if (ConnectNamedPipe (pipeH, &over))
  204628. {
  204629. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204630. }
  204631. else
  204632. {
  204633. const int err = GetLastError();
  204634. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204635. {
  204636. HANDLE handles[] = { over.hEvent, cancelEvent };
  204637. if (WaitForMultipleObjects (2, handles, FALSE,
  204638. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204639. connected = true;
  204640. }
  204641. else if (err == ERROR_PIPE_CONNECTED)
  204642. {
  204643. connected = true;
  204644. }
  204645. }
  204646. CloseHandle (over.hEvent);
  204647. }
  204648. return connected;
  204649. }
  204650. void disconnectPipe()
  204651. {
  204652. if (connected)
  204653. {
  204654. DisconnectNamedPipe (pipeH);
  204655. connected = false;
  204656. }
  204657. }
  204658. HANDLE pipeH;
  204659. HANDLE cancelEvent;
  204660. bool connected, isPipe;
  204661. };
  204662. void NamedPipe::close()
  204663. {
  204664. cancelPendingReads();
  204665. const ScopedLock sl (lock);
  204666. delete static_cast<NamedPipeInternal*> (internal);
  204667. internal = 0;
  204668. }
  204669. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204670. {
  204671. close();
  204672. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204673. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204674. {
  204675. internal = intern.release();
  204676. return true;
  204677. }
  204678. return false;
  204679. }
  204680. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204681. {
  204682. const ScopedLock sl (lock);
  204683. int bytesRead = -1;
  204684. bool waitAgain = true;
  204685. while (waitAgain && internal != 0)
  204686. {
  204687. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204688. waitAgain = false;
  204689. if (! intern->connect (timeOutMilliseconds))
  204690. break;
  204691. if (maxBytesToRead <= 0)
  204692. return 0;
  204693. OVERLAPPED over;
  204694. zerostruct (over);
  204695. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204696. unsigned long numRead;
  204697. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204698. {
  204699. bytesRead = (int) numRead;
  204700. }
  204701. else if (GetLastError() == ERROR_IO_PENDING)
  204702. {
  204703. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204704. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204705. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204706. : INFINITE);
  204707. if (waitResult != WAIT_OBJECT_0)
  204708. {
  204709. // if the operation timed out, let's cancel it...
  204710. CancelIo (intern->pipeH);
  204711. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204712. }
  204713. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204714. {
  204715. bytesRead = (int) numRead;
  204716. }
  204717. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204718. {
  204719. intern->disconnectPipe();
  204720. waitAgain = true;
  204721. }
  204722. }
  204723. else
  204724. {
  204725. waitAgain = internal != 0;
  204726. Sleep (5);
  204727. }
  204728. CloseHandle (over.hEvent);
  204729. }
  204730. return bytesRead;
  204731. }
  204732. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204733. {
  204734. int bytesWritten = -1;
  204735. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204736. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204737. {
  204738. if (numBytesToWrite <= 0)
  204739. return 0;
  204740. OVERLAPPED over;
  204741. zerostruct (over);
  204742. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204743. unsigned long numWritten;
  204744. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204745. {
  204746. bytesWritten = (int) numWritten;
  204747. }
  204748. else if (GetLastError() == ERROR_IO_PENDING)
  204749. {
  204750. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204751. DWORD waitResult;
  204752. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204753. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204754. : INFINITE);
  204755. if (waitResult != WAIT_OBJECT_0)
  204756. {
  204757. CancelIo (intern->pipeH);
  204758. WaitForSingleObject (over.hEvent, INFINITE);
  204759. }
  204760. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204761. {
  204762. bytesWritten = (int) numWritten;
  204763. }
  204764. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204765. {
  204766. intern->disconnectPipe();
  204767. }
  204768. }
  204769. CloseHandle (over.hEvent);
  204770. }
  204771. return bytesWritten;
  204772. }
  204773. void NamedPipe::cancelPendingReads()
  204774. {
  204775. if (internal != 0)
  204776. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204777. }
  204778. #endif
  204779. /*** End of inlined file: juce_win32_Files.cpp ***/
  204780. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204781. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204782. // compiled on its own).
  204783. #if JUCE_INCLUDED_FILE
  204784. #ifndef INTERNET_FLAG_NEED_FILE
  204785. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204786. #endif
  204787. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204788. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204789. #endif
  204790. struct ConnectionAndRequestStruct
  204791. {
  204792. HINTERNET connection, request;
  204793. };
  204794. static HINTERNET sessionHandle = 0;
  204795. #ifndef WORKAROUND_TIMEOUT_BUG
  204796. //#define WORKAROUND_TIMEOUT_BUG 1
  204797. #endif
  204798. #if WORKAROUND_TIMEOUT_BUG
  204799. // Required because of a Microsoft bug in setting a timeout
  204800. class InternetConnectThread : public Thread
  204801. {
  204802. public:
  204803. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204804. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204805. {
  204806. startThread();
  204807. }
  204808. ~InternetConnectThread()
  204809. {
  204810. stopThread (60000);
  204811. }
  204812. void run()
  204813. {
  204814. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204815. uc.nPort, _T(""), _T(""),
  204816. isFtp ? INTERNET_SERVICE_FTP
  204817. : INTERNET_SERVICE_HTTP,
  204818. 0, 0);
  204819. notify();
  204820. }
  204821. juce_UseDebuggingNewOperator
  204822. private:
  204823. URL_COMPONENTS& uc;
  204824. HINTERNET& connection;
  204825. const bool isFtp;
  204826. InternetConnectThread (const InternetConnectThread&);
  204827. InternetConnectThread& operator= (const InternetConnectThread&);
  204828. };
  204829. #endif
  204830. void* juce_openInternetFile (const String& url,
  204831. const String& headers,
  204832. const MemoryBlock& postData,
  204833. const bool isPost,
  204834. URL::OpenStreamProgressCallback* callback,
  204835. void* callbackContext,
  204836. int timeOutMs)
  204837. {
  204838. if (sessionHandle == 0)
  204839. sessionHandle = InternetOpen (_T("juce"),
  204840. INTERNET_OPEN_TYPE_PRECONFIG,
  204841. 0, 0, 0);
  204842. if (sessionHandle != 0)
  204843. {
  204844. // break up the url..
  204845. TCHAR file[1024], server[1024];
  204846. URL_COMPONENTS uc;
  204847. zerostruct (uc);
  204848. uc.dwStructSize = sizeof (uc);
  204849. uc.dwUrlPathLength = sizeof (file);
  204850. uc.dwHostNameLength = sizeof (server);
  204851. uc.lpszUrlPath = file;
  204852. uc.lpszHostName = server;
  204853. if (InternetCrackUrl (url, 0, 0, &uc))
  204854. {
  204855. int disable = 1;
  204856. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204857. if (timeOutMs == 0)
  204858. timeOutMs = 30000;
  204859. else if (timeOutMs < 0)
  204860. timeOutMs = -1;
  204861. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204862. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204863. #if WORKAROUND_TIMEOUT_BUG
  204864. HINTERNET connection = 0;
  204865. {
  204866. InternetConnectThread connectThread (uc, connection, isFtp);
  204867. connectThread.wait (timeOutMs);
  204868. if (connection == 0)
  204869. {
  204870. InternetCloseHandle (sessionHandle);
  204871. sessionHandle = 0;
  204872. }
  204873. }
  204874. #else
  204875. HINTERNET connection = InternetConnect (sessionHandle,
  204876. uc.lpszHostName,
  204877. uc.nPort,
  204878. _T(""), _T(""),
  204879. isFtp ? INTERNET_SERVICE_FTP
  204880. : INTERNET_SERVICE_HTTP,
  204881. 0, 0);
  204882. #endif
  204883. if (connection != 0)
  204884. {
  204885. if (isFtp)
  204886. {
  204887. HINTERNET request = FtpOpenFile (connection,
  204888. uc.lpszUrlPath,
  204889. GENERIC_READ,
  204890. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204891. 0);
  204892. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204893. result->connection = connection;
  204894. result->request = request;
  204895. return result;
  204896. }
  204897. else
  204898. {
  204899. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204900. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204901. if (url.startsWithIgnoreCase ("https:"))
  204902. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204903. // IE7 seems to automatically work out when it's https)
  204904. HINTERNET request = HttpOpenRequest (connection,
  204905. isPost ? _T("POST")
  204906. : _T("GET"),
  204907. uc.lpszUrlPath,
  204908. 0, 0, mimeTypes, flags, 0);
  204909. if (request != 0)
  204910. {
  204911. INTERNET_BUFFERS buffers;
  204912. zerostruct (buffers);
  204913. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204914. buffers.lpcszHeader = (LPCTSTR) headers;
  204915. buffers.dwHeadersLength = headers.length();
  204916. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204917. ConnectionAndRequestStruct* result = 0;
  204918. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204919. {
  204920. int bytesSent = 0;
  204921. for (;;)
  204922. {
  204923. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204924. DWORD bytesDone = 0;
  204925. if (bytesToDo > 0
  204926. && ! InternetWriteFile (request,
  204927. static_cast <const char*> (postData.getData()) + bytesSent,
  204928. bytesToDo, &bytesDone))
  204929. {
  204930. break;
  204931. }
  204932. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204933. {
  204934. result = new ConnectionAndRequestStruct();
  204935. result->connection = connection;
  204936. result->request = request;
  204937. if (! HttpEndRequest (request, 0, 0, 0))
  204938. break;
  204939. return result;
  204940. }
  204941. bytesSent += bytesDone;
  204942. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204943. break;
  204944. }
  204945. }
  204946. InternetCloseHandle (request);
  204947. }
  204948. InternetCloseHandle (connection);
  204949. }
  204950. }
  204951. }
  204952. }
  204953. return 0;
  204954. }
  204955. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204956. {
  204957. DWORD bytesRead = 0;
  204958. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204959. if (crs != 0)
  204960. InternetReadFile (crs->request,
  204961. buffer, bytesToRead,
  204962. &bytesRead);
  204963. return bytesRead;
  204964. }
  204965. int juce_seekInInternetFile (void* handle, int newPosition)
  204966. {
  204967. if (handle != 0)
  204968. {
  204969. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204970. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204971. }
  204972. return -1;
  204973. }
  204974. int64 juce_getInternetFileContentLength (void* handle)
  204975. {
  204976. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204977. if (crs != 0)
  204978. {
  204979. DWORD index = 0, result = 0, size = sizeof (result);
  204980. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204981. return (int64) result;
  204982. }
  204983. return -1;
  204984. }
  204985. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204986. {
  204987. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204988. if (crs != 0)
  204989. {
  204990. DWORD bufferSizeBytes = 4096;
  204991. for (;;)
  204992. {
  204993. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204994. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204995. {
  204996. StringArray headersArray;
  204997. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204998. for (int i = 0; i < headersArray.size(); ++i)
  204999. {
  205000. const String& header = headersArray[i];
  205001. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  205002. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  205003. const String previousValue (headers [key]);
  205004. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  205005. }
  205006. break;
  205007. }
  205008. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  205009. break;
  205010. }
  205011. }
  205012. }
  205013. void juce_closeInternetFile (void* handle)
  205014. {
  205015. if (handle != 0)
  205016. {
  205017. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  205018. InternetCloseHandle (crs->request);
  205019. InternetCloseHandle (crs->connection);
  205020. }
  205021. }
  205022. namespace MACAddressHelpers
  205023. {
  205024. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  205025. {
  205026. DynamicLibraryLoader dll ("iphlpapi.dll");
  205027. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205028. if (getAdaptersInfo != 0)
  205029. {
  205030. ULONG len = sizeof (IP_ADAPTER_INFO);
  205031. MemoryBlock mb;
  205032. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205033. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205034. {
  205035. mb.setSize (len);
  205036. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205037. }
  205038. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205039. {
  205040. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  205041. {
  205042. if (adapter->AddressLength >= 6)
  205043. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  205044. }
  205045. }
  205046. }
  205047. }
  205048. void getViaNetBios (Array<MACAddress>& result)
  205049. {
  205050. DynamicLibraryLoader dll ("netapi32.dll");
  205051. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205052. if (NetbiosCall != 0)
  205053. {
  205054. NCB ncb;
  205055. zerostruct (ncb);
  205056. struct ASTAT
  205057. {
  205058. ADAPTER_STATUS adapt;
  205059. NAME_BUFFER NameBuff [30];
  205060. };
  205061. ASTAT astat;
  205062. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205063. LANA_ENUM enums;
  205064. zerostruct (enums);
  205065. ncb.ncb_command = NCBENUM;
  205066. ncb.ncb_buffer = (unsigned char*) &enums;
  205067. ncb.ncb_length = sizeof (LANA_ENUM);
  205068. NetbiosCall (&ncb);
  205069. for (int i = 0; i < enums.length; ++i)
  205070. {
  205071. zerostruct (ncb);
  205072. ncb.ncb_command = NCBRESET;
  205073. ncb.ncb_lana_num = enums.lana[i];
  205074. if (NetbiosCall (&ncb) == 0)
  205075. {
  205076. zerostruct (ncb);
  205077. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205078. ncb.ncb_command = NCBASTAT;
  205079. ncb.ncb_lana_num = enums.lana[i];
  205080. ncb.ncb_buffer = (unsigned char*) &astat;
  205081. ncb.ncb_length = sizeof (ASTAT);
  205082. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  205083. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  205084. }
  205085. }
  205086. }
  205087. }
  205088. }
  205089. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  205090. {
  205091. MACAddressHelpers::getViaGetAdaptersInfo (result);
  205092. MACAddressHelpers::getViaNetBios (result);
  205093. }
  205094. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205095. const String& emailSubject,
  205096. const String& bodyText,
  205097. const StringArray& filesToAttach)
  205098. {
  205099. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205100. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205101. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205102. bool ok = false;
  205103. if (mapiSendMail != 0)
  205104. {
  205105. MapiMessage message;
  205106. zerostruct (message);
  205107. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205108. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205109. MapiRecipDesc recip;
  205110. zerostruct (recip);
  205111. recip.ulRecipClass = MAPI_TO;
  205112. String targetEmailAddress_ (targetEmailAddress);
  205113. if (targetEmailAddress_.isEmpty())
  205114. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205115. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205116. message.nRecipCount = 1;
  205117. message.lpRecips = &recip;
  205118. HeapBlock <MapiFileDesc> files;
  205119. files.calloc (filesToAttach.size());
  205120. message.nFileCount = filesToAttach.size();
  205121. message.lpFiles = files;
  205122. for (int i = 0; i < filesToAttach.size(); ++i)
  205123. {
  205124. files[i].nPosition = (ULONG) -1;
  205125. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205126. }
  205127. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205128. }
  205129. FreeLibrary (h);
  205130. return ok;
  205131. }
  205132. #endif
  205133. /*** End of inlined file: juce_win32_Network.cpp ***/
  205134. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205135. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205136. // compiled on its own).
  205137. #if JUCE_INCLUDED_FILE
  205138. namespace
  205139. {
  205140. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  205141. {
  205142. HKEY rootKey = 0;
  205143. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205144. rootKey = HKEY_CURRENT_USER;
  205145. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205146. rootKey = HKEY_LOCAL_MACHINE;
  205147. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205148. rootKey = HKEY_CLASSES_ROOT;
  205149. if (rootKey != 0)
  205150. {
  205151. name = name.substring (name.indexOfChar ('\\') + 1);
  205152. const int lastSlash = name.lastIndexOfChar ('\\');
  205153. valueName = name.substring (lastSlash + 1);
  205154. name = name.substring (0, lastSlash);
  205155. HKEY key;
  205156. DWORD result;
  205157. if (createForWriting)
  205158. {
  205159. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205160. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205161. return key;
  205162. }
  205163. else
  205164. {
  205165. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205166. return key;
  205167. }
  205168. }
  205169. return 0;
  205170. }
  205171. }
  205172. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205173. const String& defaultValue)
  205174. {
  205175. String valueName, result (defaultValue);
  205176. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205177. if (k != 0)
  205178. {
  205179. WCHAR buffer [2048];
  205180. unsigned long bufferSize = sizeof (buffer);
  205181. DWORD type = REG_SZ;
  205182. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205183. {
  205184. if (type == REG_SZ)
  205185. result = buffer;
  205186. else if (type == REG_DWORD)
  205187. result = String ((int) *(DWORD*) buffer);
  205188. }
  205189. RegCloseKey (k);
  205190. }
  205191. return result;
  205192. }
  205193. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205194. const String& value)
  205195. {
  205196. String valueName;
  205197. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205198. if (k != 0)
  205199. {
  205200. RegSetValueEx (k, valueName, 0, REG_SZ,
  205201. (const BYTE*) (const WCHAR*) value,
  205202. sizeof (WCHAR) * (value.length() + 1));
  205203. RegCloseKey (k);
  205204. }
  205205. }
  205206. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205207. {
  205208. bool exists = false;
  205209. String valueName;
  205210. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205211. if (k != 0)
  205212. {
  205213. unsigned char buffer [2048];
  205214. unsigned long bufferSize = sizeof (buffer);
  205215. DWORD type = 0;
  205216. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205217. exists = true;
  205218. RegCloseKey (k);
  205219. }
  205220. return exists;
  205221. }
  205222. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205223. {
  205224. String valueName;
  205225. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205226. if (k != 0)
  205227. {
  205228. RegDeleteValue (k, valueName);
  205229. RegCloseKey (k);
  205230. }
  205231. }
  205232. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205233. {
  205234. String valueName;
  205235. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205236. if (k != 0)
  205237. {
  205238. RegDeleteKey (k, valueName);
  205239. RegCloseKey (k);
  205240. }
  205241. }
  205242. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205243. const String& symbolicDescription,
  205244. const String& fullDescription,
  205245. const File& targetExecutable,
  205246. int iconResourceNumber)
  205247. {
  205248. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205249. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205250. if (iconResourceNumber != 0)
  205251. setRegistryValue (key + "\\DefaultIcon\\",
  205252. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205253. setRegistryValue (key + "\\", fullDescription);
  205254. setRegistryValue (key + "\\shell\\open\\command\\",
  205255. targetExecutable.getFullPathName() + " %1");
  205256. }
  205257. bool juce_IsRunningInWine()
  205258. {
  205259. HKEY key;
  205260. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205261. {
  205262. RegCloseKey (key);
  205263. return true;
  205264. }
  205265. return false;
  205266. }
  205267. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205268. {
  205269. String s (::GetCommandLineW());
  205270. StringArray tokens;
  205271. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205272. return tokens.joinIntoString (" ", 1);
  205273. }
  205274. static void* currentModuleHandle = 0;
  205275. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205276. {
  205277. if (currentModuleHandle == 0)
  205278. currentModuleHandle = GetModuleHandle (0);
  205279. return currentModuleHandle;
  205280. }
  205281. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205282. {
  205283. currentModuleHandle = newHandle;
  205284. }
  205285. void PlatformUtilities::fpuReset()
  205286. {
  205287. #if JUCE_MSVC
  205288. _clearfp();
  205289. #endif
  205290. }
  205291. void PlatformUtilities::beep()
  205292. {
  205293. MessageBeep (MB_OK);
  205294. }
  205295. #endif
  205296. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205297. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205298. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205299. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205300. // compiled on its own).
  205301. #if JUCE_INCLUDED_FILE
  205302. static const unsigned int specialId = WM_APP + 0x4400;
  205303. static const unsigned int broadcastId = WM_APP + 0x4403;
  205304. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205305. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205306. HWND juce_messageWindowHandle = 0;
  205307. extern long improbableWindowNumber; // defined in windowing.cpp
  205308. #ifndef WM_APPCOMMAND
  205309. #define WM_APPCOMMAND 0x0319
  205310. #endif
  205311. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205312. const UINT message,
  205313. const WPARAM wParam,
  205314. const LPARAM lParam) throw()
  205315. {
  205316. JUCE_TRY
  205317. {
  205318. if (h == juce_messageWindowHandle)
  205319. {
  205320. if (message == specialCallbackId)
  205321. {
  205322. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205323. return (LRESULT) (*func) ((void*) lParam);
  205324. }
  205325. else if (message == specialId)
  205326. {
  205327. // these are trapped early in the dispatch call, but must also be checked
  205328. // here in case there are windows modal dialog boxes doing their own
  205329. // dispatch loop and not calling our version
  205330. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205331. return 0;
  205332. }
  205333. else if (message == broadcastId)
  205334. {
  205335. const ScopedPointer <String> messageString ((String*) lParam);
  205336. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205337. return 0;
  205338. }
  205339. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205340. {
  205341. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205342. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205343. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205344. return 0;
  205345. }
  205346. }
  205347. }
  205348. JUCE_CATCH_EXCEPTION
  205349. return DefWindowProc (h, message, wParam, lParam);
  205350. }
  205351. static bool isEventBlockedByModalComps (MSG& m)
  205352. {
  205353. if (Component::getNumCurrentlyModalComponents() == 0
  205354. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205355. return false;
  205356. switch (m.message)
  205357. {
  205358. case WM_MOUSEMOVE:
  205359. case WM_NCMOUSEMOVE:
  205360. case 0x020A: /* WM_MOUSEWHEEL */
  205361. case 0x020E: /* WM_MOUSEHWHEEL */
  205362. case WM_KEYUP:
  205363. case WM_SYSKEYUP:
  205364. case WM_CHAR:
  205365. case WM_APPCOMMAND:
  205366. case WM_LBUTTONUP:
  205367. case WM_MBUTTONUP:
  205368. case WM_RBUTTONUP:
  205369. case WM_MOUSEACTIVATE:
  205370. case WM_NCMOUSEHOVER:
  205371. case WM_MOUSEHOVER:
  205372. return true;
  205373. case WM_NCLBUTTONDOWN:
  205374. case WM_NCLBUTTONDBLCLK:
  205375. case WM_NCRBUTTONDOWN:
  205376. case WM_NCRBUTTONDBLCLK:
  205377. case WM_NCMBUTTONDOWN:
  205378. case WM_NCMBUTTONDBLCLK:
  205379. case WM_LBUTTONDOWN:
  205380. case WM_LBUTTONDBLCLK:
  205381. case WM_MBUTTONDOWN:
  205382. case WM_MBUTTONDBLCLK:
  205383. case WM_RBUTTONDOWN:
  205384. case WM_RBUTTONDBLCLK:
  205385. case WM_KEYDOWN:
  205386. case WM_SYSKEYDOWN:
  205387. {
  205388. Component* const modal = Component::getCurrentlyModalComponent (0);
  205389. if (modal != 0)
  205390. modal->inputAttemptWhenModal();
  205391. return true;
  205392. }
  205393. default:
  205394. break;
  205395. }
  205396. return false;
  205397. }
  205398. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205399. {
  205400. MSG m;
  205401. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205402. return false;
  205403. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205404. {
  205405. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205406. {
  205407. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205408. }
  205409. else if (m.message == WM_QUIT)
  205410. {
  205411. if (JUCEApplication::getInstance() != 0)
  205412. JUCEApplication::getInstance()->systemRequestedQuit();
  205413. }
  205414. else if (! isEventBlockedByModalComps (m))
  205415. {
  205416. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205417. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205418. {
  205419. // if it's someone else's window being clicked on, and the focus is
  205420. // currently on a juce window, pass the kb focus over..
  205421. HWND currentFocus = GetFocus();
  205422. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205423. SetFocus (m.hwnd);
  205424. }
  205425. TranslateMessage (&m);
  205426. DispatchMessage (&m);
  205427. }
  205428. }
  205429. return true;
  205430. }
  205431. bool juce_postMessageToSystemQueue (Message* message)
  205432. {
  205433. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205434. }
  205435. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205436. void* userData)
  205437. {
  205438. if (MessageManager::getInstance()->isThisTheMessageThread())
  205439. {
  205440. return (*callback) (userData);
  205441. }
  205442. else
  205443. {
  205444. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205445. // deadlock because the message manager is blocked from running, and can't
  205446. // call your function..
  205447. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205448. return (void*) SendMessage (juce_messageWindowHandle,
  205449. specialCallbackId,
  205450. (WPARAM) callback,
  205451. (LPARAM) userData);
  205452. }
  205453. }
  205454. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205455. {
  205456. if (hwnd != juce_messageWindowHandle)
  205457. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205458. return TRUE;
  205459. }
  205460. void MessageManager::broadcastMessage (const String& value)
  205461. {
  205462. Array<void*> windows;
  205463. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205464. const String localCopy (value);
  205465. COPYDATASTRUCT data;
  205466. data.dwData = broadcastId;
  205467. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205468. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205469. for (int i = windows.size(); --i >= 0;)
  205470. {
  205471. HWND hwnd = (HWND) windows.getUnchecked(i);
  205472. TCHAR windowName [64]; // no need to read longer strings than this
  205473. GetWindowText (hwnd, windowName, 64);
  205474. windowName [63] = 0;
  205475. if (String (windowName) == messageWindowName)
  205476. {
  205477. DWORD_PTR result;
  205478. SendMessageTimeout (hwnd, WM_COPYDATA,
  205479. (WPARAM) juce_messageWindowHandle,
  205480. (LPARAM) &data,
  205481. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205482. 8000,
  205483. &result);
  205484. }
  205485. }
  205486. }
  205487. static const String getMessageWindowClassName()
  205488. {
  205489. // this name has to be different for each app/dll instance because otherwise
  205490. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205491. // window class).
  205492. static int number = 0;
  205493. if (number == 0)
  205494. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205495. return "JUCEcs_" + String (number);
  205496. }
  205497. void MessageManager::doPlatformSpecificInitialisation()
  205498. {
  205499. OleInitialize (0);
  205500. const String className (getMessageWindowClassName());
  205501. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205502. WNDCLASSEX wc;
  205503. zerostruct (wc);
  205504. wc.cbSize = sizeof (wc);
  205505. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205506. wc.cbWndExtra = 4;
  205507. wc.hInstance = hmod;
  205508. wc.lpszClassName = className;
  205509. RegisterClassEx (&wc);
  205510. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205511. messageWindowName,
  205512. 0, 0, 0, 0, 0, 0, 0,
  205513. hmod, 0);
  205514. }
  205515. void MessageManager::doPlatformSpecificShutdown()
  205516. {
  205517. DestroyWindow (juce_messageWindowHandle);
  205518. UnregisterClass (getMessageWindowClassName(), 0);
  205519. OleUninitialize();
  205520. }
  205521. #endif
  205522. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205523. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205524. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205525. // compiled on its own).
  205526. #if JUCE_INCLUDED_FILE
  205527. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205528. NEWTEXTMETRICEXW*,
  205529. int type,
  205530. LPARAM lParam)
  205531. {
  205532. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205533. {
  205534. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205535. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205536. }
  205537. return 1;
  205538. }
  205539. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205540. NEWTEXTMETRICEXW*,
  205541. int type,
  205542. LPARAM lParam)
  205543. {
  205544. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205545. {
  205546. LOGFONTW lf;
  205547. zerostruct (lf);
  205548. lf.lfWeight = FW_DONTCARE;
  205549. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205550. lf.lfQuality = DEFAULT_QUALITY;
  205551. lf.lfCharSet = DEFAULT_CHARSET;
  205552. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205553. lf.lfPitchAndFamily = FF_DONTCARE;
  205554. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205555. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205556. HDC dc = CreateCompatibleDC (0);
  205557. EnumFontFamiliesEx (dc, &lf,
  205558. (FONTENUMPROCW) &wfontEnum2,
  205559. lParam, 0);
  205560. DeleteDC (dc);
  205561. }
  205562. return 1;
  205563. }
  205564. const StringArray Font::findAllTypefaceNames()
  205565. {
  205566. StringArray results;
  205567. HDC dc = CreateCompatibleDC (0);
  205568. {
  205569. LOGFONTW lf;
  205570. zerostruct (lf);
  205571. lf.lfWeight = FW_DONTCARE;
  205572. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205573. lf.lfQuality = DEFAULT_QUALITY;
  205574. lf.lfCharSet = DEFAULT_CHARSET;
  205575. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205576. lf.lfPitchAndFamily = FF_DONTCARE;
  205577. lf.lfFaceName[0] = 0;
  205578. EnumFontFamiliesEx (dc, &lf,
  205579. (FONTENUMPROCW) &wfontEnum1,
  205580. (LPARAM) &results, 0);
  205581. }
  205582. DeleteDC (dc);
  205583. results.sort (true);
  205584. return results;
  205585. }
  205586. extern bool juce_IsRunningInWine();
  205587. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205588. {
  205589. if (juce_IsRunningInWine())
  205590. {
  205591. // If we're running in Wine, then use fonts that might be available on Linux..
  205592. defaultSans = "Bitstream Vera Sans";
  205593. defaultSerif = "Bitstream Vera Serif";
  205594. defaultFixed = "Bitstream Vera Sans Mono";
  205595. }
  205596. else
  205597. {
  205598. defaultSans = "Verdana";
  205599. defaultSerif = "Times";
  205600. defaultFixed = "Lucida Console";
  205601. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205602. }
  205603. }
  205604. class FontDCHolder : private DeletedAtShutdown
  205605. {
  205606. public:
  205607. FontDCHolder()
  205608. : dc (0), numKPs (0), size (0),
  205609. bold (false), italic (false)
  205610. {
  205611. }
  205612. ~FontDCHolder()
  205613. {
  205614. if (dc != 0)
  205615. {
  205616. DeleteDC (dc);
  205617. DeleteObject (fontH);
  205618. }
  205619. clearSingletonInstance();
  205620. }
  205621. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205622. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205623. {
  205624. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205625. {
  205626. fontName = fontName_;
  205627. bold = bold_;
  205628. italic = italic_;
  205629. size = size_;
  205630. if (dc != 0)
  205631. {
  205632. DeleteDC (dc);
  205633. DeleteObject (fontH);
  205634. kps.free();
  205635. }
  205636. fontH = 0;
  205637. dc = CreateCompatibleDC (0);
  205638. SetMapperFlags (dc, 0);
  205639. SetMapMode (dc, MM_TEXT);
  205640. LOGFONTW lfw;
  205641. zerostruct (lfw);
  205642. lfw.lfCharSet = DEFAULT_CHARSET;
  205643. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205644. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205645. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205646. lfw.lfQuality = PROOF_QUALITY;
  205647. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205648. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205649. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205650. lfw.lfHeight = size > 0 ? size : -256;
  205651. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205652. if (standardSizedFont != 0)
  205653. {
  205654. if (SelectObject (dc, standardSizedFont) != 0)
  205655. {
  205656. fontH = standardSizedFont;
  205657. if (size == 0)
  205658. {
  205659. OUTLINETEXTMETRIC otm;
  205660. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205661. {
  205662. lfw.lfHeight = -(int) otm.otmEMSquare;
  205663. fontH = CreateFontIndirect (&lfw);
  205664. SelectObject (dc, fontH);
  205665. DeleteObject (standardSizedFont);
  205666. }
  205667. }
  205668. }
  205669. else
  205670. {
  205671. jassertfalse;
  205672. }
  205673. }
  205674. else
  205675. {
  205676. jassertfalse;
  205677. }
  205678. }
  205679. return dc;
  205680. }
  205681. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205682. {
  205683. if (kps == 0)
  205684. {
  205685. numKPs = GetKerningPairs (dc, 0, 0);
  205686. kps.calloc (numKPs);
  205687. GetKerningPairs (dc, numKPs, kps);
  205688. }
  205689. numKPs_ = numKPs;
  205690. return kps;
  205691. }
  205692. private:
  205693. HFONT fontH;
  205694. HDC dc;
  205695. String fontName;
  205696. HeapBlock <KERNINGPAIR> kps;
  205697. int numKPs, size;
  205698. bool bold, italic;
  205699. FontDCHolder (const FontDCHolder&);
  205700. FontDCHolder& operator= (const FontDCHolder&);
  205701. };
  205702. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205703. class WindowsTypeface : public CustomTypeface
  205704. {
  205705. public:
  205706. WindowsTypeface (const Font& font)
  205707. {
  205708. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205709. font.isBold(), font.isItalic(), 0);
  205710. TEXTMETRIC tm;
  205711. tm.tmAscent = tm.tmHeight = 1;
  205712. tm.tmDefaultChar = 0;
  205713. GetTextMetrics (dc, &tm);
  205714. setCharacteristics (font.getTypefaceName(),
  205715. tm.tmAscent / (float) tm.tmHeight,
  205716. font.isBold(), font.isItalic(),
  205717. tm.tmDefaultChar);
  205718. }
  205719. bool loadGlyphIfPossible (juce_wchar character)
  205720. {
  205721. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205722. GLYPHMETRICS gm;
  205723. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205724. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205725. // gets correctly created later on.
  205726. if (! isFallbackFont)
  205727. {
  205728. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205729. WORD index = 0;
  205730. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205731. && index == 0xffff)
  205732. {
  205733. return false;
  205734. }
  205735. }
  205736. Path glyphPath;
  205737. TEXTMETRIC tm;
  205738. if (! GetTextMetrics (dc, &tm))
  205739. {
  205740. addGlyph (character, glyphPath, 0);
  205741. return true;
  205742. }
  205743. const float height = (float) tm.tmHeight;
  205744. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205745. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205746. &gm, 0, 0, &identityMatrix);
  205747. if (bufSize > 0)
  205748. {
  205749. HeapBlock<char> data (bufSize);
  205750. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205751. bufSize, data, &identityMatrix);
  205752. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205753. const float scaleX = 1.0f / height;
  205754. const float scaleY = -1.0f / height;
  205755. while ((char*) pheader < data + bufSize)
  205756. {
  205757. float x = scaleX * pheader->pfxStart.x.value;
  205758. float y = scaleY * pheader->pfxStart.y.value;
  205759. glyphPath.startNewSubPath (x, y);
  205760. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205761. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205762. while ((const char*) curve < curveEnd)
  205763. {
  205764. if (curve->wType == TT_PRIM_LINE)
  205765. {
  205766. for (int i = 0; i < curve->cpfx; ++i)
  205767. {
  205768. x = scaleX * curve->apfx[i].x.value;
  205769. y = scaleY * curve->apfx[i].y.value;
  205770. glyphPath.lineTo (x, y);
  205771. }
  205772. }
  205773. else if (curve->wType == TT_PRIM_QSPLINE)
  205774. {
  205775. for (int i = 0; i < curve->cpfx - 1; ++i)
  205776. {
  205777. const float x2 = scaleX * curve->apfx[i].x.value;
  205778. const float y2 = scaleY * curve->apfx[i].y.value;
  205779. float x3, y3;
  205780. if (i < curve->cpfx - 2)
  205781. {
  205782. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205783. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205784. }
  205785. else
  205786. {
  205787. x3 = scaleX * curve->apfx[i + 1].x.value;
  205788. y3 = scaleY * curve->apfx[i + 1].y.value;
  205789. }
  205790. glyphPath.quadraticTo (x2, y2, x3, y3);
  205791. x = x3;
  205792. y = y3;
  205793. }
  205794. }
  205795. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205796. }
  205797. pheader = (const TTPOLYGONHEADER*) curve;
  205798. glyphPath.closeSubPath();
  205799. }
  205800. }
  205801. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205802. int numKPs;
  205803. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205804. for (int i = 0; i < numKPs; ++i)
  205805. {
  205806. if (kps[i].wFirst == character)
  205807. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205808. kps[i].iKernAmount / height);
  205809. }
  205810. return true;
  205811. }
  205812. juce_UseDebuggingNewOperator
  205813. };
  205814. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205815. {
  205816. return new WindowsTypeface (font);
  205817. }
  205818. #endif
  205819. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205820. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205821. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205822. // compiled on its own).
  205823. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205824. class SharedD2DFactory : public DeletedAtShutdown
  205825. {
  205826. public:
  205827. SharedD2DFactory()
  205828. {
  205829. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205830. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205831. if (directWriteFactory != 0)
  205832. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205833. }
  205834. ~SharedD2DFactory()
  205835. {
  205836. clearSingletonInstance();
  205837. }
  205838. juce_DeclareSingleton (SharedD2DFactory, false);
  205839. ComSmartPtr <ID2D1Factory> d2dFactory;
  205840. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205841. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205842. };
  205843. juce_ImplementSingleton (SharedD2DFactory)
  205844. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205845. {
  205846. public:
  205847. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205848. : hwnd (hwnd_),
  205849. currentState (0)
  205850. {
  205851. RECT windowRect;
  205852. GetClientRect (hwnd, &windowRect);
  205853. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205854. bounds.setSize (size.width, size.height);
  205855. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205856. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205857. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205858. // xxx check for error
  205859. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205860. }
  205861. ~Direct2DLowLevelGraphicsContext()
  205862. {
  205863. states.clear();
  205864. }
  205865. void resized()
  205866. {
  205867. RECT windowRect;
  205868. GetClientRect (hwnd, &windowRect);
  205869. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205870. renderingTarget->Resize (size);
  205871. bounds.setSize (size.width, size.height);
  205872. }
  205873. void clear()
  205874. {
  205875. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205876. }
  205877. void start()
  205878. {
  205879. renderingTarget->BeginDraw();
  205880. saveState();
  205881. }
  205882. void end()
  205883. {
  205884. states.clear();
  205885. currentState = 0;
  205886. renderingTarget->EndDraw();
  205887. renderingTarget->CheckWindowState();
  205888. }
  205889. bool isVectorDevice() const { return false; }
  205890. void setOrigin (int x, int y)
  205891. {
  205892. currentState->origin.addXY (x, y);
  205893. }
  205894. void addTransform (const AffineTransform& transform)
  205895. {
  205896. //xxx todo
  205897. jassertfalse;
  205898. }
  205899. bool clipToRectangle (const Rectangle<int>& r)
  205900. {
  205901. currentState->clipToRectangle (r);
  205902. return ! isClipEmpty();
  205903. }
  205904. bool clipToRectangleList (const RectangleList& clipRegion)
  205905. {
  205906. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205907. return ! isClipEmpty();
  205908. }
  205909. void excludeClipRectangle (const Rectangle<int>&)
  205910. {
  205911. //xxx
  205912. }
  205913. void clipToPath (const Path& path, const AffineTransform& transform)
  205914. {
  205915. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205916. }
  205917. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205918. {
  205919. currentState->clipToImage (sourceImage,transform);
  205920. }
  205921. bool clipRegionIntersects (const Rectangle<int>& r)
  205922. {
  205923. const Rectangle<int> r2 (r + currentState->origin);
  205924. return currentState->clipRect.intersects (r2);
  205925. }
  205926. const Rectangle<int> getClipBounds() const
  205927. {
  205928. // xxx could this take into account complex clip regions?
  205929. return currentState->clipRect - currentState->origin;
  205930. }
  205931. bool isClipEmpty() const
  205932. {
  205933. return currentState->clipRect.isEmpty();
  205934. }
  205935. void saveState()
  205936. {
  205937. states.add (new SavedState (*this));
  205938. currentState = states.getLast();
  205939. }
  205940. void restoreState()
  205941. {
  205942. jassert (states.size() > 1) //you should never pop the last state!
  205943. states.removeLast (1);
  205944. currentState = states.getLast();
  205945. }
  205946. void setFill (const FillType& fillType)
  205947. {
  205948. currentState->setFill (fillType);
  205949. }
  205950. void setOpacity (float newOpacity)
  205951. {
  205952. currentState->setOpacity (newOpacity);
  205953. }
  205954. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205955. {
  205956. }
  205957. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205958. {
  205959. currentState->createBrush();
  205960. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205961. }
  205962. void fillPath (const Path& p, const AffineTransform& transform)
  205963. {
  205964. currentState->createBrush();
  205965. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205966. if (renderingTarget != 0)
  205967. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205968. }
  205969. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205970. {
  205971. const int x = currentState->origin.getX();
  205972. const int y = currentState->origin.getY();
  205973. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205974. D2D1_SIZE_U size;
  205975. size.width = image.getWidth();
  205976. size.height = image.getHeight();
  205977. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205978. Image img (image.convertedToFormat (Image::ARGB));
  205979. Image::BitmapData bd (img, false);
  205980. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205981. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205982. {
  205983. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205984. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  205985. if (tempBitmap != 0)
  205986. renderingTarget->DrawBitmap (tempBitmap);
  205987. }
  205988. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205989. }
  205990. void drawLine (const Line <float>& line)
  205991. {
  205992. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205993. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205994. line.getEnd() + currentState->origin.toFloat());
  205995. currentState->createBrush();
  205996. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205997. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205998. currentState->currentBrush);
  205999. }
  206000. void drawVerticalLine (int x, float top, float bottom)
  206001. {
  206002. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206003. currentState->createBrush();
  206004. x += currentState->origin.getX();
  206005. const int y = currentState->origin.getY();
  206006. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  206007. D2D1::Point2F (x, y + bottom),
  206008. currentState->currentBrush);
  206009. }
  206010. void drawHorizontalLine (int y, float left, float right)
  206011. {
  206012. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206013. currentState->createBrush();
  206014. y += currentState->origin.getY();
  206015. const int x = currentState->origin.getX();
  206016. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  206017. D2D1::Point2F (x + right, y),
  206018. currentState->currentBrush);
  206019. }
  206020. void setFont (const Font& newFont)
  206021. {
  206022. currentState->setFont (newFont);
  206023. }
  206024. const Font getFont()
  206025. {
  206026. return currentState->font;
  206027. }
  206028. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206029. {
  206030. const float x = currentState->origin.getX();
  206031. const float y = currentState->origin.getY();
  206032. currentState->createBrush();
  206033. currentState->createFont();
  206034. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206035. float hScale = currentState->font.getHorizontalScale();
  206036. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206037. float dpiX = 0, dpiY = 0;
  206038. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206039. UINT32 glyphNum = glyphNumber;
  206040. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206041. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206042. DWRITE_GLYPH_OFFSET offset;
  206043. offset.advanceOffset = 0;
  206044. offset.ascenderOffset = 0;
  206045. float glyphAdvances = 0;
  206046. DWRITE_GLYPH_RUN glyph;
  206047. glyph.fontFace = currentState->currentFontFace;
  206048. glyph.glyphCount = 1;
  206049. glyph.glyphIndices = &glyphNum1;
  206050. glyph.isSideways = FALSE;
  206051. glyph.glyphAdvances = &glyphAdvances;
  206052. glyph.glyphOffsets = &offset;
  206053. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206054. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206055. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206056. }
  206057. class SavedState
  206058. {
  206059. public:
  206060. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206061. : owner (owner_), currentBrush (0),
  206062. fontScaling (1.0f), currentFontFace (0),
  206063. clipsRect (false), shouldClipRect (false),
  206064. clipsRectList (false), shouldClipRectList (false),
  206065. clipsComplex (false), shouldClipComplex (false),
  206066. clipsBitmap (false), shouldClipBitmap (false)
  206067. {
  206068. if (owner.currentState != 0)
  206069. {
  206070. // xxx seems like a very slow way to create one of these, and this is a performance
  206071. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206072. setFill (owner.currentState->fillType);
  206073. currentBrush = owner.currentState->currentBrush;
  206074. origin = owner.currentState->origin;
  206075. clipRect = owner.currentState->clipRect;
  206076. font = owner.currentState->font;
  206077. currentFontFace = owner.currentState->currentFontFace;
  206078. }
  206079. else
  206080. {
  206081. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206082. clipRect.setSize (size.width, size.height);
  206083. setFill (FillType (Colours::black));
  206084. }
  206085. }
  206086. ~SavedState()
  206087. {
  206088. clearClip();
  206089. clearFont();
  206090. clearFill();
  206091. clearPathClip();
  206092. clearImageClip();
  206093. complexClipLayer = 0;
  206094. bitmapMaskLayer = 0;
  206095. }
  206096. void clearClip()
  206097. {
  206098. popClips();
  206099. shouldClipRect = false;
  206100. }
  206101. void clipToRectangle (const Rectangle<int>& r)
  206102. {
  206103. clearClip();
  206104. clipRect = r + origin;
  206105. shouldClipRect = true;
  206106. pushClips();
  206107. }
  206108. void clearPathClip()
  206109. {
  206110. popClips();
  206111. if (shouldClipComplex)
  206112. {
  206113. complexClipGeometry = 0;
  206114. shouldClipComplex = false;
  206115. }
  206116. }
  206117. void clipToPath (ID2D1Geometry* geometry)
  206118. {
  206119. clearPathClip();
  206120. if (complexClipLayer == 0)
  206121. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206122. complexClipGeometry = geometry;
  206123. shouldClipComplex = true;
  206124. pushClips();
  206125. }
  206126. void clearRectListClip()
  206127. {
  206128. popClips();
  206129. if (shouldClipRectList)
  206130. {
  206131. rectListGeometry = 0;
  206132. shouldClipRectList = false;
  206133. }
  206134. }
  206135. void clipToRectList (ID2D1Geometry* geometry)
  206136. {
  206137. clearRectListClip();
  206138. if (rectListLayer == 0)
  206139. owner.renderingTarget->CreateLayer (&rectListLayer);
  206140. rectListGeometry = geometry;
  206141. shouldClipRectList = true;
  206142. pushClips();
  206143. }
  206144. void clearImageClip()
  206145. {
  206146. popClips();
  206147. if (shouldClipBitmap)
  206148. {
  206149. maskBitmap = 0;
  206150. bitmapMaskBrush = 0;
  206151. shouldClipBitmap = false;
  206152. }
  206153. }
  206154. void clipToImage (const Image& image, const AffineTransform& transform)
  206155. {
  206156. clearImageClip();
  206157. if (bitmapMaskLayer == 0)
  206158. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206159. D2D1_BRUSH_PROPERTIES brushProps;
  206160. brushProps.opacity = 1;
  206161. brushProps.transform = transfromToMatrix (transform);
  206162. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206163. D2D1_SIZE_U size;
  206164. size.width = image.getWidth();
  206165. size.height = image.getHeight();
  206166. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206167. maskImage = image.convertedToFormat (Image::ARGB);
  206168. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206169. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206170. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206171. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206172. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206173. imageMaskLayerParams = D2D1::LayerParameters();
  206174. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206175. shouldClipBitmap = true;
  206176. pushClips();
  206177. }
  206178. void popClips()
  206179. {
  206180. if (clipsBitmap)
  206181. {
  206182. owner.renderingTarget->PopLayer();
  206183. clipsBitmap = false;
  206184. }
  206185. if (clipsComplex)
  206186. {
  206187. owner.renderingTarget->PopLayer();
  206188. clipsComplex = false;
  206189. }
  206190. if (clipsRectList)
  206191. {
  206192. owner.renderingTarget->PopLayer();
  206193. clipsRectList = false;
  206194. }
  206195. if (clipsRect)
  206196. {
  206197. owner.renderingTarget->PopAxisAlignedClip();
  206198. clipsRect = false;
  206199. }
  206200. }
  206201. void pushClips()
  206202. {
  206203. if (shouldClipRect && ! clipsRect)
  206204. {
  206205. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206206. clipsRect = true;
  206207. }
  206208. if (shouldClipRectList && ! clipsRectList)
  206209. {
  206210. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206211. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206212. layerParams.geometricMask = rectListGeometry;
  206213. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206214. clipsRectList = true;
  206215. }
  206216. if (shouldClipComplex && ! clipsComplex)
  206217. {
  206218. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206219. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206220. layerParams.geometricMask = complexClipGeometry;
  206221. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206222. clipsComplex = true;
  206223. }
  206224. if (shouldClipBitmap && ! clipsBitmap)
  206225. {
  206226. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206227. clipsBitmap = true;
  206228. }
  206229. }
  206230. void setFill (const FillType& newFillType)
  206231. {
  206232. if (fillType != newFillType)
  206233. {
  206234. fillType = newFillType;
  206235. clearFill();
  206236. }
  206237. }
  206238. void clearFont()
  206239. {
  206240. currentFontFace = localFontFace = 0;
  206241. }
  206242. void setFont (const Font& newFont)
  206243. {
  206244. if (font != newFont)
  206245. {
  206246. font = newFont;
  206247. clearFont();
  206248. }
  206249. }
  206250. void createFont()
  206251. {
  206252. // xxx The font shouldn't be managed by the graphics context.
  206253. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206254. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206255. // WindowsTypeface class.
  206256. if (currentFontFace == 0)
  206257. {
  206258. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206259. fontScaling = systemType->getAscent();
  206260. BOOL fontFound;
  206261. uint32 fontIndex;
  206262. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206263. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206264. if (! fontFound)
  206265. fontIndex = 0;
  206266. ComSmartPtr <IDWriteFontFamily> fontFam;
  206267. fonts->GetFontFamily (fontIndex, &fontFam);
  206268. ComSmartPtr <IDWriteFont> font;
  206269. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206270. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206271. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206272. font->CreateFontFace (&localFontFace);
  206273. currentFontFace = localFontFace;
  206274. }
  206275. }
  206276. void setOpacity (float newOpacity)
  206277. {
  206278. fillType.setOpacity (newOpacity);
  206279. if (currentBrush != 0)
  206280. currentBrush->SetOpacity (newOpacity);
  206281. }
  206282. void clearFill()
  206283. {
  206284. gradientStops = 0;
  206285. linearGradient = 0;
  206286. radialGradient = 0;
  206287. bitmap = 0;
  206288. bitmapBrush = 0;
  206289. currentBrush = 0;
  206290. }
  206291. void createBrush()
  206292. {
  206293. if (currentBrush == 0)
  206294. {
  206295. const int x = origin.getX();
  206296. const int y = origin.getY();
  206297. if (fillType.isColour())
  206298. {
  206299. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206300. owner.colourBrush->SetColor (colour);
  206301. currentBrush = owner.colourBrush;
  206302. }
  206303. else if (fillType.isTiledImage())
  206304. {
  206305. D2D1_BRUSH_PROPERTIES brushProps;
  206306. brushProps.opacity = fillType.getOpacity();
  206307. brushProps.transform = transfromToMatrix (fillType.transform);
  206308. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206309. image = fillType.image;
  206310. D2D1_SIZE_U size;
  206311. size.width = image.getWidth();
  206312. size.height = image.getHeight();
  206313. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206314. this->image = image.convertedToFormat (Image::ARGB);
  206315. Image::BitmapData bd (this->image, false);
  206316. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206317. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206318. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206319. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206320. currentBrush = bitmapBrush;
  206321. }
  206322. else if (fillType.isGradient())
  206323. {
  206324. gradientStops = 0;
  206325. D2D1_BRUSH_PROPERTIES brushProps;
  206326. brushProps.opacity = fillType.getOpacity();
  206327. brushProps.transform = transfromToMatrix (fillType.transform);
  206328. const int numColors = fillType.gradient->getNumColours();
  206329. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206330. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206331. {
  206332. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206333. stops[i].position = fillType.gradient->getColourPosition(i);
  206334. }
  206335. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206336. if (fillType.gradient->isRadial)
  206337. {
  206338. radialGradient = 0;
  206339. const Point<float>& p1 = fillType.gradient->point1;
  206340. const Point<float>& p2 = fillType.gradient->point2;
  206341. float r = p1.getDistanceFrom (p2);
  206342. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206343. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206344. D2D1::Point2F (0, 0),
  206345. r, r);
  206346. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206347. currentBrush = radialGradient;
  206348. }
  206349. else
  206350. {
  206351. linearGradient = 0;
  206352. const Point<float>& p1 = fillType.gradient->point1;
  206353. const Point<float>& p2 = fillType.gradient->point2;
  206354. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206355. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206356. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206357. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206358. currentBrush = linearGradient;
  206359. }
  206360. }
  206361. }
  206362. }
  206363. juce_UseDebuggingNewOperator
  206364. //xxx most of these members should probably be private...
  206365. Direct2DLowLevelGraphicsContext& owner;
  206366. Point<int> origin;
  206367. Font font;
  206368. float fontScaling;
  206369. IDWriteFontFace* currentFontFace;
  206370. ComSmartPtr <IDWriteFontFace> localFontFace;
  206371. FillType fillType;
  206372. Image image;
  206373. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206374. Rectangle<int> clipRect;
  206375. bool clipsRect, shouldClipRect;
  206376. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206377. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206378. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206379. bool clipsComplex, shouldClipComplex;
  206380. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206381. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206382. ComSmartPtr <ID2D1Layer> rectListLayer;
  206383. bool clipsRectList, shouldClipRectList;
  206384. Image maskImage;
  206385. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206386. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206387. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206388. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206389. bool clipsBitmap, shouldClipBitmap;
  206390. ID2D1Brush* currentBrush;
  206391. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206392. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206393. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206394. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206395. private:
  206396. SavedState (const SavedState&);
  206397. SavedState& operator= (const SavedState& other);
  206398. };
  206399. juce_UseDebuggingNewOperator
  206400. private:
  206401. HWND hwnd;
  206402. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206403. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206404. Rectangle<int> bounds;
  206405. SavedState* currentState;
  206406. OwnedArray<SavedState> states;
  206407. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206408. {
  206409. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206410. }
  206411. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206412. {
  206413. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206414. }
  206415. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206416. {
  206417. transform.transformPoint (x, y);
  206418. return D2D1::Point2F (x, y);
  206419. }
  206420. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206421. {
  206422. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206423. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206424. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206425. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206426. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206427. }
  206428. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206429. {
  206430. ID2D1PathGeometry* p = 0;
  206431. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206432. ComSmartPtr <ID2D1GeometrySink> sink;
  206433. HRESULT hr = p->Open (&sink); // xxx handle error
  206434. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206435. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206436. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206437. hr = sink->Close();
  206438. return p;
  206439. }
  206440. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206441. {
  206442. Path::Iterator it (path);
  206443. while (it.next())
  206444. {
  206445. switch (it.elementType)
  206446. {
  206447. case Path::Iterator::cubicTo:
  206448. {
  206449. D2D1_BEZIER_SEGMENT seg;
  206450. transform.transformPoint (it.x1, it.y1);
  206451. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206452. transform.transformPoint (it.x2, it.y2);
  206453. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206454. transform.transformPoint(it.x3, it.y3);
  206455. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206456. sink->AddBezier (seg);
  206457. break;
  206458. }
  206459. case Path::Iterator::lineTo:
  206460. {
  206461. transform.transformPoint (it.x1, it.y1);
  206462. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206463. break;
  206464. }
  206465. case Path::Iterator::quadraticTo:
  206466. {
  206467. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206468. transform.transformPoint (it.x1, it.y1);
  206469. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206470. transform.transformPoint (it.x2, it.y2);
  206471. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206472. sink->AddQuadraticBezier (seg);
  206473. break;
  206474. }
  206475. case Path::Iterator::closePath:
  206476. {
  206477. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206478. break;
  206479. }
  206480. case Path::Iterator::startNewSubPath:
  206481. {
  206482. transform.transformPoint (it.x1, it.y1);
  206483. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206484. break;
  206485. }
  206486. }
  206487. }
  206488. }
  206489. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206490. {
  206491. ID2D1PathGeometry* p = 0;
  206492. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206493. ComSmartPtr <ID2D1GeometrySink> sink;
  206494. HRESULT hr = p->Open (&sink);
  206495. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206496. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206497. hr = sink->Close();
  206498. return p;
  206499. }
  206500. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206501. {
  206502. D2D1::Matrix3x2F matrix;
  206503. matrix._11 = transform.mat00;
  206504. matrix._12 = transform.mat10;
  206505. matrix._21 = transform.mat01;
  206506. matrix._22 = transform.mat11;
  206507. matrix._31 = transform.mat02;
  206508. matrix._32 = transform.mat12;
  206509. return matrix;
  206510. }
  206511. };
  206512. #endif
  206513. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206514. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206515. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206516. // compiled on its own).
  206517. #if JUCE_INCLUDED_FILE
  206518. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206519. // these are in the windows SDK, but need to be repeated here for GCC..
  206520. #ifndef GET_APPCOMMAND_LPARAM
  206521. #define FAPPCOMMAND_MASK 0xF000
  206522. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206523. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206524. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206525. #define APPCOMMAND_MEDIA_STOP 13
  206526. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206527. #define WM_APPCOMMAND 0x0319
  206528. #endif
  206529. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206530. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206531. extern bool juce_IsRunningInWine();
  206532. #ifndef ULW_ALPHA
  206533. #define ULW_ALPHA 0x00000002
  206534. #endif
  206535. #ifndef AC_SRC_ALPHA
  206536. #define AC_SRC_ALPHA 0x01
  206537. #endif
  206538. static HPALETTE palette = 0;
  206539. static bool createPaletteIfNeeded = true;
  206540. static bool shouldDeactivateTitleBar = true;
  206541. #define WM_TRAYNOTIFY WM_USER + 100
  206542. using ::abs;
  206543. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206544. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206545. bool Desktop::canUseSemiTransparentWindows() throw()
  206546. {
  206547. if (updateLayeredWindow == 0)
  206548. {
  206549. if (! juce_IsRunningInWine())
  206550. {
  206551. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206552. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206553. }
  206554. }
  206555. return updateLayeredWindow != 0;
  206556. }
  206557. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206558. {
  206559. return upright;
  206560. }
  206561. const int extendedKeyModifier = 0x10000;
  206562. const int KeyPress::spaceKey = VK_SPACE;
  206563. const int KeyPress::returnKey = VK_RETURN;
  206564. const int KeyPress::escapeKey = VK_ESCAPE;
  206565. const int KeyPress::backspaceKey = VK_BACK;
  206566. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206567. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206568. const int KeyPress::tabKey = VK_TAB;
  206569. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206570. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206571. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206572. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206573. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206574. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206575. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206576. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206577. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206578. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206579. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206580. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206581. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206582. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206583. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206584. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206585. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206586. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206587. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206588. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206589. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206590. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206591. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206592. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206593. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206594. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206595. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206596. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206597. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206598. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206599. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206600. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206601. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206602. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206603. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206604. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206605. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206606. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206607. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206608. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206609. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206610. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206611. const int KeyPress::playKey = 0x30000;
  206612. const int KeyPress::stopKey = 0x30001;
  206613. const int KeyPress::fastForwardKey = 0x30002;
  206614. const int KeyPress::rewindKey = 0x30003;
  206615. class WindowsBitmapImage : public Image::SharedImage
  206616. {
  206617. public:
  206618. HBITMAP hBitmap;
  206619. BITMAPV4HEADER bitmapInfo;
  206620. HDC hdc;
  206621. unsigned char* bitmapData;
  206622. WindowsBitmapImage (const Image::PixelFormat format_,
  206623. const int w, const int h, const bool clearImage)
  206624. : Image::SharedImage (format_, w, h)
  206625. {
  206626. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206627. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206628. zerostruct (bitmapInfo);
  206629. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206630. bitmapInfo.bV4Width = w;
  206631. bitmapInfo.bV4Height = h;
  206632. bitmapInfo.bV4Planes = 1;
  206633. bitmapInfo.bV4CSType = 1;
  206634. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206635. if (format_ == Image::ARGB)
  206636. {
  206637. bitmapInfo.bV4AlphaMask = 0xff000000;
  206638. bitmapInfo.bV4RedMask = 0xff0000;
  206639. bitmapInfo.bV4GreenMask = 0xff00;
  206640. bitmapInfo.bV4BlueMask = 0xff;
  206641. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206642. }
  206643. else
  206644. {
  206645. bitmapInfo.bV4V4Compression = BI_RGB;
  206646. }
  206647. lineStride = -((w * pixelStride + 3) & ~3);
  206648. HDC dc = GetDC (0);
  206649. hdc = CreateCompatibleDC (dc);
  206650. ReleaseDC (0, dc);
  206651. SetMapMode (hdc, MM_TEXT);
  206652. hBitmap = CreateDIBSection (hdc,
  206653. (BITMAPINFO*) &(bitmapInfo),
  206654. DIB_RGB_COLORS,
  206655. (void**) &bitmapData,
  206656. 0, 0);
  206657. SelectObject (hdc, hBitmap);
  206658. if (format_ == Image::ARGB && clearImage)
  206659. zeromem (bitmapData, abs (h * lineStride));
  206660. imageData = bitmapData - (lineStride * (h - 1));
  206661. }
  206662. ~WindowsBitmapImage()
  206663. {
  206664. DeleteDC (hdc);
  206665. DeleteObject (hBitmap);
  206666. }
  206667. Image::ImageType getType() const { return Image::NativeImage; }
  206668. LowLevelGraphicsContext* createLowLevelContext()
  206669. {
  206670. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206671. }
  206672. Image::SharedImage* clone()
  206673. {
  206674. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206675. for (int i = 0; i < height; ++i)
  206676. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206677. return im;
  206678. }
  206679. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206680. const int x, const int y,
  206681. const RectangleList& maskedRegion,
  206682. const uint8 updateLayeredWindowAlpha) throw()
  206683. {
  206684. static HDRAWDIB hdd = 0;
  206685. static bool needToCreateDrawDib = true;
  206686. if (needToCreateDrawDib)
  206687. {
  206688. needToCreateDrawDib = false;
  206689. HDC dc = GetDC (0);
  206690. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206691. ReleaseDC (0, dc);
  206692. // only open if we're not palettised
  206693. if (n > 8)
  206694. hdd = DrawDibOpen();
  206695. }
  206696. if (createPaletteIfNeeded)
  206697. {
  206698. HDC dc = GetDC (0);
  206699. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206700. ReleaseDC (0, dc);
  206701. if (n <= 8)
  206702. palette = CreateHalftonePalette (dc);
  206703. createPaletteIfNeeded = false;
  206704. }
  206705. if (palette != 0)
  206706. {
  206707. SelectPalette (dc, palette, FALSE);
  206708. RealizePalette (dc);
  206709. SetStretchBltMode (dc, HALFTONE);
  206710. }
  206711. SetMapMode (dc, MM_TEXT);
  206712. if (transparent)
  206713. {
  206714. POINT p, pos;
  206715. SIZE size;
  206716. RECT windowBounds;
  206717. GetWindowRect (hwnd, &windowBounds);
  206718. p.x = -x;
  206719. p.y = -y;
  206720. pos.x = windowBounds.left;
  206721. pos.y = windowBounds.top;
  206722. size.cx = windowBounds.right - windowBounds.left;
  206723. size.cy = windowBounds.bottom - windowBounds.top;
  206724. BLENDFUNCTION bf;
  206725. bf.AlphaFormat = AC_SRC_ALPHA;
  206726. bf.BlendFlags = 0;
  206727. bf.BlendOp = AC_SRC_OVER;
  206728. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206729. if (! maskedRegion.isEmpty())
  206730. {
  206731. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206732. {
  206733. const Rectangle<int>& r = *i.getRectangle();
  206734. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206735. }
  206736. }
  206737. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206738. }
  206739. else
  206740. {
  206741. int savedDC = 0;
  206742. if (! maskedRegion.isEmpty())
  206743. {
  206744. savedDC = SaveDC (dc);
  206745. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206746. {
  206747. const Rectangle<int>& r = *i.getRectangle();
  206748. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206749. }
  206750. }
  206751. if (hdd == 0)
  206752. {
  206753. StretchDIBits (dc,
  206754. x, y, width, height,
  206755. 0, 0, width, height,
  206756. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206757. DIB_RGB_COLORS, SRCCOPY);
  206758. }
  206759. else
  206760. {
  206761. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206762. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206763. 0, 0, width, height, 0);
  206764. }
  206765. if (! maskedRegion.isEmpty())
  206766. RestoreDC (dc, savedDC);
  206767. }
  206768. }
  206769. juce_UseDebuggingNewOperator
  206770. private:
  206771. WindowsBitmapImage (const WindowsBitmapImage&);
  206772. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206773. };
  206774. namespace IconConverters
  206775. {
  206776. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206777. {
  206778. Image im;
  206779. if (bitmap != 0)
  206780. {
  206781. BITMAP bm;
  206782. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206783. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206784. {
  206785. HDC tempDC = GetDC (0);
  206786. HDC dc = CreateCompatibleDC (tempDC);
  206787. ReleaseDC (0, tempDC);
  206788. SelectObject (dc, bitmap);
  206789. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206790. Image::BitmapData imageData (im, true);
  206791. for (int y = bm.bmHeight; --y >= 0;)
  206792. {
  206793. for (int x = bm.bmWidth; --x >= 0;)
  206794. {
  206795. COLORREF col = GetPixel (dc, x, y);
  206796. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206797. (uint8) GetGValue (col),
  206798. (uint8) GetBValue (col)));
  206799. }
  206800. }
  206801. DeleteDC (dc);
  206802. }
  206803. }
  206804. return im;
  206805. }
  206806. const Image createImageFromHICON (HICON icon)
  206807. {
  206808. ICONINFO info;
  206809. if (GetIconInfo (icon, &info))
  206810. {
  206811. Image mask (createImageFromHBITMAP (info.hbmMask));
  206812. Image image (createImageFromHBITMAP (info.hbmColor));
  206813. if (mask.isValid() && image.isValid())
  206814. {
  206815. for (int y = image.getHeight(); --y >= 0;)
  206816. {
  206817. for (int x = image.getWidth(); --x >= 0;)
  206818. {
  206819. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206820. if (brightness > 0.0f)
  206821. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206822. }
  206823. }
  206824. return image;
  206825. }
  206826. }
  206827. return Image::null;
  206828. }
  206829. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206830. {
  206831. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206832. Image bitmap (nativeBitmap);
  206833. {
  206834. Graphics g (bitmap);
  206835. g.drawImageAt (image, 0, 0);
  206836. }
  206837. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206838. ICONINFO info;
  206839. info.fIcon = isIcon;
  206840. info.xHotspot = hotspotX;
  206841. info.yHotspot = hotspotY;
  206842. info.hbmMask = mask;
  206843. info.hbmColor = nativeBitmap->hBitmap;
  206844. HICON hi = CreateIconIndirect (&info);
  206845. DeleteObject (mask);
  206846. return hi;
  206847. }
  206848. }
  206849. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206850. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206851. {
  206852. SHORT k = (SHORT) keyCode;
  206853. if ((keyCode & extendedKeyModifier) == 0
  206854. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206855. k += (SHORT) 'A' - (SHORT) 'a';
  206856. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206857. (SHORT) '+', VK_OEM_PLUS,
  206858. (SHORT) '-', VK_OEM_MINUS,
  206859. (SHORT) '.', VK_OEM_PERIOD,
  206860. (SHORT) ';', VK_OEM_1,
  206861. (SHORT) ':', VK_OEM_1,
  206862. (SHORT) '/', VK_OEM_2,
  206863. (SHORT) '?', VK_OEM_2,
  206864. (SHORT) '[', VK_OEM_4,
  206865. (SHORT) ']', VK_OEM_6 };
  206866. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206867. if (k == translatedValues [i])
  206868. k = translatedValues [i + 1];
  206869. return (GetKeyState (k) & 0x8000) != 0;
  206870. }
  206871. class Win32ComponentPeer : public ComponentPeer
  206872. {
  206873. public:
  206874. enum RenderingEngineType
  206875. {
  206876. softwareRenderingEngine = 0,
  206877. direct2DRenderingEngine
  206878. };
  206879. Win32ComponentPeer (Component* const component,
  206880. const int windowStyleFlags,
  206881. HWND parentToAddTo_)
  206882. : ComponentPeer (component, windowStyleFlags),
  206883. dontRepaint (false),
  206884. #if JUCE_DIRECT2D
  206885. currentRenderingEngine (direct2DRenderingEngine),
  206886. #else
  206887. currentRenderingEngine (softwareRenderingEngine),
  206888. #endif
  206889. fullScreen (false),
  206890. isDragging (false),
  206891. isMouseOver (false),
  206892. hasCreatedCaret (false),
  206893. currentWindowIcon (0),
  206894. dropTarget (0),
  206895. updateLayeredWindowAlpha (255),
  206896. parentToAddTo (parentToAddTo_)
  206897. {
  206898. callFunctionIfNotLocked (&createWindowCallback, this);
  206899. setTitle (component->getName());
  206900. if ((windowStyleFlags & windowHasDropShadow) != 0
  206901. && Desktop::canUseSemiTransparentWindows())
  206902. {
  206903. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206904. if (shadower != 0)
  206905. shadower->setOwner (component);
  206906. }
  206907. }
  206908. ~Win32ComponentPeer()
  206909. {
  206910. setTaskBarIcon (Image());
  206911. shadower = 0;
  206912. // do this before the next bit to avoid messages arriving for this window
  206913. // before it's destroyed
  206914. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206915. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206916. if (currentWindowIcon != 0)
  206917. DestroyIcon (currentWindowIcon);
  206918. if (dropTarget != 0)
  206919. {
  206920. dropTarget->Release();
  206921. dropTarget = 0;
  206922. }
  206923. #if JUCE_DIRECT2D
  206924. direct2DContext = 0;
  206925. #endif
  206926. }
  206927. void* getNativeHandle() const
  206928. {
  206929. return hwnd;
  206930. }
  206931. void setVisible (bool shouldBeVisible)
  206932. {
  206933. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206934. if (shouldBeVisible)
  206935. InvalidateRect (hwnd, 0, 0);
  206936. else
  206937. lastPaintTime = 0;
  206938. }
  206939. void setTitle (const String& title)
  206940. {
  206941. SetWindowText (hwnd, title);
  206942. }
  206943. void setPosition (int x, int y)
  206944. {
  206945. offsetWithinParent (x, y);
  206946. SetWindowPos (hwnd, 0,
  206947. x - windowBorder.getLeft(),
  206948. y - windowBorder.getTop(),
  206949. 0, 0,
  206950. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206951. }
  206952. void repaintNowIfTransparent()
  206953. {
  206954. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206955. handlePaintMessage();
  206956. }
  206957. void updateBorderSize()
  206958. {
  206959. WINDOWINFO info;
  206960. info.cbSize = sizeof (info);
  206961. if (GetWindowInfo (hwnd, &info))
  206962. {
  206963. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206964. info.rcClient.left - info.rcWindow.left,
  206965. info.rcWindow.bottom - info.rcClient.bottom,
  206966. info.rcWindow.right - info.rcClient.right);
  206967. }
  206968. #if JUCE_DIRECT2D
  206969. if (direct2DContext != 0)
  206970. direct2DContext->resized();
  206971. #endif
  206972. }
  206973. void setSize (int w, int h)
  206974. {
  206975. SetWindowPos (hwnd, 0, 0, 0,
  206976. w + windowBorder.getLeftAndRight(),
  206977. h + windowBorder.getTopAndBottom(),
  206978. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206979. updateBorderSize();
  206980. repaintNowIfTransparent();
  206981. }
  206982. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206983. {
  206984. fullScreen = isNowFullScreen;
  206985. offsetWithinParent (x, y);
  206986. SetWindowPos (hwnd, 0,
  206987. x - windowBorder.getLeft(),
  206988. y - windowBorder.getTop(),
  206989. w + windowBorder.getLeftAndRight(),
  206990. h + windowBorder.getTopAndBottom(),
  206991. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206992. updateBorderSize();
  206993. repaintNowIfTransparent();
  206994. }
  206995. const Rectangle<int> getBounds() const
  206996. {
  206997. RECT r;
  206998. GetWindowRect (hwnd, &r);
  206999. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  207000. HWND parentH = GetParent (hwnd);
  207001. if (parentH != 0)
  207002. {
  207003. GetWindowRect (parentH, &r);
  207004. bounds.translate (-r.left, -r.top);
  207005. }
  207006. return windowBorder.subtractedFrom (bounds);
  207007. }
  207008. const Point<int> getScreenPosition() const
  207009. {
  207010. RECT r;
  207011. GetWindowRect (hwnd, &r);
  207012. return Point<int> (r.left + windowBorder.getLeft(),
  207013. r.top + windowBorder.getTop());
  207014. }
  207015. const Point<int> localToGlobal (const Point<int>& relativePosition)
  207016. {
  207017. return relativePosition + getScreenPosition();
  207018. }
  207019. const Point<int> globalToLocal (const Point<int>& screenPosition)
  207020. {
  207021. return screenPosition - getScreenPosition();
  207022. }
  207023. void setAlpha (float newAlpha)
  207024. {
  207025. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  207026. if (component->isOpaque())
  207027. {
  207028. if (newAlpha < 1.0f)
  207029. {
  207030. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  207031. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  207032. }
  207033. else
  207034. {
  207035. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  207036. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  207037. }
  207038. }
  207039. else
  207040. {
  207041. updateLayeredWindowAlpha = intAlpha;
  207042. component->repaint();
  207043. }
  207044. }
  207045. void setMinimised (bool shouldBeMinimised)
  207046. {
  207047. if (shouldBeMinimised != isMinimised())
  207048. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  207049. }
  207050. bool isMinimised() const
  207051. {
  207052. WINDOWPLACEMENT wp;
  207053. wp.length = sizeof (WINDOWPLACEMENT);
  207054. GetWindowPlacement (hwnd, &wp);
  207055. return wp.showCmd == SW_SHOWMINIMIZED;
  207056. }
  207057. void setFullScreen (bool shouldBeFullScreen)
  207058. {
  207059. setMinimised (false);
  207060. if (fullScreen != shouldBeFullScreen)
  207061. {
  207062. fullScreen = shouldBeFullScreen;
  207063. const Component::SafePointer<Component> deletionChecker (component);
  207064. if (! fullScreen)
  207065. {
  207066. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  207067. if (hasTitleBar())
  207068. ShowWindow (hwnd, SW_SHOWNORMAL);
  207069. if (! boundsCopy.isEmpty())
  207070. {
  207071. setBounds (boundsCopy.getX(),
  207072. boundsCopy.getY(),
  207073. boundsCopy.getWidth(),
  207074. boundsCopy.getHeight(),
  207075. false);
  207076. }
  207077. }
  207078. else
  207079. {
  207080. if (hasTitleBar())
  207081. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207082. else
  207083. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207084. }
  207085. if (deletionChecker != 0)
  207086. handleMovedOrResized();
  207087. }
  207088. }
  207089. bool isFullScreen() const
  207090. {
  207091. if (! hasTitleBar())
  207092. return fullScreen;
  207093. WINDOWPLACEMENT wp;
  207094. wp.length = sizeof (wp);
  207095. GetWindowPlacement (hwnd, &wp);
  207096. return wp.showCmd == SW_SHOWMAXIMIZED;
  207097. }
  207098. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207099. {
  207100. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  207101. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  207102. return false;
  207103. RECT r;
  207104. GetWindowRect (hwnd, &r);
  207105. POINT p;
  207106. p.x = position.getX() + r.left + windowBorder.getLeft();
  207107. p.y = position.getY() + r.top + windowBorder.getTop();
  207108. HWND w = WindowFromPoint (p);
  207109. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207110. }
  207111. const BorderSize getFrameSize() const
  207112. {
  207113. return windowBorder;
  207114. }
  207115. bool setAlwaysOnTop (bool alwaysOnTop)
  207116. {
  207117. const bool oldDeactivate = shouldDeactivateTitleBar;
  207118. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207119. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207120. 0, 0, 0, 0,
  207121. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207122. shouldDeactivateTitleBar = oldDeactivate;
  207123. if (shadower != 0)
  207124. shadower->componentBroughtToFront (*component);
  207125. return true;
  207126. }
  207127. void toFront (bool makeActive)
  207128. {
  207129. setMinimised (false);
  207130. const bool oldDeactivate = shouldDeactivateTitleBar;
  207131. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207132. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207133. shouldDeactivateTitleBar = oldDeactivate;
  207134. if (! makeActive)
  207135. {
  207136. // in this case a broughttofront call won't have occured, so do it now..
  207137. handleBroughtToFront();
  207138. }
  207139. }
  207140. void toBehind (ComponentPeer* other)
  207141. {
  207142. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207143. jassert (otherPeer != 0); // wrong type of window?
  207144. if (otherPeer != 0)
  207145. {
  207146. setMinimised (false);
  207147. // must be careful not to try to put a topmost window behind a normal one, or win32
  207148. // promotes the normal one to be topmost!
  207149. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207150. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207151. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207152. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207153. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207154. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207155. }
  207156. }
  207157. bool isFocused() const
  207158. {
  207159. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207160. }
  207161. void grabFocus()
  207162. {
  207163. const bool oldDeactivate = shouldDeactivateTitleBar;
  207164. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207165. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207166. shouldDeactivateTitleBar = oldDeactivate;
  207167. }
  207168. void textInputRequired (const Point<int>&)
  207169. {
  207170. if (! hasCreatedCaret)
  207171. {
  207172. hasCreatedCaret = true;
  207173. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207174. }
  207175. ShowCaret (hwnd);
  207176. SetCaretPos (0, 0);
  207177. }
  207178. void repaint (const Rectangle<int>& area)
  207179. {
  207180. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207181. InvalidateRect (hwnd, &r, FALSE);
  207182. }
  207183. void performAnyPendingRepaintsNow()
  207184. {
  207185. MSG m;
  207186. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207187. DispatchMessage (&m);
  207188. }
  207189. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207190. {
  207191. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207192. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207193. return 0;
  207194. }
  207195. void setTaskBarIcon (const Image& image)
  207196. {
  207197. if (image.isValid())
  207198. {
  207199. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  207200. if (taskBarIcon == 0)
  207201. {
  207202. taskBarIcon = new NOTIFYICONDATA();
  207203. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  207204. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207205. taskBarIcon->hWnd = (HWND) hwnd;
  207206. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207207. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207208. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207209. taskBarIcon->hIcon = hicon;
  207210. taskBarIcon->szTip[0] = 0;
  207211. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207212. }
  207213. else
  207214. {
  207215. HICON oldIcon = taskBarIcon->hIcon;
  207216. taskBarIcon->hIcon = hicon;
  207217. taskBarIcon->uFlags = NIF_ICON;
  207218. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207219. DestroyIcon (oldIcon);
  207220. }
  207221. }
  207222. else if (taskBarIcon != 0)
  207223. {
  207224. taskBarIcon->uFlags = 0;
  207225. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207226. DestroyIcon (taskBarIcon->hIcon);
  207227. taskBarIcon = 0;
  207228. }
  207229. }
  207230. void setTaskBarIconToolTip (const String& toolTip) const
  207231. {
  207232. if (taskBarIcon != 0)
  207233. {
  207234. taskBarIcon->uFlags = NIF_TIP;
  207235. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207236. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207237. }
  207238. }
  207239. void handleTaskBarEvent (const LPARAM lParam, const WPARAM wParam)
  207240. {
  207241. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207242. {
  207243. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207244. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207245. {
  207246. Component* const current = Component::getCurrentlyModalComponent();
  207247. if (current != 0)
  207248. current->inputAttemptWhenModal();
  207249. }
  207250. }
  207251. else
  207252. {
  207253. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  207254. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207255. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  207256. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207257. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  207258. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207259. eventMods = eventMods.withoutMouseButtons();
  207260. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  207261. Point<int>(), eventMods, component, component, getMouseEventTime(),
  207262. Point<int>(), getMouseEventTime(), 1, false);
  207263. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207264. {
  207265. SetFocus (hwnd);
  207266. SetForegroundWindow (hwnd);
  207267. component->mouseDown (e);
  207268. }
  207269. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207270. {
  207271. component->mouseUp (e);
  207272. }
  207273. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207274. {
  207275. component->mouseDoubleClick (e);
  207276. }
  207277. else if (lParam == WM_MOUSEMOVE)
  207278. {
  207279. component->mouseMove (e);
  207280. }
  207281. }
  207282. }
  207283. bool isInside (HWND h) const
  207284. {
  207285. return GetAncestor (hwnd, GA_ROOT) == h;
  207286. }
  207287. static void updateKeyModifiers() throw()
  207288. {
  207289. int keyMods = 0;
  207290. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207291. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207292. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207293. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207294. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207295. }
  207296. static void updateModifiersFromWParam (const WPARAM wParam)
  207297. {
  207298. int mouseMods = 0;
  207299. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207300. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207301. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207302. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207303. updateKeyModifiers();
  207304. }
  207305. static int64 getMouseEventTime()
  207306. {
  207307. static int64 eventTimeOffset = 0;
  207308. static DWORD lastMessageTime = 0;
  207309. const DWORD thisMessageTime = GetMessageTime();
  207310. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207311. {
  207312. lastMessageTime = thisMessageTime;
  207313. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207314. }
  207315. return eventTimeOffset + thisMessageTime;
  207316. }
  207317. juce_UseDebuggingNewOperator
  207318. bool dontRepaint;
  207319. static ModifierKeys currentModifiers;
  207320. static ModifierKeys modifiersAtLastCallback;
  207321. private:
  207322. HWND hwnd, parentToAddTo;
  207323. ScopedPointer<DropShadower> shadower;
  207324. RenderingEngineType currentRenderingEngine;
  207325. #if JUCE_DIRECT2D
  207326. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207327. #endif
  207328. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207329. BorderSize windowBorder;
  207330. HICON currentWindowIcon;
  207331. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207332. IDropTarget* dropTarget;
  207333. uint8 updateLayeredWindowAlpha;
  207334. class TemporaryImage : public Timer
  207335. {
  207336. public:
  207337. TemporaryImage() {}
  207338. ~TemporaryImage() {}
  207339. const Image& getImage (const bool transparent, const int w, const int h)
  207340. {
  207341. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207342. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207343. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207344. startTimer (3000);
  207345. return image;
  207346. }
  207347. void timerCallback()
  207348. {
  207349. stopTimer();
  207350. image = Image::null;
  207351. }
  207352. private:
  207353. Image image;
  207354. TemporaryImage (const TemporaryImage&);
  207355. TemporaryImage& operator= (const TemporaryImage&);
  207356. };
  207357. TemporaryImage offscreenImageGenerator;
  207358. class WindowClassHolder : public DeletedAtShutdown
  207359. {
  207360. public:
  207361. WindowClassHolder()
  207362. : windowClassName ("JUCE_")
  207363. {
  207364. // this name has to be different for each app/dll instance because otherwise
  207365. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207366. // window class).
  207367. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207368. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207369. TCHAR moduleFile [1024];
  207370. moduleFile[0] = 0;
  207371. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207372. WORD iconNum = 0;
  207373. WNDCLASSEX wcex;
  207374. wcex.cbSize = sizeof (wcex);
  207375. wcex.style = CS_OWNDC;
  207376. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207377. wcex.lpszClassName = windowClassName;
  207378. wcex.cbClsExtra = 0;
  207379. wcex.cbWndExtra = 32;
  207380. wcex.hInstance = moduleHandle;
  207381. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207382. iconNum = 1;
  207383. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207384. wcex.hCursor = 0;
  207385. wcex.hbrBackground = 0;
  207386. wcex.lpszMenuName = 0;
  207387. RegisterClassEx (&wcex);
  207388. }
  207389. ~WindowClassHolder()
  207390. {
  207391. if (ComponentPeer::getNumPeers() == 0)
  207392. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207393. clearSingletonInstance();
  207394. }
  207395. String windowClassName;
  207396. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207397. };
  207398. static void* createWindowCallback (void* userData)
  207399. {
  207400. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207401. return 0;
  207402. }
  207403. void createWindow()
  207404. {
  207405. DWORD exstyle = WS_EX_ACCEPTFILES;
  207406. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207407. if (hasTitleBar())
  207408. {
  207409. type |= WS_OVERLAPPED;
  207410. if ((styleFlags & windowHasCloseButton) != 0)
  207411. {
  207412. type |= WS_SYSMENU;
  207413. }
  207414. else
  207415. {
  207416. // annoyingly, windows won't let you have a min/max button without a close button
  207417. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207418. }
  207419. if ((styleFlags & windowIsResizable) != 0)
  207420. type |= WS_THICKFRAME;
  207421. }
  207422. else if (parentToAddTo != 0)
  207423. {
  207424. type |= WS_CHILD;
  207425. }
  207426. else
  207427. {
  207428. type |= WS_POPUP | WS_SYSMENU;
  207429. }
  207430. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207431. exstyle |= WS_EX_TOOLWINDOW;
  207432. else
  207433. exstyle |= WS_EX_APPWINDOW;
  207434. if ((styleFlags & windowHasMinimiseButton) != 0)
  207435. type |= WS_MINIMIZEBOX;
  207436. if ((styleFlags & windowHasMaximiseButton) != 0)
  207437. type |= WS_MAXIMIZEBOX;
  207438. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207439. exstyle |= WS_EX_TRANSPARENT;
  207440. if ((styleFlags & windowIsSemiTransparent) != 0
  207441. && Desktop::canUseSemiTransparentWindows())
  207442. exstyle |= WS_EX_LAYERED;
  207443. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207444. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207445. #if JUCE_DIRECT2D
  207446. updateDirect2DContext();
  207447. #endif
  207448. if (hwnd != 0)
  207449. {
  207450. SetWindowLongPtr (hwnd, 0, 0);
  207451. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207452. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207453. if (dropTarget == 0)
  207454. dropTarget = new JuceDropTarget (this);
  207455. RegisterDragDrop (hwnd, dropTarget);
  207456. updateBorderSize();
  207457. // Calling this function here is (for some reason) necessary to make Windows
  207458. // correctly enable the menu items that we specify in the wm_initmenu message.
  207459. GetSystemMenu (hwnd, false);
  207460. const float alpha = component->getAlpha();
  207461. if (alpha < 1.0f)
  207462. setAlpha (alpha);
  207463. }
  207464. else
  207465. {
  207466. jassertfalse;
  207467. }
  207468. }
  207469. static void* destroyWindowCallback (void* handle)
  207470. {
  207471. RevokeDragDrop ((HWND) handle);
  207472. DestroyWindow ((HWND) handle);
  207473. return 0;
  207474. }
  207475. static void* toFrontCallback1 (void* h)
  207476. {
  207477. SetForegroundWindow ((HWND) h);
  207478. return 0;
  207479. }
  207480. static void* toFrontCallback2 (void* h)
  207481. {
  207482. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207483. return 0;
  207484. }
  207485. static void* setFocusCallback (void* h)
  207486. {
  207487. SetFocus ((HWND) h);
  207488. return 0;
  207489. }
  207490. static void* getFocusCallback (void*)
  207491. {
  207492. return GetFocus();
  207493. }
  207494. void offsetWithinParent (int& x, int& y) const
  207495. {
  207496. if (isUsingUpdateLayeredWindow())
  207497. {
  207498. HWND parentHwnd = GetParent (hwnd);
  207499. if (parentHwnd != 0)
  207500. {
  207501. RECT parentRect;
  207502. GetWindowRect (parentHwnd, &parentRect);
  207503. x += parentRect.left;
  207504. y += parentRect.top;
  207505. }
  207506. }
  207507. }
  207508. bool isUsingUpdateLayeredWindow() const
  207509. {
  207510. return ! component->isOpaque();
  207511. }
  207512. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207513. void setIcon (const Image& newIcon)
  207514. {
  207515. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207516. if (hicon != 0)
  207517. {
  207518. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207519. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207520. if (currentWindowIcon != 0)
  207521. DestroyIcon (currentWindowIcon);
  207522. currentWindowIcon = hicon;
  207523. }
  207524. }
  207525. void handlePaintMessage()
  207526. {
  207527. #if JUCE_DIRECT2D
  207528. if (direct2DContext != 0)
  207529. {
  207530. RECT r;
  207531. if (GetUpdateRect (hwnd, &r, false))
  207532. {
  207533. direct2DContext->start();
  207534. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207535. handlePaint (*direct2DContext);
  207536. direct2DContext->end();
  207537. }
  207538. }
  207539. else
  207540. #endif
  207541. {
  207542. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207543. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207544. PAINTSTRUCT paintStruct;
  207545. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207546. // message and become re-entrant, but that's OK
  207547. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207548. // corrupt the image it's using to paint into, so do a check here.
  207549. static bool reentrant = false;
  207550. if (reentrant)
  207551. {
  207552. DeleteObject (rgn);
  207553. EndPaint (hwnd, &paintStruct);
  207554. return;
  207555. }
  207556. reentrant = true;
  207557. // this is the rectangle to update..
  207558. int x = paintStruct.rcPaint.left;
  207559. int y = paintStruct.rcPaint.top;
  207560. int w = paintStruct.rcPaint.right - x;
  207561. int h = paintStruct.rcPaint.bottom - y;
  207562. const bool transparent = isUsingUpdateLayeredWindow();
  207563. if (transparent)
  207564. {
  207565. // it's not possible to have a transparent window with a title bar at the moment!
  207566. jassert (! hasTitleBar());
  207567. RECT r;
  207568. GetWindowRect (hwnd, &r);
  207569. x = y = 0;
  207570. w = r.right - r.left;
  207571. h = r.bottom - r.top;
  207572. }
  207573. if (w > 0 && h > 0)
  207574. {
  207575. clearMaskedRegion();
  207576. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207577. RectangleList contextClip;
  207578. const Rectangle<int> clipBounds (0, 0, w, h);
  207579. bool needToPaintAll = true;
  207580. if (regionType == COMPLEXREGION && ! transparent)
  207581. {
  207582. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207583. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207584. DeleteObject (clipRgn);
  207585. char rgnData [8192];
  207586. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207587. if (res > 0 && res <= sizeof (rgnData))
  207588. {
  207589. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207590. if (hdr->iType == RDH_RECTANGLES
  207591. && hdr->rcBound.right - hdr->rcBound.left >= w
  207592. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207593. {
  207594. needToPaintAll = false;
  207595. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207596. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207597. while (--num >= 0)
  207598. {
  207599. if (rects->right <= x + w && rects->bottom <= y + h)
  207600. {
  207601. const int cx = jmax (x, (int) rects->left);
  207602. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207603. .getIntersection (clipBounds));
  207604. }
  207605. else
  207606. {
  207607. needToPaintAll = true;
  207608. break;
  207609. }
  207610. ++rects;
  207611. }
  207612. }
  207613. }
  207614. }
  207615. if (needToPaintAll)
  207616. {
  207617. contextClip.clear();
  207618. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207619. }
  207620. if (transparent)
  207621. {
  207622. RectangleList::Iterator i (contextClip);
  207623. while (i.next())
  207624. offscreenImage.clear (*i.getRectangle());
  207625. }
  207626. // if the component's not opaque, this won't draw properly unless the platform can support this
  207627. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207628. updateCurrentModifiers();
  207629. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207630. handlePaint (context);
  207631. if (! dontRepaint)
  207632. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207633. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207634. }
  207635. DeleteObject (rgn);
  207636. EndPaint (hwnd, &paintStruct);
  207637. reentrant = false;
  207638. }
  207639. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207640. _fpreset(); // because some graphics cards can unmask FP exceptions
  207641. #endif
  207642. lastPaintTime = Time::getMillisecondCounter();
  207643. }
  207644. void doMouseEvent (const Point<int>& position)
  207645. {
  207646. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207647. }
  207648. const StringArray getAvailableRenderingEngines()
  207649. {
  207650. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207651. #if JUCE_DIRECT2D
  207652. // xxx is this correct? Seems to enable it on Vista too??
  207653. OSVERSIONINFO info;
  207654. zerostruct (info);
  207655. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207656. GetVersionEx (&info);
  207657. if (info.dwMajorVersion >= 6)
  207658. s.add ("Direct2D");
  207659. #endif
  207660. return s;
  207661. }
  207662. int getCurrentRenderingEngine() throw()
  207663. {
  207664. return currentRenderingEngine;
  207665. }
  207666. #if JUCE_DIRECT2D
  207667. void updateDirect2DContext()
  207668. {
  207669. if (currentRenderingEngine != direct2DRenderingEngine)
  207670. direct2DContext = 0;
  207671. else if (direct2DContext == 0)
  207672. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207673. }
  207674. #endif
  207675. void setCurrentRenderingEngine (int index)
  207676. {
  207677. (void) index;
  207678. #if JUCE_DIRECT2D
  207679. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207680. updateDirect2DContext();
  207681. repaint (component->getLocalBounds());
  207682. #endif
  207683. }
  207684. void doMouseMove (const Point<int>& position)
  207685. {
  207686. if (! isMouseOver)
  207687. {
  207688. isMouseOver = true;
  207689. updateKeyModifiers();
  207690. TRACKMOUSEEVENT tme;
  207691. tme.cbSize = sizeof (tme);
  207692. tme.dwFlags = TME_LEAVE;
  207693. tme.hwndTrack = hwnd;
  207694. tme.dwHoverTime = 0;
  207695. if (! TrackMouseEvent (&tme))
  207696. jassertfalse;
  207697. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207698. }
  207699. else if (! isDragging)
  207700. {
  207701. if (! contains (position, false))
  207702. return;
  207703. }
  207704. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207705. static uint32 lastMouseTime = 0;
  207706. const uint32 now = Time::getMillisecondCounter();
  207707. const int maxMouseMovesPerSecond = 60;
  207708. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207709. {
  207710. lastMouseTime = now;
  207711. doMouseEvent (position);
  207712. }
  207713. }
  207714. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207715. {
  207716. if (GetCapture() != hwnd)
  207717. SetCapture (hwnd);
  207718. doMouseMove (position);
  207719. updateModifiersFromWParam (wParam);
  207720. isDragging = true;
  207721. doMouseEvent (position);
  207722. }
  207723. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207724. {
  207725. updateModifiersFromWParam (wParam);
  207726. isDragging = false;
  207727. // release the mouse capture if the user has released all buttons
  207728. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207729. ReleaseCapture();
  207730. doMouseEvent (position);
  207731. }
  207732. void doCaptureChanged()
  207733. {
  207734. if (isDragging)
  207735. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207736. }
  207737. void doMouseExit()
  207738. {
  207739. isMouseOver = false;
  207740. doMouseEvent (getCurrentMousePos());
  207741. }
  207742. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207743. {
  207744. updateKeyModifiers();
  207745. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207746. handleMouseWheel (0, position, getMouseEventTime(),
  207747. isVertical ? 0.0f : amount,
  207748. isVertical ? amount : 0.0f);
  207749. }
  207750. void sendModifierKeyChangeIfNeeded()
  207751. {
  207752. if (modifiersAtLastCallback != currentModifiers)
  207753. {
  207754. modifiersAtLastCallback = currentModifiers;
  207755. handleModifierKeysChange();
  207756. }
  207757. }
  207758. bool doKeyUp (const WPARAM key)
  207759. {
  207760. updateKeyModifiers();
  207761. switch (key)
  207762. {
  207763. case VK_SHIFT:
  207764. case VK_CONTROL:
  207765. case VK_MENU:
  207766. case VK_CAPITAL:
  207767. case VK_LWIN:
  207768. case VK_RWIN:
  207769. case VK_APPS:
  207770. case VK_NUMLOCK:
  207771. case VK_SCROLL:
  207772. case VK_LSHIFT:
  207773. case VK_RSHIFT:
  207774. case VK_LCONTROL:
  207775. case VK_LMENU:
  207776. case VK_RCONTROL:
  207777. case VK_RMENU:
  207778. sendModifierKeyChangeIfNeeded();
  207779. }
  207780. return handleKeyUpOrDown (false)
  207781. || Component::getCurrentlyModalComponent() != 0;
  207782. }
  207783. bool doKeyDown (const WPARAM key)
  207784. {
  207785. updateKeyModifiers();
  207786. bool used = false;
  207787. switch (key)
  207788. {
  207789. case VK_SHIFT:
  207790. case VK_LSHIFT:
  207791. case VK_RSHIFT:
  207792. case VK_CONTROL:
  207793. case VK_LCONTROL:
  207794. case VK_RCONTROL:
  207795. case VK_MENU:
  207796. case VK_LMENU:
  207797. case VK_RMENU:
  207798. case VK_LWIN:
  207799. case VK_RWIN:
  207800. case VK_CAPITAL:
  207801. case VK_NUMLOCK:
  207802. case VK_SCROLL:
  207803. case VK_APPS:
  207804. sendModifierKeyChangeIfNeeded();
  207805. break;
  207806. case VK_LEFT:
  207807. case VK_RIGHT:
  207808. case VK_UP:
  207809. case VK_DOWN:
  207810. case VK_PRIOR:
  207811. case VK_NEXT:
  207812. case VK_HOME:
  207813. case VK_END:
  207814. case VK_DELETE:
  207815. case VK_INSERT:
  207816. case VK_F1:
  207817. case VK_F2:
  207818. case VK_F3:
  207819. case VK_F4:
  207820. case VK_F5:
  207821. case VK_F6:
  207822. case VK_F7:
  207823. case VK_F8:
  207824. case VK_F9:
  207825. case VK_F10:
  207826. case VK_F11:
  207827. case VK_F12:
  207828. case VK_F13:
  207829. case VK_F14:
  207830. case VK_F15:
  207831. case VK_F16:
  207832. used = handleKeyUpOrDown (true);
  207833. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207834. break;
  207835. case VK_ADD:
  207836. case VK_SUBTRACT:
  207837. case VK_MULTIPLY:
  207838. case VK_DIVIDE:
  207839. case VK_SEPARATOR:
  207840. case VK_DECIMAL:
  207841. used = handleKeyUpOrDown (true);
  207842. break;
  207843. default:
  207844. used = handleKeyUpOrDown (true);
  207845. {
  207846. MSG msg;
  207847. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207848. {
  207849. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207850. // manually generate the key-press event that matches this key-down.
  207851. const UINT keyChar = MapVirtualKey (key, 2);
  207852. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207853. }
  207854. }
  207855. break;
  207856. }
  207857. if (Component::getCurrentlyModalComponent() != 0)
  207858. used = true;
  207859. return used;
  207860. }
  207861. bool doKeyChar (int key, const LPARAM flags)
  207862. {
  207863. updateKeyModifiers();
  207864. juce_wchar textChar = (juce_wchar) key;
  207865. const int virtualScanCode = (flags >> 16) & 0xff;
  207866. if (key >= '0' && key <= '9')
  207867. {
  207868. switch (virtualScanCode) // check for a numeric keypad scan-code
  207869. {
  207870. case 0x52:
  207871. case 0x4f:
  207872. case 0x50:
  207873. case 0x51:
  207874. case 0x4b:
  207875. case 0x4c:
  207876. case 0x4d:
  207877. case 0x47:
  207878. case 0x48:
  207879. case 0x49:
  207880. key = (key - '0') + KeyPress::numberPad0;
  207881. break;
  207882. default:
  207883. break;
  207884. }
  207885. }
  207886. else
  207887. {
  207888. // convert the scan code to an unmodified character code..
  207889. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207890. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207891. keyChar = LOWORD (keyChar);
  207892. if (keyChar != 0)
  207893. key = (int) keyChar;
  207894. // avoid sending junk text characters for some control-key combinations
  207895. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207896. textChar = 0;
  207897. }
  207898. return handleKeyPress (key, textChar);
  207899. }
  207900. bool doAppCommand (const LPARAM lParam)
  207901. {
  207902. int key = 0;
  207903. switch (GET_APPCOMMAND_LPARAM (lParam))
  207904. {
  207905. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  207906. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  207907. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  207908. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  207909. default: break;
  207910. }
  207911. if (key != 0)
  207912. {
  207913. updateKeyModifiers();
  207914. if (hwnd == GetActiveWindow())
  207915. {
  207916. handleKeyPress (key, 0);
  207917. return true;
  207918. }
  207919. }
  207920. return false;
  207921. }
  207922. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  207923. {
  207924. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207925. {
  207926. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  207927. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  207928. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207929. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  207930. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  207931. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  207932. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  207933. r->left = pos.getX();
  207934. r->top = pos.getY();
  207935. r->right = pos.getRight();
  207936. r->bottom = pos.getBottom();
  207937. }
  207938. return TRUE;
  207939. }
  207940. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  207941. {
  207942. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207943. {
  207944. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  207945. && ! Component::isMouseButtonDownAnywhere())
  207946. {
  207947. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207948. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  207949. constrainer->checkBounds (pos, current,
  207950. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207951. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207952. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207953. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207954. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207955. wp->x = pos.getX();
  207956. wp->y = pos.getY();
  207957. wp->cx = pos.getWidth();
  207958. wp->cy = pos.getHeight();
  207959. }
  207960. }
  207961. return 0;
  207962. }
  207963. void handleAppActivation (const WPARAM wParam)
  207964. {
  207965. modifiersAtLastCallback = -1;
  207966. updateKeyModifiers();
  207967. if (isMinimised())
  207968. {
  207969. component->repaint();
  207970. handleMovedOrResized();
  207971. if (! ComponentPeer::isValidPeer (this))
  207972. return;
  207973. }
  207974. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  207975. {
  207976. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  207977. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207978. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207979. }
  207980. else
  207981. {
  207982. handleBroughtToFront();
  207983. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207984. Component::getCurrentlyModalComponent()->toFront (true);
  207985. }
  207986. }
  207987. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207988. {
  207989. public:
  207990. JuceDropTarget (Win32ComponentPeer* const owner_)
  207991. : owner (owner_)
  207992. {
  207993. }
  207994. ~JuceDropTarget() {}
  207995. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207996. {
  207997. updateFileList (pDataObject);
  207998. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207999. *pdwEffect = DROPEFFECT_COPY;
  208000. return S_OK;
  208001. }
  208002. HRESULT __stdcall DragLeave()
  208003. {
  208004. owner->handleFileDragExit (files);
  208005. return S_OK;
  208006. }
  208007. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208008. {
  208009. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208010. *pdwEffect = DROPEFFECT_COPY;
  208011. return S_OK;
  208012. }
  208013. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208014. {
  208015. updateFileList (pDataObject);
  208016. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208017. *pdwEffect = DROPEFFECT_COPY;
  208018. return S_OK;
  208019. }
  208020. private:
  208021. Win32ComponentPeer* const owner;
  208022. StringArray files;
  208023. void updateFileList (IDataObject* const pDataObject)
  208024. {
  208025. files.clear();
  208026. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208027. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208028. if (pDataObject->GetData (&format, &medium) == S_OK)
  208029. {
  208030. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  208031. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  208032. unsigned int i = 0;
  208033. if (pDropFiles->fWide)
  208034. {
  208035. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  208036. for (;;)
  208037. {
  208038. unsigned int len = 0;
  208039. while (i + len < totalLen && fname [i + len] != 0)
  208040. ++len;
  208041. if (len == 0)
  208042. break;
  208043. files.add (String (fname + i, len));
  208044. i += len + 1;
  208045. }
  208046. }
  208047. else
  208048. {
  208049. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  208050. for (;;)
  208051. {
  208052. unsigned int len = 0;
  208053. while (i + len < totalLen && fname [i + len] != 0)
  208054. ++len;
  208055. if (len == 0)
  208056. break;
  208057. files.add (String (fname + i, len));
  208058. i += len + 1;
  208059. }
  208060. }
  208061. GlobalUnlock (medium.hGlobal);
  208062. }
  208063. }
  208064. JuceDropTarget (const JuceDropTarget&);
  208065. JuceDropTarget& operator= (const JuceDropTarget&);
  208066. };
  208067. void doSettingChange()
  208068. {
  208069. Desktop::getInstance().refreshMonitorSizes();
  208070. if (fullScreen && ! isMinimised())
  208071. {
  208072. const Rectangle<int> r (component->getParentMonitorArea());
  208073. SetWindowPos (hwnd, 0,
  208074. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  208075. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  208076. }
  208077. }
  208078. public:
  208079. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208080. {
  208081. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  208082. if (peer != 0)
  208083. return peer->peerWindowProc (h, message, wParam, lParam);
  208084. return DefWindowProcW (h, message, wParam, lParam);
  208085. }
  208086. private:
  208087. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  208088. {
  208089. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  208090. return callback (userData);
  208091. else
  208092. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  208093. }
  208094. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  208095. {
  208096. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  208097. }
  208098. const Point<int> getCurrentMousePos() throw()
  208099. {
  208100. RECT wr;
  208101. GetWindowRect (hwnd, &wr);
  208102. const DWORD mp = GetMessagePos();
  208103. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  208104. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  208105. }
  208106. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208107. {
  208108. if (isValidPeer (this))
  208109. {
  208110. switch (message)
  208111. {
  208112. case WM_NCHITTEST:
  208113. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  208114. return HTTRANSPARENT;
  208115. else if (! hasTitleBar())
  208116. return HTCLIENT;
  208117. break;
  208118. case WM_PAINT:
  208119. handlePaintMessage();
  208120. return 0;
  208121. case WM_NCPAINT:
  208122. if (wParam != 1)
  208123. handlePaintMessage();
  208124. if (hasTitleBar())
  208125. break;
  208126. return 0;
  208127. case WM_ERASEBKGND:
  208128. case WM_NCCALCSIZE:
  208129. if (hasTitleBar())
  208130. break;
  208131. return 1;
  208132. case WM_MOUSEMOVE:
  208133. doMouseMove (getPointFromLParam (lParam));
  208134. return 0;
  208135. case WM_MOUSELEAVE:
  208136. doMouseExit();
  208137. return 0;
  208138. case WM_LBUTTONDOWN:
  208139. case WM_MBUTTONDOWN:
  208140. case WM_RBUTTONDOWN:
  208141. doMouseDown (getPointFromLParam (lParam), wParam);
  208142. return 0;
  208143. case WM_LBUTTONUP:
  208144. case WM_MBUTTONUP:
  208145. case WM_RBUTTONUP:
  208146. doMouseUp (getPointFromLParam (lParam), wParam);
  208147. return 0;
  208148. case WM_CAPTURECHANGED:
  208149. doCaptureChanged();
  208150. return 0;
  208151. case WM_NCMOUSEMOVE:
  208152. if (hasTitleBar())
  208153. break;
  208154. return 0;
  208155. case 0x020A: /* WM_MOUSEWHEEL */
  208156. doMouseWheel (getCurrentMousePos(), wParam, true);
  208157. return 0;
  208158. case 0x020E: /* WM_MOUSEHWHEEL */
  208159. doMouseWheel (getCurrentMousePos(), wParam, false);
  208160. return 0;
  208161. case WM_SIZING:
  208162. return handleSizeConstraining ((RECT*) lParam, wParam);
  208163. case WM_WINDOWPOSCHANGING:
  208164. return handlePositionChanging ((WINDOWPOS*) lParam);
  208165. case WM_WINDOWPOSCHANGED:
  208166. {
  208167. const Point<int> pos (getCurrentMousePos());
  208168. if (contains (pos, false))
  208169. doMouseEvent (pos);
  208170. }
  208171. handleMovedOrResized();
  208172. if (dontRepaint)
  208173. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208174. return 0;
  208175. case WM_KEYDOWN:
  208176. case WM_SYSKEYDOWN:
  208177. if (doKeyDown (wParam))
  208178. return 0;
  208179. break;
  208180. case WM_KEYUP:
  208181. case WM_SYSKEYUP:
  208182. if (doKeyUp (wParam))
  208183. return 0;
  208184. break;
  208185. case WM_CHAR:
  208186. if (doKeyChar ((int) wParam, lParam))
  208187. return 0;
  208188. break;
  208189. case WM_APPCOMMAND:
  208190. if (doAppCommand (lParam))
  208191. return TRUE;
  208192. break;
  208193. case WM_SETFOCUS:
  208194. updateKeyModifiers();
  208195. handleFocusGain();
  208196. break;
  208197. case WM_KILLFOCUS:
  208198. if (hasCreatedCaret)
  208199. {
  208200. hasCreatedCaret = false;
  208201. DestroyCaret();
  208202. }
  208203. handleFocusLoss();
  208204. break;
  208205. case WM_ACTIVATEAPP:
  208206. // Windows does weird things to process priority when you swap apps,
  208207. // so this forces an update when the app is brought to the front
  208208. if (wParam != FALSE)
  208209. juce_repeatLastProcessPriority();
  208210. else
  208211. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208212. juce_CheckCurrentlyFocusedTopLevelWindow();
  208213. modifiersAtLastCallback = -1;
  208214. return 0;
  208215. case WM_ACTIVATE:
  208216. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208217. {
  208218. handleAppActivation (wParam);
  208219. return 0;
  208220. }
  208221. break;
  208222. case WM_NCACTIVATE:
  208223. // while a temporary window is being shown, prevent Windows from deactivating the
  208224. // title bars of our main windows.
  208225. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208226. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208227. break;
  208228. case WM_MOUSEACTIVATE:
  208229. if (! component->getMouseClickGrabsKeyboardFocus())
  208230. return MA_NOACTIVATE;
  208231. break;
  208232. case WM_SHOWWINDOW:
  208233. if (wParam != 0)
  208234. handleBroughtToFront();
  208235. break;
  208236. case WM_CLOSE:
  208237. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208238. handleUserClosingWindow();
  208239. return 0;
  208240. case WM_QUERYENDSESSION:
  208241. if (JUCEApplication::getInstance() != 0)
  208242. {
  208243. JUCEApplication::getInstance()->systemRequestedQuit();
  208244. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208245. }
  208246. return TRUE;
  208247. case WM_TRAYNOTIFY:
  208248. handleTaskBarEvent (lParam, wParam);
  208249. break;
  208250. case WM_SYNCPAINT:
  208251. return 0;
  208252. case WM_PALETTECHANGED:
  208253. InvalidateRect (h, 0, 0);
  208254. break;
  208255. case WM_DISPLAYCHANGE:
  208256. InvalidateRect (h, 0, 0);
  208257. createPaletteIfNeeded = true;
  208258. // intentional fall-through...
  208259. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208260. doSettingChange();
  208261. break;
  208262. case WM_INITMENU:
  208263. if (! hasTitleBar())
  208264. {
  208265. if (isFullScreen())
  208266. {
  208267. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208268. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208269. }
  208270. else if (! isMinimised())
  208271. {
  208272. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208273. }
  208274. }
  208275. break;
  208276. case WM_SYSCOMMAND:
  208277. switch (wParam & 0xfff0)
  208278. {
  208279. case SC_CLOSE:
  208280. if (sendInputAttemptWhenModalMessage())
  208281. return 0;
  208282. if (hasTitleBar())
  208283. {
  208284. PostMessage (h, WM_CLOSE, 0, 0);
  208285. return 0;
  208286. }
  208287. break;
  208288. case SC_KEYMENU:
  208289. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  208290. // situations that can arise if a modal loop is started from an alt-key keypress).
  208291. if (hasTitleBar() && h == GetCapture())
  208292. ReleaseCapture();
  208293. break;
  208294. case SC_MAXIMIZE:
  208295. if (sendInputAttemptWhenModalMessage())
  208296. return 0;
  208297. setFullScreen (true);
  208298. return 0;
  208299. case SC_MINIMIZE:
  208300. if (sendInputAttemptWhenModalMessage())
  208301. return 0;
  208302. if (! hasTitleBar())
  208303. {
  208304. setMinimised (true);
  208305. return 0;
  208306. }
  208307. break;
  208308. case SC_RESTORE:
  208309. if (sendInputAttemptWhenModalMessage())
  208310. return 0;
  208311. if (hasTitleBar())
  208312. {
  208313. if (isFullScreen())
  208314. {
  208315. setFullScreen (false);
  208316. return 0;
  208317. }
  208318. }
  208319. else
  208320. {
  208321. if (isMinimised())
  208322. setMinimised (false);
  208323. else if (isFullScreen())
  208324. setFullScreen (false);
  208325. return 0;
  208326. }
  208327. break;
  208328. }
  208329. break;
  208330. case WM_NCLBUTTONDOWN:
  208331. case WM_NCRBUTTONDOWN:
  208332. case WM_NCMBUTTONDOWN:
  208333. sendInputAttemptWhenModalMessage();
  208334. break;
  208335. //case WM_IME_STARTCOMPOSITION;
  208336. // return 0;
  208337. case WM_GETDLGCODE:
  208338. return DLGC_WANTALLKEYS;
  208339. default:
  208340. if (taskBarIcon != 0)
  208341. {
  208342. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208343. if (message == taskbarCreatedMessage)
  208344. {
  208345. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208346. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208347. }
  208348. }
  208349. break;
  208350. }
  208351. }
  208352. return DefWindowProcW (h, message, wParam, lParam);
  208353. }
  208354. bool sendInputAttemptWhenModalMessage()
  208355. {
  208356. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208357. {
  208358. Component* const current = Component::getCurrentlyModalComponent();
  208359. if (current != 0)
  208360. current->inputAttemptWhenModal();
  208361. return true;
  208362. }
  208363. return false;
  208364. }
  208365. Win32ComponentPeer (const Win32ComponentPeer&);
  208366. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208367. };
  208368. ModifierKeys Win32ComponentPeer::currentModifiers;
  208369. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208370. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208371. {
  208372. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208373. }
  208374. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208375. void ModifierKeys::updateCurrentModifiers() throw()
  208376. {
  208377. currentModifiers = Win32ComponentPeer::currentModifiers;
  208378. }
  208379. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208380. {
  208381. Win32ComponentPeer::updateKeyModifiers();
  208382. int mouseMods = 0;
  208383. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208384. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208385. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208386. Win32ComponentPeer::currentModifiers
  208387. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208388. return Win32ComponentPeer::currentModifiers;
  208389. }
  208390. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208391. {
  208392. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208393. if (wp != 0)
  208394. wp->setTaskBarIcon (newImage);
  208395. }
  208396. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208397. {
  208398. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208399. if (wp != 0)
  208400. wp->setTaskBarIconToolTip (tooltip);
  208401. }
  208402. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208403. {
  208404. DWORD val = GetWindowLong (h, styleType);
  208405. if (bitIsSet)
  208406. val |= feature;
  208407. else
  208408. val &= ~feature;
  208409. SetWindowLongPtr (h, styleType, val);
  208410. SetWindowPos (h, 0, 0, 0, 0, 0,
  208411. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208412. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208413. }
  208414. bool Process::isForegroundProcess()
  208415. {
  208416. HWND fg = GetForegroundWindow();
  208417. if (fg == 0)
  208418. return true;
  208419. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208420. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208421. // have to see if any of our windows are children of the foreground window
  208422. fg = GetAncestor (fg, GA_ROOT);
  208423. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208424. {
  208425. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208426. if (wp != 0 && wp->isInside (fg))
  208427. return true;
  208428. }
  208429. return false;
  208430. }
  208431. bool AlertWindow::showNativeDialogBox (const String& title,
  208432. const String& bodyText,
  208433. bool isOkCancel)
  208434. {
  208435. return MessageBox (0, bodyText, title,
  208436. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208437. : MB_OK)) == IDOK;
  208438. }
  208439. void Desktop::createMouseInputSources()
  208440. {
  208441. mouseSources.add (new MouseInputSource (0, true));
  208442. }
  208443. const Point<int> Desktop::getMousePosition()
  208444. {
  208445. POINT mousePos;
  208446. GetCursorPos (&mousePos);
  208447. return Point<int> (mousePos.x, mousePos.y);
  208448. }
  208449. void Desktop::setMousePosition (const Point<int>& newPosition)
  208450. {
  208451. SetCursorPos (newPosition.getX(), newPosition.getY());
  208452. }
  208453. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208454. {
  208455. return createSoftwareImage (format, width, height, clearImage);
  208456. }
  208457. class ScreenSaverDefeater : public Timer,
  208458. public DeletedAtShutdown
  208459. {
  208460. public:
  208461. ScreenSaverDefeater()
  208462. {
  208463. startTimer (10000);
  208464. timerCallback();
  208465. }
  208466. ~ScreenSaverDefeater() {}
  208467. void timerCallback()
  208468. {
  208469. if (Process::isForegroundProcess())
  208470. {
  208471. // simulate a shift key getting pressed..
  208472. INPUT input[2];
  208473. input[0].type = INPUT_KEYBOARD;
  208474. input[0].ki.wVk = VK_SHIFT;
  208475. input[0].ki.dwFlags = 0;
  208476. input[0].ki.dwExtraInfo = 0;
  208477. input[1].type = INPUT_KEYBOARD;
  208478. input[1].ki.wVk = VK_SHIFT;
  208479. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208480. input[1].ki.dwExtraInfo = 0;
  208481. SendInput (2, input, sizeof (INPUT));
  208482. }
  208483. }
  208484. };
  208485. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208486. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208487. {
  208488. if (isEnabled)
  208489. deleteAndZero (screenSaverDefeater);
  208490. else if (screenSaverDefeater == 0)
  208491. screenSaverDefeater = new ScreenSaverDefeater();
  208492. }
  208493. bool Desktop::isScreenSaverEnabled()
  208494. {
  208495. return screenSaverDefeater == 0;
  208496. }
  208497. /* (The code below is the "correct" way to disable the screen saver, but it
  208498. completely fails on winXP when the saver is password-protected...)
  208499. static bool juce_screenSaverEnabled = true;
  208500. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208501. {
  208502. juce_screenSaverEnabled = isEnabled;
  208503. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208504. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208505. }
  208506. bool Desktop::isScreenSaverEnabled() throw()
  208507. {
  208508. return juce_screenSaverEnabled;
  208509. }
  208510. */
  208511. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208512. {
  208513. if (enableOrDisable)
  208514. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208515. }
  208516. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208517. {
  208518. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208519. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208520. return TRUE;
  208521. }
  208522. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208523. {
  208524. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208525. // make sure the first in the list is the main monitor
  208526. for (int i = 1; i < monitorCoords.size(); ++i)
  208527. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208528. monitorCoords.swap (i, 0);
  208529. if (monitorCoords.size() == 0)
  208530. {
  208531. RECT r;
  208532. GetWindowRect (GetDesktopWindow(), &r);
  208533. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208534. }
  208535. if (clipToWorkArea)
  208536. {
  208537. // clip the main monitor to the active non-taskbar area
  208538. RECT r;
  208539. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208540. Rectangle<int>& screen = monitorCoords.getReference (0);
  208541. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208542. jmax (screen.getY(), (int) r.top));
  208543. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208544. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208545. }
  208546. }
  208547. const Image juce_createIconForFile (const File& file)
  208548. {
  208549. Image image;
  208550. WCHAR filename [1024];
  208551. file.getFullPathName().copyToUnicode (filename, 1023);
  208552. WORD iconNum = 0;
  208553. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208554. filename, &iconNum);
  208555. if (icon != 0)
  208556. {
  208557. image = IconConverters::createImageFromHICON (icon);
  208558. DestroyIcon (icon);
  208559. }
  208560. return image;
  208561. }
  208562. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208563. {
  208564. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208565. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208566. Image im (image);
  208567. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208568. {
  208569. im = im.rescaled (maxW, maxH);
  208570. hotspotX = (hotspotX * maxW) / image.getWidth();
  208571. hotspotY = (hotspotY * maxH) / image.getHeight();
  208572. }
  208573. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208574. }
  208575. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208576. {
  208577. if (cursorHandle != 0 && ! isStandard)
  208578. DestroyCursor ((HCURSOR) cursorHandle);
  208579. }
  208580. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208581. {
  208582. LPCTSTR cursorName = IDC_ARROW;
  208583. switch (type)
  208584. {
  208585. case NormalCursor: break;
  208586. case NoCursor: return 0;
  208587. case WaitCursor: cursorName = IDC_WAIT; break;
  208588. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208589. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208590. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208591. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208592. case LeftRightResizeCursor:
  208593. case LeftEdgeResizeCursor:
  208594. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208595. case UpDownResizeCursor:
  208596. case TopEdgeResizeCursor:
  208597. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208598. case TopLeftCornerResizeCursor:
  208599. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208600. case TopRightCornerResizeCursor:
  208601. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208602. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208603. case DraggingHandCursor:
  208604. {
  208605. static void* dragHandCursor = 0;
  208606. if (dragHandCursor == 0)
  208607. {
  208608. static const unsigned char dragHandData[] =
  208609. { 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,
  208610. 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,
  208611. 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 };
  208612. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208613. }
  208614. return dragHandCursor;
  208615. }
  208616. default:
  208617. jassertfalse; break;
  208618. }
  208619. HCURSOR cursorH = LoadCursor (0, cursorName);
  208620. if (cursorH == 0)
  208621. cursorH = LoadCursor (0, IDC_ARROW);
  208622. return cursorH;
  208623. }
  208624. void MouseCursor::showInWindow (ComponentPeer*) const
  208625. {
  208626. HCURSOR c = (HCURSOR) getHandle();
  208627. if (c == 0)
  208628. c = LoadCursor (0, IDC_ARROW);
  208629. SetCursor (c);
  208630. }
  208631. void MouseCursor::showInAllWindows() const
  208632. {
  208633. showInWindow (0);
  208634. }
  208635. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208636. {
  208637. public:
  208638. JuceDropSource() {}
  208639. ~JuceDropSource() {}
  208640. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208641. {
  208642. if (escapePressed)
  208643. return DRAGDROP_S_CANCEL;
  208644. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208645. return DRAGDROP_S_DROP;
  208646. return S_OK;
  208647. }
  208648. HRESULT __stdcall GiveFeedback (DWORD)
  208649. {
  208650. return DRAGDROP_S_USEDEFAULTCURSORS;
  208651. }
  208652. };
  208653. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208654. {
  208655. public:
  208656. JuceEnumFormatEtc (const FORMATETC* const format_)
  208657. : format (format_),
  208658. index (0)
  208659. {
  208660. }
  208661. ~JuceEnumFormatEtc() {}
  208662. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208663. {
  208664. if (result == 0)
  208665. return E_POINTER;
  208666. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208667. newOne->index = index;
  208668. *result = newOne;
  208669. return S_OK;
  208670. }
  208671. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208672. {
  208673. if (pceltFetched != 0)
  208674. *pceltFetched = 0;
  208675. else if (celt != 1)
  208676. return S_FALSE;
  208677. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208678. {
  208679. copyFormatEtc (lpFormatEtc [0], *format);
  208680. ++index;
  208681. if (pceltFetched != 0)
  208682. *pceltFetched = 1;
  208683. return S_OK;
  208684. }
  208685. return S_FALSE;
  208686. }
  208687. HRESULT __stdcall Skip (ULONG celt)
  208688. {
  208689. if (index + (int) celt >= 1)
  208690. return S_FALSE;
  208691. index += celt;
  208692. return S_OK;
  208693. }
  208694. HRESULT __stdcall Reset()
  208695. {
  208696. index = 0;
  208697. return S_OK;
  208698. }
  208699. private:
  208700. const FORMATETC* const format;
  208701. int index;
  208702. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208703. {
  208704. dest = source;
  208705. if (source.ptd != 0)
  208706. {
  208707. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208708. *(dest.ptd) = *(source.ptd);
  208709. }
  208710. }
  208711. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208712. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208713. };
  208714. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208715. {
  208716. public:
  208717. JuceDataObject (JuceDropSource* const dropSource_,
  208718. const FORMATETC* const format_,
  208719. const STGMEDIUM* const medium_)
  208720. : dropSource (dropSource_),
  208721. format (format_),
  208722. medium (medium_)
  208723. {
  208724. }
  208725. ~JuceDataObject()
  208726. {
  208727. jassert (refCount == 0);
  208728. }
  208729. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208730. {
  208731. if ((pFormatEtc->tymed & format->tymed) != 0
  208732. && pFormatEtc->cfFormat == format->cfFormat
  208733. && pFormatEtc->dwAspect == format->dwAspect)
  208734. {
  208735. pMedium->tymed = format->tymed;
  208736. pMedium->pUnkForRelease = 0;
  208737. if (format->tymed == TYMED_HGLOBAL)
  208738. {
  208739. const SIZE_T len = GlobalSize (medium->hGlobal);
  208740. void* const src = GlobalLock (medium->hGlobal);
  208741. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208742. memcpy (dst, src, len);
  208743. GlobalUnlock (medium->hGlobal);
  208744. pMedium->hGlobal = dst;
  208745. return S_OK;
  208746. }
  208747. }
  208748. return DV_E_FORMATETC;
  208749. }
  208750. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208751. {
  208752. if (f == 0)
  208753. return E_INVALIDARG;
  208754. if (f->tymed == format->tymed
  208755. && f->cfFormat == format->cfFormat
  208756. && f->dwAspect == format->dwAspect)
  208757. return S_OK;
  208758. return DV_E_FORMATETC;
  208759. }
  208760. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208761. {
  208762. pFormatEtcOut->ptd = 0;
  208763. return E_NOTIMPL;
  208764. }
  208765. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208766. {
  208767. if (result == 0)
  208768. return E_POINTER;
  208769. if (direction == DATADIR_GET)
  208770. {
  208771. *result = new JuceEnumFormatEtc (format);
  208772. return S_OK;
  208773. }
  208774. *result = 0;
  208775. return E_NOTIMPL;
  208776. }
  208777. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208778. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208779. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208780. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208781. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208782. private:
  208783. JuceDropSource* const dropSource;
  208784. const FORMATETC* const format;
  208785. const STGMEDIUM* const medium;
  208786. JuceDataObject (const JuceDataObject&);
  208787. JuceDataObject& operator= (const JuceDataObject&);
  208788. };
  208789. static HDROP createHDrop (const StringArray& fileNames)
  208790. {
  208791. int totalChars = 0;
  208792. for (int i = fileNames.size(); --i >= 0;)
  208793. totalChars += fileNames[i].length() + 1;
  208794. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208795. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208796. if (hDrop != 0)
  208797. {
  208798. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208799. pDropFiles->pFiles = sizeof (DROPFILES);
  208800. pDropFiles->fWide = true;
  208801. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208802. for (int i = 0; i < fileNames.size(); ++i)
  208803. {
  208804. fileNames[i].copyToUnicode (fname, 2048);
  208805. fname += fileNames[i].length() + 1;
  208806. }
  208807. *fname = 0;
  208808. GlobalUnlock (hDrop);
  208809. }
  208810. return hDrop;
  208811. }
  208812. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208813. {
  208814. JuceDropSource* const source = new JuceDropSource();
  208815. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208816. DWORD effect;
  208817. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208818. data->Release();
  208819. source->Release();
  208820. return res == DRAGDROP_S_DROP;
  208821. }
  208822. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208823. {
  208824. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208825. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208826. medium.hGlobal = createHDrop (files);
  208827. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208828. : DROPEFFECT_COPY);
  208829. }
  208830. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208831. {
  208832. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208833. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208834. const int numChars = text.length();
  208835. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208836. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208837. text.copyToUnicode (data, numChars + 1);
  208838. format.cfFormat = CF_UNICODETEXT;
  208839. GlobalUnlock (medium.hGlobal);
  208840. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208841. }
  208842. #endif
  208843. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208844. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208845. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208846. // compiled on its own).
  208847. #if JUCE_INCLUDED_FILE
  208848. namespace FileChooserHelpers
  208849. {
  208850. static bool areThereAnyAlwaysOnTopWindows()
  208851. {
  208852. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208853. {
  208854. Component* c = Desktop::getInstance().getComponent (i);
  208855. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208856. return true;
  208857. }
  208858. return false;
  208859. }
  208860. struct FileChooserCallbackInfo
  208861. {
  208862. String initialPath;
  208863. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208864. ScopedPointer<Component> customComponent;
  208865. };
  208866. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208867. {
  208868. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208869. if (msg == BFFM_INITIALIZED)
  208870. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  208871. else if (msg == BFFM_VALIDATEFAILEDW)
  208872. info->returnedString = (LPCWSTR) lParam;
  208873. else if (msg == BFFM_VALIDATEFAILEDA)
  208874. info->returnedString = (const char*) lParam;
  208875. return 0;
  208876. }
  208877. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208878. {
  208879. if (uiMsg == WM_INITDIALOG)
  208880. {
  208881. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208882. HWND dialogH = GetParent (hdlg);
  208883. jassert (dialogH != 0);
  208884. if (dialogH == 0)
  208885. dialogH = hdlg;
  208886. RECT r, cr;
  208887. GetWindowRect (dialogH, &r);
  208888. GetClientRect (dialogH, &cr);
  208889. SetWindowPos (dialogH, 0,
  208890. r.left, r.top,
  208891. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208892. jmax (150, (int) (r.bottom - r.top)),
  208893. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208894. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208895. customComp->addToDesktop (0, dialogH);
  208896. }
  208897. else if (uiMsg == WM_NOTIFY)
  208898. {
  208899. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208900. if (ofn->hdr.code == CDN_SELCHANGE)
  208901. {
  208902. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208903. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208904. if (comp != 0)
  208905. {
  208906. WCHAR path [MAX_PATH * 2];
  208907. zerostruct (path);
  208908. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208909. comp->selectedFileChanged (File (path));
  208910. }
  208911. }
  208912. }
  208913. return 0;
  208914. }
  208915. class CustomComponentHolder : public Component
  208916. {
  208917. public:
  208918. CustomComponentHolder (Component* customComp)
  208919. {
  208920. setVisible (true);
  208921. setOpaque (true);
  208922. addAndMakeVisible (customComp);
  208923. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208924. }
  208925. void paint (Graphics& g)
  208926. {
  208927. g.fillAll (Colours::lightgrey);
  208928. }
  208929. void resized()
  208930. {
  208931. if (getNumChildComponents() > 0)
  208932. getChildComponent(0)->setBounds (getLocalBounds());
  208933. }
  208934. juce_UseDebuggingNewOperator
  208935. private:
  208936. CustomComponentHolder (const CustomComponentHolder&);
  208937. CustomComponentHolder& operator= (const CustomComponentHolder&);
  208938. };
  208939. }
  208940. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208941. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208942. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208943. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208944. {
  208945. using namespace FileChooserHelpers;
  208946. HeapBlock<WCHAR> files;
  208947. const int charsAvailableForResult = 32768;
  208948. files.calloc (charsAvailableForResult + 1);
  208949. int filenameOffset = 0;
  208950. FileChooserCallbackInfo info;
  208951. // use a modal window as the parent for this dialog box
  208952. // to block input from other app windows
  208953. Component parentWindow (String::empty);
  208954. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208955. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208956. mainMon.getY() + mainMon.getHeight() / 4,
  208957. 0, 0);
  208958. parentWindow.setOpaque (true);
  208959. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208960. parentWindow.addToDesktop (0);
  208961. if (extraInfoComponent == 0)
  208962. parentWindow.enterModalState();
  208963. if (currentFileOrDirectory.isDirectory())
  208964. {
  208965. info.initialPath = currentFileOrDirectory.getFullPathName();
  208966. }
  208967. else
  208968. {
  208969. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  208970. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208971. }
  208972. if (selectsDirectory)
  208973. {
  208974. BROWSEINFO bi;
  208975. zerostruct (bi);
  208976. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208977. bi.pszDisplayName = files;
  208978. bi.lpszTitle = title;
  208979. bi.lParam = (LPARAM) &info;
  208980. bi.lpfn = browseCallbackProc;
  208981. #ifdef BIF_USENEWUI
  208982. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208983. #else
  208984. bi.ulFlags = 0x50;
  208985. #endif
  208986. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208987. if (! SHGetPathFromIDListW (list, files))
  208988. {
  208989. files[0] = 0;
  208990. info.returnedString = String::empty;
  208991. }
  208992. LPMALLOC al;
  208993. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208994. al->Free (list);
  208995. if (info.returnedString.isNotEmpty())
  208996. {
  208997. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208998. return;
  208999. }
  209000. }
  209001. else
  209002. {
  209003. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  209004. if (warnAboutOverwritingExistingFiles)
  209005. flags |= OFN_OVERWRITEPROMPT;
  209006. if (selectMultipleFiles)
  209007. flags |= OFN_ALLOWMULTISELECT;
  209008. if (extraInfoComponent != 0)
  209009. {
  209010. flags |= OFN_ENABLEHOOK;
  209011. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  209012. info.customComponent->enterModalState();
  209013. }
  209014. WCHAR filters [1024];
  209015. zerostruct (filters);
  209016. filter.copyToUnicode (filters, 1024);
  209017. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  209018. OPENFILENAMEW of;
  209019. zerostruct (of);
  209020. #ifdef OPENFILENAME_SIZE_VERSION_400W
  209021. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  209022. #else
  209023. of.lStructSize = sizeof (of);
  209024. #endif
  209025. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209026. of.lpstrFilter = filters;
  209027. of.nFilterIndex = 1;
  209028. of.lpstrFile = files;
  209029. of.nMaxFile = charsAvailableForResult;
  209030. of.lpstrInitialDir = info.initialPath;
  209031. of.lpstrTitle = title;
  209032. of.Flags = flags;
  209033. of.lCustData = (LPARAM) &info;
  209034. if (extraInfoComponent != 0)
  209035. of.lpfnHook = &openCallback;
  209036. if (! (isSaveDialogue ? GetSaveFileName (&of)
  209037. : GetOpenFileName (&of)))
  209038. return;
  209039. filenameOffset = of.nFileOffset;
  209040. }
  209041. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  209042. {
  209043. const WCHAR* filename = files + filenameOffset;
  209044. while (*filename != 0)
  209045. {
  209046. results.add (File (String (files) + "\\" + String (filename)));
  209047. filename += CharacterFunctions::length (filename) + 1;
  209048. }
  209049. }
  209050. else if (files[0] != 0)
  209051. {
  209052. results.add (File (String (files)));
  209053. }
  209054. }
  209055. #endif
  209056. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209057. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209058. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209059. // compiled on its own).
  209060. #if JUCE_INCLUDED_FILE
  209061. void SystemClipboard::copyTextToClipboard (const String& text)
  209062. {
  209063. if (OpenClipboard (0) != 0)
  209064. {
  209065. if (EmptyClipboard() != 0)
  209066. {
  209067. const int len = text.length();
  209068. if (len > 0)
  209069. {
  209070. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  209071. (len + 1) * sizeof (wchar_t));
  209072. if (bufH != 0)
  209073. {
  209074. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209075. text.copyToUnicode (data, len);
  209076. GlobalUnlock (bufH);
  209077. SetClipboardData (CF_UNICODETEXT, bufH);
  209078. }
  209079. }
  209080. }
  209081. CloseClipboard();
  209082. }
  209083. }
  209084. const String SystemClipboard::getTextFromClipboard()
  209085. {
  209086. String result;
  209087. if (OpenClipboard (0) != 0)
  209088. {
  209089. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209090. if (bufH != 0)
  209091. {
  209092. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209093. if (data != 0)
  209094. {
  209095. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  209096. GlobalUnlock (bufH);
  209097. }
  209098. }
  209099. CloseClipboard();
  209100. }
  209101. return result;
  209102. }
  209103. #endif
  209104. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209105. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209106. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209107. // compiled on its own).
  209108. #if JUCE_INCLUDED_FILE
  209109. namespace ActiveXHelpers
  209110. {
  209111. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209112. {
  209113. public:
  209114. JuceIStorage() {}
  209115. ~JuceIStorage() {}
  209116. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209117. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209118. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209119. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209120. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209121. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209122. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209123. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209124. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209125. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209126. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209127. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209128. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209129. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209130. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209131. juce_UseDebuggingNewOperator
  209132. };
  209133. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209134. {
  209135. HWND window;
  209136. public:
  209137. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209138. ~JuceOleInPlaceFrame() {}
  209139. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209140. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209141. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209142. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209143. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209144. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209145. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209146. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209147. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209148. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209149. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209150. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209151. juce_UseDebuggingNewOperator
  209152. };
  209153. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209154. {
  209155. HWND window;
  209156. JuceOleInPlaceFrame* frame;
  209157. public:
  209158. JuceIOleInPlaceSite (HWND window_)
  209159. : window (window_),
  209160. frame (new JuceOleInPlaceFrame (window))
  209161. {}
  209162. ~JuceIOleInPlaceSite()
  209163. {
  209164. frame->Release();
  209165. }
  209166. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209167. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209168. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209169. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209170. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209171. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209172. {
  209173. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209174. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209175. */
  209176. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209177. if (lplpDoc != 0) *lplpDoc = 0;
  209178. lpFrameInfo->fMDIApp = FALSE;
  209179. lpFrameInfo->hwndFrame = window;
  209180. lpFrameInfo->haccel = 0;
  209181. lpFrameInfo->cAccelEntries = 0;
  209182. return S_OK;
  209183. }
  209184. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209185. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209186. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209187. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209188. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209189. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209190. juce_UseDebuggingNewOperator
  209191. };
  209192. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209193. {
  209194. JuceIOleInPlaceSite* inplaceSite;
  209195. public:
  209196. JuceIOleClientSite (HWND window)
  209197. : inplaceSite (new JuceIOleInPlaceSite (window))
  209198. {}
  209199. ~JuceIOleClientSite()
  209200. {
  209201. inplaceSite->Release();
  209202. }
  209203. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209204. {
  209205. if (type == IID_IOleInPlaceSite)
  209206. {
  209207. inplaceSite->AddRef();
  209208. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209209. return S_OK;
  209210. }
  209211. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209212. }
  209213. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209214. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209215. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209216. HRESULT __stdcall ShowObject() { return S_OK; }
  209217. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209218. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209219. juce_UseDebuggingNewOperator
  209220. };
  209221. static Array<ActiveXControlComponent*> activeXComps;
  209222. static HWND getHWND (const ActiveXControlComponent* const component)
  209223. {
  209224. HWND hwnd = 0;
  209225. const IID iid = IID_IOleWindow;
  209226. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209227. if (window != 0)
  209228. {
  209229. window->GetWindow (&hwnd);
  209230. window->Release();
  209231. }
  209232. return hwnd;
  209233. }
  209234. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209235. {
  209236. RECT activeXRect, peerRect;
  209237. GetWindowRect (hwnd, &activeXRect);
  209238. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209239. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209240. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209241. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209242. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209243. switch (message)
  209244. {
  209245. case WM_MOUSEMOVE:
  209246. case WM_LBUTTONDOWN:
  209247. case WM_MBUTTONDOWN:
  209248. case WM_RBUTTONDOWN:
  209249. case WM_LBUTTONUP:
  209250. case WM_MBUTTONUP:
  209251. case WM_RBUTTONUP:
  209252. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209253. break;
  209254. default:
  209255. break;
  209256. }
  209257. }
  209258. }
  209259. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209260. {
  209261. ActiveXControlComponent& owner;
  209262. bool wasShowing;
  209263. public:
  209264. HWND controlHWND;
  209265. IStorage* storage;
  209266. IOleClientSite* clientSite;
  209267. IOleObject* control;
  209268. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209269. : ComponentMovementWatcher (&owner_),
  209270. owner (owner_),
  209271. wasShowing (owner_.isShowing()),
  209272. controlHWND (0),
  209273. storage (new ActiveXHelpers::JuceIStorage()),
  209274. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209275. control (0)
  209276. {
  209277. }
  209278. ~Pimpl()
  209279. {
  209280. if (control != 0)
  209281. {
  209282. control->Close (OLECLOSE_NOSAVE);
  209283. control->Release();
  209284. }
  209285. clientSite->Release();
  209286. storage->Release();
  209287. }
  209288. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209289. {
  209290. Component* const topComp = owner.getTopLevelComponent();
  209291. if (topComp->getPeer() != 0)
  209292. {
  209293. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  209294. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209295. }
  209296. }
  209297. void componentPeerChanged()
  209298. {
  209299. const bool isShowingNow = owner.isShowing();
  209300. if (wasShowing != isShowingNow)
  209301. {
  209302. wasShowing = isShowingNow;
  209303. owner.setControlVisible (isShowingNow);
  209304. }
  209305. componentMovedOrResized (true, true);
  209306. }
  209307. void componentVisibilityChanged (Component&)
  209308. {
  209309. componentPeerChanged();
  209310. }
  209311. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209312. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209313. {
  209314. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209315. {
  209316. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209317. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209318. {
  209319. switch (message)
  209320. {
  209321. case WM_MOUSEMOVE:
  209322. case WM_LBUTTONDOWN:
  209323. case WM_MBUTTONDOWN:
  209324. case WM_RBUTTONDOWN:
  209325. case WM_LBUTTONUP:
  209326. case WM_MBUTTONUP:
  209327. case WM_RBUTTONUP:
  209328. case WM_LBUTTONDBLCLK:
  209329. case WM_MBUTTONDBLCLK:
  209330. case WM_RBUTTONDBLCLK:
  209331. if (ax->isShowing())
  209332. {
  209333. ComponentPeer* const peer = ax->getPeer();
  209334. if (peer != 0)
  209335. {
  209336. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209337. if (! ax->areMouseEventsAllowed())
  209338. return 0;
  209339. }
  209340. }
  209341. break;
  209342. default:
  209343. break;
  209344. }
  209345. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209346. }
  209347. }
  209348. return DefWindowProc (hwnd, message, wParam, lParam);
  209349. }
  209350. };
  209351. ActiveXControlComponent::ActiveXControlComponent()
  209352. : originalWndProc (0),
  209353. mouseEventsAllowed (true)
  209354. {
  209355. ActiveXHelpers::activeXComps.add (this);
  209356. }
  209357. ActiveXControlComponent::~ActiveXControlComponent()
  209358. {
  209359. deleteControl();
  209360. ActiveXHelpers::activeXComps.removeValue (this);
  209361. }
  209362. void ActiveXControlComponent::paint (Graphics& g)
  209363. {
  209364. if (control == 0)
  209365. g.fillAll (Colours::lightgrey);
  209366. }
  209367. bool ActiveXControlComponent::createControl (const void* controlIID)
  209368. {
  209369. deleteControl();
  209370. ComponentPeer* const peer = getPeer();
  209371. // the component must have already been added to a real window when you call this!
  209372. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209373. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209374. {
  209375. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209376. HWND hwnd = (HWND) peer->getNativeHandle();
  209377. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209378. HRESULT hr;
  209379. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209380. newControl->clientSite, newControl->storage,
  209381. (void**) &(newControl->control))) == S_OK)
  209382. {
  209383. newControl->control->SetHostNames (L"Juce", 0);
  209384. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209385. {
  209386. RECT rect;
  209387. rect.left = pos.getX();
  209388. rect.top = pos.getY();
  209389. rect.right = pos.getX() + getWidth();
  209390. rect.bottom = pos.getY() + getHeight();
  209391. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209392. {
  209393. control = newControl;
  209394. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209395. control->controlHWND = ActiveXHelpers::getHWND (this);
  209396. if (control->controlHWND != 0)
  209397. {
  209398. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209399. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209400. }
  209401. return true;
  209402. }
  209403. }
  209404. }
  209405. }
  209406. return false;
  209407. }
  209408. void ActiveXControlComponent::deleteControl()
  209409. {
  209410. control = 0;
  209411. originalWndProc = 0;
  209412. }
  209413. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209414. {
  209415. void* result = 0;
  209416. if (control != 0 && control->control != 0
  209417. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209418. return result;
  209419. return 0;
  209420. }
  209421. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209422. {
  209423. if (control->controlHWND != 0)
  209424. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209425. }
  209426. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209427. {
  209428. if (control->controlHWND != 0)
  209429. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209430. }
  209431. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209432. {
  209433. mouseEventsAllowed = eventsCanReachControl;
  209434. }
  209435. #endif
  209436. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209437. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209438. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209439. // compiled on its own).
  209440. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209441. using namespace QTOLibrary;
  209442. using namespace QTOControlLib;
  209443. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209444. static bool isQTAvailable = false;
  209445. class QuickTimeMovieComponent::Pimpl
  209446. {
  209447. public:
  209448. Pimpl() : dataHandle (0)
  209449. {
  209450. }
  209451. ~Pimpl()
  209452. {
  209453. clearHandle();
  209454. }
  209455. void clearHandle()
  209456. {
  209457. if (dataHandle != 0)
  209458. {
  209459. DisposeHandle (dataHandle);
  209460. dataHandle = 0;
  209461. }
  209462. }
  209463. IQTControlPtr qtControl;
  209464. IQTMoviePtr qtMovie;
  209465. Handle dataHandle;
  209466. };
  209467. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209468. : movieLoaded (false),
  209469. controllerVisible (true)
  209470. {
  209471. pimpl = new Pimpl();
  209472. setMouseEventsAllowed (false);
  209473. }
  209474. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209475. {
  209476. closeMovie();
  209477. pimpl->qtControl = 0;
  209478. deleteControl();
  209479. pimpl = 0;
  209480. }
  209481. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209482. {
  209483. if (! isQTAvailable)
  209484. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209485. return isQTAvailable;
  209486. }
  209487. void QuickTimeMovieComponent::createControlIfNeeded()
  209488. {
  209489. if (isShowing() && ! isControlCreated())
  209490. {
  209491. const IID qtIID = __uuidof (QTControl);
  209492. if (createControl (&qtIID))
  209493. {
  209494. const IID qtInterfaceIID = __uuidof (IQTControl);
  209495. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209496. if (pimpl->qtControl != 0)
  209497. {
  209498. pimpl->qtControl->Release(); // it has one ref too many at this point
  209499. pimpl->qtControl->QuickTimeInitialize();
  209500. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209501. if (movieFile != File::nonexistent)
  209502. loadMovie (movieFile, controllerVisible);
  209503. }
  209504. }
  209505. }
  209506. }
  209507. bool QuickTimeMovieComponent::isControlCreated() const
  209508. {
  209509. return isControlOpen();
  209510. }
  209511. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209512. const bool isControllerVisible)
  209513. {
  209514. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209515. movieFile = File::nonexistent;
  209516. movieLoaded = false;
  209517. pimpl->qtMovie = 0;
  209518. controllerVisible = isControllerVisible;
  209519. createControlIfNeeded();
  209520. if (isControlCreated())
  209521. {
  209522. if (pimpl->qtControl != 0)
  209523. {
  209524. pimpl->qtControl->Put_MovieHandle (0);
  209525. pimpl->clearHandle();
  209526. Movie movie;
  209527. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209528. {
  209529. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209530. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209531. if (pimpl->qtMovie != 0)
  209532. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209533. : qtMovieControllerTypeNone);
  209534. }
  209535. if (movie == 0)
  209536. pimpl->clearHandle();
  209537. }
  209538. movieLoaded = (pimpl->qtMovie != 0);
  209539. }
  209540. else
  209541. {
  209542. // You're trying to open a movie when the control hasn't yet been created, probably because
  209543. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209544. jassertfalse;
  209545. }
  209546. return movieLoaded;
  209547. }
  209548. void QuickTimeMovieComponent::closeMovie()
  209549. {
  209550. stop();
  209551. movieFile = File::nonexistent;
  209552. movieLoaded = false;
  209553. pimpl->qtMovie = 0;
  209554. if (pimpl->qtControl != 0)
  209555. pimpl->qtControl->Put_MovieHandle (0);
  209556. pimpl->clearHandle();
  209557. }
  209558. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209559. {
  209560. return movieFile;
  209561. }
  209562. bool QuickTimeMovieComponent::isMovieOpen() const
  209563. {
  209564. return movieLoaded;
  209565. }
  209566. double QuickTimeMovieComponent::getMovieDuration() const
  209567. {
  209568. if (pimpl->qtMovie != 0)
  209569. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209570. return 0.0;
  209571. }
  209572. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209573. {
  209574. if (pimpl->qtMovie != 0)
  209575. {
  209576. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209577. width = r.right - r.left;
  209578. height = r.bottom - r.top;
  209579. }
  209580. else
  209581. {
  209582. width = height = 0;
  209583. }
  209584. }
  209585. void QuickTimeMovieComponent::play()
  209586. {
  209587. if (pimpl->qtMovie != 0)
  209588. pimpl->qtMovie->Play();
  209589. }
  209590. void QuickTimeMovieComponent::stop()
  209591. {
  209592. if (pimpl->qtMovie != 0)
  209593. pimpl->qtMovie->Stop();
  209594. }
  209595. bool QuickTimeMovieComponent::isPlaying() const
  209596. {
  209597. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209598. }
  209599. void QuickTimeMovieComponent::setPosition (const double seconds)
  209600. {
  209601. if (pimpl->qtMovie != 0)
  209602. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209603. }
  209604. double QuickTimeMovieComponent::getPosition() const
  209605. {
  209606. if (pimpl->qtMovie != 0)
  209607. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209608. return 0.0;
  209609. }
  209610. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209611. {
  209612. if (pimpl->qtMovie != 0)
  209613. pimpl->qtMovie->PutRate (newSpeed);
  209614. }
  209615. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209616. {
  209617. if (pimpl->qtMovie != 0)
  209618. {
  209619. pimpl->qtMovie->PutAudioVolume (newVolume);
  209620. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209621. }
  209622. }
  209623. float QuickTimeMovieComponent::getMovieVolume() const
  209624. {
  209625. if (pimpl->qtMovie != 0)
  209626. return pimpl->qtMovie->GetAudioVolume();
  209627. return 0.0f;
  209628. }
  209629. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209630. {
  209631. if (pimpl->qtMovie != 0)
  209632. pimpl->qtMovie->PutLoop (shouldLoop);
  209633. }
  209634. bool QuickTimeMovieComponent::isLooping() const
  209635. {
  209636. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209637. }
  209638. bool QuickTimeMovieComponent::isControllerVisible() const
  209639. {
  209640. return controllerVisible;
  209641. }
  209642. void QuickTimeMovieComponent::parentHierarchyChanged()
  209643. {
  209644. createControlIfNeeded();
  209645. QTCompBaseClass::parentHierarchyChanged();
  209646. }
  209647. void QuickTimeMovieComponent::visibilityChanged()
  209648. {
  209649. createControlIfNeeded();
  209650. QTCompBaseClass::visibilityChanged();
  209651. }
  209652. void QuickTimeMovieComponent::paint (Graphics& g)
  209653. {
  209654. if (! isControlCreated())
  209655. g.fillAll (Colours::black);
  209656. }
  209657. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209658. {
  209659. Handle dataRef = 0;
  209660. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209661. if (err == noErr)
  209662. {
  209663. Str255 suffix;
  209664. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209665. StringPtr name = suffix;
  209666. err = PtrAndHand (name, dataRef, name[0] + 1);
  209667. if (err == noErr)
  209668. {
  209669. long atoms[3];
  209670. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209671. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209672. atoms[2] = EndianU32_NtoB (MovieFileType);
  209673. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209674. if (err == noErr)
  209675. return dataRef;
  209676. }
  209677. DisposeHandle (dataRef);
  209678. }
  209679. return 0;
  209680. }
  209681. static CFStringRef juceStringToCFString (const String& s)
  209682. {
  209683. const int len = s.length();
  209684. const juce_wchar* const t = s;
  209685. HeapBlock <UniChar> temp (len + 2);
  209686. for (int i = 0; i <= len; ++i)
  209687. temp[i] = t[i];
  209688. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209689. }
  209690. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209691. {
  209692. Boolean trueBool = true;
  209693. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209694. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209695. props[prop].propValueSize = sizeof (trueBool);
  209696. props[prop].propValueAddress = &trueBool;
  209697. ++prop;
  209698. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209699. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209700. props[prop].propValueSize = sizeof (trueBool);
  209701. props[prop].propValueAddress = &trueBool;
  209702. ++prop;
  209703. Boolean isActive = true;
  209704. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209705. props[prop].propID = kQTNewMoviePropertyID_Active;
  209706. props[prop].propValueSize = sizeof (isActive);
  209707. props[prop].propValueAddress = &isActive;
  209708. ++prop;
  209709. MacSetPort (0);
  209710. jassert (prop <= 5);
  209711. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209712. return err == noErr;
  209713. }
  209714. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209715. {
  209716. if (input == 0)
  209717. return false;
  209718. dataHandle = 0;
  209719. bool ok = false;
  209720. QTNewMoviePropertyElement props[5];
  209721. zeromem (props, sizeof (props));
  209722. int prop = 0;
  209723. DataReferenceRecord dr;
  209724. props[prop].propClass = kQTPropertyClass_DataLocation;
  209725. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209726. props[prop].propValueSize = sizeof (dr);
  209727. props[prop].propValueAddress = &dr;
  209728. ++prop;
  209729. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209730. if (fin != 0)
  209731. {
  209732. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209733. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209734. &dr.dataRef, &dr.dataRefType);
  209735. ok = openMovie (props, prop, movie);
  209736. DisposeHandle (dr.dataRef);
  209737. CFRelease (filePath);
  209738. }
  209739. else
  209740. {
  209741. // sanity-check because this currently needs to load the whole stream into memory..
  209742. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209743. dataHandle = NewHandle ((Size) input->getTotalLength());
  209744. HLock (dataHandle);
  209745. // read the entire stream into memory - this is a pain, but can't get it to work
  209746. // properly using a custom callback to supply the data.
  209747. input->read (*dataHandle, (int) input->getTotalLength());
  209748. HUnlock (dataHandle);
  209749. // different types to get QT to try. (We should really be a bit smarter here by
  209750. // working out in advance which one the stream contains, rather than just trying
  209751. // each one)
  209752. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209753. "\04.avi", "\04.m4a" };
  209754. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209755. {
  209756. /* // this fails for some bizarre reason - it can be bodged to work with
  209757. // movies, but can't seem to do it for other file types..
  209758. QTNewMovieUserProcRecord procInfo;
  209759. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209760. procInfo.getMovieUserProcRefcon = this;
  209761. procInfo.defaultDataRef.dataRef = dataRef;
  209762. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209763. props[prop].propClass = kQTPropertyClass_DataLocation;
  209764. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209765. props[prop].propValueSize = sizeof (procInfo);
  209766. props[prop].propValueAddress = (void*) &procInfo;
  209767. ++prop; */
  209768. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209769. dr.dataRefType = HandleDataHandlerSubType;
  209770. ok = openMovie (props, prop, movie);
  209771. DisposeHandle (dr.dataRef);
  209772. }
  209773. }
  209774. return ok;
  209775. }
  209776. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209777. const bool isControllerVisible)
  209778. {
  209779. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209780. movieFile = movieFile_;
  209781. return ok;
  209782. }
  209783. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209784. const bool isControllerVisible)
  209785. {
  209786. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209787. }
  209788. void QuickTimeMovieComponent::goToStart()
  209789. {
  209790. setPosition (0.0);
  209791. }
  209792. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209793. const RectanglePlacement& placement)
  209794. {
  209795. int normalWidth, normalHeight;
  209796. getMovieNormalSize (normalWidth, normalHeight);
  209797. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209798. {
  209799. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209800. placement.applyTo (x, y, w, h,
  209801. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209802. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209803. if (w > 0 && h > 0)
  209804. {
  209805. setBounds (roundToInt (x), roundToInt (y),
  209806. roundToInt (w), roundToInt (h));
  209807. }
  209808. }
  209809. else
  209810. {
  209811. setBounds (spaceToFitWithin);
  209812. }
  209813. }
  209814. #endif
  209815. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209816. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209817. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209818. // compiled on its own).
  209819. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209820. class WebBrowserComponentInternal : public ActiveXControlComponent
  209821. {
  209822. public:
  209823. WebBrowserComponentInternal()
  209824. : browser (0),
  209825. connectionPoint (0),
  209826. adviseCookie (0)
  209827. {
  209828. }
  209829. ~WebBrowserComponentInternal()
  209830. {
  209831. if (connectionPoint != 0)
  209832. connectionPoint->Unadvise (adviseCookie);
  209833. if (browser != 0)
  209834. browser->Release();
  209835. }
  209836. void createBrowser()
  209837. {
  209838. createControl (&CLSID_WebBrowser);
  209839. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209840. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209841. if (connectionPointContainer != 0)
  209842. {
  209843. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209844. &connectionPoint);
  209845. if (connectionPoint != 0)
  209846. {
  209847. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209848. jassert (owner != 0);
  209849. EventHandler* handler = new EventHandler (owner);
  209850. connectionPoint->Advise (handler, &adviseCookie);
  209851. handler->Release();
  209852. }
  209853. }
  209854. }
  209855. void goToURL (const String& url,
  209856. const StringArray* headers,
  209857. const MemoryBlock* postData)
  209858. {
  209859. if (browser != 0)
  209860. {
  209861. LPSAFEARRAY sa = 0;
  209862. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209863. VariantInit (&flags);
  209864. VariantInit (&frame);
  209865. VariantInit (&postDataVar);
  209866. VariantInit (&headersVar);
  209867. if (headers != 0)
  209868. {
  209869. V_VT (&headersVar) = VT_BSTR;
  209870. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209871. }
  209872. if (postData != 0 && postData->getSize() > 0)
  209873. {
  209874. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209875. if (sa != 0)
  209876. {
  209877. void* data = 0;
  209878. SafeArrayAccessData (sa, &data);
  209879. jassert (data != 0);
  209880. if (data != 0)
  209881. {
  209882. postData->copyTo (data, 0, postData->getSize());
  209883. SafeArrayUnaccessData (sa);
  209884. VARIANT postDataVar2;
  209885. VariantInit (&postDataVar2);
  209886. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209887. V_ARRAY (&postDataVar2) = sa;
  209888. postDataVar = postDataVar2;
  209889. }
  209890. }
  209891. }
  209892. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209893. &flags, &frame,
  209894. &postDataVar, &headersVar);
  209895. if (sa != 0)
  209896. SafeArrayDestroy (sa);
  209897. VariantClear (&flags);
  209898. VariantClear (&frame);
  209899. VariantClear (&postDataVar);
  209900. VariantClear (&headersVar);
  209901. }
  209902. }
  209903. IWebBrowser2* browser;
  209904. juce_UseDebuggingNewOperator
  209905. private:
  209906. IConnectionPoint* connectionPoint;
  209907. DWORD adviseCookie;
  209908. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209909. public ComponentMovementWatcher
  209910. {
  209911. public:
  209912. EventHandler (WebBrowserComponent* const owner_)
  209913. : ComponentMovementWatcher (owner_),
  209914. owner (owner_)
  209915. {
  209916. }
  209917. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  209918. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  209919. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  209920. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  209921. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  209922. {
  209923. switch (dispIdMember)
  209924. {
  209925. case DISPID_BEFORENAVIGATE2:
  209926. {
  209927. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209928. String url;
  209929. if ((vurl->vt & VT_BYREF) != 0)
  209930. url = *vurl->pbstrVal;
  209931. else
  209932. url = vurl->bstrVal;
  209933. *pDispParams->rgvarg->pboolVal
  209934. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209935. : VARIANT_TRUE;
  209936. return S_OK;
  209937. }
  209938. default:
  209939. break;
  209940. }
  209941. return E_NOTIMPL;
  209942. }
  209943. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209944. void componentPeerChanged() {}
  209945. void componentVisibilityChanged (Component&)
  209946. {
  209947. owner->visibilityChanged();
  209948. }
  209949. juce_UseDebuggingNewOperator
  209950. private:
  209951. WebBrowserComponent* const owner;
  209952. EventHandler (const EventHandler&);
  209953. EventHandler& operator= (const EventHandler&);
  209954. };
  209955. };
  209956. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209957. : browser (0),
  209958. blankPageShown (false),
  209959. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209960. {
  209961. setOpaque (true);
  209962. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209963. }
  209964. WebBrowserComponent::~WebBrowserComponent()
  209965. {
  209966. delete browser;
  209967. }
  209968. void WebBrowserComponent::goToURL (const String& url,
  209969. const StringArray* headers,
  209970. const MemoryBlock* postData)
  209971. {
  209972. lastURL = url;
  209973. lastHeaders.clear();
  209974. if (headers != 0)
  209975. lastHeaders = *headers;
  209976. lastPostData.setSize (0);
  209977. if (postData != 0)
  209978. lastPostData = *postData;
  209979. blankPageShown = false;
  209980. browser->goToURL (url, headers, postData);
  209981. }
  209982. void WebBrowserComponent::stop()
  209983. {
  209984. if (browser->browser != 0)
  209985. browser->browser->Stop();
  209986. }
  209987. void WebBrowserComponent::goBack()
  209988. {
  209989. lastURL = String::empty;
  209990. blankPageShown = false;
  209991. if (browser->browser != 0)
  209992. browser->browser->GoBack();
  209993. }
  209994. void WebBrowserComponent::goForward()
  209995. {
  209996. lastURL = String::empty;
  209997. if (browser->browser != 0)
  209998. browser->browser->GoForward();
  209999. }
  210000. void WebBrowserComponent::refresh()
  210001. {
  210002. if (browser->browser != 0)
  210003. browser->browser->Refresh();
  210004. }
  210005. void WebBrowserComponent::paint (Graphics& g)
  210006. {
  210007. if (browser->browser == 0)
  210008. g.fillAll (Colours::white);
  210009. }
  210010. void WebBrowserComponent::checkWindowAssociation()
  210011. {
  210012. if (isShowing())
  210013. {
  210014. if (browser->browser == 0 && getPeer() != 0)
  210015. {
  210016. browser->createBrowser();
  210017. reloadLastURL();
  210018. }
  210019. else
  210020. {
  210021. if (blankPageShown)
  210022. goBack();
  210023. }
  210024. }
  210025. else
  210026. {
  210027. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  210028. {
  210029. // when the component becomes invisible, some stuff like flash
  210030. // carries on playing audio, so we need to force it onto a blank
  210031. // page to avoid this..
  210032. blankPageShown = true;
  210033. browser->goToURL ("about:blank", 0, 0);
  210034. }
  210035. }
  210036. }
  210037. void WebBrowserComponent::reloadLastURL()
  210038. {
  210039. if (lastURL.isNotEmpty())
  210040. {
  210041. goToURL (lastURL, &lastHeaders, &lastPostData);
  210042. lastURL = String::empty;
  210043. }
  210044. }
  210045. void WebBrowserComponent::parentHierarchyChanged()
  210046. {
  210047. checkWindowAssociation();
  210048. }
  210049. void WebBrowserComponent::resized()
  210050. {
  210051. browser->setSize (getWidth(), getHeight());
  210052. }
  210053. void WebBrowserComponent::visibilityChanged()
  210054. {
  210055. checkWindowAssociation();
  210056. }
  210057. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210058. {
  210059. return true;
  210060. }
  210061. #endif
  210062. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210063. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210064. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210065. // compiled on its own).
  210066. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210067. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210068. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210069. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210070. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210071. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210072. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210073. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210074. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210075. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210076. #define WGL_ACCELERATION_ARB 0x2003
  210077. #define WGL_SWAP_METHOD_ARB 0x2007
  210078. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210079. #define WGL_PIXEL_TYPE_ARB 0x2013
  210080. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210081. #define WGL_COLOR_BITS_ARB 0x2014
  210082. #define WGL_RED_BITS_ARB 0x2015
  210083. #define WGL_GREEN_BITS_ARB 0x2017
  210084. #define WGL_BLUE_BITS_ARB 0x2019
  210085. #define WGL_ALPHA_BITS_ARB 0x201B
  210086. #define WGL_DEPTH_BITS_ARB 0x2022
  210087. #define WGL_STENCIL_BITS_ARB 0x2023
  210088. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210089. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210090. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210091. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210092. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210093. #define WGL_STEREO_ARB 0x2012
  210094. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210095. #define WGL_SAMPLES_ARB 0x2042
  210096. #define WGL_TYPE_RGBA_ARB 0x202B
  210097. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210098. {
  210099. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210100. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210101. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210102. else
  210103. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210104. }
  210105. class WindowedGLContext : public OpenGLContext
  210106. {
  210107. public:
  210108. WindowedGLContext (Component* const component_,
  210109. HGLRC contextToShareWith,
  210110. const OpenGLPixelFormat& pixelFormat)
  210111. : renderContext (0),
  210112. dc (0),
  210113. component (component_)
  210114. {
  210115. jassert (component != 0);
  210116. createNativeWindow();
  210117. // Use a default pixel format that should be supported everywhere
  210118. PIXELFORMATDESCRIPTOR pfd;
  210119. zerostruct (pfd);
  210120. pfd.nSize = sizeof (pfd);
  210121. pfd.nVersion = 1;
  210122. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210123. pfd.iPixelType = PFD_TYPE_RGBA;
  210124. pfd.cColorBits = 24;
  210125. pfd.cDepthBits = 16;
  210126. const int format = ChoosePixelFormat (dc, &pfd);
  210127. if (format != 0)
  210128. SetPixelFormat (dc, format, &pfd);
  210129. renderContext = wglCreateContext (dc);
  210130. makeActive();
  210131. setPixelFormat (pixelFormat);
  210132. if (contextToShareWith != 0 && renderContext != 0)
  210133. wglShareLists (contextToShareWith, renderContext);
  210134. }
  210135. ~WindowedGLContext()
  210136. {
  210137. deleteContext();
  210138. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210139. nativeWindow = 0;
  210140. }
  210141. void deleteContext()
  210142. {
  210143. makeInactive();
  210144. if (renderContext != 0)
  210145. {
  210146. wglDeleteContext (renderContext);
  210147. renderContext = 0;
  210148. }
  210149. }
  210150. bool makeActive() const throw()
  210151. {
  210152. jassert (renderContext != 0);
  210153. return wglMakeCurrent (dc, renderContext) != 0;
  210154. }
  210155. bool makeInactive() const throw()
  210156. {
  210157. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210158. }
  210159. bool isActive() const throw()
  210160. {
  210161. return wglGetCurrentContext() == renderContext;
  210162. }
  210163. const OpenGLPixelFormat getPixelFormat() const
  210164. {
  210165. OpenGLPixelFormat pf;
  210166. makeActive();
  210167. StringArray availableExtensions;
  210168. getWglExtensions (dc, availableExtensions);
  210169. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210170. return pf;
  210171. }
  210172. void* getRawContext() const throw()
  210173. {
  210174. return renderContext;
  210175. }
  210176. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210177. {
  210178. makeActive();
  210179. PIXELFORMATDESCRIPTOR pfd;
  210180. zerostruct (pfd);
  210181. pfd.nSize = sizeof (pfd);
  210182. pfd.nVersion = 1;
  210183. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210184. pfd.iPixelType = PFD_TYPE_RGBA;
  210185. pfd.iLayerType = PFD_MAIN_PLANE;
  210186. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210187. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210188. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210189. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210190. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210191. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210192. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210193. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210194. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210195. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210196. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210197. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210198. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210199. int format = 0;
  210200. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210201. StringArray availableExtensions;
  210202. getWglExtensions (dc, availableExtensions);
  210203. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210204. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210205. {
  210206. int attributes[64];
  210207. int n = 0;
  210208. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210209. attributes[n++] = GL_TRUE;
  210210. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210211. attributes[n++] = GL_TRUE;
  210212. attributes[n++] = WGL_ACCELERATION_ARB;
  210213. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210214. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210215. attributes[n++] = GL_TRUE;
  210216. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210217. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210218. attributes[n++] = WGL_COLOR_BITS_ARB;
  210219. attributes[n++] = pfd.cColorBits;
  210220. attributes[n++] = WGL_RED_BITS_ARB;
  210221. attributes[n++] = pixelFormat.redBits;
  210222. attributes[n++] = WGL_GREEN_BITS_ARB;
  210223. attributes[n++] = pixelFormat.greenBits;
  210224. attributes[n++] = WGL_BLUE_BITS_ARB;
  210225. attributes[n++] = pixelFormat.blueBits;
  210226. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210227. attributes[n++] = pixelFormat.alphaBits;
  210228. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210229. attributes[n++] = pixelFormat.depthBufferBits;
  210230. if (pixelFormat.stencilBufferBits > 0)
  210231. {
  210232. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210233. attributes[n++] = pixelFormat.stencilBufferBits;
  210234. }
  210235. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210236. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210237. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210238. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210239. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210240. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210241. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210242. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210243. if (availableExtensions.contains ("WGL_ARB_multisample")
  210244. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210245. {
  210246. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210247. attributes[n++] = 1;
  210248. attributes[n++] = WGL_SAMPLES_ARB;
  210249. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210250. }
  210251. attributes[n++] = 0;
  210252. UINT formatsCount;
  210253. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210254. (void) ok;
  210255. jassert (ok);
  210256. }
  210257. else
  210258. {
  210259. format = ChoosePixelFormat (dc, &pfd);
  210260. }
  210261. if (format != 0)
  210262. {
  210263. makeInactive();
  210264. // win32 can't change the pixel format of a window, so need to delete the
  210265. // old one and create a new one..
  210266. jassert (nativeWindow != 0);
  210267. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210268. nativeWindow = 0;
  210269. createNativeWindow();
  210270. if (SetPixelFormat (dc, format, &pfd))
  210271. {
  210272. wglDeleteContext (renderContext);
  210273. renderContext = wglCreateContext (dc);
  210274. jassert (renderContext != 0);
  210275. return renderContext != 0;
  210276. }
  210277. }
  210278. return false;
  210279. }
  210280. void updateWindowPosition (int x, int y, int w, int h, int)
  210281. {
  210282. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210283. x, y, w, h,
  210284. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210285. }
  210286. void repaint()
  210287. {
  210288. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210289. }
  210290. void swapBuffers()
  210291. {
  210292. SwapBuffers (dc);
  210293. }
  210294. bool setSwapInterval (int numFramesPerSwap)
  210295. {
  210296. makeActive();
  210297. StringArray availableExtensions;
  210298. getWglExtensions (dc, availableExtensions);
  210299. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210300. return availableExtensions.contains ("WGL_EXT_swap_control")
  210301. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210302. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210303. }
  210304. int getSwapInterval() const
  210305. {
  210306. makeActive();
  210307. StringArray availableExtensions;
  210308. getWglExtensions (dc, availableExtensions);
  210309. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210310. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210311. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210312. return wglGetSwapIntervalEXT();
  210313. return 0;
  210314. }
  210315. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210316. {
  210317. jassert (isActive());
  210318. StringArray availableExtensions;
  210319. getWglExtensions (dc, availableExtensions);
  210320. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210321. int numTypes = 0;
  210322. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210323. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210324. {
  210325. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210326. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210327. jassertfalse;
  210328. }
  210329. else
  210330. {
  210331. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210332. }
  210333. OpenGLPixelFormat pf;
  210334. for (int i = 0; i < numTypes; ++i)
  210335. {
  210336. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210337. {
  210338. bool alreadyListed = false;
  210339. for (int j = results.size(); --j >= 0;)
  210340. if (pf == *results.getUnchecked(j))
  210341. alreadyListed = true;
  210342. if (! alreadyListed)
  210343. results.add (new OpenGLPixelFormat (pf));
  210344. }
  210345. }
  210346. }
  210347. void* getNativeWindowHandle() const
  210348. {
  210349. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210350. }
  210351. juce_UseDebuggingNewOperator
  210352. HGLRC renderContext;
  210353. private:
  210354. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210355. Component* const component;
  210356. HDC dc;
  210357. void createNativeWindow()
  210358. {
  210359. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210360. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210361. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210362. nativeWindow->dontRepaint = true;
  210363. nativeWindow->setVisible (true);
  210364. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210365. }
  210366. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210367. OpenGLPixelFormat& result,
  210368. const StringArray& availableExtensions) const throw()
  210369. {
  210370. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210371. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210372. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210373. {
  210374. int attributes[32];
  210375. int numAttributes = 0;
  210376. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210377. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210378. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210379. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210380. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210381. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210382. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210383. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210384. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210385. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210386. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210387. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210388. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210389. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210390. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210391. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210392. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210393. int values[32];
  210394. zeromem (values, sizeof (values));
  210395. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210396. {
  210397. int n = 0;
  210398. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210399. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210400. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210401. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210402. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210403. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210404. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210405. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210406. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210407. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210408. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210409. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210410. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210411. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210412. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210413. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210414. return isValidFormat;
  210415. }
  210416. else
  210417. {
  210418. jassertfalse;
  210419. }
  210420. }
  210421. else
  210422. {
  210423. PIXELFORMATDESCRIPTOR pfd;
  210424. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210425. {
  210426. result.redBits = pfd.cRedBits;
  210427. result.greenBits = pfd.cGreenBits;
  210428. result.blueBits = pfd.cBlueBits;
  210429. result.alphaBits = pfd.cAlphaBits;
  210430. result.depthBufferBits = pfd.cDepthBits;
  210431. result.stencilBufferBits = pfd.cStencilBits;
  210432. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210433. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210434. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210435. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210436. result.fullSceneAntiAliasingNumSamples = 0;
  210437. return true;
  210438. }
  210439. else
  210440. {
  210441. jassertfalse;
  210442. }
  210443. }
  210444. return false;
  210445. }
  210446. WindowedGLContext (const WindowedGLContext&);
  210447. WindowedGLContext& operator= (const WindowedGLContext&);
  210448. };
  210449. OpenGLContext* OpenGLComponent::createContext()
  210450. {
  210451. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210452. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210453. preferredPixelFormat));
  210454. return (c->renderContext != 0) ? c.release() : 0;
  210455. }
  210456. void* OpenGLComponent::getNativeWindowHandle() const
  210457. {
  210458. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210459. }
  210460. void juce_glViewport (const int w, const int h)
  210461. {
  210462. glViewport (0, 0, w, h);
  210463. }
  210464. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210465. OwnedArray <OpenGLPixelFormat>& results)
  210466. {
  210467. Component tempComp;
  210468. {
  210469. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210470. wc.makeActive();
  210471. wc.findAlternativeOpenGLPixelFormats (results);
  210472. }
  210473. }
  210474. #endif
  210475. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210476. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210477. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210478. // compiled on its own).
  210479. #if JUCE_INCLUDED_FILE
  210480. #if JUCE_USE_CDREADER
  210481. namespace CDReaderHelpers
  210482. {
  210483. //***************************************************************************
  210484. // %%% TARGET STATUS VALUES %%%
  210485. //***************************************************************************
  210486. #define STATUS_GOOD 0x00 // Status Good
  210487. #define STATUS_CHKCOND 0x02 // Check Condition
  210488. #define STATUS_CONDMET 0x04 // Condition Met
  210489. #define STATUS_BUSY 0x08 // Busy
  210490. #define STATUS_INTERM 0x10 // Intermediate
  210491. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210492. #define STATUS_RESCONF 0x18 // Reservation conflict
  210493. #define STATUS_COMTERM 0x22 // Command Terminated
  210494. #define STATUS_QFULL 0x28 // Queue full
  210495. //***************************************************************************
  210496. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210497. //***************************************************************************
  210498. #define MAXLUN 7 // Maximum Logical Unit Id
  210499. #define MAXTARG 7 // Maximum Target Id
  210500. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210501. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210502. //***************************************************************************
  210503. // %%% Commands for all Device Types %%%
  210504. //***************************************************************************
  210505. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210506. #define SCSI_COMPARE 0x39 // Compare (O)
  210507. #define SCSI_COPY 0x18 // Copy (O)
  210508. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210509. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210510. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210511. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210512. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210513. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210514. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210515. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210516. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210517. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210518. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210519. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210520. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210521. //***************************************************************************
  210522. // %%% Commands Unique to Direct Access Devices %%%
  210523. //***************************************************************************
  210524. #define SCSI_COMPARE 0x39 // Compare (O)
  210525. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210526. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210527. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210528. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210529. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210530. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210531. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210532. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210533. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210534. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210535. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210536. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210537. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210538. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210539. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210540. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210541. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210542. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210543. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210544. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210545. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210546. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210547. #define SCSI_VERIFY 0x2F // Verify (O)
  210548. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210549. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210550. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210551. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210552. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210553. //***************************************************************************
  210554. // %%% Commands Unique to Sequential Access Devices %%%
  210555. //***************************************************************************
  210556. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210557. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210558. #define SCSI_LOCATE 0x2B // Locate (O)
  210559. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210560. #define SCSI_READ_POS 0x34 // Read Position (O)
  210561. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210562. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210563. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210564. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210565. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210566. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210567. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210568. //***************************************************************************
  210569. // %%% Commands Unique to Printer Devices %%%
  210570. //***************************************************************************
  210571. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210572. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210573. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210574. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210575. //***************************************************************************
  210576. // %%% Commands Unique to Processor Devices %%%
  210577. //***************************************************************************
  210578. #define SCSI_RECEIVE 0x08 // Receive (O)
  210579. #define SCSI_SEND 0x0A // Send (O)
  210580. //***************************************************************************
  210581. // %%% Commands Unique to Write-Once Devices %%%
  210582. //***************************************************************************
  210583. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210584. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210585. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210586. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210587. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210588. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210589. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210590. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210591. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210592. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210593. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210594. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210595. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210596. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210597. //***************************************************************************
  210598. // %%% Commands Unique to CD-ROM Devices %%%
  210599. //***************************************************************************
  210600. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210601. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210602. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210603. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210604. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210605. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210606. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210607. #define SCSI_READHEADER 0x44 // Read Header (O)
  210608. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210609. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210610. //***************************************************************************
  210611. // %%% Commands Unique to Scanner Devices %%%
  210612. //***************************************************************************
  210613. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210614. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210615. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210616. #define SCSI_SCAN 0x1B // Scan (O)
  210617. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210618. //***************************************************************************
  210619. // %%% Commands Unique to Optical Memory Devices %%%
  210620. //***************************************************************************
  210621. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210622. //***************************************************************************
  210623. // %%% Commands Unique to Medium Changer Devices %%%
  210624. //***************************************************************************
  210625. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210626. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210627. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210628. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210629. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210630. //***************************************************************************
  210631. // %%% Commands Unique to Communication Devices %%%
  210632. //***************************************************************************
  210633. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210634. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210635. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210636. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210637. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210638. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210639. //***************************************************************************
  210640. // %%% Request Sense Data Format %%%
  210641. //***************************************************************************
  210642. typedef struct {
  210643. BYTE ErrorCode; // Error Code (70H or 71H)
  210644. BYTE SegmentNum; // Number of current segment descriptor
  210645. BYTE SenseKey; // Sense Key(See bit definitions too)
  210646. BYTE InfoByte0; // Information MSB
  210647. BYTE InfoByte1; // Information MID
  210648. BYTE InfoByte2; // Information MID
  210649. BYTE InfoByte3; // Information LSB
  210650. BYTE AddSenLen; // Additional Sense Length
  210651. BYTE ComSpecInf0; // Command Specific Information MSB
  210652. BYTE ComSpecInf1; // Command Specific Information MID
  210653. BYTE ComSpecInf2; // Command Specific Information MID
  210654. BYTE ComSpecInf3; // Command Specific Information LSB
  210655. BYTE AddSenseCode; // Additional Sense Code
  210656. BYTE AddSenQual; // Additional Sense Code Qualifier
  210657. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210658. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210659. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210660. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210661. BYTE AddSenseBytes; // Additional Sense Bytes
  210662. } SENSE_DATA_FMT;
  210663. //***************************************************************************
  210664. // %%% REQUEST SENSE ERROR CODE %%%
  210665. //***************************************************************************
  210666. #define SERROR_CURRENT 0x70 // Current Errors
  210667. #define SERROR_DEFERED 0x71 // Deferred Errors
  210668. //***************************************************************************
  210669. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210670. //***************************************************************************
  210671. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210672. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210673. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210674. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210675. //***************************************************************************
  210676. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210677. //***************************************************************************
  210678. #define KEY_NOSENSE 0x00 // No Sense
  210679. #define KEY_RECERROR 0x01 // Recovered Error
  210680. #define KEY_NOTREADY 0x02 // Not Ready
  210681. #define KEY_MEDIUMERR 0x03 // Medium Error
  210682. #define KEY_HARDERROR 0x04 // Hardware Error
  210683. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210684. #define KEY_UNITATT 0x06 // Unit Attention
  210685. #define KEY_DATAPROT 0x07 // Data Protect
  210686. #define KEY_BLANKCHK 0x08 // Blank Check
  210687. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210688. #define KEY_COPYABORT 0x0A // Copy Abort
  210689. #define KEY_EQUAL 0x0C // Equal (Search)
  210690. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210691. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210692. #define KEY_RESERVED 0x0F // Reserved
  210693. //***************************************************************************
  210694. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210695. //***************************************************************************
  210696. #define DTYPE_DASD 0x00 // Disk Device
  210697. #define DTYPE_SEQD 0x01 // Tape Device
  210698. #define DTYPE_PRNT 0x02 // Printer
  210699. #define DTYPE_PROC 0x03 // Processor
  210700. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210701. #define DTYPE_CROM 0x05 // CD-ROM device
  210702. #define DTYPE_SCAN 0x06 // Scanner device
  210703. #define DTYPE_OPTI 0x07 // Optical memory device
  210704. #define DTYPE_JUKE 0x08 // Medium Changer device
  210705. #define DTYPE_COMM 0x09 // Communications device
  210706. #define DTYPE_RESL 0x0A // Reserved (low)
  210707. #define DTYPE_RESH 0x1E // Reserved (high)
  210708. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210709. //***************************************************************************
  210710. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210711. //***************************************************************************
  210712. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210713. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210714. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210715. #define ANSI_RESLO 0x3 // Reserved (low)
  210716. #define ANSI_RESHI 0x7 // Reserved (high)
  210717. typedef struct
  210718. {
  210719. USHORT Length;
  210720. UCHAR ScsiStatus;
  210721. UCHAR PathId;
  210722. UCHAR TargetId;
  210723. UCHAR Lun;
  210724. UCHAR CdbLength;
  210725. UCHAR SenseInfoLength;
  210726. UCHAR DataIn;
  210727. ULONG DataTransferLength;
  210728. ULONG TimeOutValue;
  210729. ULONG DataBufferOffset;
  210730. ULONG SenseInfoOffset;
  210731. UCHAR Cdb[16];
  210732. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210733. typedef struct
  210734. {
  210735. USHORT Length;
  210736. UCHAR ScsiStatus;
  210737. UCHAR PathId;
  210738. UCHAR TargetId;
  210739. UCHAR Lun;
  210740. UCHAR CdbLength;
  210741. UCHAR SenseInfoLength;
  210742. UCHAR DataIn;
  210743. ULONG DataTransferLength;
  210744. ULONG TimeOutValue;
  210745. PVOID DataBuffer;
  210746. ULONG SenseInfoOffset;
  210747. UCHAR Cdb[16];
  210748. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210749. typedef struct
  210750. {
  210751. SCSI_PASS_THROUGH_DIRECT spt;
  210752. ULONG Filler;
  210753. UCHAR ucSenseBuf[32];
  210754. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210755. typedef struct
  210756. {
  210757. ULONG Length;
  210758. UCHAR PortNumber;
  210759. UCHAR PathId;
  210760. UCHAR TargetId;
  210761. UCHAR Lun;
  210762. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210763. #define METHOD_BUFFERED 0
  210764. #define METHOD_IN_DIRECT 1
  210765. #define METHOD_OUT_DIRECT 2
  210766. #define METHOD_NEITHER 3
  210767. #define FILE_ANY_ACCESS 0
  210768. #ifndef FILE_READ_ACCESS
  210769. #define FILE_READ_ACCESS (0x0001)
  210770. #endif
  210771. #ifndef FILE_WRITE_ACCESS
  210772. #define FILE_WRITE_ACCESS (0x0002)
  210773. #endif
  210774. #define IOCTL_SCSI_BASE 0x00000004
  210775. #define SCSI_IOCTL_DATA_OUT 0
  210776. #define SCSI_IOCTL_DATA_IN 1
  210777. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210778. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210779. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210780. )
  210781. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210782. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210783. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210784. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210785. #define SENSE_LEN 14
  210786. #define SRB_DIR_SCSI 0x00
  210787. #define SRB_POSTING 0x01
  210788. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210789. #define SRB_DIR_IN 0x08
  210790. #define SRB_DIR_OUT 0x10
  210791. #define SRB_EVENT_NOTIFY 0x40
  210792. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210793. #define MAX_SRB_TIMEOUT 1080001u
  210794. #define DEFAULT_SRB_TIMEOUT 1080001u
  210795. #define SC_HA_INQUIRY 0x00
  210796. #define SC_GET_DEV_TYPE 0x01
  210797. #define SC_EXEC_SCSI_CMD 0x02
  210798. #define SC_ABORT_SRB 0x03
  210799. #define SC_RESET_DEV 0x04
  210800. #define SC_SET_HA_PARMS 0x05
  210801. #define SC_GET_DISK_INFO 0x06
  210802. #define SC_RESCAN_SCSI_BUS 0x07
  210803. #define SC_GETSET_TIMEOUTS 0x08
  210804. #define SS_PENDING 0x00
  210805. #define SS_COMP 0x01
  210806. #define SS_ABORTED 0x02
  210807. #define SS_ABORT_FAIL 0x03
  210808. #define SS_ERR 0x04
  210809. #define SS_INVALID_CMD 0x80
  210810. #define SS_INVALID_HA 0x81
  210811. #define SS_NO_DEVICE 0x82
  210812. #define SS_INVALID_SRB 0xE0
  210813. #define SS_OLD_MANAGER 0xE1
  210814. #define SS_BUFFER_ALIGN 0xE1
  210815. #define SS_ILLEGAL_MODE 0xE2
  210816. #define SS_NO_ASPI 0xE3
  210817. #define SS_FAILED_INIT 0xE4
  210818. #define SS_ASPI_IS_BUSY 0xE5
  210819. #define SS_BUFFER_TO_BIG 0xE6
  210820. #define SS_BUFFER_TOO_BIG 0xE6
  210821. #define SS_MISMATCHED_COMPONENTS 0xE7
  210822. #define SS_NO_ADAPTERS 0xE8
  210823. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210824. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210825. #define SS_BAD_INSTALL 0xEB
  210826. #define HASTAT_OK 0x00
  210827. #define HASTAT_SEL_TO 0x11
  210828. #define HASTAT_DO_DU 0x12
  210829. #define HASTAT_BUS_FREE 0x13
  210830. #define HASTAT_PHASE_ERR 0x14
  210831. #define HASTAT_TIMEOUT 0x09
  210832. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210833. #define HASTAT_MESSAGE_REJECT 0x0D
  210834. #define HASTAT_BUS_RESET 0x0E
  210835. #define HASTAT_PARITY_ERROR 0x0F
  210836. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210837. #define PACKED
  210838. #pragma pack(1)
  210839. typedef struct
  210840. {
  210841. BYTE SRB_Cmd;
  210842. BYTE SRB_Status;
  210843. BYTE SRB_HaID;
  210844. BYTE SRB_Flags;
  210845. DWORD SRB_Hdr_Rsvd;
  210846. BYTE HA_Count;
  210847. BYTE HA_SCSI_ID;
  210848. BYTE HA_ManagerId[16];
  210849. BYTE HA_Identifier[16];
  210850. BYTE HA_Unique[16];
  210851. WORD HA_Rsvd1;
  210852. BYTE pad[20];
  210853. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210854. typedef struct
  210855. {
  210856. BYTE SRB_Cmd;
  210857. BYTE SRB_Status;
  210858. BYTE SRB_HaID;
  210859. BYTE SRB_Flags;
  210860. DWORD SRB_Hdr_Rsvd;
  210861. BYTE SRB_Target;
  210862. BYTE SRB_Lun;
  210863. BYTE SRB_DeviceType;
  210864. BYTE SRB_Rsvd1;
  210865. BYTE pad[68];
  210866. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  210867. typedef struct
  210868. {
  210869. BYTE SRB_Cmd;
  210870. BYTE SRB_Status;
  210871. BYTE SRB_HaID;
  210872. BYTE SRB_Flags;
  210873. DWORD SRB_Hdr_Rsvd;
  210874. BYTE SRB_Target;
  210875. BYTE SRB_Lun;
  210876. WORD SRB_Rsvd1;
  210877. DWORD SRB_BufLen;
  210878. BYTE FAR *SRB_BufPointer;
  210879. BYTE SRB_SenseLen;
  210880. BYTE SRB_CDBLen;
  210881. BYTE SRB_HaStat;
  210882. BYTE SRB_TargStat;
  210883. VOID FAR *SRB_PostProc;
  210884. BYTE SRB_Rsvd2[20];
  210885. BYTE CDBByte[16];
  210886. BYTE SenseArea[SENSE_LEN+2];
  210887. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  210888. typedef struct
  210889. {
  210890. BYTE SRB_Cmd;
  210891. BYTE SRB_Status;
  210892. BYTE SRB_HaId;
  210893. BYTE SRB_Flags;
  210894. DWORD SRB_Hdr_Rsvd;
  210895. } PACKED SRB, *PSRB, FAR *LPSRB;
  210896. #pragma pack()
  210897. struct CDDeviceInfo
  210898. {
  210899. char vendor[9];
  210900. char productId[17];
  210901. char rev[5];
  210902. char vendorSpec[21];
  210903. BYTE ha;
  210904. BYTE tgt;
  210905. BYTE lun;
  210906. char scsiDriveLetter; // will be 0 if not using scsi
  210907. };
  210908. class CDReadBuffer
  210909. {
  210910. public:
  210911. int startFrame;
  210912. int numFrames;
  210913. int dataStartOffset;
  210914. int dataLength;
  210915. int bufferSize;
  210916. HeapBlock<BYTE> buffer;
  210917. int index;
  210918. bool wantsIndex;
  210919. CDReadBuffer (const int numberOfFrames)
  210920. : startFrame (0),
  210921. numFrames (0),
  210922. dataStartOffset (0),
  210923. dataLength (0),
  210924. bufferSize (2352 * numberOfFrames),
  210925. buffer (bufferSize),
  210926. index (0),
  210927. wantsIndex (false)
  210928. {
  210929. }
  210930. bool isZero() const throw()
  210931. {
  210932. BYTE* p = buffer + dataStartOffset;
  210933. for (int i = dataLength; --i >= 0;)
  210934. if (*p++ != 0)
  210935. return false;
  210936. return true;
  210937. }
  210938. };
  210939. class CDDeviceHandle;
  210940. class CDController
  210941. {
  210942. public:
  210943. CDController();
  210944. virtual ~CDController();
  210945. virtual bool read (CDReadBuffer* t) = 0;
  210946. virtual void shutDown();
  210947. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  210948. int getLastIndex();
  210949. public:
  210950. bool initialised;
  210951. CDDeviceHandle* deviceInfo;
  210952. int framesToCheck, framesOverlap;
  210953. void prepare (SRB_ExecSCSICmd& s);
  210954. void perform (SRB_ExecSCSICmd& s);
  210955. void setPaused (bool paused);
  210956. };
  210957. #pragma pack(1)
  210958. struct TOCTRACK
  210959. {
  210960. BYTE rsvd;
  210961. BYTE ADR;
  210962. BYTE trackNumber;
  210963. BYTE rsvd2;
  210964. BYTE addr[4];
  210965. };
  210966. struct TOC
  210967. {
  210968. WORD tocLen;
  210969. BYTE firstTrack;
  210970. BYTE lastTrack;
  210971. TOCTRACK tracks[100];
  210972. };
  210973. #pragma pack()
  210974. enum
  210975. {
  210976. READTYPE_ANY = 0,
  210977. READTYPE_ATAPI1 = 1,
  210978. READTYPE_ATAPI2 = 2,
  210979. READTYPE_READ6 = 3,
  210980. READTYPE_READ10 = 4,
  210981. READTYPE_READ_D8 = 5,
  210982. READTYPE_READ_D4 = 6,
  210983. READTYPE_READ_D4_1 = 7,
  210984. READTYPE_READ10_2 = 8
  210985. };
  210986. class CDDeviceHandle
  210987. {
  210988. public:
  210989. CDDeviceHandle (const CDDeviceInfo* const device)
  210990. : scsiHandle (0),
  210991. readType (READTYPE_ANY),
  210992. controller (0)
  210993. {
  210994. memcpy (&info, device, sizeof (info));
  210995. }
  210996. ~CDDeviceHandle()
  210997. {
  210998. if (controller != 0)
  210999. {
  211000. controller->shutDown();
  211001. controller = 0;
  211002. }
  211003. if (scsiHandle != 0)
  211004. CloseHandle (scsiHandle);
  211005. }
  211006. bool readTOC (TOC* lpToc);
  211007. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  211008. void openDrawer (bool shouldBeOpen);
  211009. CDDeviceInfo info;
  211010. HANDLE scsiHandle;
  211011. BYTE readType;
  211012. private:
  211013. ScopedPointer<CDController> controller;
  211014. bool testController (const int readType,
  211015. CDController* const newController,
  211016. CDReadBuffer* const bufferToUse);
  211017. };
  211018. DWORD (*fGetASPI32SupportInfo)(void);
  211019. DWORD (*fSendASPI32Command)(LPSRB);
  211020. static HINSTANCE winAspiLib = 0;
  211021. static bool usingScsi = false;
  211022. static bool initialised = false;
  211023. bool InitialiseCDRipper()
  211024. {
  211025. if (! initialised)
  211026. {
  211027. initialised = true;
  211028. OSVERSIONINFO info;
  211029. info.dwOSVersionInfoSize = sizeof (info);
  211030. GetVersionEx (&info);
  211031. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  211032. if (! usingScsi)
  211033. {
  211034. fGetASPI32SupportInfo = 0;
  211035. fSendASPI32Command = 0;
  211036. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  211037. if (winAspiLib != 0)
  211038. {
  211039. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  211040. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  211041. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  211042. return false;
  211043. }
  211044. else
  211045. {
  211046. usingScsi = true;
  211047. }
  211048. }
  211049. }
  211050. return true;
  211051. }
  211052. void DeinitialiseCDRipper()
  211053. {
  211054. if (winAspiLib != 0)
  211055. {
  211056. fGetASPI32SupportInfo = 0;
  211057. fSendASPI32Command = 0;
  211058. FreeLibrary (winAspiLib);
  211059. winAspiLib = 0;
  211060. }
  211061. initialised = false;
  211062. }
  211063. HANDLE CreateSCSIDeviceHandle (char driveLetter)
  211064. {
  211065. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  211066. OSVERSIONINFO info;
  211067. info.dwOSVersionInfoSize = sizeof (info);
  211068. GetVersionEx (&info);
  211069. DWORD flags = GENERIC_READ;
  211070. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  211071. flags = GENERIC_READ | GENERIC_WRITE;
  211072. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211073. if (h == INVALID_HANDLE_VALUE)
  211074. {
  211075. flags ^= GENERIC_WRITE;
  211076. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211077. }
  211078. return h;
  211079. }
  211080. DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb, const char driveLetter,
  211081. HANDLE& deviceHandle, const bool retryOnFailure = true)
  211082. {
  211083. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  211084. zerostruct (s);
  211085. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  211086. s.spt.CdbLength = srb->SRB_CDBLen;
  211087. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  211088. ? SCSI_IOCTL_DATA_IN
  211089. : ((srb->SRB_Flags & SRB_DIR_OUT)
  211090. ? SCSI_IOCTL_DATA_OUT
  211091. : SCSI_IOCTL_DATA_UNSPECIFIED));
  211092. s.spt.DataTransferLength = srb->SRB_BufLen;
  211093. s.spt.TimeOutValue = 5;
  211094. s.spt.DataBuffer = srb->SRB_BufPointer;
  211095. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211096. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  211097. srb->SRB_Status = SS_ERR;
  211098. srb->SRB_TargStat = 0x0004;
  211099. DWORD bytesReturned = 0;
  211100. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211101. &s, sizeof (s),
  211102. &s, sizeof (s),
  211103. &bytesReturned, 0) != 0)
  211104. {
  211105. srb->SRB_Status = SS_COMP;
  211106. }
  211107. else if (retryOnFailure)
  211108. {
  211109. const DWORD error = GetLastError();
  211110. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  211111. {
  211112. if (error != ERROR_INVALID_HANDLE)
  211113. CloseHandle (deviceHandle);
  211114. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  211115. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  211116. }
  211117. }
  211118. return srb->SRB_Status;
  211119. }
  211120. // Controller types..
  211121. class ControllerType1 : public CDController
  211122. {
  211123. public:
  211124. ControllerType1() {}
  211125. ~ControllerType1() {}
  211126. bool read (CDReadBuffer* rb)
  211127. {
  211128. if (rb->numFrames * 2352 > rb->bufferSize)
  211129. return false;
  211130. SRB_ExecSCSICmd s;
  211131. prepare (s);
  211132. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211133. s.SRB_BufLen = rb->bufferSize;
  211134. s.SRB_BufPointer = rb->buffer;
  211135. s.SRB_CDBLen = 12;
  211136. s.CDBByte[0] = 0xBE;
  211137. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211138. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211139. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211140. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211141. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  211142. perform (s);
  211143. if (s.SRB_Status != SS_COMP)
  211144. return false;
  211145. rb->dataLength = rb->numFrames * 2352;
  211146. rb->dataStartOffset = 0;
  211147. return true;
  211148. }
  211149. };
  211150. class ControllerType2 : public CDController
  211151. {
  211152. public:
  211153. ControllerType2() {}
  211154. ~ControllerType2() {}
  211155. void shutDown()
  211156. {
  211157. if (initialised)
  211158. {
  211159. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211160. SRB_ExecSCSICmd s;
  211161. prepare (s);
  211162. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211163. s.SRB_BufLen = 0x0C;
  211164. s.SRB_BufPointer = bufPointer;
  211165. s.SRB_CDBLen = 6;
  211166. s.CDBByte[0] = 0x15;
  211167. s.CDBByte[4] = 0x0C;
  211168. perform (s);
  211169. }
  211170. }
  211171. bool init()
  211172. {
  211173. SRB_ExecSCSICmd s;
  211174. s.SRB_Status = SS_ERR;
  211175. if (deviceInfo->readType == READTYPE_READ10_2)
  211176. {
  211177. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211178. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211179. for (int i = 0; i < 2; ++i)
  211180. {
  211181. prepare (s);
  211182. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211183. s.SRB_BufLen = 0x14;
  211184. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211185. s.SRB_CDBLen = 6;
  211186. s.CDBByte[0] = 0x15;
  211187. s.CDBByte[1] = 0x10;
  211188. s.CDBByte[4] = 0x14;
  211189. perform (s);
  211190. if (s.SRB_Status != SS_COMP)
  211191. return false;
  211192. }
  211193. }
  211194. else
  211195. {
  211196. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211197. prepare (s);
  211198. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211199. s.SRB_BufLen = 0x0C;
  211200. s.SRB_BufPointer = bufPointer;
  211201. s.SRB_CDBLen = 6;
  211202. s.CDBByte[0] = 0x15;
  211203. s.CDBByte[4] = 0x0C;
  211204. perform (s);
  211205. }
  211206. return s.SRB_Status == SS_COMP;
  211207. }
  211208. bool read (CDReadBuffer* rb)
  211209. {
  211210. if (rb->numFrames * 2352 > rb->bufferSize)
  211211. return false;
  211212. if (!initialised)
  211213. {
  211214. initialised = init();
  211215. if (!initialised)
  211216. return false;
  211217. }
  211218. SRB_ExecSCSICmd s;
  211219. prepare (s);
  211220. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211221. s.SRB_BufLen = rb->bufferSize;
  211222. s.SRB_BufPointer = rb->buffer;
  211223. s.SRB_CDBLen = 10;
  211224. s.CDBByte[0] = 0x28;
  211225. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211226. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211227. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211228. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211229. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211230. perform (s);
  211231. if (s.SRB_Status != SS_COMP)
  211232. return false;
  211233. rb->dataLength = rb->numFrames * 2352;
  211234. rb->dataStartOffset = 0;
  211235. return true;
  211236. }
  211237. };
  211238. class ControllerType3 : public CDController
  211239. {
  211240. public:
  211241. ControllerType3() {}
  211242. ~ControllerType3() {}
  211243. bool read (CDReadBuffer* rb)
  211244. {
  211245. if (rb->numFrames * 2352 > rb->bufferSize)
  211246. return false;
  211247. if (!initialised)
  211248. {
  211249. setPaused (false);
  211250. initialised = true;
  211251. }
  211252. SRB_ExecSCSICmd s;
  211253. prepare (s);
  211254. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211255. s.SRB_BufLen = rb->numFrames * 2352;
  211256. s.SRB_BufPointer = rb->buffer;
  211257. s.SRB_CDBLen = 12;
  211258. s.CDBByte[0] = 0xD8;
  211259. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211260. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211261. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211262. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211263. perform (s);
  211264. if (s.SRB_Status != SS_COMP)
  211265. return false;
  211266. rb->dataLength = rb->numFrames * 2352;
  211267. rb->dataStartOffset = 0;
  211268. return true;
  211269. }
  211270. };
  211271. class ControllerType4 : public CDController
  211272. {
  211273. public:
  211274. ControllerType4() {}
  211275. ~ControllerType4() {}
  211276. bool selectD4Mode()
  211277. {
  211278. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211279. SRB_ExecSCSICmd s;
  211280. prepare (s);
  211281. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211282. s.SRB_CDBLen = 6;
  211283. s.SRB_BufLen = 12;
  211284. s.SRB_BufPointer = bufPointer;
  211285. s.CDBByte[0] = 0x15;
  211286. s.CDBByte[1] = 0x10;
  211287. s.CDBByte[4] = 0x08;
  211288. perform (s);
  211289. return s.SRB_Status == SS_COMP;
  211290. }
  211291. bool read (CDReadBuffer* rb)
  211292. {
  211293. if (rb->numFrames * 2352 > rb->bufferSize)
  211294. return false;
  211295. if (!initialised)
  211296. {
  211297. setPaused (true);
  211298. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211299. selectD4Mode();
  211300. initialised = true;
  211301. }
  211302. SRB_ExecSCSICmd s;
  211303. prepare (s);
  211304. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211305. s.SRB_BufLen = rb->bufferSize;
  211306. s.SRB_BufPointer = rb->buffer;
  211307. s.SRB_CDBLen = 10;
  211308. s.CDBByte[0] = 0xD4;
  211309. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211310. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211311. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211312. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211313. perform (s);
  211314. if (s.SRB_Status != SS_COMP)
  211315. return false;
  211316. rb->dataLength = rb->numFrames * 2352;
  211317. rb->dataStartOffset = 0;
  211318. return true;
  211319. }
  211320. };
  211321. CDController::CDController() : initialised (false)
  211322. {
  211323. }
  211324. CDController::~CDController()
  211325. {
  211326. }
  211327. void CDController::prepare (SRB_ExecSCSICmd& s)
  211328. {
  211329. zerostruct (s);
  211330. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211331. s.SRB_HaID = deviceInfo->info.ha;
  211332. s.SRB_Target = deviceInfo->info.tgt;
  211333. s.SRB_Lun = deviceInfo->info.lun;
  211334. s.SRB_SenseLen = SENSE_LEN;
  211335. }
  211336. void CDController::perform (SRB_ExecSCSICmd& s)
  211337. {
  211338. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211339. s.SRB_PostProc = event;
  211340. ResetEvent (event);
  211341. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211342. deviceInfo->info.scsiDriveLetter,
  211343. deviceInfo->scsiHandle)
  211344. : fSendASPI32Command ((LPSRB)&s);
  211345. if (status == SS_PENDING)
  211346. WaitForSingleObject (event, 4000);
  211347. CloseHandle (event);
  211348. }
  211349. void CDController::setPaused (bool paused)
  211350. {
  211351. SRB_ExecSCSICmd s;
  211352. prepare (s);
  211353. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211354. s.SRB_CDBLen = 10;
  211355. s.CDBByte[0] = 0x4B;
  211356. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211357. perform (s);
  211358. }
  211359. void CDController::shutDown()
  211360. {
  211361. }
  211362. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211363. {
  211364. if (overlapBuffer != 0)
  211365. {
  211366. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211367. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211368. if (doJitter
  211369. && overlapBuffer->startFrame > 0
  211370. && overlapBuffer->numFrames > 0
  211371. && overlapBuffer->dataLength > 0)
  211372. {
  211373. const int numFrames = rb->numFrames;
  211374. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211375. {
  211376. rb->startFrame -= framesOverlap;
  211377. if (framesToCheck < framesOverlap
  211378. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211379. rb->numFrames += framesOverlap;
  211380. }
  211381. else
  211382. {
  211383. overlapBuffer->dataLength = 0;
  211384. overlapBuffer->startFrame = 0;
  211385. overlapBuffer->numFrames = 0;
  211386. }
  211387. }
  211388. if (! read (rb))
  211389. return false;
  211390. if (doJitter)
  211391. {
  211392. const int checkLen = framesToCheck * 2352;
  211393. const int maxToCheck = rb->dataLength - checkLen;
  211394. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211395. return true;
  211396. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211397. bool found = false;
  211398. for (int i = 0; i < maxToCheck; ++i)
  211399. {
  211400. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211401. {
  211402. i += checkLen;
  211403. rb->dataStartOffset = i;
  211404. rb->dataLength -= i;
  211405. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211406. found = true;
  211407. break;
  211408. }
  211409. }
  211410. rb->numFrames = rb->dataLength / 2352;
  211411. rb->dataLength = 2352 * rb->numFrames;
  211412. if (!found)
  211413. return false;
  211414. }
  211415. if (canDoJitter)
  211416. {
  211417. memcpy (overlapBuffer->buffer,
  211418. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211419. 2352 * framesToCheck);
  211420. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211421. overlapBuffer->numFrames = framesToCheck;
  211422. overlapBuffer->dataLength = 2352 * framesToCheck;
  211423. overlapBuffer->dataStartOffset = 0;
  211424. }
  211425. else
  211426. {
  211427. overlapBuffer->startFrame = 0;
  211428. overlapBuffer->numFrames = 0;
  211429. overlapBuffer->dataLength = 0;
  211430. }
  211431. return true;
  211432. }
  211433. else
  211434. {
  211435. return read (rb);
  211436. }
  211437. }
  211438. int CDController::getLastIndex()
  211439. {
  211440. char qdata[100];
  211441. SRB_ExecSCSICmd s;
  211442. prepare (s);
  211443. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211444. s.SRB_BufLen = sizeof (qdata);
  211445. s.SRB_BufPointer = (BYTE*)qdata;
  211446. s.SRB_CDBLen = 12;
  211447. s.CDBByte[0] = 0x42;
  211448. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211449. s.CDBByte[2] = 64;
  211450. s.CDBByte[3] = 1; // get current position
  211451. s.CDBByte[7] = 0;
  211452. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211453. perform (s);
  211454. if (s.SRB_Status == SS_COMP)
  211455. return qdata[7];
  211456. return 0;
  211457. }
  211458. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211459. {
  211460. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211461. SRB_ExecSCSICmd s;
  211462. zerostruct (s);
  211463. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211464. s.SRB_HaID = info.ha;
  211465. s.SRB_Target = info.tgt;
  211466. s.SRB_Lun = info.lun;
  211467. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211468. s.SRB_BufLen = 0x324;
  211469. s.SRB_BufPointer = (BYTE*)lpToc;
  211470. s.SRB_SenseLen = 0x0E;
  211471. s.SRB_CDBLen = 0x0A;
  211472. s.SRB_PostProc = event;
  211473. s.CDBByte[0] = 0x43;
  211474. s.CDBByte[1] = 0x00;
  211475. s.CDBByte[7] = 0x03;
  211476. s.CDBByte[8] = 0x24;
  211477. ResetEvent (event);
  211478. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211479. : fSendASPI32Command ((LPSRB)&s);
  211480. if (status == SS_PENDING)
  211481. WaitForSingleObject (event, 4000);
  211482. CloseHandle (event);
  211483. return (s.SRB_Status == SS_COMP);
  211484. }
  211485. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211486. CDReadBuffer* const overlapBuffer)
  211487. {
  211488. if (controller == 0)
  211489. {
  211490. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211491. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211492. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211493. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211494. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211495. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211496. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211497. }
  211498. buffer->index = 0;
  211499. if ((controller != 0)
  211500. && controller->readAudio (buffer, overlapBuffer))
  211501. {
  211502. if (buffer->wantsIndex)
  211503. buffer->index = controller->getLastIndex();
  211504. return true;
  211505. }
  211506. return false;
  211507. }
  211508. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211509. {
  211510. if (shouldBeOpen)
  211511. {
  211512. if (controller != 0)
  211513. {
  211514. controller->shutDown();
  211515. controller = 0;
  211516. }
  211517. if (scsiHandle != 0)
  211518. {
  211519. CloseHandle (scsiHandle);
  211520. scsiHandle = 0;
  211521. }
  211522. }
  211523. SRB_ExecSCSICmd s;
  211524. zerostruct (s);
  211525. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211526. s.SRB_HaID = info.ha;
  211527. s.SRB_Target = info.tgt;
  211528. s.SRB_Lun = info.lun;
  211529. s.SRB_SenseLen = SENSE_LEN;
  211530. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211531. s.SRB_BufLen = 0;
  211532. s.SRB_BufPointer = 0;
  211533. s.SRB_CDBLen = 12;
  211534. s.CDBByte[0] = 0x1b;
  211535. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211536. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211537. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211538. s.SRB_PostProc = event;
  211539. ResetEvent (event);
  211540. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211541. : fSendASPI32Command ((LPSRB)&s);
  211542. if (status == SS_PENDING)
  211543. WaitForSingleObject (event, 4000);
  211544. CloseHandle (event);
  211545. }
  211546. bool CDDeviceHandle::testController (const int type,
  211547. CDController* const newController,
  211548. CDReadBuffer* const rb)
  211549. {
  211550. controller = newController;
  211551. readType = (BYTE)type;
  211552. controller->deviceInfo = this;
  211553. controller->framesToCheck = 1;
  211554. controller->framesOverlap = 3;
  211555. bool passed = false;
  211556. memset (rb->buffer, 0xcd, rb->bufferSize);
  211557. if (controller->read (rb))
  211558. {
  211559. passed = true;
  211560. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211561. int wrong = 0;
  211562. for (int i = rb->dataLength / 4; --i >= 0;)
  211563. {
  211564. if (*p++ == (int) 0xcdcdcdcd)
  211565. {
  211566. if (++wrong == 4)
  211567. {
  211568. passed = false;
  211569. break;
  211570. }
  211571. }
  211572. else
  211573. {
  211574. wrong = 0;
  211575. }
  211576. }
  211577. }
  211578. if (! passed)
  211579. {
  211580. controller->shutDown();
  211581. controller = 0;
  211582. }
  211583. return passed;
  211584. }
  211585. void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211586. {
  211587. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211588. const int bufSize = 128;
  211589. BYTE buffer[bufSize];
  211590. zeromem (buffer, bufSize);
  211591. SRB_ExecSCSICmd s;
  211592. zerostruct (s);
  211593. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211594. s.SRB_HaID = ha;
  211595. s.SRB_Target = tgt;
  211596. s.SRB_Lun = lun;
  211597. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211598. s.SRB_BufLen = bufSize;
  211599. s.SRB_BufPointer = buffer;
  211600. s.SRB_SenseLen = SENSE_LEN;
  211601. s.SRB_CDBLen = 6;
  211602. s.SRB_PostProc = event;
  211603. s.CDBByte[0] = SCSI_INQUIRY;
  211604. s.CDBByte[4] = 100;
  211605. ResetEvent (event);
  211606. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211607. WaitForSingleObject (event, 4000);
  211608. CloseHandle (event);
  211609. if (s.SRB_Status == SS_COMP)
  211610. {
  211611. memcpy (dev->vendor, &buffer[8], 8);
  211612. memcpy (dev->productId, &buffer[16], 16);
  211613. memcpy (dev->rev, &buffer[32], 4);
  211614. memcpy (dev->vendorSpec, &buffer[36], 20);
  211615. }
  211616. }
  211617. int FindCDDevices (CDDeviceInfo* const list, int maxItems)
  211618. {
  211619. int count = 0;
  211620. if (usingScsi)
  211621. {
  211622. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211623. {
  211624. TCHAR drivePath[8];
  211625. drivePath[0] = driveLetter;
  211626. drivePath[1] = ':';
  211627. drivePath[2] = '\\';
  211628. drivePath[3] = 0;
  211629. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211630. {
  211631. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211632. if (h != INVALID_HANDLE_VALUE)
  211633. {
  211634. BYTE buffer[100], passThroughStruct[1024];
  211635. zeromem (buffer, sizeof (buffer));
  211636. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211637. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211638. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211639. p->spt.CdbLength = 6;
  211640. p->spt.SenseInfoLength = 24;
  211641. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211642. p->spt.DataTransferLength = 100;
  211643. p->spt.TimeOutValue = 2;
  211644. p->spt.DataBuffer = buffer;
  211645. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211646. p->spt.Cdb[0] = 0x12;
  211647. p->spt.Cdb[4] = 100;
  211648. DWORD bytesReturned = 0;
  211649. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211650. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211651. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211652. &bytesReturned, 0) != 0)
  211653. {
  211654. zeromem (&list[count], sizeof (CDDeviceInfo));
  211655. list[count].scsiDriveLetter = driveLetter;
  211656. memcpy (list[count].vendor, &buffer[8], 8);
  211657. memcpy (list[count].productId, &buffer[16], 16);
  211658. memcpy (list[count].rev, &buffer[32], 4);
  211659. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211660. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211661. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211662. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211663. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211664. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211665. &bytesReturned, 0) != 0)
  211666. {
  211667. list[count].ha = scsiAddr->PortNumber;
  211668. list[count].tgt = scsiAddr->TargetId;
  211669. list[count].lun = scsiAddr->Lun;
  211670. ++count;
  211671. }
  211672. }
  211673. CloseHandle (h);
  211674. }
  211675. }
  211676. }
  211677. }
  211678. else
  211679. {
  211680. const DWORD d = fGetASPI32SupportInfo();
  211681. BYTE status = HIBYTE (LOWORD (d));
  211682. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211683. return 0;
  211684. const int numAdapters = LOBYTE (LOWORD (d));
  211685. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211686. {
  211687. SRB_HAInquiry s;
  211688. zerostruct (s);
  211689. s.SRB_Cmd = SC_HA_INQUIRY;
  211690. s.SRB_HaID = ha;
  211691. fSendASPI32Command ((LPSRB)&s);
  211692. if (s.SRB_Status == SS_COMP)
  211693. {
  211694. maxItems = (int)s.HA_Unique[3];
  211695. if (maxItems == 0)
  211696. maxItems = 8;
  211697. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211698. {
  211699. for (BYTE lun = 0; lun < 8; ++lun)
  211700. {
  211701. SRB_GDEVBlock sb;
  211702. zerostruct (sb);
  211703. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211704. sb.SRB_HaID = ha;
  211705. sb.SRB_Target = tgt;
  211706. sb.SRB_Lun = lun;
  211707. fSendASPI32Command ((LPSRB) &sb);
  211708. if (sb.SRB_Status == SS_COMP
  211709. && sb.SRB_DeviceType == DTYPE_CROM)
  211710. {
  211711. zeromem (&list[count], sizeof (CDDeviceInfo));
  211712. list[count].ha = ha;
  211713. list[count].tgt = tgt;
  211714. list[count].lun = lun;
  211715. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211716. ++count;
  211717. }
  211718. }
  211719. }
  211720. }
  211721. }
  211722. }
  211723. return count;
  211724. }
  211725. static int ripperUsers = 0;
  211726. static bool initialisedOk = false;
  211727. class DeinitialiseTimer : private Timer,
  211728. private DeletedAtShutdown
  211729. {
  211730. DeinitialiseTimer (const DeinitialiseTimer&);
  211731. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211732. public:
  211733. DeinitialiseTimer()
  211734. {
  211735. startTimer (4000);
  211736. }
  211737. ~DeinitialiseTimer()
  211738. {
  211739. if (--ripperUsers == 0)
  211740. DeinitialiseCDRipper();
  211741. }
  211742. void timerCallback()
  211743. {
  211744. delete this;
  211745. }
  211746. juce_UseDebuggingNewOperator
  211747. };
  211748. static void incUserCount()
  211749. {
  211750. if (ripperUsers++ == 0)
  211751. initialisedOk = InitialiseCDRipper();
  211752. }
  211753. static void decUserCount()
  211754. {
  211755. new DeinitialiseTimer();
  211756. }
  211757. struct CDDeviceWrapper
  211758. {
  211759. ScopedPointer<CDDeviceHandle> cdH;
  211760. ScopedPointer<CDReadBuffer> overlapBuffer;
  211761. bool jitter;
  211762. };
  211763. int getAddressOf (const TOCTRACK* const t)
  211764. {
  211765. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211766. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211767. }
  211768. static const int samplesPerFrame = 44100 / 75;
  211769. static const int bytesPerFrame = samplesPerFrame * 4;
  211770. CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211771. {
  211772. SRB_GDEVBlock s;
  211773. zerostruct (s);
  211774. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211775. s.SRB_HaID = device->ha;
  211776. s.SRB_Target = device->tgt;
  211777. s.SRB_Lun = device->lun;
  211778. if (usingScsi)
  211779. {
  211780. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211781. if (h != INVALID_HANDLE_VALUE)
  211782. {
  211783. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211784. cdh->scsiHandle = h;
  211785. return cdh;
  211786. }
  211787. }
  211788. else
  211789. {
  211790. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211791. && s.SRB_DeviceType == DTYPE_CROM)
  211792. {
  211793. return new CDDeviceHandle (device);
  211794. }
  211795. }
  211796. return 0;
  211797. }
  211798. }
  211799. const StringArray AudioCDReader::getAvailableCDNames()
  211800. {
  211801. using namespace CDReaderHelpers;
  211802. StringArray results;
  211803. incUserCount();
  211804. if (initialisedOk)
  211805. {
  211806. CDDeviceInfo list[8];
  211807. const int num = FindCDDevices (list, 8);
  211808. decUserCount();
  211809. for (int i = 0; i < num; ++i)
  211810. {
  211811. String s;
  211812. if (list[i].scsiDriveLetter > 0)
  211813. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211814. s << String (list[i].vendor).trim()
  211815. << ' ' << String (list[i].productId).trim()
  211816. << ' ' << String (list[i].rev).trim();
  211817. results.add (s);
  211818. }
  211819. }
  211820. return results;
  211821. }
  211822. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211823. {
  211824. using namespace CDReaderHelpers;
  211825. incUserCount();
  211826. if (initialisedOk)
  211827. {
  211828. CDDeviceInfo list[8];
  211829. const int num = FindCDDevices (list, 8);
  211830. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211831. {
  211832. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211833. if (handle != 0)
  211834. {
  211835. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211836. d->cdH = handle;
  211837. d->overlapBuffer = new CDReadBuffer(3);
  211838. return new AudioCDReader (d);
  211839. }
  211840. }
  211841. }
  211842. decUserCount();
  211843. return 0;
  211844. }
  211845. AudioCDReader::AudioCDReader (void* handle_)
  211846. : AudioFormatReader (0, "CD Audio"),
  211847. handle (handle_),
  211848. indexingEnabled (false),
  211849. lastIndex (0),
  211850. firstFrameInBuffer (0),
  211851. samplesInBuffer (0)
  211852. {
  211853. using namespace CDReaderHelpers;
  211854. jassert (handle_ != 0);
  211855. refreshTrackLengths();
  211856. sampleRate = 44100.0;
  211857. bitsPerSample = 16;
  211858. numChannels = 2;
  211859. usesFloatingPointData = false;
  211860. buffer.setSize (4 * bytesPerFrame, true);
  211861. }
  211862. AudioCDReader::~AudioCDReader()
  211863. {
  211864. using namespace CDReaderHelpers;
  211865. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211866. delete device;
  211867. decUserCount();
  211868. }
  211869. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211870. int64 startSampleInFile, int numSamples)
  211871. {
  211872. using namespace CDReaderHelpers;
  211873. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211874. bool ok = true;
  211875. while (numSamples > 0)
  211876. {
  211877. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211878. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211879. if (startSampleInFile >= bufferStartSample
  211880. && startSampleInFile < bufferEndSample)
  211881. {
  211882. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211883. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211884. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211885. const short* src = (const short*) buffer.getData();
  211886. src += 2 * (startSampleInFile - bufferStartSample);
  211887. for (int i = 0; i < toDo; ++i)
  211888. {
  211889. l[i] = src [i << 1] << 16;
  211890. if (r != 0)
  211891. r[i] = src [(i << 1) + 1] << 16;
  211892. }
  211893. startOffsetInDestBuffer += toDo;
  211894. startSampleInFile += toDo;
  211895. numSamples -= toDo;
  211896. }
  211897. else
  211898. {
  211899. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211900. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211901. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211902. {
  211903. device->overlapBuffer->dataLength = 0;
  211904. device->overlapBuffer->startFrame = 0;
  211905. device->overlapBuffer->numFrames = 0;
  211906. device->jitter = false;
  211907. }
  211908. firstFrameInBuffer = frameNeeded;
  211909. lastIndex = 0;
  211910. CDReadBuffer readBuffer (framesInBuffer + 4);
  211911. readBuffer.wantsIndex = indexingEnabled;
  211912. int i;
  211913. for (i = 5; --i >= 0;)
  211914. {
  211915. readBuffer.startFrame = frameNeeded;
  211916. readBuffer.numFrames = framesInBuffer;
  211917. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  211918. break;
  211919. else
  211920. device->overlapBuffer->dataLength = 0;
  211921. }
  211922. if (i >= 0)
  211923. {
  211924. memcpy ((char*) buffer.getData(),
  211925. readBuffer.buffer + readBuffer.dataStartOffset,
  211926. readBuffer.dataLength);
  211927. samplesInBuffer = readBuffer.dataLength >> 2;
  211928. lastIndex = readBuffer.index;
  211929. }
  211930. else
  211931. {
  211932. int* l = destSamples[0] + startOffsetInDestBuffer;
  211933. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211934. while (--numSamples >= 0)
  211935. {
  211936. *l++ = 0;
  211937. if (r != 0)
  211938. *r++ = 0;
  211939. }
  211940. // sometimes the read fails for just the very last couple of blocks, so
  211941. // we'll ignore and errors in the last half-second of the disk..
  211942. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211943. break;
  211944. }
  211945. }
  211946. }
  211947. return ok;
  211948. }
  211949. bool AudioCDReader::isCDStillPresent() const
  211950. {
  211951. using namespace CDReaderHelpers;
  211952. TOC toc;
  211953. zerostruct (toc);
  211954. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  211955. }
  211956. void AudioCDReader::refreshTrackLengths()
  211957. {
  211958. using namespace CDReaderHelpers;
  211959. trackStartSamples.clear();
  211960. zeromem (audioTracks, sizeof (audioTracks));
  211961. TOC toc;
  211962. zerostruct (toc);
  211963. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  211964. {
  211965. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211966. for (int i = 0; i <= numTracks; ++i)
  211967. {
  211968. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  211969. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211970. }
  211971. }
  211972. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211973. }
  211974. bool AudioCDReader::isTrackAudio (int trackNum) const
  211975. {
  211976. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211977. }
  211978. void AudioCDReader::enableIndexScanning (bool b)
  211979. {
  211980. indexingEnabled = b;
  211981. }
  211982. int AudioCDReader::getLastIndex() const
  211983. {
  211984. return lastIndex;
  211985. }
  211986. const int framesPerIndexRead = 4;
  211987. int AudioCDReader::getIndexAt (int samplePos)
  211988. {
  211989. using namespace CDReaderHelpers;
  211990. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211991. const int frameNeeded = samplePos / samplesPerFrame;
  211992. device->overlapBuffer->dataLength = 0;
  211993. device->overlapBuffer->startFrame = 0;
  211994. device->overlapBuffer->numFrames = 0;
  211995. device->jitter = false;
  211996. firstFrameInBuffer = 0;
  211997. lastIndex = 0;
  211998. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211999. readBuffer.wantsIndex = true;
  212000. int i;
  212001. for (i = 5; --i >= 0;)
  212002. {
  212003. readBuffer.startFrame = frameNeeded;
  212004. readBuffer.numFrames = framesPerIndexRead;
  212005. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212006. break;
  212007. }
  212008. if (i >= 0)
  212009. return readBuffer.index;
  212010. return -1;
  212011. }
  212012. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  212013. {
  212014. using namespace CDReaderHelpers;
  212015. Array <int> indexes;
  212016. const int trackStart = getPositionOfTrackStart (trackNumber);
  212017. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  212018. bool needToScan = true;
  212019. if (trackEnd - trackStart > 20 * 44100)
  212020. {
  212021. // check the end of the track for indexes before scanning the whole thing
  212022. needToScan = false;
  212023. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  212024. bool seenAnIndex = false;
  212025. while (pos <= trackEnd - samplesPerFrame)
  212026. {
  212027. const int index = getIndexAt (pos);
  212028. if (index == 0)
  212029. {
  212030. // lead-out, so skip back a bit if we've not found any indexes yet..
  212031. if (seenAnIndex)
  212032. break;
  212033. pos -= 44100 * 5;
  212034. if (pos < trackStart)
  212035. break;
  212036. }
  212037. else
  212038. {
  212039. if (index > 0)
  212040. seenAnIndex = true;
  212041. if (index > 1)
  212042. {
  212043. needToScan = true;
  212044. break;
  212045. }
  212046. pos += samplesPerFrame * framesPerIndexRead;
  212047. }
  212048. }
  212049. }
  212050. if (needToScan)
  212051. {
  212052. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212053. int pos = trackStart;
  212054. int last = -1;
  212055. while (pos < trackEnd - samplesPerFrame * 10)
  212056. {
  212057. const int frameNeeded = pos / samplesPerFrame;
  212058. device->overlapBuffer->dataLength = 0;
  212059. device->overlapBuffer->startFrame = 0;
  212060. device->overlapBuffer->numFrames = 0;
  212061. device->jitter = false;
  212062. firstFrameInBuffer = 0;
  212063. CDReadBuffer readBuffer (4);
  212064. readBuffer.wantsIndex = true;
  212065. int i;
  212066. for (i = 5; --i >= 0;)
  212067. {
  212068. readBuffer.startFrame = frameNeeded;
  212069. readBuffer.numFrames = framesPerIndexRead;
  212070. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212071. break;
  212072. }
  212073. if (i < 0)
  212074. break;
  212075. if (readBuffer.index > last && readBuffer.index > 1)
  212076. {
  212077. last = readBuffer.index;
  212078. indexes.add (pos);
  212079. }
  212080. pos += samplesPerFrame * framesPerIndexRead;
  212081. }
  212082. indexes.removeValue (trackStart);
  212083. }
  212084. return indexes;
  212085. }
  212086. void AudioCDReader::ejectDisk()
  212087. {
  212088. using namespace CDReaderHelpers;
  212089. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  212090. }
  212091. #endif
  212092. #if JUCE_USE_CDBURNER
  212093. namespace CDBurnerHelpers
  212094. {
  212095. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  212096. {
  212097. CoInitialize (0);
  212098. IDiscMaster* dm;
  212099. IDiscRecorder* result = 0;
  212100. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  212101. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  212102. IID_IDiscMaster,
  212103. (void**) &dm)))
  212104. {
  212105. if (SUCCEEDED (dm->Open()))
  212106. {
  212107. IEnumDiscRecorders* drEnum = 0;
  212108. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  212109. {
  212110. IDiscRecorder* dr = 0;
  212111. DWORD dummy;
  212112. int index = 0;
  212113. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  212114. {
  212115. if (indexToOpen == index)
  212116. {
  212117. result = dr;
  212118. break;
  212119. }
  212120. else if (list != 0)
  212121. {
  212122. BSTR path;
  212123. if (SUCCEEDED (dr->GetPath (&path)))
  212124. list->add ((const WCHAR*) path);
  212125. }
  212126. ++index;
  212127. dr->Release();
  212128. }
  212129. drEnum->Release();
  212130. }
  212131. if (master == 0)
  212132. dm->Close();
  212133. }
  212134. if (master != 0)
  212135. *master = dm;
  212136. else
  212137. dm->Release();
  212138. }
  212139. return result;
  212140. }
  212141. }
  212142. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  212143. public Timer
  212144. {
  212145. public:
  212146. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  212147. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  212148. listener (0), progress (0), shouldCancel (false)
  212149. {
  212150. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  212151. jassert (SUCCEEDED (hr));
  212152. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  212153. //jassert (SUCCEEDED (hr));
  212154. lastState = getDiskState();
  212155. startTimer (2000);
  212156. }
  212157. ~Pimpl() {}
  212158. void releaseObjects()
  212159. {
  212160. discRecorder->Close();
  212161. if (redbook != 0)
  212162. redbook->Release();
  212163. discRecorder->Release();
  212164. discMaster->Release();
  212165. Release();
  212166. }
  212167. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  212168. {
  212169. if (listener != 0 && ! shouldCancel)
  212170. shouldCancel = listener->audioCDBurnProgress (progress);
  212171. *pbCancel = shouldCancel;
  212172. return S_OK;
  212173. }
  212174. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  212175. {
  212176. progress = nCompleted / (float) nTotal;
  212177. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  212178. return E_NOTIMPL;
  212179. }
  212180. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  212181. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212182. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212183. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212184. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212185. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212186. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212187. class ScopedDiscOpener
  212188. {
  212189. public:
  212190. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  212191. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  212192. private:
  212193. Pimpl& pimpl;
  212194. ScopedDiscOpener (const ScopedDiscOpener&);
  212195. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  212196. };
  212197. DiskState getDiskState()
  212198. {
  212199. const ScopedDiscOpener opener (*this);
  212200. long type, flags;
  212201. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  212202. if (FAILED (hr))
  212203. return unknown;
  212204. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  212205. return writableDiskPresent;
  212206. if (type == 0)
  212207. return noDisc;
  212208. else
  212209. return readOnlyDiskPresent;
  212210. }
  212211. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  212212. {
  212213. ComSmartPtr<IPropertyStorage> prop;
  212214. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212215. return defaultReturn;
  212216. PROPSPEC iPropSpec;
  212217. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212218. iPropSpec.lpwstr = name;
  212219. PROPVARIANT iPropVariant;
  212220. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  212221. ? defaultReturn : (int) iPropVariant.lVal;
  212222. }
  212223. bool setIntProperty (const LPOLESTR name, const int value) const
  212224. {
  212225. ComSmartPtr<IPropertyStorage> prop;
  212226. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212227. return false;
  212228. PROPSPEC iPropSpec;
  212229. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212230. iPropSpec.lpwstr = name;
  212231. PROPVARIANT iPropVariant;
  212232. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  212233. return false;
  212234. iPropVariant.lVal = (long) value;
  212235. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  212236. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  212237. }
  212238. void timerCallback()
  212239. {
  212240. const DiskState state = getDiskState();
  212241. if (state != lastState)
  212242. {
  212243. lastState = state;
  212244. owner.sendChangeMessage();
  212245. }
  212246. }
  212247. AudioCDBurner& owner;
  212248. DiskState lastState;
  212249. IDiscMaster* discMaster;
  212250. IDiscRecorder* discRecorder;
  212251. IRedbookDiscMaster* redbook;
  212252. AudioCDBurner::BurnProgressListener* listener;
  212253. float progress;
  212254. bool shouldCancel;
  212255. };
  212256. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212257. {
  212258. IDiscMaster* discMaster = 0;
  212259. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  212260. if (discRecorder != 0)
  212261. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212262. }
  212263. AudioCDBurner::~AudioCDBurner()
  212264. {
  212265. if (pimpl != 0)
  212266. pimpl.release()->releaseObjects();
  212267. }
  212268. const StringArray AudioCDBurner::findAvailableDevices()
  212269. {
  212270. StringArray devs;
  212271. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  212272. return devs;
  212273. }
  212274. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212275. {
  212276. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212277. if (b->pimpl == 0)
  212278. b = 0;
  212279. return b.release();
  212280. }
  212281. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212282. {
  212283. return pimpl->getDiskState();
  212284. }
  212285. bool AudioCDBurner::isDiskPresent() const
  212286. {
  212287. return getDiskState() == writableDiskPresent;
  212288. }
  212289. bool AudioCDBurner::openTray()
  212290. {
  212291. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212292. return SUCCEEDED (pimpl->discRecorder->Eject());
  212293. }
  212294. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212295. {
  212296. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212297. DiskState oldState = getDiskState();
  212298. DiskState newState = oldState;
  212299. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212300. {
  212301. newState = getDiskState();
  212302. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212303. }
  212304. return newState;
  212305. }
  212306. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212307. {
  212308. Array<int> results;
  212309. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212310. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212311. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212312. if (speeds[i] <= maxSpeed)
  212313. results.add (speeds[i]);
  212314. results.addIfNotAlreadyThere (maxSpeed);
  212315. return results;
  212316. }
  212317. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212318. {
  212319. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212320. return false;
  212321. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212322. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212323. }
  212324. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212325. {
  212326. long blocksFree = 0;
  212327. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212328. return blocksFree;
  212329. }
  212330. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212331. bool performFakeBurnForTesting, int writeSpeed)
  212332. {
  212333. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212334. pimpl->listener = listener;
  212335. pimpl->progress = 0;
  212336. pimpl->shouldCancel = false;
  212337. UINT_PTR cookie;
  212338. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212339. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212340. ejectDiscAfterwards);
  212341. String error;
  212342. if (hr != S_OK)
  212343. {
  212344. const char* e = "Couldn't open or write to the CD device";
  212345. if (hr == IMAPI_E_USERABORT)
  212346. e = "User cancelled the write operation";
  212347. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212348. e = "No Disk present";
  212349. error = e;
  212350. }
  212351. pimpl->discMaster->ProgressUnadvise (cookie);
  212352. pimpl->listener = 0;
  212353. return error;
  212354. }
  212355. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212356. {
  212357. if (audioSource == 0)
  212358. return false;
  212359. ScopedPointer<AudioSource> source (audioSource);
  212360. long bytesPerBlock;
  212361. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212362. const int samplesPerBlock = bytesPerBlock / 4;
  212363. bool ok = true;
  212364. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212365. HeapBlock <byte> buffer (bytesPerBlock);
  212366. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212367. int samplesDone = 0;
  212368. source->prepareToPlay (samplesPerBlock, 44100.0);
  212369. while (ok)
  212370. {
  212371. {
  212372. AudioSourceChannelInfo info;
  212373. info.buffer = &sourceBuffer;
  212374. info.numSamples = samplesPerBlock;
  212375. info.startSample = 0;
  212376. sourceBuffer.clear();
  212377. source->getNextAudioBlock (info);
  212378. }
  212379. zeromem (buffer, bytesPerBlock);
  212380. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212381. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212382. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212383. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212384. CDSampleFormat left (buffer, 2);
  212385. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212386. CDSampleFormat right (buffer + 2, 2);
  212387. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212388. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212389. if (FAILED (hr))
  212390. ok = false;
  212391. samplesDone += samplesPerBlock;
  212392. if (samplesDone >= numSamples)
  212393. break;
  212394. }
  212395. hr = pimpl->redbook->CloseAudioTrack();
  212396. return ok && hr == S_OK;
  212397. }
  212398. #endif
  212399. #endif
  212400. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212401. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212402. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212403. // compiled on its own).
  212404. #if JUCE_INCLUDED_FILE
  212405. class MidiInCollector
  212406. {
  212407. public:
  212408. MidiInCollector (MidiInput* const input_,
  212409. MidiInputCallback& callback_)
  212410. : deviceHandle (0),
  212411. input (input_),
  212412. callback (callback_),
  212413. concatenator (4096),
  212414. isStarted (false),
  212415. startTime (0)
  212416. {
  212417. }
  212418. ~MidiInCollector()
  212419. {
  212420. stop();
  212421. if (deviceHandle != 0)
  212422. {
  212423. int count = 5;
  212424. while (--count >= 0)
  212425. {
  212426. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212427. break;
  212428. Sleep (20);
  212429. }
  212430. }
  212431. }
  212432. void handleMessage (const uint32 message, const uint32 timeStamp)
  212433. {
  212434. if ((message & 0xff) >= 0x80 && isStarted)
  212435. {
  212436. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212437. writeFinishedBlocks();
  212438. }
  212439. }
  212440. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212441. {
  212442. if (isStarted)
  212443. {
  212444. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212445. writeFinishedBlocks();
  212446. }
  212447. }
  212448. void start()
  212449. {
  212450. jassert (deviceHandle != 0);
  212451. if (deviceHandle != 0 && ! isStarted)
  212452. {
  212453. activeMidiCollectors.addIfNotAlreadyThere (this);
  212454. for (int i = 0; i < (int) numHeaders; ++i)
  212455. headers[i].write (deviceHandle);
  212456. startTime = Time::getMillisecondCounter();
  212457. MMRESULT res = midiInStart (deviceHandle);
  212458. if (res == MMSYSERR_NOERROR)
  212459. {
  212460. concatenator.reset();
  212461. isStarted = true;
  212462. }
  212463. else
  212464. {
  212465. unprepareAllHeaders();
  212466. }
  212467. }
  212468. }
  212469. void stop()
  212470. {
  212471. if (isStarted)
  212472. {
  212473. isStarted = false;
  212474. midiInReset (deviceHandle);
  212475. midiInStop (deviceHandle);
  212476. activeMidiCollectors.removeValue (this);
  212477. unprepareAllHeaders();
  212478. concatenator.reset();
  212479. }
  212480. }
  212481. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212482. {
  212483. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212484. if (activeMidiCollectors.contains (collector))
  212485. {
  212486. if (uMsg == MIM_DATA)
  212487. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212488. else if (uMsg == MIM_LONGDATA)
  212489. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212490. }
  212491. }
  212492. juce_UseDebuggingNewOperator
  212493. HMIDIIN deviceHandle;
  212494. private:
  212495. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212496. MidiInput* input;
  212497. MidiInputCallback& callback;
  212498. MidiDataConcatenator concatenator;
  212499. bool volatile isStarted;
  212500. uint32 startTime;
  212501. class MidiHeader
  212502. {
  212503. public:
  212504. MidiHeader()
  212505. {
  212506. zerostruct (hdr);
  212507. hdr.lpData = data;
  212508. hdr.dwBufferLength = numElementsInArray (data);
  212509. }
  212510. void write (HMIDIIN deviceHandle)
  212511. {
  212512. hdr.dwBytesRecorded = 0;
  212513. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212514. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212515. }
  212516. void writeIfFinished (HMIDIIN deviceHandle)
  212517. {
  212518. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212519. {
  212520. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212521. (void) res;
  212522. write (deviceHandle);
  212523. }
  212524. }
  212525. void unprepare (HMIDIIN deviceHandle)
  212526. {
  212527. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212528. {
  212529. int c = 10;
  212530. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212531. Thread::sleep (20);
  212532. jassert (c >= 0);
  212533. }
  212534. }
  212535. private:
  212536. MIDIHDR hdr;
  212537. char data [256];
  212538. MidiHeader (const MidiHeader&);
  212539. MidiHeader& operator= (const MidiHeader&);
  212540. };
  212541. enum { numHeaders = 32 };
  212542. MidiHeader headers [numHeaders];
  212543. void writeFinishedBlocks()
  212544. {
  212545. for (int i = 0; i < (int) numHeaders; ++i)
  212546. headers[i].writeIfFinished (deviceHandle);
  212547. }
  212548. void unprepareAllHeaders()
  212549. {
  212550. for (int i = 0; i < (int) numHeaders; ++i)
  212551. headers[i].unprepare (deviceHandle);
  212552. }
  212553. double convertTimeStamp (uint32 timeStamp)
  212554. {
  212555. timeStamp += startTime;
  212556. const uint32 now = Time::getMillisecondCounter();
  212557. if (timeStamp > now)
  212558. {
  212559. if (timeStamp > now + 2)
  212560. --startTime;
  212561. timeStamp = now;
  212562. }
  212563. return timeStamp * 0.001;
  212564. }
  212565. MidiInCollector (const MidiInCollector&);
  212566. MidiInCollector& operator= (const MidiInCollector&);
  212567. };
  212568. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212569. const StringArray MidiInput::getDevices()
  212570. {
  212571. StringArray s;
  212572. const int num = midiInGetNumDevs();
  212573. for (int i = 0; i < num; ++i)
  212574. {
  212575. MIDIINCAPS mc;
  212576. zerostruct (mc);
  212577. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212578. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212579. }
  212580. return s;
  212581. }
  212582. int MidiInput::getDefaultDeviceIndex()
  212583. {
  212584. return 0;
  212585. }
  212586. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212587. {
  212588. if (callback == 0)
  212589. return 0;
  212590. UINT deviceId = MIDI_MAPPER;
  212591. int n = 0;
  212592. String name;
  212593. const int num = midiInGetNumDevs();
  212594. for (int i = 0; i < num; ++i)
  212595. {
  212596. MIDIINCAPS mc;
  212597. zerostruct (mc);
  212598. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212599. {
  212600. if (index == n)
  212601. {
  212602. deviceId = i;
  212603. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212604. break;
  212605. }
  212606. ++n;
  212607. }
  212608. }
  212609. ScopedPointer <MidiInput> in (new MidiInput (name));
  212610. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212611. HMIDIIN h;
  212612. HRESULT err = midiInOpen (&h, deviceId,
  212613. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212614. (DWORD_PTR) (MidiInCollector*) collector,
  212615. CALLBACK_FUNCTION);
  212616. if (err == MMSYSERR_NOERROR)
  212617. {
  212618. collector->deviceHandle = h;
  212619. in->internal = collector.release();
  212620. return in.release();
  212621. }
  212622. return 0;
  212623. }
  212624. MidiInput::MidiInput (const String& name_)
  212625. : name (name_),
  212626. internal (0)
  212627. {
  212628. }
  212629. MidiInput::~MidiInput()
  212630. {
  212631. delete static_cast <MidiInCollector*> (internal);
  212632. }
  212633. void MidiInput::start()
  212634. {
  212635. static_cast <MidiInCollector*> (internal)->start();
  212636. }
  212637. void MidiInput::stop()
  212638. {
  212639. static_cast <MidiInCollector*> (internal)->stop();
  212640. }
  212641. struct MidiOutHandle
  212642. {
  212643. int refCount;
  212644. UINT deviceId;
  212645. HMIDIOUT handle;
  212646. static Array<MidiOutHandle*> activeHandles;
  212647. juce_UseDebuggingNewOperator
  212648. };
  212649. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212650. const StringArray MidiOutput::getDevices()
  212651. {
  212652. StringArray s;
  212653. const int num = midiOutGetNumDevs();
  212654. for (int i = 0; i < num; ++i)
  212655. {
  212656. MIDIOUTCAPS mc;
  212657. zerostruct (mc);
  212658. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212659. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212660. }
  212661. return s;
  212662. }
  212663. int MidiOutput::getDefaultDeviceIndex()
  212664. {
  212665. const int num = midiOutGetNumDevs();
  212666. int n = 0;
  212667. for (int i = 0; i < num; ++i)
  212668. {
  212669. MIDIOUTCAPS mc;
  212670. zerostruct (mc);
  212671. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212672. {
  212673. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212674. return n;
  212675. ++n;
  212676. }
  212677. }
  212678. return 0;
  212679. }
  212680. MidiOutput* MidiOutput::openDevice (int index)
  212681. {
  212682. UINT deviceId = MIDI_MAPPER;
  212683. const int num = midiOutGetNumDevs();
  212684. int i, n = 0;
  212685. for (i = 0; i < num; ++i)
  212686. {
  212687. MIDIOUTCAPS mc;
  212688. zerostruct (mc);
  212689. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212690. {
  212691. // use the microsoft sw synth as a default - best not to allow deviceId
  212692. // to be MIDI_MAPPER, or else device sharing breaks
  212693. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212694. deviceId = i;
  212695. if (index == n)
  212696. {
  212697. deviceId = i;
  212698. break;
  212699. }
  212700. ++n;
  212701. }
  212702. }
  212703. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212704. {
  212705. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212706. if (han != 0 && han->deviceId == deviceId)
  212707. {
  212708. han->refCount++;
  212709. MidiOutput* const out = new MidiOutput();
  212710. out->internal = han;
  212711. return out;
  212712. }
  212713. }
  212714. for (i = 4; --i >= 0;)
  212715. {
  212716. HMIDIOUT h = 0;
  212717. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212718. if (res == MMSYSERR_NOERROR)
  212719. {
  212720. MidiOutHandle* const han = new MidiOutHandle();
  212721. han->deviceId = deviceId;
  212722. han->refCount = 1;
  212723. han->handle = h;
  212724. MidiOutHandle::activeHandles.add (han);
  212725. MidiOutput* const out = new MidiOutput();
  212726. out->internal = han;
  212727. return out;
  212728. }
  212729. else if (res == MMSYSERR_ALLOCATED)
  212730. {
  212731. Sleep (100);
  212732. }
  212733. else
  212734. {
  212735. break;
  212736. }
  212737. }
  212738. return 0;
  212739. }
  212740. MidiOutput::~MidiOutput()
  212741. {
  212742. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212743. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212744. {
  212745. midiOutClose (h->handle);
  212746. MidiOutHandle::activeHandles.removeValue (h);
  212747. delete h;
  212748. }
  212749. }
  212750. void MidiOutput::reset()
  212751. {
  212752. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212753. midiOutReset (h->handle);
  212754. }
  212755. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212756. {
  212757. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212758. DWORD n;
  212759. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212760. {
  212761. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212762. rightVol = nn[0] / (float) 0xffff;
  212763. leftVol = nn[1] / (float) 0xffff;
  212764. return true;
  212765. }
  212766. else
  212767. {
  212768. rightVol = leftVol = 1.0f;
  212769. return false;
  212770. }
  212771. }
  212772. void MidiOutput::setVolume (float leftVol, float rightVol)
  212773. {
  212774. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212775. DWORD n;
  212776. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212777. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212778. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212779. midiOutSetVolume (handle->handle, n);
  212780. }
  212781. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212782. {
  212783. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212784. if (message.getRawDataSize() > 3
  212785. || message.isSysEx())
  212786. {
  212787. MIDIHDR h;
  212788. zerostruct (h);
  212789. h.lpData = (char*) message.getRawData();
  212790. h.dwBufferLength = message.getRawDataSize();
  212791. h.dwBytesRecorded = message.getRawDataSize();
  212792. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212793. {
  212794. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212795. if (res == MMSYSERR_NOERROR)
  212796. {
  212797. while ((h.dwFlags & MHDR_DONE) == 0)
  212798. Sleep (1);
  212799. int count = 500; // 1 sec timeout
  212800. while (--count >= 0)
  212801. {
  212802. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212803. if (res == MIDIERR_STILLPLAYING)
  212804. Sleep (2);
  212805. else
  212806. break;
  212807. }
  212808. }
  212809. }
  212810. }
  212811. else
  212812. {
  212813. midiOutShortMsg (handle->handle,
  212814. *(unsigned int*) message.getRawData());
  212815. }
  212816. }
  212817. #endif
  212818. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212819. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212820. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212821. // compiled on its own).
  212822. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212823. #undef WINDOWS
  212824. // #define ASIO_DEBUGGING 1
  212825. #undef log
  212826. #if ASIO_DEBUGGING
  212827. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212828. #else
  212829. #define log(a) {}
  212830. #endif
  212831. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  212832. to be pretty random about whether or not they do this. If you hit an error using these functions
  212833. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  212834. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  212835. */
  212836. #define JUCE_ASIOCALLBACK __cdecl
  212837. namespace ASIODebugging
  212838. {
  212839. #if ASIO_DEBUGGING
  212840. static void log (const String& context, long error)
  212841. {
  212842. String err ("unknown error");
  212843. if (error == ASE_NotPresent) err = "Not Present";
  212844. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212845. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212846. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212847. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212848. else if (error == ASE_NoClock) err = "No Clock";
  212849. else if (error == ASE_NoMemory) err = "Out of memory";
  212850. log ("!!error: " + context + " - " + err);
  212851. }
  212852. #define logError(a, b) ASIODebugging::log ((a), (b))
  212853. #else
  212854. #define logError(a, b) {}
  212855. #endif
  212856. }
  212857. class ASIOAudioIODevice;
  212858. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212859. static const int maxASIOChannels = 160;
  212860. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212861. private Timer
  212862. {
  212863. public:
  212864. Component ourWindow;
  212865. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212866. const String& optionalDllForDirectLoading_)
  212867. : AudioIODevice (name_, "ASIO"),
  212868. asioObject (0),
  212869. classId (classId_),
  212870. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212871. currentBitDepth (16),
  212872. currentSampleRate (0),
  212873. isOpen_ (false),
  212874. isStarted (false),
  212875. postOutput (true),
  212876. insideControlPanelModalLoop (false),
  212877. shouldUsePreferredSize (false)
  212878. {
  212879. name = name_;
  212880. ourWindow.addToDesktop (0);
  212881. windowHandle = ourWindow.getWindowHandle();
  212882. jassert (currentASIODev [slotNumber] == 0);
  212883. currentASIODev [slotNumber] = this;
  212884. openDevice();
  212885. }
  212886. ~ASIOAudioIODevice()
  212887. {
  212888. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212889. if (currentASIODev[i] == this)
  212890. currentASIODev[i] = 0;
  212891. close();
  212892. log ("ASIO - exiting");
  212893. removeCurrentDriver();
  212894. }
  212895. void updateSampleRates()
  212896. {
  212897. // find a list of sample rates..
  212898. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212899. sampleRates.clear();
  212900. if (asioObject != 0)
  212901. {
  212902. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212903. {
  212904. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212905. if (err == 0)
  212906. {
  212907. sampleRates.add ((int) possibleSampleRates[index]);
  212908. log ("rate: " + String ((int) possibleSampleRates[index]));
  212909. }
  212910. else if (err != ASE_NoClock)
  212911. {
  212912. logError ("CanSampleRate", err);
  212913. }
  212914. }
  212915. if (sampleRates.size() == 0)
  212916. {
  212917. double cr = 0;
  212918. const long err = asioObject->getSampleRate (&cr);
  212919. log ("No sample rates supported - current rate: " + String ((int) cr));
  212920. if (err == 0)
  212921. sampleRates.add ((int) cr);
  212922. }
  212923. }
  212924. }
  212925. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212926. const StringArray getInputChannelNames() { return inputChannelNames; }
  212927. int getNumSampleRates() { return sampleRates.size(); }
  212928. double getSampleRate (int index) { return sampleRates [index]; }
  212929. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212930. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212931. int getDefaultBufferSize() { return preferredSize; }
  212932. const String open (const BigInteger& inputChannels,
  212933. const BigInteger& outputChannels,
  212934. double sr,
  212935. int bufferSizeSamples)
  212936. {
  212937. close();
  212938. currentCallback = 0;
  212939. if (bufferSizeSamples <= 0)
  212940. shouldUsePreferredSize = true;
  212941. if (asioObject == 0 || ! isASIOOpen)
  212942. {
  212943. log ("Warning: device not open");
  212944. const String err (openDevice());
  212945. if (asioObject == 0 || ! isASIOOpen)
  212946. return err;
  212947. }
  212948. isStarted = false;
  212949. bufferIndex = -1;
  212950. long err = 0;
  212951. long newPreferredSize = 0;
  212952. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212953. minSize = 0;
  212954. maxSize = 0;
  212955. newPreferredSize = 0;
  212956. granularity = 0;
  212957. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212958. {
  212959. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212960. shouldUsePreferredSize = true;
  212961. preferredSize = newPreferredSize;
  212962. }
  212963. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212964. // dynamic changes to the buffer size...
  212965. shouldUsePreferredSize = shouldUsePreferredSize
  212966. || getName().containsIgnoreCase ("Digidesign");
  212967. if (shouldUsePreferredSize)
  212968. {
  212969. log ("Using preferred size for buffer..");
  212970. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212971. {
  212972. bufferSizeSamples = preferredSize;
  212973. }
  212974. else
  212975. {
  212976. bufferSizeSamples = 1024;
  212977. logError ("GetBufferSize1", err);
  212978. }
  212979. shouldUsePreferredSize = false;
  212980. }
  212981. int sampleRate = roundDoubleToInt (sr);
  212982. currentSampleRate = sampleRate;
  212983. currentBlockSizeSamples = bufferSizeSamples;
  212984. currentChansOut.clear();
  212985. currentChansIn.clear();
  212986. zeromem (inBuffers, sizeof (inBuffers));
  212987. zeromem (outBuffers, sizeof (outBuffers));
  212988. updateSampleRates();
  212989. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212990. sampleRate = sampleRates[0];
  212991. jassert (sampleRate != 0);
  212992. if (sampleRate == 0)
  212993. sampleRate = 44100;
  212994. long numSources = 32;
  212995. ASIOClockSource clocks[32];
  212996. zeromem (clocks, sizeof (clocks));
  212997. asioObject->getClockSources (clocks, &numSources);
  212998. bool isSourceSet = false;
  212999. // careful not to remove this loop because it does more than just logging!
  213000. int i;
  213001. for (i = 0; i < numSources; ++i)
  213002. {
  213003. String s ("clock: ");
  213004. s += clocks[i].name;
  213005. if (clocks[i].isCurrentSource)
  213006. {
  213007. isSourceSet = true;
  213008. s << " (cur)";
  213009. }
  213010. log (s);
  213011. }
  213012. if (numSources > 1 && ! isSourceSet)
  213013. {
  213014. log ("setting clock source");
  213015. asioObject->setClockSource (clocks[0].index);
  213016. Thread::sleep (20);
  213017. }
  213018. else
  213019. {
  213020. if (numSources == 0)
  213021. {
  213022. log ("ASIO - no clock sources!");
  213023. }
  213024. }
  213025. double cr = 0;
  213026. err = asioObject->getSampleRate (&cr);
  213027. if (err == 0)
  213028. {
  213029. currentSampleRate = cr;
  213030. }
  213031. else
  213032. {
  213033. logError ("GetSampleRate", err);
  213034. currentSampleRate = 0;
  213035. }
  213036. error = String::empty;
  213037. needToReset = false;
  213038. isReSync = false;
  213039. err = 0;
  213040. bool buffersCreated = false;
  213041. if (currentSampleRate != sampleRate)
  213042. {
  213043. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  213044. err = asioObject->setSampleRate (sampleRate);
  213045. if (err == ASE_NoClock && numSources > 0)
  213046. {
  213047. log ("trying to set a clock source..");
  213048. Thread::sleep (10);
  213049. err = asioObject->setClockSource (clocks[0].index);
  213050. if (err != 0)
  213051. {
  213052. logError ("SetClock", err);
  213053. }
  213054. Thread::sleep (10);
  213055. err = asioObject->setSampleRate (sampleRate);
  213056. }
  213057. }
  213058. if (err == 0)
  213059. {
  213060. currentSampleRate = sampleRate;
  213061. if (needToReset)
  213062. {
  213063. if (isReSync)
  213064. {
  213065. log ("Resync request");
  213066. }
  213067. log ("! Resetting ASIO after sample rate change");
  213068. removeCurrentDriver();
  213069. loadDriver();
  213070. const String error (initDriver());
  213071. if (error.isNotEmpty())
  213072. {
  213073. log ("ASIOInit: " + error);
  213074. }
  213075. needToReset = false;
  213076. isReSync = false;
  213077. }
  213078. numActiveInputChans = 0;
  213079. numActiveOutputChans = 0;
  213080. ASIOBufferInfo* info = bufferInfos;
  213081. int i;
  213082. for (i = 0; i < totalNumInputChans; ++i)
  213083. {
  213084. if (inputChannels[i])
  213085. {
  213086. currentChansIn.setBit (i);
  213087. info->isInput = 1;
  213088. info->channelNum = i;
  213089. info->buffers[0] = info->buffers[1] = 0;
  213090. ++info;
  213091. ++numActiveInputChans;
  213092. }
  213093. }
  213094. for (i = 0; i < totalNumOutputChans; ++i)
  213095. {
  213096. if (outputChannels[i])
  213097. {
  213098. currentChansOut.setBit (i);
  213099. info->isInput = 0;
  213100. info->channelNum = i;
  213101. info->buffers[0] = info->buffers[1] = 0;
  213102. ++info;
  213103. ++numActiveOutputChans;
  213104. }
  213105. }
  213106. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  213107. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213108. if (currentASIODev[0] == this)
  213109. {
  213110. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213111. callbacks.asioMessage = &asioMessagesCallback0;
  213112. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213113. }
  213114. else if (currentASIODev[1] == this)
  213115. {
  213116. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213117. callbacks.asioMessage = &asioMessagesCallback1;
  213118. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213119. }
  213120. else if (currentASIODev[2] == this)
  213121. {
  213122. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213123. callbacks.asioMessage = &asioMessagesCallback2;
  213124. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213125. }
  213126. else
  213127. {
  213128. jassertfalse;
  213129. }
  213130. log ("disposing buffers");
  213131. err = asioObject->disposeBuffers();
  213132. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  213133. err = asioObject->createBuffers (bufferInfos,
  213134. totalBuffers,
  213135. currentBlockSizeSamples,
  213136. &callbacks);
  213137. if (err != 0)
  213138. {
  213139. currentBlockSizeSamples = preferredSize;
  213140. logError ("create buffers 2", err);
  213141. asioObject->disposeBuffers();
  213142. err = asioObject->createBuffers (bufferInfos,
  213143. totalBuffers,
  213144. currentBlockSizeSamples,
  213145. &callbacks);
  213146. }
  213147. if (err == 0)
  213148. {
  213149. buffersCreated = true;
  213150. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  213151. int n = 0;
  213152. Array <int> types;
  213153. currentBitDepth = 16;
  213154. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  213155. {
  213156. if (inputChannels[i])
  213157. {
  213158. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  213159. ASIOChannelInfo channelInfo;
  213160. zerostruct (channelInfo);
  213161. channelInfo.channel = i;
  213162. channelInfo.isInput = 1;
  213163. asioObject->getChannelInfo (&channelInfo);
  213164. types.addIfNotAlreadyThere (channelInfo.type);
  213165. typeToFormatParameters (channelInfo.type,
  213166. inputChannelBitDepths[n],
  213167. inputChannelBytesPerSample[n],
  213168. inputChannelIsFloat[n],
  213169. inputChannelLittleEndian[n]);
  213170. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213171. ++n;
  213172. }
  213173. }
  213174. jassert (numActiveInputChans == n);
  213175. n = 0;
  213176. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213177. {
  213178. if (outputChannels[i])
  213179. {
  213180. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213181. ASIOChannelInfo channelInfo;
  213182. zerostruct (channelInfo);
  213183. channelInfo.channel = i;
  213184. channelInfo.isInput = 0;
  213185. asioObject->getChannelInfo (&channelInfo);
  213186. types.addIfNotAlreadyThere (channelInfo.type);
  213187. typeToFormatParameters (channelInfo.type,
  213188. outputChannelBitDepths[n],
  213189. outputChannelBytesPerSample[n],
  213190. outputChannelIsFloat[n],
  213191. outputChannelLittleEndian[n]);
  213192. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213193. ++n;
  213194. }
  213195. }
  213196. jassert (numActiveOutputChans == n);
  213197. for (i = types.size(); --i >= 0;)
  213198. {
  213199. log ("channel format: " + String (types[i]));
  213200. }
  213201. jassert (n <= totalBuffers);
  213202. for (i = 0; i < numActiveOutputChans; ++i)
  213203. {
  213204. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213205. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213206. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213207. {
  213208. log ("!! Null buffers");
  213209. }
  213210. else
  213211. {
  213212. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213213. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213214. }
  213215. }
  213216. inputLatency = outputLatency = 0;
  213217. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213218. {
  213219. log ("ASIO - no latencies");
  213220. }
  213221. else
  213222. {
  213223. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213224. }
  213225. isOpen_ = true;
  213226. log ("starting ASIO");
  213227. calledback = false;
  213228. err = asioObject->start();
  213229. if (err != 0)
  213230. {
  213231. isOpen_ = false;
  213232. log ("ASIO - stop on failure");
  213233. Thread::sleep (10);
  213234. asioObject->stop();
  213235. error = "Can't start device";
  213236. Thread::sleep (10);
  213237. }
  213238. else
  213239. {
  213240. int count = 300;
  213241. while (--count > 0 && ! calledback)
  213242. Thread::sleep (10);
  213243. isStarted = true;
  213244. if (! calledback)
  213245. {
  213246. error = "Device didn't start correctly";
  213247. log ("ASIO didn't callback - stopping..");
  213248. asioObject->stop();
  213249. }
  213250. }
  213251. }
  213252. else
  213253. {
  213254. error = "Can't create i/o buffers";
  213255. }
  213256. }
  213257. else
  213258. {
  213259. error = "Can't set sample rate: ";
  213260. error << sampleRate;
  213261. }
  213262. if (error.isNotEmpty())
  213263. {
  213264. logError (error, err);
  213265. if (asioObject != 0 && buffersCreated)
  213266. asioObject->disposeBuffers();
  213267. Thread::sleep (20);
  213268. isStarted = false;
  213269. isOpen_ = false;
  213270. const String errorCopy (error);
  213271. close(); // (this resets the error string)
  213272. error = errorCopy;
  213273. }
  213274. needToReset = false;
  213275. isReSync = false;
  213276. return error;
  213277. }
  213278. void close()
  213279. {
  213280. error = String::empty;
  213281. stopTimer();
  213282. stop();
  213283. if (isASIOOpen && isOpen_)
  213284. {
  213285. const ScopedLock sl (callbackLock);
  213286. isOpen_ = false;
  213287. isStarted = false;
  213288. needToReset = false;
  213289. isReSync = false;
  213290. log ("ASIO - stopping");
  213291. if (asioObject != 0)
  213292. {
  213293. Thread::sleep (20);
  213294. asioObject->stop();
  213295. Thread::sleep (10);
  213296. asioObject->disposeBuffers();
  213297. }
  213298. Thread::sleep (10);
  213299. }
  213300. }
  213301. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  213302. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  213303. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  213304. double getCurrentSampleRate() { return currentSampleRate; }
  213305. int getCurrentBitDepth() { return currentBitDepth; }
  213306. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  213307. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  213308. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  213309. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  213310. void start (AudioIODeviceCallback* callback)
  213311. {
  213312. if (callback != 0)
  213313. {
  213314. callback->audioDeviceAboutToStart (this);
  213315. const ScopedLock sl (callbackLock);
  213316. currentCallback = callback;
  213317. }
  213318. }
  213319. void stop()
  213320. {
  213321. AudioIODeviceCallback* const lastCallback = currentCallback;
  213322. {
  213323. const ScopedLock sl (callbackLock);
  213324. currentCallback = 0;
  213325. }
  213326. if (lastCallback != 0)
  213327. lastCallback->audioDeviceStopped();
  213328. }
  213329. const String getLastError() { return error; }
  213330. bool hasControlPanel() const { return true; }
  213331. bool showControlPanel()
  213332. {
  213333. log ("ASIO - showing control panel");
  213334. Component modalWindow (String::empty);
  213335. modalWindow.setOpaque (true);
  213336. modalWindow.addToDesktop (0);
  213337. modalWindow.enterModalState();
  213338. bool done = false;
  213339. JUCE_TRY
  213340. {
  213341. // are there are devices that need to be closed before showing their control panel?
  213342. // close();
  213343. insideControlPanelModalLoop = true;
  213344. const uint32 started = Time::getMillisecondCounter();
  213345. if (asioObject != 0)
  213346. {
  213347. asioObject->controlPanel();
  213348. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213349. log ("spent: " + String (spent));
  213350. if (spent > 300)
  213351. {
  213352. shouldUsePreferredSize = true;
  213353. done = true;
  213354. }
  213355. }
  213356. }
  213357. JUCE_CATCH_ALL
  213358. insideControlPanelModalLoop = false;
  213359. return done;
  213360. }
  213361. void resetRequest() throw()
  213362. {
  213363. needToReset = true;
  213364. }
  213365. void resyncRequest() throw()
  213366. {
  213367. needToReset = true;
  213368. isReSync = true;
  213369. }
  213370. void timerCallback()
  213371. {
  213372. if (! insideControlPanelModalLoop)
  213373. {
  213374. stopTimer();
  213375. // used to cause a reset
  213376. log ("! ASIO restart request!");
  213377. if (isOpen_)
  213378. {
  213379. AudioIODeviceCallback* const oldCallback = currentCallback;
  213380. close();
  213381. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213382. currentSampleRate, currentBlockSizeSamples);
  213383. if (oldCallback != 0)
  213384. start (oldCallback);
  213385. }
  213386. }
  213387. else
  213388. {
  213389. startTimer (100);
  213390. }
  213391. }
  213392. juce_UseDebuggingNewOperator
  213393. private:
  213394. IASIO* volatile asioObject;
  213395. ASIOCallbacks callbacks;
  213396. void* windowHandle;
  213397. CLSID classId;
  213398. const String optionalDllForDirectLoading;
  213399. String error;
  213400. long totalNumInputChans, totalNumOutputChans;
  213401. StringArray inputChannelNames, outputChannelNames;
  213402. Array<int> sampleRates, bufferSizes;
  213403. long inputLatency, outputLatency;
  213404. long minSize, maxSize, preferredSize, granularity;
  213405. int volatile currentBlockSizeSamples;
  213406. int volatile currentBitDepth;
  213407. double volatile currentSampleRate;
  213408. BigInteger currentChansOut, currentChansIn;
  213409. AudioIODeviceCallback* volatile currentCallback;
  213410. CriticalSection callbackLock;
  213411. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213412. float* inBuffers [maxASIOChannels];
  213413. float* outBuffers [maxASIOChannels];
  213414. int inputChannelBitDepths [maxASIOChannels];
  213415. int outputChannelBitDepths [maxASIOChannels];
  213416. int inputChannelBytesPerSample [maxASIOChannels];
  213417. int outputChannelBytesPerSample [maxASIOChannels];
  213418. bool inputChannelIsFloat [maxASIOChannels];
  213419. bool outputChannelIsFloat [maxASIOChannels];
  213420. bool inputChannelLittleEndian [maxASIOChannels];
  213421. bool outputChannelLittleEndian [maxASIOChannels];
  213422. WaitableEvent event1;
  213423. HeapBlock <float> tempBuffer;
  213424. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213425. bool isOpen_, isStarted;
  213426. bool volatile isASIOOpen;
  213427. bool volatile calledback;
  213428. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213429. bool volatile insideControlPanelModalLoop;
  213430. bool volatile shouldUsePreferredSize;
  213431. void removeCurrentDriver()
  213432. {
  213433. if (asioObject != 0)
  213434. {
  213435. asioObject->Release();
  213436. asioObject = 0;
  213437. }
  213438. }
  213439. bool loadDriver()
  213440. {
  213441. removeCurrentDriver();
  213442. JUCE_TRY
  213443. {
  213444. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213445. classId, (void**) &asioObject) == S_OK)
  213446. {
  213447. return true;
  213448. }
  213449. // If a class isn't registered but we have a path for it, we can fallback to
  213450. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213451. if (optionalDllForDirectLoading.isNotEmpty())
  213452. {
  213453. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213454. if (h != 0)
  213455. {
  213456. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213457. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213458. if (dllGetClassObject != 0)
  213459. {
  213460. IClassFactory* classFactory = 0;
  213461. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213462. if (classFactory != 0)
  213463. {
  213464. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213465. classFactory->Release();
  213466. }
  213467. return asioObject != 0;
  213468. }
  213469. }
  213470. }
  213471. }
  213472. JUCE_CATCH_ALL
  213473. asioObject = 0;
  213474. return false;
  213475. }
  213476. const String initDriver()
  213477. {
  213478. if (asioObject != 0)
  213479. {
  213480. char buffer [256];
  213481. zeromem (buffer, sizeof (buffer));
  213482. if (! asioObject->init (windowHandle))
  213483. {
  213484. asioObject->getErrorMessage (buffer);
  213485. return String (buffer, sizeof (buffer) - 1);
  213486. }
  213487. // just in case any daft drivers expect this to be called..
  213488. asioObject->getDriverName (buffer);
  213489. return String::empty;
  213490. }
  213491. return "No Driver";
  213492. }
  213493. const String openDevice()
  213494. {
  213495. // use this in case the driver starts opening dialog boxes..
  213496. Component modalWindow (String::empty);
  213497. modalWindow.setOpaque (true);
  213498. modalWindow.addToDesktop (0);
  213499. modalWindow.enterModalState();
  213500. // open the device and get its info..
  213501. log ("opening ASIO device: " + getName());
  213502. needToReset = false;
  213503. isReSync = false;
  213504. outputChannelNames.clear();
  213505. inputChannelNames.clear();
  213506. bufferSizes.clear();
  213507. sampleRates.clear();
  213508. isASIOOpen = false;
  213509. isOpen_ = false;
  213510. totalNumInputChans = 0;
  213511. totalNumOutputChans = 0;
  213512. numActiveInputChans = 0;
  213513. numActiveOutputChans = 0;
  213514. currentCallback = 0;
  213515. error = String::empty;
  213516. if (getName().isEmpty())
  213517. return error;
  213518. long err = 0;
  213519. if (loadDriver())
  213520. {
  213521. if ((error = initDriver()).isEmpty())
  213522. {
  213523. numActiveInputChans = 0;
  213524. numActiveOutputChans = 0;
  213525. totalNumInputChans = 0;
  213526. totalNumOutputChans = 0;
  213527. if (asioObject != 0
  213528. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213529. {
  213530. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213531. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213532. {
  213533. // find a list of buffer sizes..
  213534. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213535. if (granularity >= 0)
  213536. {
  213537. granularity = jmax (1, (int) granularity);
  213538. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213539. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213540. }
  213541. else if (granularity < 0)
  213542. {
  213543. for (int i = 0; i < 18; ++i)
  213544. {
  213545. const int s = (1 << i);
  213546. if (s >= minSize && s <= maxSize)
  213547. bufferSizes.add (s);
  213548. }
  213549. }
  213550. if (! bufferSizes.contains (preferredSize))
  213551. bufferSizes.insert (0, preferredSize);
  213552. double currentRate = 0;
  213553. asioObject->getSampleRate (&currentRate);
  213554. if (currentRate <= 0.0 || currentRate > 192001.0)
  213555. {
  213556. log ("setting sample rate");
  213557. err = asioObject->setSampleRate (44100.0);
  213558. if (err != 0)
  213559. {
  213560. logError ("setting sample rate", err);
  213561. }
  213562. asioObject->getSampleRate (&currentRate);
  213563. }
  213564. currentSampleRate = currentRate;
  213565. postOutput = (asioObject->outputReady() == 0);
  213566. if (postOutput)
  213567. {
  213568. log ("ASIO outputReady = ok");
  213569. }
  213570. updateSampleRates();
  213571. // ..because cubase does it at this point
  213572. inputLatency = outputLatency = 0;
  213573. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213574. {
  213575. log ("ASIO - no latencies");
  213576. }
  213577. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213578. // create some dummy buffers now.. because cubase does..
  213579. numActiveInputChans = 0;
  213580. numActiveOutputChans = 0;
  213581. ASIOBufferInfo* info = bufferInfos;
  213582. int i, numChans = 0;
  213583. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213584. {
  213585. info->isInput = 1;
  213586. info->channelNum = i;
  213587. info->buffers[0] = info->buffers[1] = 0;
  213588. ++info;
  213589. ++numChans;
  213590. }
  213591. const int outputBufferIndex = numChans;
  213592. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213593. {
  213594. info->isInput = 0;
  213595. info->channelNum = i;
  213596. info->buffers[0] = info->buffers[1] = 0;
  213597. ++info;
  213598. ++numChans;
  213599. }
  213600. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213601. if (currentASIODev[0] == this)
  213602. {
  213603. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213604. callbacks.asioMessage = &asioMessagesCallback0;
  213605. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213606. }
  213607. else if (currentASIODev[1] == this)
  213608. {
  213609. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213610. callbacks.asioMessage = &asioMessagesCallback1;
  213611. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213612. }
  213613. else if (currentASIODev[2] == this)
  213614. {
  213615. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213616. callbacks.asioMessage = &asioMessagesCallback2;
  213617. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213618. }
  213619. else
  213620. {
  213621. jassertfalse;
  213622. }
  213623. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213624. if (preferredSize > 0)
  213625. {
  213626. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213627. if (err != 0)
  213628. {
  213629. logError ("dummy buffers", err);
  213630. }
  213631. }
  213632. long newInps = 0, newOuts = 0;
  213633. asioObject->getChannels (&newInps, &newOuts);
  213634. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213635. {
  213636. totalNumInputChans = newInps;
  213637. totalNumOutputChans = newOuts;
  213638. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213639. }
  213640. updateSampleRates();
  213641. ASIOChannelInfo channelInfo;
  213642. channelInfo.type = 0;
  213643. for (i = 0; i < totalNumInputChans; ++i)
  213644. {
  213645. zerostruct (channelInfo);
  213646. channelInfo.channel = i;
  213647. channelInfo.isInput = 1;
  213648. asioObject->getChannelInfo (&channelInfo);
  213649. inputChannelNames.add (String (channelInfo.name));
  213650. }
  213651. for (i = 0; i < totalNumOutputChans; ++i)
  213652. {
  213653. zerostruct (channelInfo);
  213654. channelInfo.channel = i;
  213655. channelInfo.isInput = 0;
  213656. asioObject->getChannelInfo (&channelInfo);
  213657. outputChannelNames.add (String (channelInfo.name));
  213658. typeToFormatParameters (channelInfo.type,
  213659. outputChannelBitDepths[i],
  213660. outputChannelBytesPerSample[i],
  213661. outputChannelIsFloat[i],
  213662. outputChannelLittleEndian[i]);
  213663. if (i < 2)
  213664. {
  213665. // clear the channels that are used with the dummy stuff
  213666. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213667. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213668. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213669. }
  213670. }
  213671. outputChannelNames.trim();
  213672. inputChannelNames.trim();
  213673. outputChannelNames.appendNumbersToDuplicates (false, true);
  213674. inputChannelNames.appendNumbersToDuplicates (false, true);
  213675. // start and stop because cubase does it..
  213676. asioObject->getLatencies (&inputLatency, &outputLatency);
  213677. if ((err = asioObject->start()) != 0)
  213678. {
  213679. // ignore an error here, as it might start later after setting other stuff up
  213680. logError ("ASIO start", err);
  213681. }
  213682. Thread::sleep (100);
  213683. asioObject->stop();
  213684. }
  213685. else
  213686. {
  213687. error = "Can't detect buffer sizes";
  213688. }
  213689. }
  213690. else
  213691. {
  213692. error = "Can't detect asio channels";
  213693. }
  213694. }
  213695. }
  213696. else
  213697. {
  213698. error = "No such device";
  213699. }
  213700. if (error.isNotEmpty())
  213701. {
  213702. logError (error, err);
  213703. if (asioObject != 0)
  213704. asioObject->disposeBuffers();
  213705. removeCurrentDriver();
  213706. isASIOOpen = false;
  213707. }
  213708. else
  213709. {
  213710. isASIOOpen = true;
  213711. log ("ASIO device open");
  213712. }
  213713. isOpen_ = false;
  213714. needToReset = false;
  213715. isReSync = false;
  213716. return error;
  213717. }
  213718. void JUCE_ASIOCALLBACK callback (const long index)
  213719. {
  213720. if (isStarted)
  213721. {
  213722. bufferIndex = index;
  213723. processBuffer();
  213724. }
  213725. else
  213726. {
  213727. if (postOutput && (asioObject != 0))
  213728. asioObject->outputReady();
  213729. }
  213730. calledback = true;
  213731. }
  213732. void processBuffer()
  213733. {
  213734. const ASIOBufferInfo* const infos = bufferInfos;
  213735. const int bi = bufferIndex;
  213736. const ScopedLock sl (callbackLock);
  213737. if (needToReset)
  213738. {
  213739. needToReset = false;
  213740. if (isReSync)
  213741. {
  213742. log ("! ASIO resync");
  213743. isReSync = false;
  213744. }
  213745. else
  213746. {
  213747. startTimer (20);
  213748. }
  213749. }
  213750. if (bi >= 0)
  213751. {
  213752. const int samps = currentBlockSizeSamples;
  213753. if (currentCallback != 0)
  213754. {
  213755. int i;
  213756. for (i = 0; i < numActiveInputChans; ++i)
  213757. {
  213758. float* const dst = inBuffers[i];
  213759. jassert (dst != 0);
  213760. const char* const src = (const char*) (infos[i].buffers[bi]);
  213761. if (inputChannelIsFloat[i])
  213762. {
  213763. memcpy (dst, src, samps * sizeof (float));
  213764. }
  213765. else
  213766. {
  213767. jassert (dst == tempBuffer + (samps * i));
  213768. switch (inputChannelBitDepths[i])
  213769. {
  213770. case 16:
  213771. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213772. samps, inputChannelLittleEndian[i]);
  213773. break;
  213774. case 24:
  213775. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213776. samps, inputChannelLittleEndian[i]);
  213777. break;
  213778. case 32:
  213779. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213780. samps, inputChannelLittleEndian[i]);
  213781. break;
  213782. case 64:
  213783. jassertfalse;
  213784. break;
  213785. }
  213786. }
  213787. }
  213788. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213789. outBuffers, numActiveOutputChans, samps);
  213790. for (i = 0; i < numActiveOutputChans; ++i)
  213791. {
  213792. float* const src = outBuffers[i];
  213793. jassert (src != 0);
  213794. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213795. if (outputChannelIsFloat[i])
  213796. {
  213797. memcpy (dst, src, samps * sizeof (float));
  213798. }
  213799. else
  213800. {
  213801. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213802. switch (outputChannelBitDepths[i])
  213803. {
  213804. case 16:
  213805. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213806. samps, outputChannelLittleEndian[i]);
  213807. break;
  213808. case 24:
  213809. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213810. samps, outputChannelLittleEndian[i]);
  213811. break;
  213812. case 32:
  213813. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213814. samps, outputChannelLittleEndian[i]);
  213815. break;
  213816. case 64:
  213817. jassertfalse;
  213818. break;
  213819. }
  213820. }
  213821. }
  213822. }
  213823. else
  213824. {
  213825. for (int i = 0; i < numActiveOutputChans; ++i)
  213826. {
  213827. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213828. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213829. }
  213830. }
  213831. }
  213832. if (postOutput)
  213833. asioObject->outputReady();
  213834. }
  213835. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213836. {
  213837. if (currentASIODev[0] != 0)
  213838. currentASIODev[0]->callback (index);
  213839. return 0;
  213840. }
  213841. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213842. {
  213843. if (currentASIODev[1] != 0)
  213844. currentASIODev[1]->callback (index);
  213845. return 0;
  213846. }
  213847. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213848. {
  213849. if (currentASIODev[2] != 0)
  213850. currentASIODev[2]->callback (index);
  213851. return 0;
  213852. }
  213853. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213854. {
  213855. if (currentASIODev[0] != 0)
  213856. currentASIODev[0]->callback (index);
  213857. }
  213858. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213859. {
  213860. if (currentASIODev[1] != 0)
  213861. currentASIODev[1]->callback (index);
  213862. }
  213863. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213864. {
  213865. if (currentASIODev[2] != 0)
  213866. currentASIODev[2]->callback (index);
  213867. }
  213868. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  213869. {
  213870. return asioMessagesCallback (selector, value, 0);
  213871. }
  213872. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  213873. {
  213874. return asioMessagesCallback (selector, value, 1);
  213875. }
  213876. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  213877. {
  213878. return asioMessagesCallback (selector, value, 2);
  213879. }
  213880. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  213881. {
  213882. switch (selector)
  213883. {
  213884. case kAsioSelectorSupported:
  213885. if (value == kAsioResetRequest
  213886. || value == kAsioEngineVersion
  213887. || value == kAsioResyncRequest
  213888. || value == kAsioLatenciesChanged
  213889. || value == kAsioSupportsInputMonitor)
  213890. return 1;
  213891. break;
  213892. case kAsioBufferSizeChange:
  213893. break;
  213894. case kAsioResetRequest:
  213895. if (currentASIODev[deviceIndex] != 0)
  213896. currentASIODev[deviceIndex]->resetRequest();
  213897. return 1;
  213898. case kAsioResyncRequest:
  213899. if (currentASIODev[deviceIndex] != 0)
  213900. currentASIODev[deviceIndex]->resyncRequest();
  213901. return 1;
  213902. case kAsioLatenciesChanged:
  213903. return 1;
  213904. case kAsioEngineVersion:
  213905. return 2;
  213906. case kAsioSupportsTimeInfo:
  213907. case kAsioSupportsTimeCode:
  213908. return 0;
  213909. }
  213910. return 0;
  213911. }
  213912. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213913. {
  213914. }
  213915. static void convertInt16ToFloat (const char* src,
  213916. float* dest,
  213917. const int srcStrideBytes,
  213918. int numSamples,
  213919. const bool littleEndian) throw()
  213920. {
  213921. const double g = 1.0 / 32768.0;
  213922. if (littleEndian)
  213923. {
  213924. while (--numSamples >= 0)
  213925. {
  213926. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213927. src += srcStrideBytes;
  213928. }
  213929. }
  213930. else
  213931. {
  213932. while (--numSamples >= 0)
  213933. {
  213934. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213935. src += srcStrideBytes;
  213936. }
  213937. }
  213938. }
  213939. static void convertFloatToInt16 (const float* src,
  213940. char* dest,
  213941. const int dstStrideBytes,
  213942. int numSamples,
  213943. const bool littleEndian) throw()
  213944. {
  213945. const double maxVal = (double) 0x7fff;
  213946. if (littleEndian)
  213947. {
  213948. while (--numSamples >= 0)
  213949. {
  213950. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213951. dest += dstStrideBytes;
  213952. }
  213953. }
  213954. else
  213955. {
  213956. while (--numSamples >= 0)
  213957. {
  213958. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213959. dest += dstStrideBytes;
  213960. }
  213961. }
  213962. }
  213963. static void convertInt24ToFloat (const char* src,
  213964. float* dest,
  213965. const int srcStrideBytes,
  213966. int numSamples,
  213967. const bool littleEndian) throw()
  213968. {
  213969. const double g = 1.0 / 0x7fffff;
  213970. if (littleEndian)
  213971. {
  213972. while (--numSamples >= 0)
  213973. {
  213974. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213975. src += srcStrideBytes;
  213976. }
  213977. }
  213978. else
  213979. {
  213980. while (--numSamples >= 0)
  213981. {
  213982. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213983. src += srcStrideBytes;
  213984. }
  213985. }
  213986. }
  213987. static void convertFloatToInt24 (const float* src,
  213988. char* dest,
  213989. const int dstStrideBytes,
  213990. int numSamples,
  213991. const bool littleEndian) throw()
  213992. {
  213993. const double maxVal = (double) 0x7fffff;
  213994. if (littleEndian)
  213995. {
  213996. while (--numSamples >= 0)
  213997. {
  213998. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213999. dest += dstStrideBytes;
  214000. }
  214001. }
  214002. else
  214003. {
  214004. while (--numSamples >= 0)
  214005. {
  214006. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214007. dest += dstStrideBytes;
  214008. }
  214009. }
  214010. }
  214011. static void convertInt32ToFloat (const char* src,
  214012. float* dest,
  214013. const int srcStrideBytes,
  214014. int numSamples,
  214015. const bool littleEndian) throw()
  214016. {
  214017. const double g = 1.0 / 0x7fffffff;
  214018. if (littleEndian)
  214019. {
  214020. while (--numSamples >= 0)
  214021. {
  214022. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  214023. src += srcStrideBytes;
  214024. }
  214025. }
  214026. else
  214027. {
  214028. while (--numSamples >= 0)
  214029. {
  214030. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  214031. src += srcStrideBytes;
  214032. }
  214033. }
  214034. }
  214035. static void convertFloatToInt32 (const float* src,
  214036. char* dest,
  214037. const int dstStrideBytes,
  214038. int numSamples,
  214039. const bool littleEndian) throw()
  214040. {
  214041. const double maxVal = (double) 0x7fffffff;
  214042. if (littleEndian)
  214043. {
  214044. while (--numSamples >= 0)
  214045. {
  214046. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214047. dest += dstStrideBytes;
  214048. }
  214049. }
  214050. else
  214051. {
  214052. while (--numSamples >= 0)
  214053. {
  214054. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214055. dest += dstStrideBytes;
  214056. }
  214057. }
  214058. }
  214059. static void typeToFormatParameters (const long type,
  214060. int& bitDepth,
  214061. int& byteStride,
  214062. bool& formatIsFloat,
  214063. bool& littleEndian) throw()
  214064. {
  214065. bitDepth = 0;
  214066. littleEndian = false;
  214067. formatIsFloat = false;
  214068. switch (type)
  214069. {
  214070. case ASIOSTInt16MSB:
  214071. case ASIOSTInt16LSB:
  214072. case ASIOSTInt32MSB16:
  214073. case ASIOSTInt32LSB16:
  214074. bitDepth = 16; break;
  214075. case ASIOSTFloat32MSB:
  214076. case ASIOSTFloat32LSB:
  214077. formatIsFloat = true;
  214078. bitDepth = 32; break;
  214079. case ASIOSTInt32MSB:
  214080. case ASIOSTInt32LSB:
  214081. bitDepth = 32; break;
  214082. case ASIOSTInt24MSB:
  214083. case ASIOSTInt24LSB:
  214084. case ASIOSTInt32MSB24:
  214085. case ASIOSTInt32LSB24:
  214086. case ASIOSTInt32MSB18:
  214087. case ASIOSTInt32MSB20:
  214088. case ASIOSTInt32LSB18:
  214089. case ASIOSTInt32LSB20:
  214090. bitDepth = 24; break;
  214091. case ASIOSTFloat64MSB:
  214092. case ASIOSTFloat64LSB:
  214093. default:
  214094. bitDepth = 64;
  214095. break;
  214096. }
  214097. switch (type)
  214098. {
  214099. case ASIOSTInt16MSB:
  214100. case ASIOSTInt32MSB16:
  214101. case ASIOSTFloat32MSB:
  214102. case ASIOSTFloat64MSB:
  214103. case ASIOSTInt32MSB:
  214104. case ASIOSTInt32MSB18:
  214105. case ASIOSTInt32MSB20:
  214106. case ASIOSTInt32MSB24:
  214107. case ASIOSTInt24MSB:
  214108. littleEndian = false; break;
  214109. case ASIOSTInt16LSB:
  214110. case ASIOSTInt32LSB16:
  214111. case ASIOSTFloat32LSB:
  214112. case ASIOSTFloat64LSB:
  214113. case ASIOSTInt32LSB:
  214114. case ASIOSTInt32LSB18:
  214115. case ASIOSTInt32LSB20:
  214116. case ASIOSTInt32LSB24:
  214117. case ASIOSTInt24LSB:
  214118. littleEndian = true; break;
  214119. default:
  214120. break;
  214121. }
  214122. switch (type)
  214123. {
  214124. case ASIOSTInt16LSB:
  214125. case ASIOSTInt16MSB:
  214126. byteStride = 2; break;
  214127. case ASIOSTInt24LSB:
  214128. case ASIOSTInt24MSB:
  214129. byteStride = 3; break;
  214130. case ASIOSTInt32MSB16:
  214131. case ASIOSTInt32LSB16:
  214132. case ASIOSTInt32MSB:
  214133. case ASIOSTInt32MSB18:
  214134. case ASIOSTInt32MSB20:
  214135. case ASIOSTInt32MSB24:
  214136. case ASIOSTInt32LSB:
  214137. case ASIOSTInt32LSB18:
  214138. case ASIOSTInt32LSB20:
  214139. case ASIOSTInt32LSB24:
  214140. case ASIOSTFloat32LSB:
  214141. case ASIOSTFloat32MSB:
  214142. byteStride = 4; break;
  214143. case ASIOSTFloat64MSB:
  214144. case ASIOSTFloat64LSB:
  214145. byteStride = 8; break;
  214146. default:
  214147. break;
  214148. }
  214149. }
  214150. };
  214151. class ASIOAudioIODeviceType : public AudioIODeviceType
  214152. {
  214153. public:
  214154. ASIOAudioIODeviceType()
  214155. : AudioIODeviceType ("ASIO"),
  214156. hasScanned (false)
  214157. {
  214158. CoInitialize (0);
  214159. }
  214160. ~ASIOAudioIODeviceType()
  214161. {
  214162. }
  214163. void scanForDevices()
  214164. {
  214165. hasScanned = true;
  214166. deviceNames.clear();
  214167. classIds.clear();
  214168. HKEY hk = 0;
  214169. int index = 0;
  214170. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214171. {
  214172. for (;;)
  214173. {
  214174. char name [256];
  214175. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214176. {
  214177. addDriverInfo (name, hk);
  214178. }
  214179. else
  214180. {
  214181. break;
  214182. }
  214183. }
  214184. RegCloseKey (hk);
  214185. }
  214186. }
  214187. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214188. {
  214189. jassert (hasScanned); // need to call scanForDevices() before doing this
  214190. return deviceNames;
  214191. }
  214192. int getDefaultDeviceIndex (bool) const
  214193. {
  214194. jassert (hasScanned); // need to call scanForDevices() before doing this
  214195. for (int i = deviceNames.size(); --i >= 0;)
  214196. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214197. return i; // asio4all is a safe choice for a default..
  214198. #if JUCE_DEBUG
  214199. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214200. return 1; // (the digi m-box driver crashes the app when you run
  214201. // it in the debugger, which can be a bit annoying)
  214202. #endif
  214203. return 0;
  214204. }
  214205. static int findFreeSlot()
  214206. {
  214207. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214208. if (currentASIODev[i] == 0)
  214209. return i;
  214210. jassertfalse; // unfortunately you can only have a finite number
  214211. // of ASIO devices open at the same time..
  214212. return -1;
  214213. }
  214214. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214215. {
  214216. jassert (hasScanned); // need to call scanForDevices() before doing this
  214217. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214218. }
  214219. bool hasSeparateInputsAndOutputs() const { return false; }
  214220. AudioIODevice* createDevice (const String& outputDeviceName,
  214221. const String& inputDeviceName)
  214222. {
  214223. // ASIO can't open two different devices for input and output - they must be the same one.
  214224. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214225. jassert (hasScanned); // need to call scanForDevices() before doing this
  214226. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214227. : inputDeviceName);
  214228. if (index >= 0)
  214229. {
  214230. const int freeSlot = findFreeSlot();
  214231. if (freeSlot >= 0)
  214232. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214233. }
  214234. return 0;
  214235. }
  214236. juce_UseDebuggingNewOperator
  214237. private:
  214238. StringArray deviceNames;
  214239. OwnedArray <CLSID> classIds;
  214240. bool hasScanned;
  214241. static bool checkClassIsOk (const String& classId)
  214242. {
  214243. HKEY hk = 0;
  214244. bool ok = false;
  214245. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214246. {
  214247. int index = 0;
  214248. for (;;)
  214249. {
  214250. WCHAR buf [512];
  214251. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214252. {
  214253. if (classId.equalsIgnoreCase (buf))
  214254. {
  214255. HKEY subKey, pathKey;
  214256. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214257. {
  214258. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214259. {
  214260. WCHAR pathName [1024];
  214261. DWORD dtype = REG_SZ;
  214262. DWORD dsize = sizeof (pathName);
  214263. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214264. ok = File (pathName).exists();
  214265. RegCloseKey (pathKey);
  214266. }
  214267. RegCloseKey (subKey);
  214268. }
  214269. break;
  214270. }
  214271. }
  214272. else
  214273. {
  214274. break;
  214275. }
  214276. }
  214277. RegCloseKey (hk);
  214278. }
  214279. return ok;
  214280. }
  214281. void addDriverInfo (const String& keyName, HKEY hk)
  214282. {
  214283. HKEY subKey;
  214284. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214285. {
  214286. WCHAR buf [256];
  214287. zerostruct (buf);
  214288. DWORD dtype = REG_SZ;
  214289. DWORD dsize = sizeof (buf);
  214290. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214291. {
  214292. if (dsize > 0 && checkClassIsOk (buf))
  214293. {
  214294. CLSID classId;
  214295. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214296. {
  214297. dtype = REG_SZ;
  214298. dsize = sizeof (buf);
  214299. String deviceName;
  214300. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214301. deviceName = buf;
  214302. else
  214303. deviceName = keyName;
  214304. log ("found " + deviceName);
  214305. deviceNames.add (deviceName);
  214306. classIds.add (new CLSID (classId));
  214307. }
  214308. }
  214309. RegCloseKey (subKey);
  214310. }
  214311. }
  214312. }
  214313. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214314. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214315. };
  214316. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214317. {
  214318. return new ASIOAudioIODeviceType();
  214319. }
  214320. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214321. void* guid,
  214322. const String& optionalDllForDirectLoading)
  214323. {
  214324. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214325. if (freeSlot < 0)
  214326. return 0;
  214327. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214328. }
  214329. #undef logError
  214330. #undef log
  214331. #endif
  214332. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214333. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214334. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214335. // compiled on its own).
  214336. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214337. END_JUCE_NAMESPACE
  214338. extern "C"
  214339. {
  214340. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214341. typedef struct typeDSBUFFERDESC
  214342. {
  214343. DWORD dwSize;
  214344. DWORD dwFlags;
  214345. DWORD dwBufferBytes;
  214346. DWORD dwReserved;
  214347. LPWAVEFORMATEX lpwfxFormat;
  214348. GUID guid3DAlgorithm;
  214349. } DSBUFFERDESC;
  214350. struct IDirectSoundBuffer;
  214351. #undef INTERFACE
  214352. #define INTERFACE IDirectSound
  214353. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214354. {
  214355. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214356. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214357. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214358. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214359. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214360. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214361. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214362. STDMETHOD(Compact) (THIS) PURE;
  214363. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214364. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214365. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214366. };
  214367. #undef INTERFACE
  214368. #define INTERFACE IDirectSoundBuffer
  214369. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214370. {
  214371. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214372. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214373. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214374. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214375. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214376. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214377. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214378. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214379. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214380. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214381. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214382. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214383. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214384. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214385. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214386. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214387. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214388. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214389. STDMETHOD(Stop) (THIS) PURE;
  214390. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214391. STDMETHOD(Restore) (THIS) PURE;
  214392. };
  214393. typedef struct typeDSCBUFFERDESC
  214394. {
  214395. DWORD dwSize;
  214396. DWORD dwFlags;
  214397. DWORD dwBufferBytes;
  214398. DWORD dwReserved;
  214399. LPWAVEFORMATEX lpwfxFormat;
  214400. } DSCBUFFERDESC;
  214401. struct IDirectSoundCaptureBuffer;
  214402. #undef INTERFACE
  214403. #define INTERFACE IDirectSoundCapture
  214404. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214405. {
  214406. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214407. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214408. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214409. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214410. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214411. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214412. };
  214413. #undef INTERFACE
  214414. #define INTERFACE IDirectSoundCaptureBuffer
  214415. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214416. {
  214417. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214418. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214419. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214420. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214421. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214422. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214423. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214424. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214425. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214426. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214427. STDMETHOD(Stop) (THIS) PURE;
  214428. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214429. };
  214430. };
  214431. BEGIN_JUCE_NAMESPACE
  214432. namespace
  214433. {
  214434. const String getDSErrorMessage (HRESULT hr)
  214435. {
  214436. const char* result = 0;
  214437. switch (hr)
  214438. {
  214439. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214440. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214441. case E_INVALIDARG: result = "Invalid parameter"; break;
  214442. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214443. case E_FAIL: result = "Generic error"; break;
  214444. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214445. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214446. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214447. case E_NOTIMPL: result = "Unsupported function"; break;
  214448. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214449. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214450. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214451. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214452. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214453. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214454. case E_NOINTERFACE: result = "No interface"; break;
  214455. case S_OK: result = "No error"; break;
  214456. default: return "Unknown error: " + String ((int) hr);
  214457. }
  214458. return result;
  214459. }
  214460. #define DS_DEBUGGING 1
  214461. #ifdef DS_DEBUGGING
  214462. #define CATCH JUCE_CATCH_EXCEPTION
  214463. #undef log
  214464. #define log(a) Logger::writeToLog(a);
  214465. #undef logError
  214466. #define logError(a) logDSError(a, __LINE__);
  214467. static void logDSError (HRESULT hr, int lineNum)
  214468. {
  214469. if (hr != S_OK)
  214470. {
  214471. String error ("DS error at line ");
  214472. error << lineNum << " - " << getDSErrorMessage (hr);
  214473. log (error);
  214474. }
  214475. }
  214476. #else
  214477. #define CATCH JUCE_CATCH_ALL
  214478. #define log(a)
  214479. #define logError(a)
  214480. #endif
  214481. #define DSOUND_FUNCTION(functionName, params) \
  214482. typedef HRESULT (WINAPI *type##functionName) params; \
  214483. static type##functionName ds##functionName = 0;
  214484. #define DSOUND_FUNCTION_LOAD(functionName) \
  214485. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214486. jassert (ds##functionName != 0);
  214487. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214488. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214489. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214490. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214491. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214492. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214493. void initialiseDSoundFunctions()
  214494. {
  214495. if (dsDirectSoundCreate == 0)
  214496. {
  214497. HMODULE h = LoadLibraryA ("dsound.dll");
  214498. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214499. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214500. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214501. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214502. }
  214503. }
  214504. }
  214505. class DSoundInternalOutChannel
  214506. {
  214507. String name;
  214508. LPGUID guid;
  214509. int sampleRate, bufferSizeSamples;
  214510. float* leftBuffer;
  214511. float* rightBuffer;
  214512. IDirectSound* pDirectSound;
  214513. IDirectSoundBuffer* pOutputBuffer;
  214514. DWORD writeOffset;
  214515. int totalBytesPerBuffer;
  214516. int bytesPerBuffer;
  214517. unsigned int lastPlayCursor;
  214518. public:
  214519. int bitDepth;
  214520. bool doneFlag;
  214521. DSoundInternalOutChannel (const String& name_,
  214522. LPGUID guid_,
  214523. int rate,
  214524. int bufferSize,
  214525. float* left,
  214526. float* right)
  214527. : name (name_),
  214528. guid (guid_),
  214529. sampleRate (rate),
  214530. bufferSizeSamples (bufferSize),
  214531. leftBuffer (left),
  214532. rightBuffer (right),
  214533. pDirectSound (0),
  214534. pOutputBuffer (0),
  214535. bitDepth (16)
  214536. {
  214537. }
  214538. ~DSoundInternalOutChannel()
  214539. {
  214540. close();
  214541. }
  214542. void close()
  214543. {
  214544. HRESULT hr;
  214545. if (pOutputBuffer != 0)
  214546. {
  214547. JUCE_TRY
  214548. {
  214549. log ("closing dsound out: " + name);
  214550. hr = pOutputBuffer->Stop();
  214551. logError (hr);
  214552. }
  214553. CATCH
  214554. JUCE_TRY
  214555. {
  214556. hr = pOutputBuffer->Release();
  214557. logError (hr);
  214558. }
  214559. CATCH
  214560. pOutputBuffer = 0;
  214561. }
  214562. if (pDirectSound != 0)
  214563. {
  214564. JUCE_TRY
  214565. {
  214566. hr = pDirectSound->Release();
  214567. logError (hr);
  214568. }
  214569. CATCH
  214570. pDirectSound = 0;
  214571. }
  214572. }
  214573. const String open()
  214574. {
  214575. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214576. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214577. pDirectSound = 0;
  214578. pOutputBuffer = 0;
  214579. writeOffset = 0;
  214580. String error;
  214581. HRESULT hr = E_NOINTERFACE;
  214582. if (dsDirectSoundCreate != 0)
  214583. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214584. if (hr == S_OK)
  214585. {
  214586. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214587. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214588. const int numChannels = 2;
  214589. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214590. logError (hr);
  214591. if (hr == S_OK)
  214592. {
  214593. IDirectSoundBuffer* pPrimaryBuffer;
  214594. DSBUFFERDESC primaryDesc;
  214595. zerostruct (primaryDesc);
  214596. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214597. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214598. primaryDesc.dwBufferBytes = 0;
  214599. primaryDesc.lpwfxFormat = 0;
  214600. log ("opening dsound out step 2");
  214601. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214602. logError (hr);
  214603. if (hr == S_OK)
  214604. {
  214605. WAVEFORMATEX wfFormat;
  214606. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214607. wfFormat.nChannels = (unsigned short) numChannels;
  214608. wfFormat.nSamplesPerSec = sampleRate;
  214609. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214610. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214611. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214612. wfFormat.cbSize = 0;
  214613. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214614. logError (hr);
  214615. if (hr == S_OK)
  214616. {
  214617. DSBUFFERDESC secondaryDesc;
  214618. zerostruct (secondaryDesc);
  214619. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214620. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214621. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214622. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214623. secondaryDesc.lpwfxFormat = &wfFormat;
  214624. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214625. logError (hr);
  214626. if (hr == S_OK)
  214627. {
  214628. log ("opening dsound out step 3");
  214629. DWORD dwDataLen;
  214630. unsigned char* pDSBuffData;
  214631. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214632. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214633. logError (hr);
  214634. if (hr == S_OK)
  214635. {
  214636. zeromem (pDSBuffData, dwDataLen);
  214637. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214638. if (hr == S_OK)
  214639. {
  214640. hr = pOutputBuffer->SetCurrentPosition (0);
  214641. if (hr == S_OK)
  214642. {
  214643. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214644. if (hr == S_OK)
  214645. return String::empty;
  214646. }
  214647. }
  214648. }
  214649. }
  214650. }
  214651. }
  214652. }
  214653. }
  214654. error = getDSErrorMessage (hr);
  214655. close();
  214656. return error;
  214657. }
  214658. void synchronisePosition()
  214659. {
  214660. if (pOutputBuffer != 0)
  214661. {
  214662. DWORD playCursor;
  214663. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214664. }
  214665. }
  214666. bool service()
  214667. {
  214668. if (pOutputBuffer == 0)
  214669. return true;
  214670. DWORD playCursor, writeCursor;
  214671. for (;;)
  214672. {
  214673. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214674. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214675. {
  214676. pOutputBuffer->Restore();
  214677. continue;
  214678. }
  214679. if (hr == S_OK)
  214680. break;
  214681. logError (hr);
  214682. jassertfalse;
  214683. return true;
  214684. }
  214685. int playWriteGap = writeCursor - playCursor;
  214686. if (playWriteGap < 0)
  214687. playWriteGap += totalBytesPerBuffer;
  214688. int bytesEmpty = playCursor - writeOffset;
  214689. if (bytesEmpty < 0)
  214690. bytesEmpty += totalBytesPerBuffer;
  214691. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214692. {
  214693. writeOffset = writeCursor;
  214694. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214695. }
  214696. if (bytesEmpty >= bytesPerBuffer)
  214697. {
  214698. void* lpbuf1 = 0;
  214699. void* lpbuf2 = 0;
  214700. DWORD dwSize1 = 0;
  214701. DWORD dwSize2 = 0;
  214702. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214703. bytesPerBuffer,
  214704. &lpbuf1, &dwSize1,
  214705. &lpbuf2, &dwSize2, 0);
  214706. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214707. {
  214708. pOutputBuffer->Restore();
  214709. hr = pOutputBuffer->Lock (writeOffset,
  214710. bytesPerBuffer,
  214711. &lpbuf1, &dwSize1,
  214712. &lpbuf2, &dwSize2, 0);
  214713. }
  214714. if (hr == S_OK)
  214715. {
  214716. if (bitDepth == 16)
  214717. {
  214718. const float gainL = 32767.0f;
  214719. const float gainR = 32767.0f;
  214720. int* dest = static_cast<int*> (lpbuf1);
  214721. const float* left = leftBuffer;
  214722. const float* right = rightBuffer;
  214723. int samples1 = dwSize1 >> 2;
  214724. int samples2 = dwSize2 >> 2;
  214725. if (left == 0)
  214726. {
  214727. while (--samples1 >= 0)
  214728. {
  214729. int r = roundToInt (gainR * *right++);
  214730. if (r < -32768)
  214731. r = -32768;
  214732. else if (r > 32767)
  214733. r = 32767;
  214734. *dest++ = (r << 16);
  214735. }
  214736. dest = static_cast<int*> (lpbuf2);
  214737. while (--samples2 >= 0)
  214738. {
  214739. int r = roundToInt (gainR * *right++);
  214740. if (r < -32768)
  214741. r = -32768;
  214742. else if (r > 32767)
  214743. r = 32767;
  214744. *dest++ = (r << 16);
  214745. }
  214746. }
  214747. else if (right == 0)
  214748. {
  214749. while (--samples1 >= 0)
  214750. {
  214751. int l = roundToInt (gainL * *left++);
  214752. if (l < -32768)
  214753. l = -32768;
  214754. else if (l > 32767)
  214755. l = 32767;
  214756. l &= 0xffff;
  214757. *dest++ = l;
  214758. }
  214759. dest = static_cast<int*> (lpbuf2);
  214760. while (--samples2 >= 0)
  214761. {
  214762. int l = roundToInt (gainL * *left++);
  214763. if (l < -32768)
  214764. l = -32768;
  214765. else if (l > 32767)
  214766. l = 32767;
  214767. l &= 0xffff;
  214768. *dest++ = l;
  214769. }
  214770. }
  214771. else
  214772. {
  214773. while (--samples1 >= 0)
  214774. {
  214775. int l = roundToInt (gainL * *left++);
  214776. if (l < -32768)
  214777. l = -32768;
  214778. else if (l > 32767)
  214779. l = 32767;
  214780. l &= 0xffff;
  214781. int r = roundToInt (gainR * *right++);
  214782. if (r < -32768)
  214783. r = -32768;
  214784. else if (r > 32767)
  214785. r = 32767;
  214786. *dest++ = (r << 16) | l;
  214787. }
  214788. dest = static_cast<int*> (lpbuf2);
  214789. while (--samples2 >= 0)
  214790. {
  214791. int l = roundToInt (gainL * *left++);
  214792. if (l < -32768)
  214793. l = -32768;
  214794. else if (l > 32767)
  214795. l = 32767;
  214796. l &= 0xffff;
  214797. int r = roundToInt (gainR * *right++);
  214798. if (r < -32768)
  214799. r = -32768;
  214800. else if (r > 32767)
  214801. r = 32767;
  214802. *dest++ = (r << 16) | l;
  214803. }
  214804. }
  214805. }
  214806. else
  214807. {
  214808. jassertfalse;
  214809. }
  214810. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214811. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214812. }
  214813. else
  214814. {
  214815. jassertfalse;
  214816. logError (hr);
  214817. }
  214818. bytesEmpty -= bytesPerBuffer;
  214819. return true;
  214820. }
  214821. else
  214822. {
  214823. return false;
  214824. }
  214825. }
  214826. };
  214827. struct DSoundInternalInChannel
  214828. {
  214829. String name;
  214830. LPGUID guid;
  214831. int sampleRate, bufferSizeSamples;
  214832. float* leftBuffer;
  214833. float* rightBuffer;
  214834. IDirectSound* pDirectSound;
  214835. IDirectSoundCapture* pDirectSoundCapture;
  214836. IDirectSoundCaptureBuffer* pInputBuffer;
  214837. public:
  214838. unsigned int readOffset;
  214839. int bytesPerBuffer, totalBytesPerBuffer;
  214840. int bitDepth;
  214841. bool doneFlag;
  214842. DSoundInternalInChannel (const String& name_,
  214843. LPGUID guid_,
  214844. int rate,
  214845. int bufferSize,
  214846. float* left,
  214847. float* right)
  214848. : name (name_),
  214849. guid (guid_),
  214850. sampleRate (rate),
  214851. bufferSizeSamples (bufferSize),
  214852. leftBuffer (left),
  214853. rightBuffer (right),
  214854. pDirectSound (0),
  214855. pDirectSoundCapture (0),
  214856. pInputBuffer (0),
  214857. bitDepth (16)
  214858. {
  214859. }
  214860. ~DSoundInternalInChannel()
  214861. {
  214862. close();
  214863. }
  214864. void close()
  214865. {
  214866. HRESULT hr;
  214867. if (pInputBuffer != 0)
  214868. {
  214869. JUCE_TRY
  214870. {
  214871. log ("closing dsound in: " + name);
  214872. hr = pInputBuffer->Stop();
  214873. logError (hr);
  214874. }
  214875. CATCH
  214876. JUCE_TRY
  214877. {
  214878. hr = pInputBuffer->Release();
  214879. logError (hr);
  214880. }
  214881. CATCH
  214882. pInputBuffer = 0;
  214883. }
  214884. if (pDirectSoundCapture != 0)
  214885. {
  214886. JUCE_TRY
  214887. {
  214888. hr = pDirectSoundCapture->Release();
  214889. logError (hr);
  214890. }
  214891. CATCH
  214892. pDirectSoundCapture = 0;
  214893. }
  214894. if (pDirectSound != 0)
  214895. {
  214896. JUCE_TRY
  214897. {
  214898. hr = pDirectSound->Release();
  214899. logError (hr);
  214900. }
  214901. CATCH
  214902. pDirectSound = 0;
  214903. }
  214904. }
  214905. const String open()
  214906. {
  214907. log ("opening dsound in device: " + name
  214908. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214909. pDirectSound = 0;
  214910. pDirectSoundCapture = 0;
  214911. pInputBuffer = 0;
  214912. readOffset = 0;
  214913. totalBytesPerBuffer = 0;
  214914. String error;
  214915. HRESULT hr = E_NOINTERFACE;
  214916. if (dsDirectSoundCaptureCreate != 0)
  214917. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214918. logError (hr);
  214919. if (hr == S_OK)
  214920. {
  214921. const int numChannels = 2;
  214922. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214923. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214924. WAVEFORMATEX wfFormat;
  214925. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214926. wfFormat.nChannels = (unsigned short)numChannels;
  214927. wfFormat.nSamplesPerSec = sampleRate;
  214928. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214929. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214930. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214931. wfFormat.cbSize = 0;
  214932. DSCBUFFERDESC captureDesc;
  214933. zerostruct (captureDesc);
  214934. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214935. captureDesc.dwFlags = 0;
  214936. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214937. captureDesc.lpwfxFormat = &wfFormat;
  214938. log ("opening dsound in step 2");
  214939. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214940. logError (hr);
  214941. if (hr == S_OK)
  214942. {
  214943. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214944. logError (hr);
  214945. if (hr == S_OK)
  214946. return String::empty;
  214947. }
  214948. }
  214949. error = getDSErrorMessage (hr);
  214950. close();
  214951. return error;
  214952. }
  214953. void synchronisePosition()
  214954. {
  214955. if (pInputBuffer != 0)
  214956. {
  214957. DWORD capturePos;
  214958. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214959. }
  214960. }
  214961. bool service()
  214962. {
  214963. if (pInputBuffer == 0)
  214964. return true;
  214965. DWORD capturePos, readPos;
  214966. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214967. logError (hr);
  214968. if (hr != S_OK)
  214969. return true;
  214970. int bytesFilled = readPos - readOffset;
  214971. if (bytesFilled < 0)
  214972. bytesFilled += totalBytesPerBuffer;
  214973. if (bytesFilled >= bytesPerBuffer)
  214974. {
  214975. LPBYTE lpbuf1 = 0;
  214976. LPBYTE lpbuf2 = 0;
  214977. DWORD dwsize1 = 0;
  214978. DWORD dwsize2 = 0;
  214979. HRESULT hr = pInputBuffer->Lock (readOffset,
  214980. bytesPerBuffer,
  214981. (void**) &lpbuf1, &dwsize1,
  214982. (void**) &lpbuf2, &dwsize2, 0);
  214983. if (hr == S_OK)
  214984. {
  214985. if (bitDepth == 16)
  214986. {
  214987. const float g = 1.0f / 32768.0f;
  214988. float* destL = leftBuffer;
  214989. float* destR = rightBuffer;
  214990. int samples1 = dwsize1 >> 2;
  214991. int samples2 = dwsize2 >> 2;
  214992. const short* src = (const short*)lpbuf1;
  214993. if (destL == 0)
  214994. {
  214995. while (--samples1 >= 0)
  214996. {
  214997. ++src;
  214998. *destR++ = *src++ * g;
  214999. }
  215000. src = (const short*)lpbuf2;
  215001. while (--samples2 >= 0)
  215002. {
  215003. ++src;
  215004. *destR++ = *src++ * g;
  215005. }
  215006. }
  215007. else if (destR == 0)
  215008. {
  215009. while (--samples1 >= 0)
  215010. {
  215011. *destL++ = *src++ * g;
  215012. ++src;
  215013. }
  215014. src = (const short*)lpbuf2;
  215015. while (--samples2 >= 0)
  215016. {
  215017. *destL++ = *src++ * g;
  215018. ++src;
  215019. }
  215020. }
  215021. else
  215022. {
  215023. while (--samples1 >= 0)
  215024. {
  215025. *destL++ = *src++ * g;
  215026. *destR++ = *src++ * g;
  215027. }
  215028. src = (const short*)lpbuf2;
  215029. while (--samples2 >= 0)
  215030. {
  215031. *destL++ = *src++ * g;
  215032. *destR++ = *src++ * g;
  215033. }
  215034. }
  215035. }
  215036. else
  215037. {
  215038. jassertfalse;
  215039. }
  215040. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  215041. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  215042. }
  215043. else
  215044. {
  215045. logError (hr);
  215046. jassertfalse;
  215047. }
  215048. bytesFilled -= bytesPerBuffer;
  215049. return true;
  215050. }
  215051. else
  215052. {
  215053. return false;
  215054. }
  215055. }
  215056. };
  215057. class DSoundAudioIODevice : public AudioIODevice,
  215058. public Thread
  215059. {
  215060. public:
  215061. DSoundAudioIODevice (const String& deviceName,
  215062. const int outputDeviceIndex_,
  215063. const int inputDeviceIndex_)
  215064. : AudioIODevice (deviceName, "DirectSound"),
  215065. Thread ("Juce DSound"),
  215066. isOpen_ (false),
  215067. isStarted (false),
  215068. outputDeviceIndex (outputDeviceIndex_),
  215069. inputDeviceIndex (inputDeviceIndex_),
  215070. totalSamplesOut (0),
  215071. sampleRate (0.0),
  215072. inputBuffers (1, 1),
  215073. outputBuffers (1, 1),
  215074. callback (0),
  215075. bufferSizeSamples (0)
  215076. {
  215077. if (outputDeviceIndex_ >= 0)
  215078. {
  215079. outChannels.add (TRANS("Left"));
  215080. outChannels.add (TRANS("Right"));
  215081. }
  215082. if (inputDeviceIndex_ >= 0)
  215083. {
  215084. inChannels.add (TRANS("Left"));
  215085. inChannels.add (TRANS("Right"));
  215086. }
  215087. }
  215088. ~DSoundAudioIODevice()
  215089. {
  215090. close();
  215091. }
  215092. const StringArray getOutputChannelNames()
  215093. {
  215094. return outChannels;
  215095. }
  215096. const StringArray getInputChannelNames()
  215097. {
  215098. return inChannels;
  215099. }
  215100. int getNumSampleRates()
  215101. {
  215102. return 4;
  215103. }
  215104. double getSampleRate (int index)
  215105. {
  215106. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215107. return samps [jlimit (0, 3, index)];
  215108. }
  215109. int getNumBufferSizesAvailable()
  215110. {
  215111. return 50;
  215112. }
  215113. int getBufferSizeSamples (int index)
  215114. {
  215115. int n = 64;
  215116. for (int i = 0; i < index; ++i)
  215117. n += (n < 512) ? 32
  215118. : ((n < 1024) ? 64
  215119. : ((n < 2048) ? 128 : 256));
  215120. return n;
  215121. }
  215122. int getDefaultBufferSize()
  215123. {
  215124. return 2560;
  215125. }
  215126. const String open (const BigInteger& inputChannels,
  215127. const BigInteger& outputChannels,
  215128. double sampleRate,
  215129. int bufferSizeSamples)
  215130. {
  215131. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215132. isOpen_ = lastError.isEmpty();
  215133. return lastError;
  215134. }
  215135. void close()
  215136. {
  215137. stop();
  215138. if (isOpen_)
  215139. {
  215140. closeDevice();
  215141. isOpen_ = false;
  215142. }
  215143. }
  215144. bool isOpen()
  215145. {
  215146. return isOpen_ && isThreadRunning();
  215147. }
  215148. int getCurrentBufferSizeSamples()
  215149. {
  215150. return bufferSizeSamples;
  215151. }
  215152. double getCurrentSampleRate()
  215153. {
  215154. return sampleRate;
  215155. }
  215156. int getCurrentBitDepth()
  215157. {
  215158. int i, bits = 256;
  215159. for (i = inChans.size(); --i >= 0;)
  215160. bits = jmin (bits, inChans[i]->bitDepth);
  215161. for (i = outChans.size(); --i >= 0;)
  215162. bits = jmin (bits, outChans[i]->bitDepth);
  215163. if (bits > 32)
  215164. bits = 16;
  215165. return bits;
  215166. }
  215167. const BigInteger getActiveOutputChannels() const
  215168. {
  215169. return enabledOutputs;
  215170. }
  215171. const BigInteger getActiveInputChannels() const
  215172. {
  215173. return enabledInputs;
  215174. }
  215175. int getOutputLatencyInSamples()
  215176. {
  215177. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215178. }
  215179. int getInputLatencyInSamples()
  215180. {
  215181. return getOutputLatencyInSamples();
  215182. }
  215183. void start (AudioIODeviceCallback* call)
  215184. {
  215185. if (isOpen_ && call != 0 && ! isStarted)
  215186. {
  215187. if (! isThreadRunning())
  215188. {
  215189. // something gone wrong and the thread's stopped..
  215190. isOpen_ = false;
  215191. return;
  215192. }
  215193. call->audioDeviceAboutToStart (this);
  215194. const ScopedLock sl (startStopLock);
  215195. callback = call;
  215196. isStarted = true;
  215197. }
  215198. }
  215199. void stop()
  215200. {
  215201. if (isStarted)
  215202. {
  215203. AudioIODeviceCallback* const callbackLocal = callback;
  215204. {
  215205. const ScopedLock sl (startStopLock);
  215206. isStarted = false;
  215207. }
  215208. if (callbackLocal != 0)
  215209. callbackLocal->audioDeviceStopped();
  215210. }
  215211. }
  215212. bool isPlaying()
  215213. {
  215214. return isStarted && isOpen_ && isThreadRunning();
  215215. }
  215216. const String getLastError()
  215217. {
  215218. return lastError;
  215219. }
  215220. juce_UseDebuggingNewOperator
  215221. StringArray inChannels, outChannels;
  215222. int outputDeviceIndex, inputDeviceIndex;
  215223. private:
  215224. bool isOpen_;
  215225. bool isStarted;
  215226. String lastError;
  215227. OwnedArray <DSoundInternalInChannel> inChans;
  215228. OwnedArray <DSoundInternalOutChannel> outChans;
  215229. WaitableEvent startEvent;
  215230. int bufferSizeSamples;
  215231. int volatile totalSamplesOut;
  215232. int64 volatile lastBlockTime;
  215233. double sampleRate;
  215234. BigInteger enabledInputs, enabledOutputs;
  215235. AudioSampleBuffer inputBuffers, outputBuffers;
  215236. AudioIODeviceCallback* callback;
  215237. CriticalSection startStopLock;
  215238. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215239. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215240. const String openDevice (const BigInteger& inputChannels,
  215241. const BigInteger& outputChannels,
  215242. double sampleRate_,
  215243. int bufferSizeSamples_);
  215244. void closeDevice()
  215245. {
  215246. isStarted = false;
  215247. stopThread (5000);
  215248. inChans.clear();
  215249. outChans.clear();
  215250. inputBuffers.setSize (1, 1);
  215251. outputBuffers.setSize (1, 1);
  215252. }
  215253. void resync()
  215254. {
  215255. if (! threadShouldExit())
  215256. {
  215257. sleep (5);
  215258. int i;
  215259. for (i = 0; i < outChans.size(); ++i)
  215260. outChans.getUnchecked(i)->synchronisePosition();
  215261. for (i = 0; i < inChans.size(); ++i)
  215262. inChans.getUnchecked(i)->synchronisePosition();
  215263. }
  215264. }
  215265. public:
  215266. void run()
  215267. {
  215268. while (! threadShouldExit())
  215269. {
  215270. if (wait (100))
  215271. break;
  215272. }
  215273. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215274. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215275. while (! threadShouldExit())
  215276. {
  215277. int numToDo = 0;
  215278. uint32 startTime = Time::getMillisecondCounter();
  215279. int i;
  215280. for (i = inChans.size(); --i >= 0;)
  215281. {
  215282. inChans.getUnchecked(i)->doneFlag = false;
  215283. ++numToDo;
  215284. }
  215285. for (i = outChans.size(); --i >= 0;)
  215286. {
  215287. outChans.getUnchecked(i)->doneFlag = false;
  215288. ++numToDo;
  215289. }
  215290. if (numToDo > 0)
  215291. {
  215292. const int maxCount = 3;
  215293. int count = maxCount;
  215294. for (;;)
  215295. {
  215296. for (i = inChans.size(); --i >= 0;)
  215297. {
  215298. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215299. if ((! in->doneFlag) && in->service())
  215300. {
  215301. in->doneFlag = true;
  215302. --numToDo;
  215303. }
  215304. }
  215305. for (i = outChans.size(); --i >= 0;)
  215306. {
  215307. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215308. if ((! out->doneFlag) && out->service())
  215309. {
  215310. out->doneFlag = true;
  215311. --numToDo;
  215312. }
  215313. }
  215314. if (numToDo <= 0)
  215315. break;
  215316. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215317. {
  215318. resync();
  215319. break;
  215320. }
  215321. if (--count <= 0)
  215322. {
  215323. Sleep (1);
  215324. count = maxCount;
  215325. }
  215326. if (threadShouldExit())
  215327. return;
  215328. }
  215329. }
  215330. else
  215331. {
  215332. sleep (1);
  215333. }
  215334. const ScopedLock sl (startStopLock);
  215335. if (isStarted)
  215336. {
  215337. JUCE_TRY
  215338. {
  215339. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215340. inputBuffers.getNumChannels(),
  215341. outputBuffers.getArrayOfChannels(),
  215342. outputBuffers.getNumChannels(),
  215343. bufferSizeSamples);
  215344. }
  215345. JUCE_CATCH_EXCEPTION
  215346. totalSamplesOut += bufferSizeSamples;
  215347. }
  215348. else
  215349. {
  215350. outputBuffers.clear();
  215351. totalSamplesOut = 0;
  215352. sleep (1);
  215353. }
  215354. }
  215355. }
  215356. };
  215357. class DSoundAudioIODeviceType : public AudioIODeviceType
  215358. {
  215359. public:
  215360. DSoundAudioIODeviceType()
  215361. : AudioIODeviceType ("DirectSound"),
  215362. hasScanned (false)
  215363. {
  215364. initialiseDSoundFunctions();
  215365. }
  215366. ~DSoundAudioIODeviceType()
  215367. {
  215368. }
  215369. void scanForDevices()
  215370. {
  215371. hasScanned = true;
  215372. outputDeviceNames.clear();
  215373. outputGuids.clear();
  215374. inputDeviceNames.clear();
  215375. inputGuids.clear();
  215376. if (dsDirectSoundEnumerateW != 0)
  215377. {
  215378. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215379. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215380. }
  215381. }
  215382. const StringArray getDeviceNames (bool wantInputNames) const
  215383. {
  215384. jassert (hasScanned); // need to call scanForDevices() before doing this
  215385. return wantInputNames ? inputDeviceNames
  215386. : outputDeviceNames;
  215387. }
  215388. int getDefaultDeviceIndex (bool /*forInput*/) const
  215389. {
  215390. jassert (hasScanned); // need to call scanForDevices() before doing this
  215391. return 0;
  215392. }
  215393. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215394. {
  215395. jassert (hasScanned); // need to call scanForDevices() before doing this
  215396. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215397. if (d == 0)
  215398. return -1;
  215399. return asInput ? d->inputDeviceIndex
  215400. : d->outputDeviceIndex;
  215401. }
  215402. bool hasSeparateInputsAndOutputs() const { return true; }
  215403. AudioIODevice* createDevice (const String& outputDeviceName,
  215404. const String& inputDeviceName)
  215405. {
  215406. jassert (hasScanned); // need to call scanForDevices() before doing this
  215407. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215408. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215409. if (outputIndex >= 0 || inputIndex >= 0)
  215410. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215411. : inputDeviceName,
  215412. outputIndex, inputIndex);
  215413. return 0;
  215414. }
  215415. juce_UseDebuggingNewOperator
  215416. StringArray outputDeviceNames;
  215417. OwnedArray <GUID> outputGuids;
  215418. StringArray inputDeviceNames;
  215419. OwnedArray <GUID> inputGuids;
  215420. private:
  215421. bool hasScanned;
  215422. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215423. {
  215424. desc = desc.trim();
  215425. if (desc.isNotEmpty())
  215426. {
  215427. const String origDesc (desc);
  215428. int n = 2;
  215429. while (outputDeviceNames.contains (desc))
  215430. desc = origDesc + " (" + String (n++) + ")";
  215431. outputDeviceNames.add (desc);
  215432. if (lpGUID != 0)
  215433. outputGuids.add (new GUID (*lpGUID));
  215434. else
  215435. outputGuids.add (0);
  215436. }
  215437. return TRUE;
  215438. }
  215439. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215440. {
  215441. return ((DSoundAudioIODeviceType*) object)
  215442. ->outputEnumProc (lpGUID, String (description));
  215443. }
  215444. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215445. {
  215446. return ((DSoundAudioIODeviceType*) object)
  215447. ->outputEnumProc (lpGUID, String (description));
  215448. }
  215449. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215450. {
  215451. desc = desc.trim();
  215452. if (desc.isNotEmpty())
  215453. {
  215454. const String origDesc (desc);
  215455. int n = 2;
  215456. while (inputDeviceNames.contains (desc))
  215457. desc = origDesc + " (" + String (n++) + ")";
  215458. inputDeviceNames.add (desc);
  215459. if (lpGUID != 0)
  215460. inputGuids.add (new GUID (*lpGUID));
  215461. else
  215462. inputGuids.add (0);
  215463. }
  215464. return TRUE;
  215465. }
  215466. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215467. {
  215468. return ((DSoundAudioIODeviceType*) object)
  215469. ->inputEnumProc (lpGUID, String (description));
  215470. }
  215471. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215472. {
  215473. return ((DSoundAudioIODeviceType*) object)
  215474. ->inputEnumProc (lpGUID, String (description));
  215475. }
  215476. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215477. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215478. };
  215479. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215480. const BigInteger& outputChannels,
  215481. double sampleRate_,
  215482. int bufferSizeSamples_)
  215483. {
  215484. closeDevice();
  215485. totalSamplesOut = 0;
  215486. sampleRate = sampleRate_;
  215487. if (bufferSizeSamples_ <= 0)
  215488. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215489. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215490. DSoundAudioIODeviceType dlh;
  215491. dlh.scanForDevices();
  215492. enabledInputs = inputChannels;
  215493. enabledInputs.setRange (inChannels.size(),
  215494. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215495. false);
  215496. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215497. inputBuffers.clear();
  215498. int i, numIns = 0;
  215499. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215500. {
  215501. float* left = 0;
  215502. if (enabledInputs[i])
  215503. left = inputBuffers.getSampleData (numIns++);
  215504. float* right = 0;
  215505. if (enabledInputs[i + 1])
  215506. right = inputBuffers.getSampleData (numIns++);
  215507. if (left != 0 || right != 0)
  215508. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215509. dlh.inputGuids [inputDeviceIndex],
  215510. (int) sampleRate, bufferSizeSamples,
  215511. left, right));
  215512. }
  215513. enabledOutputs = outputChannels;
  215514. enabledOutputs.setRange (outChannels.size(),
  215515. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215516. false);
  215517. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215518. outputBuffers.clear();
  215519. int numOuts = 0;
  215520. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215521. {
  215522. float* left = 0;
  215523. if (enabledOutputs[i])
  215524. left = outputBuffers.getSampleData (numOuts++);
  215525. float* right = 0;
  215526. if (enabledOutputs[i + 1])
  215527. right = outputBuffers.getSampleData (numOuts++);
  215528. if (left != 0 || right != 0)
  215529. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215530. dlh.outputGuids [outputDeviceIndex],
  215531. (int) sampleRate, bufferSizeSamples,
  215532. left, right));
  215533. }
  215534. String error;
  215535. // boost our priority while opening the devices to try to get better sync between them
  215536. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215537. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215538. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215539. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215540. for (i = 0; i < outChans.size(); ++i)
  215541. {
  215542. error = outChans[i]->open();
  215543. if (error.isNotEmpty())
  215544. {
  215545. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215546. break;
  215547. }
  215548. }
  215549. if (error.isEmpty())
  215550. {
  215551. for (i = 0; i < inChans.size(); ++i)
  215552. {
  215553. error = inChans[i]->open();
  215554. if (error.isNotEmpty())
  215555. {
  215556. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215557. break;
  215558. }
  215559. }
  215560. }
  215561. if (error.isEmpty())
  215562. {
  215563. totalSamplesOut = 0;
  215564. for (i = 0; i < outChans.size(); ++i)
  215565. outChans.getUnchecked(i)->synchronisePosition();
  215566. for (i = 0; i < inChans.size(); ++i)
  215567. inChans.getUnchecked(i)->synchronisePosition();
  215568. startThread (9);
  215569. sleep (10);
  215570. notify();
  215571. }
  215572. else
  215573. {
  215574. log (error);
  215575. }
  215576. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215577. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215578. return error;
  215579. }
  215580. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215581. {
  215582. return new DSoundAudioIODeviceType();
  215583. }
  215584. #undef log
  215585. #endif
  215586. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215587. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215588. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215589. // compiled on its own).
  215590. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215591. #ifndef WASAPI_ENABLE_LOGGING
  215592. #define WASAPI_ENABLE_LOGGING 1
  215593. #endif
  215594. namespace WasapiClasses
  215595. {
  215596. void logFailure (HRESULT hr)
  215597. {
  215598. (void) hr;
  215599. #if WASAPI_ENABLE_LOGGING
  215600. if (FAILED (hr))
  215601. {
  215602. String e;
  215603. e << Time::getCurrentTime().toString (true, true, true, true)
  215604. << " -- WASAPI error: ";
  215605. switch (hr)
  215606. {
  215607. case E_POINTER: e << "E_POINTER"; break;
  215608. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215609. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215610. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215611. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215612. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215613. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215614. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215615. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215616. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215617. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215618. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215619. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215620. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215621. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215622. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215623. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215624. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215625. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215626. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215627. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215628. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215629. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215630. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215631. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215632. default: e << String::toHexString ((int) hr); break;
  215633. }
  215634. DBG (e);
  215635. jassertfalse;
  215636. }
  215637. #endif
  215638. }
  215639. #undef check
  215640. bool check (HRESULT hr)
  215641. {
  215642. logFailure (hr);
  215643. return SUCCEEDED (hr);
  215644. }
  215645. const String getDeviceID (IMMDevice* const device)
  215646. {
  215647. String s;
  215648. WCHAR* deviceId = 0;
  215649. if (check (device->GetId (&deviceId)))
  215650. {
  215651. s = String (deviceId);
  215652. CoTaskMemFree (deviceId);
  215653. }
  215654. return s;
  215655. }
  215656. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215657. {
  215658. EDataFlow flow = eRender;
  215659. ComSmartPtr <IMMEndpoint> endPoint;
  215660. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215661. (void) check (endPoint->GetDataFlow (&flow));
  215662. return flow;
  215663. }
  215664. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215665. {
  215666. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215667. }
  215668. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215669. {
  215670. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215671. : sizeof (WAVEFORMATEX));
  215672. }
  215673. class WASAPIDeviceBase
  215674. {
  215675. public:
  215676. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215677. : device (device_),
  215678. sampleRate (0),
  215679. numChannels (0),
  215680. actualNumChannels (0),
  215681. defaultSampleRate (0),
  215682. minBufferSize (0),
  215683. defaultBufferSize (0),
  215684. latencySamples (0),
  215685. useExclusiveMode (useExclusiveMode_)
  215686. {
  215687. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215688. ComSmartPtr <IAudioClient> tempClient (createClient());
  215689. if (tempClient == 0)
  215690. return;
  215691. REFERENCE_TIME defaultPeriod, minPeriod;
  215692. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215693. return;
  215694. WAVEFORMATEX* mixFormat = 0;
  215695. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215696. return;
  215697. WAVEFORMATEXTENSIBLE format;
  215698. copyWavFormat (format, mixFormat);
  215699. CoTaskMemFree (mixFormat);
  215700. actualNumChannels = numChannels = format.Format.nChannels;
  215701. defaultSampleRate = format.Format.nSamplesPerSec;
  215702. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215703. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215704. rates.addUsingDefaultSort (defaultSampleRate);
  215705. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215706. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215707. {
  215708. if (ratesToTest[i] == defaultSampleRate)
  215709. continue;
  215710. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215711. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215712. (WAVEFORMATEX*) &format, 0)))
  215713. if (! rates.contains (ratesToTest[i]))
  215714. rates.addUsingDefaultSort (ratesToTest[i]);
  215715. }
  215716. }
  215717. ~WASAPIDeviceBase()
  215718. {
  215719. device = 0;
  215720. CloseHandle (clientEvent);
  215721. }
  215722. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215723. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215724. {
  215725. sampleRate = newSampleRate;
  215726. channels = newChannels;
  215727. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215728. numChannels = channels.getHighestBit() + 1;
  215729. if (numChannels == 0)
  215730. return true;
  215731. client = createClient();
  215732. if (client != 0
  215733. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215734. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215735. {
  215736. channelMaps.clear();
  215737. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215738. if (channels[i])
  215739. channelMaps.add (i);
  215740. REFERENCE_TIME latency;
  215741. if (check (client->GetStreamLatency (&latency)))
  215742. latencySamples = refTimeToSamples (latency, sampleRate);
  215743. (void) check (client->GetBufferSize (&actualBufferSize));
  215744. return check (client->SetEventHandle (clientEvent));
  215745. }
  215746. return false;
  215747. }
  215748. void closeClient()
  215749. {
  215750. if (client != 0)
  215751. client->Stop();
  215752. client = 0;
  215753. ResetEvent (clientEvent);
  215754. }
  215755. ComSmartPtr <IMMDevice> device;
  215756. ComSmartPtr <IAudioClient> client;
  215757. double sampleRate, defaultSampleRate;
  215758. int numChannels, actualNumChannels;
  215759. int minBufferSize, defaultBufferSize, latencySamples;
  215760. const bool useExclusiveMode;
  215761. Array <double> rates;
  215762. HANDLE clientEvent;
  215763. BigInteger channels;
  215764. Array <int> channelMaps;
  215765. UINT32 actualBufferSize;
  215766. int bytesPerSample;
  215767. virtual void updateFormat (bool isFloat) = 0;
  215768. private:
  215769. const ComSmartPtr <IAudioClient> createClient()
  215770. {
  215771. ComSmartPtr <IAudioClient> client;
  215772. if (device != 0)
  215773. {
  215774. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215775. logFailure (hr);
  215776. }
  215777. return client;
  215778. }
  215779. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215780. {
  215781. WAVEFORMATEXTENSIBLE format;
  215782. zerostruct (format);
  215783. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215784. {
  215785. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215786. }
  215787. else
  215788. {
  215789. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215790. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215791. }
  215792. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215793. format.Format.nChannels = (WORD) numChannels;
  215794. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215795. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215796. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215797. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215798. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215799. switch (numChannels)
  215800. {
  215801. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215802. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215803. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215804. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215805. 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;
  215806. default: break;
  215807. }
  215808. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215809. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215810. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215811. logFailure (hr);
  215812. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215813. {
  215814. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215815. hr = S_OK;
  215816. }
  215817. CoTaskMemFree (nearestFormat);
  215818. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215819. if (useExclusiveMode)
  215820. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215821. GUID session;
  215822. if (hr == S_OK
  215823. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215824. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215825. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215826. {
  215827. actualNumChannels = format.Format.nChannels;
  215828. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215829. bytesPerSample = format.Format.wBitsPerSample / 8;
  215830. updateFormat (isFloat);
  215831. return true;
  215832. }
  215833. return false;
  215834. }
  215835. WASAPIDeviceBase (const WASAPIDeviceBase&);
  215836. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  215837. };
  215838. class WASAPIInputDevice : public WASAPIDeviceBase
  215839. {
  215840. public:
  215841. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215842. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215843. reservoir (1, 1)
  215844. {
  215845. }
  215846. ~WASAPIInputDevice()
  215847. {
  215848. close();
  215849. }
  215850. bool open (const double newSampleRate, const BigInteger& newChannels)
  215851. {
  215852. reservoirSize = 0;
  215853. reservoirCapacity = 16384;
  215854. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215855. return openClient (newSampleRate, newChannels)
  215856. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient), (void**) captureClient.resetAndGetPointerAddress())));
  215857. }
  215858. void close()
  215859. {
  215860. closeClient();
  215861. captureClient = 0;
  215862. reservoir.setSize (0);
  215863. }
  215864. void updateFormat (bool isFloat)
  215865. {
  215866. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215867. if (isFloat)
  215868. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215869. else if (bytesPerSample == 4)
  215870. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215871. else if (bytesPerSample == 3)
  215872. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215873. else
  215874. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215875. }
  215876. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215877. {
  215878. if (numChannels <= 0)
  215879. return;
  215880. int offset = 0;
  215881. while (bufferSize > 0)
  215882. {
  215883. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215884. {
  215885. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215886. for (int i = 0; i < numDestBuffers; ++i)
  215887. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215888. bufferSize -= samplesToDo;
  215889. offset += samplesToDo;
  215890. reservoirSize -= samplesToDo;
  215891. }
  215892. else
  215893. {
  215894. UINT32 packetLength = 0;
  215895. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215896. break;
  215897. if (packetLength == 0)
  215898. {
  215899. if (thread.threadShouldExit())
  215900. break;
  215901. Thread::sleep (1);
  215902. continue;
  215903. }
  215904. uint8* inputData = 0;
  215905. UINT32 numSamplesAvailable;
  215906. DWORD flags;
  215907. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215908. {
  215909. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215910. for (int i = 0; i < numDestBuffers; ++i)
  215911. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215912. bufferSize -= samplesToDo;
  215913. offset += samplesToDo;
  215914. if (samplesToDo < (int) numSamplesAvailable)
  215915. {
  215916. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215917. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215918. bytesPerSample * actualNumChannels * reservoirSize);
  215919. }
  215920. captureClient->ReleaseBuffer (numSamplesAvailable);
  215921. }
  215922. }
  215923. }
  215924. }
  215925. ComSmartPtr <IAudioCaptureClient> captureClient;
  215926. MemoryBlock reservoir;
  215927. int reservoirSize, reservoirCapacity;
  215928. ScopedPointer <AudioData::Converter> converter;
  215929. private:
  215930. WASAPIInputDevice (const WASAPIInputDevice&);
  215931. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  215932. };
  215933. class WASAPIOutputDevice : public WASAPIDeviceBase
  215934. {
  215935. public:
  215936. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215937. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215938. {
  215939. }
  215940. ~WASAPIOutputDevice()
  215941. {
  215942. close();
  215943. }
  215944. bool open (const double newSampleRate, const BigInteger& newChannels)
  215945. {
  215946. return openClient (newSampleRate, newChannels)
  215947. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215948. }
  215949. void close()
  215950. {
  215951. closeClient();
  215952. renderClient = 0;
  215953. }
  215954. void updateFormat (bool isFloat)
  215955. {
  215956. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215957. if (isFloat)
  215958. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215959. else if (bytesPerSample == 4)
  215960. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215961. else if (bytesPerSample == 3)
  215962. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215963. else
  215964. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215965. }
  215966. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215967. {
  215968. if (numChannels <= 0)
  215969. return;
  215970. int offset = 0;
  215971. while (bufferSize > 0)
  215972. {
  215973. UINT32 padding = 0;
  215974. if (! check (client->GetCurrentPadding (&padding)))
  215975. return;
  215976. int samplesToDo = useExclusiveMode ? bufferSize
  215977. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215978. if (samplesToDo <= 0)
  215979. {
  215980. if (thread.threadShouldExit())
  215981. break;
  215982. Thread::sleep (0);
  215983. continue;
  215984. }
  215985. uint8* outputData = 0;
  215986. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215987. {
  215988. for (int i = 0; i < numSrcBuffers; ++i)
  215989. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  215990. renderClient->ReleaseBuffer (samplesToDo, 0);
  215991. offset += samplesToDo;
  215992. bufferSize -= samplesToDo;
  215993. }
  215994. }
  215995. }
  215996. ComSmartPtr <IAudioRenderClient> renderClient;
  215997. ScopedPointer <AudioData::Converter> converter;
  215998. private:
  215999. WASAPIOutputDevice (const WASAPIOutputDevice&);
  216000. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  216001. };
  216002. class WASAPIAudioIODevice : public AudioIODevice,
  216003. public Thread
  216004. {
  216005. public:
  216006. WASAPIAudioIODevice (const String& deviceName,
  216007. const String& outputDeviceId_,
  216008. const String& inputDeviceId_,
  216009. const bool useExclusiveMode_)
  216010. : AudioIODevice (deviceName, "Windows Audio"),
  216011. Thread ("Juce WASAPI"),
  216012. isOpen_ (false),
  216013. isStarted (false),
  216014. outputDeviceId (outputDeviceId_),
  216015. inputDeviceId (inputDeviceId_),
  216016. useExclusiveMode (useExclusiveMode_),
  216017. currentBufferSizeSamples (0),
  216018. currentSampleRate (0),
  216019. callback (0)
  216020. {
  216021. }
  216022. ~WASAPIAudioIODevice()
  216023. {
  216024. close();
  216025. }
  216026. bool initialise()
  216027. {
  216028. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  216029. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  216030. latencyIn = latencyOut = 0;
  216031. Array <double> ratesIn, ratesOut;
  216032. if (createDevices())
  216033. {
  216034. jassert (inputDevice != 0 || outputDevice != 0);
  216035. if (inputDevice != 0 && outputDevice != 0)
  216036. {
  216037. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  216038. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  216039. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  216040. sampleRates = inputDevice->rates;
  216041. sampleRates.removeValuesNotIn (outputDevice->rates);
  216042. }
  216043. else
  216044. {
  216045. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  216046. : static_cast<WASAPIDeviceBase*> (outputDevice);
  216047. defaultSampleRate = d->defaultSampleRate;
  216048. minBufferSize = d->minBufferSize;
  216049. defaultBufferSize = d->defaultBufferSize;
  216050. sampleRates = d->rates;
  216051. }
  216052. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  216053. if (minBufferSize != defaultBufferSize)
  216054. bufferSizes.addUsingDefaultSort (minBufferSize);
  216055. int n = 64;
  216056. for (int i = 0; i < 40; ++i)
  216057. {
  216058. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  216059. bufferSizes.addUsingDefaultSort (n);
  216060. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  216061. }
  216062. return true;
  216063. }
  216064. return false;
  216065. }
  216066. const StringArray getOutputChannelNames()
  216067. {
  216068. StringArray outChannels;
  216069. if (outputDevice != 0)
  216070. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  216071. outChannels.add ("Output channel " + String (i));
  216072. return outChannels;
  216073. }
  216074. const StringArray getInputChannelNames()
  216075. {
  216076. StringArray inChannels;
  216077. if (inputDevice != 0)
  216078. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  216079. inChannels.add ("Input channel " + String (i));
  216080. return inChannels;
  216081. }
  216082. int getNumSampleRates() { return sampleRates.size(); }
  216083. double getSampleRate (int index) { return sampleRates [index]; }
  216084. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  216085. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  216086. int getDefaultBufferSize() { return defaultBufferSize; }
  216087. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  216088. double getCurrentSampleRate() { return currentSampleRate; }
  216089. int getCurrentBitDepth() { return 32; }
  216090. int getOutputLatencyInSamples() { return latencyOut; }
  216091. int getInputLatencyInSamples() { return latencyIn; }
  216092. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  216093. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  216094. const String getLastError() { return lastError; }
  216095. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  216096. double sampleRate, int bufferSizeSamples)
  216097. {
  216098. close();
  216099. lastError = String::empty;
  216100. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  216101. {
  216102. lastError = "The input and output devices don't share a common sample rate!";
  216103. return lastError;
  216104. }
  216105. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  216106. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  216107. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  216108. {
  216109. lastError = "Couldn't open the input device!";
  216110. return lastError;
  216111. }
  216112. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  216113. {
  216114. close();
  216115. lastError = "Couldn't open the output device!";
  216116. return lastError;
  216117. }
  216118. if (inputDevice != 0)
  216119. ResetEvent (inputDevice->clientEvent);
  216120. if (outputDevice != 0)
  216121. ResetEvent (outputDevice->clientEvent);
  216122. startThread (8);
  216123. Thread::sleep (5);
  216124. if (inputDevice != 0 && inputDevice->client != 0)
  216125. {
  216126. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216127. HRESULT hr = inputDevice->client->Start();
  216128. logFailure (hr); //xxx handle this
  216129. }
  216130. if (outputDevice != 0 && outputDevice->client != 0)
  216131. {
  216132. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216133. HRESULT hr = outputDevice->client->Start();
  216134. logFailure (hr); //xxx handle this
  216135. }
  216136. isOpen_ = true;
  216137. return lastError;
  216138. }
  216139. void close()
  216140. {
  216141. stop();
  216142. if (inputDevice != 0)
  216143. SetEvent (inputDevice->clientEvent);
  216144. if (outputDevice != 0)
  216145. SetEvent (outputDevice->clientEvent);
  216146. stopThread (5000);
  216147. if (inputDevice != 0)
  216148. inputDevice->close();
  216149. if (outputDevice != 0)
  216150. outputDevice->close();
  216151. isOpen_ = false;
  216152. }
  216153. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216154. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216155. void start (AudioIODeviceCallback* call)
  216156. {
  216157. if (isOpen_ && call != 0 && ! isStarted)
  216158. {
  216159. if (! isThreadRunning())
  216160. {
  216161. // something's gone wrong and the thread's stopped..
  216162. isOpen_ = false;
  216163. return;
  216164. }
  216165. call->audioDeviceAboutToStart (this);
  216166. const ScopedLock sl (startStopLock);
  216167. callback = call;
  216168. isStarted = true;
  216169. }
  216170. }
  216171. void stop()
  216172. {
  216173. if (isStarted)
  216174. {
  216175. AudioIODeviceCallback* const callbackLocal = callback;
  216176. {
  216177. const ScopedLock sl (startStopLock);
  216178. isStarted = false;
  216179. }
  216180. if (callbackLocal != 0)
  216181. callbackLocal->audioDeviceStopped();
  216182. }
  216183. }
  216184. void setMMThreadPriority()
  216185. {
  216186. DynamicLibraryLoader dll ("avrt.dll");
  216187. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216188. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216189. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216190. {
  216191. DWORD dummy = 0;
  216192. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216193. if (h != 0)
  216194. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216195. }
  216196. }
  216197. void run()
  216198. {
  216199. setMMThreadPriority();
  216200. const int bufferSize = currentBufferSizeSamples;
  216201. HANDLE events[2];
  216202. int numEvents = 0;
  216203. if (inputDevice != 0)
  216204. events [numEvents++] = inputDevice->clientEvent;
  216205. if (outputDevice != 0)
  216206. events [numEvents++] = outputDevice->clientEvent;
  216207. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216208. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216209. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216210. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216211. float** const inputBuffers = ins.getArrayOfChannels();
  216212. float** const outputBuffers = outs.getArrayOfChannels();
  216213. ins.clear();
  216214. while (! threadShouldExit())
  216215. {
  216216. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216217. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216218. if (result == WAIT_TIMEOUT)
  216219. continue;
  216220. if (threadShouldExit())
  216221. break;
  216222. if (inputDevice != 0)
  216223. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216224. // Make the callback..
  216225. {
  216226. const ScopedLock sl (startStopLock);
  216227. if (isStarted)
  216228. {
  216229. JUCE_TRY
  216230. {
  216231. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216232. numInputBuffers,
  216233. outputBuffers,
  216234. numOutputBuffers,
  216235. bufferSize);
  216236. }
  216237. JUCE_CATCH_EXCEPTION
  216238. }
  216239. else
  216240. {
  216241. outs.clear();
  216242. }
  216243. }
  216244. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216245. continue;
  216246. if (outputDevice != 0)
  216247. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216248. }
  216249. }
  216250. juce_UseDebuggingNewOperator
  216251. String outputDeviceId, inputDeviceId;
  216252. String lastError;
  216253. private:
  216254. // Device stats...
  216255. ScopedPointer<WASAPIInputDevice> inputDevice;
  216256. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216257. const bool useExclusiveMode;
  216258. double defaultSampleRate;
  216259. int minBufferSize, defaultBufferSize;
  216260. int latencyIn, latencyOut;
  216261. Array <double> sampleRates;
  216262. Array <int> bufferSizes;
  216263. // Active state...
  216264. bool isOpen_, isStarted;
  216265. int currentBufferSizeSamples;
  216266. double currentSampleRate;
  216267. AudioIODeviceCallback* callback;
  216268. CriticalSection startStopLock;
  216269. bool createDevices()
  216270. {
  216271. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216272. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216273. return false;
  216274. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216275. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  216276. return false;
  216277. UINT32 numDevices = 0;
  216278. if (! check (deviceCollection->GetCount (&numDevices)))
  216279. return false;
  216280. for (UINT32 i = 0; i < numDevices; ++i)
  216281. {
  216282. ComSmartPtr <IMMDevice> device;
  216283. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216284. continue;
  216285. const String deviceId (getDeviceID (device));
  216286. if (deviceId.isEmpty())
  216287. continue;
  216288. const EDataFlow flow = getDataFlow (device);
  216289. if (deviceId == inputDeviceId && flow == eCapture)
  216290. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216291. else if (deviceId == outputDeviceId && flow == eRender)
  216292. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216293. }
  216294. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216295. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216296. }
  216297. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216298. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216299. };
  216300. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216301. {
  216302. public:
  216303. WASAPIAudioIODeviceType()
  216304. : AudioIODeviceType ("Windows Audio"),
  216305. hasScanned (false)
  216306. {
  216307. }
  216308. ~WASAPIAudioIODeviceType()
  216309. {
  216310. }
  216311. void scanForDevices()
  216312. {
  216313. hasScanned = true;
  216314. outputDeviceNames.clear();
  216315. inputDeviceNames.clear();
  216316. outputDeviceIds.clear();
  216317. inputDeviceIds.clear();
  216318. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216319. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216320. return;
  216321. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216322. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216323. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216324. UINT32 numDevices = 0;
  216325. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  216326. && check (deviceCollection->GetCount (&numDevices))))
  216327. return;
  216328. for (UINT32 i = 0; i < numDevices; ++i)
  216329. {
  216330. ComSmartPtr <IMMDevice> device;
  216331. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216332. continue;
  216333. const String deviceId (getDeviceID (device));
  216334. DWORD state = 0;
  216335. if (! check (device->GetState (&state)))
  216336. continue;
  216337. if (state != DEVICE_STATE_ACTIVE)
  216338. continue;
  216339. String name;
  216340. {
  216341. ComSmartPtr <IPropertyStore> properties;
  216342. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  216343. continue;
  216344. PROPVARIANT value;
  216345. PropVariantInit (&value);
  216346. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216347. name = value.pwszVal;
  216348. PropVariantClear (&value);
  216349. }
  216350. const EDataFlow flow = getDataFlow (device);
  216351. if (flow == eRender)
  216352. {
  216353. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216354. outputDeviceIds.insert (index, deviceId);
  216355. outputDeviceNames.insert (index, name);
  216356. }
  216357. else if (flow == eCapture)
  216358. {
  216359. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216360. inputDeviceIds.insert (index, deviceId);
  216361. inputDeviceNames.insert (index, name);
  216362. }
  216363. }
  216364. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216365. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216366. }
  216367. const StringArray getDeviceNames (bool wantInputNames) const
  216368. {
  216369. jassert (hasScanned); // need to call scanForDevices() before doing this
  216370. return wantInputNames ? inputDeviceNames
  216371. : outputDeviceNames;
  216372. }
  216373. int getDefaultDeviceIndex (bool /*forInput*/) const
  216374. {
  216375. jassert (hasScanned); // need to call scanForDevices() before doing this
  216376. return 0;
  216377. }
  216378. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216379. {
  216380. jassert (hasScanned); // need to call scanForDevices() before doing this
  216381. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216382. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216383. : outputDeviceIds.indexOf (d->outputDeviceId));
  216384. }
  216385. bool hasSeparateInputsAndOutputs() const { return true; }
  216386. AudioIODevice* createDevice (const String& outputDeviceName,
  216387. const String& inputDeviceName)
  216388. {
  216389. jassert (hasScanned); // need to call scanForDevices() before doing this
  216390. const bool useExclusiveMode = false;
  216391. ScopedPointer<WASAPIAudioIODevice> device;
  216392. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216393. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216394. if (outputIndex >= 0 || inputIndex >= 0)
  216395. {
  216396. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216397. : inputDeviceName,
  216398. outputDeviceIds [outputIndex],
  216399. inputDeviceIds [inputIndex],
  216400. useExclusiveMode);
  216401. if (! device->initialise())
  216402. device = 0;
  216403. }
  216404. return device.release();
  216405. }
  216406. juce_UseDebuggingNewOperator
  216407. StringArray outputDeviceNames, outputDeviceIds;
  216408. StringArray inputDeviceNames, inputDeviceIds;
  216409. private:
  216410. bool hasScanned;
  216411. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216412. {
  216413. String s;
  216414. IMMDevice* dev = 0;
  216415. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216416. eMultimedia, &dev)))
  216417. {
  216418. WCHAR* deviceId = 0;
  216419. if (check (dev->GetId (&deviceId)))
  216420. {
  216421. s = String (deviceId);
  216422. CoTaskMemFree (deviceId);
  216423. }
  216424. dev->Release();
  216425. }
  216426. return s;
  216427. }
  216428. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216429. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216430. };
  216431. }
  216432. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216433. {
  216434. return new WasapiClasses::WASAPIAudioIODeviceType();
  216435. }
  216436. #endif
  216437. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216438. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216439. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216440. // compiled on its own).
  216441. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216442. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216443. {
  216444. public:
  216445. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216446. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216447. const ComSmartPtr <IBaseFilter>& filter_,
  216448. int minWidth, int minHeight,
  216449. int maxWidth, int maxHeight)
  216450. : owner (owner_),
  216451. captureGraphBuilder (captureGraphBuilder_),
  216452. filter (filter_),
  216453. ok (false),
  216454. imageNeedsFlipping (false),
  216455. width (0),
  216456. height (0),
  216457. activeUsers (0),
  216458. recordNextFrameTime (false),
  216459. previewMaxFPS (60)
  216460. {
  216461. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216462. if (FAILED (hr))
  216463. return;
  216464. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216465. if (FAILED (hr))
  216466. return;
  216467. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  216468. if (FAILED (hr))
  216469. return;
  216470. {
  216471. ComSmartPtr <IAMStreamConfig> streamConfig;
  216472. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216473. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  216474. if (streamConfig != 0)
  216475. {
  216476. getVideoSizes (streamConfig);
  216477. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216478. return;
  216479. }
  216480. }
  216481. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216482. if (FAILED (hr))
  216483. return;
  216484. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216485. if (FAILED (hr))
  216486. return;
  216487. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216488. if (FAILED (hr))
  216489. return;
  216490. if (! connectFilters (filter, smartTee))
  216491. return;
  216492. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216493. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216494. if (FAILED (hr))
  216495. return;
  216496. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  216497. if (FAILED (hr))
  216498. return;
  216499. AM_MEDIA_TYPE mt;
  216500. zerostruct (mt);
  216501. mt.majortype = MEDIATYPE_Video;
  216502. mt.subtype = MEDIASUBTYPE_RGB24;
  216503. mt.formattype = FORMAT_VideoInfo;
  216504. sampleGrabber->SetMediaType (&mt);
  216505. callback = new GrabberCallback (*this);
  216506. hr = sampleGrabber->SetCallback (callback, 1);
  216507. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216508. if (FAILED (hr))
  216509. return;
  216510. ComSmartPtr <IPin> grabberInputPin;
  216511. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  216512. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  216513. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  216514. return;
  216515. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216516. if (FAILED (hr))
  216517. return;
  216518. zerostruct (mt);
  216519. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216520. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216521. width = pVih->bmiHeader.biWidth;
  216522. height = pVih->bmiHeader.biHeight;
  216523. ComSmartPtr <IBaseFilter> nullFilter;
  216524. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216525. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216526. if (connectFilters (sampleGrabberBase, nullFilter)
  216527. && addGraphToRot())
  216528. {
  216529. activeImage = Image (Image::RGB, width, height, true);
  216530. loadingImage = Image (Image::RGB, width, height, true);
  216531. ok = true;
  216532. }
  216533. }
  216534. ~DShowCameraDeviceInteral()
  216535. {
  216536. if (mediaControl != 0)
  216537. mediaControl->Stop();
  216538. removeGraphFromRot();
  216539. for (int i = viewerComps.size(); --i >= 0;)
  216540. viewerComps.getUnchecked(i)->ownerDeleted();
  216541. callback = 0;
  216542. graphBuilder = 0;
  216543. sampleGrabber = 0;
  216544. mediaControl = 0;
  216545. filter = 0;
  216546. captureGraphBuilder = 0;
  216547. smartTee = 0;
  216548. smartTeePreviewOutputPin = 0;
  216549. smartTeeCaptureOutputPin = 0;
  216550. asfWriter = 0;
  216551. }
  216552. void addUser()
  216553. {
  216554. if (ok && activeUsers++ == 0)
  216555. mediaControl->Run();
  216556. }
  216557. void removeUser()
  216558. {
  216559. if (ok && --activeUsers == 0)
  216560. mediaControl->Stop();
  216561. }
  216562. int getPreviewMaxFPS() const
  216563. {
  216564. return previewMaxFPS;
  216565. }
  216566. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216567. {
  216568. if (recordNextFrameTime)
  216569. {
  216570. const double defaultCameraLatency = 0.1;
  216571. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216572. recordNextFrameTime = false;
  216573. ComSmartPtr <IPin> pin;
  216574. if (getPin (filter, PINDIR_OUTPUT, pin))
  216575. {
  216576. ComSmartPtr <IAMPushSource> pushSource;
  216577. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  216578. if (pushSource != 0)
  216579. {
  216580. REFERENCE_TIME latency = 0;
  216581. hr = pushSource->GetLatency (&latency);
  216582. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216583. }
  216584. }
  216585. }
  216586. {
  216587. const int lineStride = width * 3;
  216588. const ScopedLock sl (imageSwapLock);
  216589. {
  216590. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216591. for (int i = 0; i < height; ++i)
  216592. memcpy (destData.getLinePointer ((height - 1) - i),
  216593. buffer + lineStride * i,
  216594. lineStride);
  216595. }
  216596. imageNeedsFlipping = true;
  216597. }
  216598. if (listeners.size() > 0)
  216599. callListeners (loadingImage);
  216600. sendChangeMessage();
  216601. }
  216602. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216603. {
  216604. if (imageNeedsFlipping)
  216605. {
  216606. const ScopedLock sl (imageSwapLock);
  216607. swapVariables (loadingImage, activeImage);
  216608. imageNeedsFlipping = false;
  216609. }
  216610. RectanglePlacement rp (RectanglePlacement::centred);
  216611. double dx = 0, dy = 0, dw = width, dh = height;
  216612. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216613. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216614. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216615. g.saveState();
  216616. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216617. g.fillAll (Colours::black);
  216618. g.restoreState();
  216619. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216620. }
  216621. bool createFileCaptureFilter (const File& file, int quality)
  216622. {
  216623. removeFileCaptureFilter();
  216624. file.deleteFile();
  216625. mediaControl->Stop();
  216626. firstRecordedTime = Time();
  216627. recordNextFrameTime = true;
  216628. previewMaxFPS = 60;
  216629. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216630. if (SUCCEEDED (hr))
  216631. {
  216632. ComSmartPtr <IFileSinkFilter> fileSink;
  216633. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216634. if (SUCCEEDED (hr))
  216635. {
  216636. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216637. if (SUCCEEDED (hr))
  216638. {
  216639. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216640. if (SUCCEEDED (hr))
  216641. {
  216642. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216643. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216644. asfConfig->SetIndexMode (true);
  216645. ComSmartPtr <IWMProfileManager> profileManager;
  216646. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216647. // This gibberish is the DirectShow profile for a video-only wmv file.
  216648. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  216649. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  216650. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216651. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  216652. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216653. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  216654. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  216655. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  216656. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216657. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216658. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216659. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  216660. "biclrused=\"0\" biclrimportant=\"0\"/>"
  216661. "</videoinfoheader>"
  216662. "</wmmediatype>"
  216663. "</streamconfig>"
  216664. "</profile>");
  216665. const int fps[] = { 10, 15, 30 };
  216666. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  216667. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216668. maxFramesPerSecond = (quality >> 24) & 0xff;
  216669. prof = prof.replace ("$WIDTH", String (width))
  216670. .replace ("$HEIGHT", String (height))
  216671. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  216672. ComSmartPtr <IWMProfile> currentProfile;
  216673. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  216674. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216675. if (SUCCEEDED (hr))
  216676. {
  216677. ComSmartPtr <IPin> asfWriterInputPin;
  216678. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216679. {
  216680. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216681. if (SUCCEEDED (hr) && ok && activeUsers > 0
  216682. && SUCCEEDED (mediaControl->Run()))
  216683. {
  216684. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  216685. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216686. previewMaxFPS = (quality >> 16) & 0xff;
  216687. return true;
  216688. }
  216689. }
  216690. }
  216691. }
  216692. }
  216693. }
  216694. }
  216695. removeFileCaptureFilter();
  216696. if (ok && activeUsers > 0)
  216697. mediaControl->Run();
  216698. return false;
  216699. }
  216700. void removeFileCaptureFilter()
  216701. {
  216702. mediaControl->Stop();
  216703. if (asfWriter != 0)
  216704. {
  216705. graphBuilder->RemoveFilter (asfWriter);
  216706. asfWriter = 0;
  216707. }
  216708. if (ok && activeUsers > 0)
  216709. mediaControl->Run();
  216710. previewMaxFPS = 60;
  216711. }
  216712. void addListener (CameraDevice::Listener* listenerToAdd)
  216713. {
  216714. const ScopedLock sl (listenerLock);
  216715. if (listeners.size() == 0)
  216716. addUser();
  216717. listeners.addIfNotAlreadyThere (listenerToAdd);
  216718. }
  216719. void removeListener (CameraDevice::Listener* listenerToRemove)
  216720. {
  216721. const ScopedLock sl (listenerLock);
  216722. listeners.removeValue (listenerToRemove);
  216723. if (listeners.size() == 0)
  216724. removeUser();
  216725. }
  216726. void callListeners (const Image& image)
  216727. {
  216728. const ScopedLock sl (listenerLock);
  216729. for (int i = listeners.size(); --i >= 0;)
  216730. {
  216731. CameraDevice::Listener* const l = listeners[i];
  216732. if (l != 0)
  216733. l->imageReceived (image);
  216734. }
  216735. }
  216736. class DShowCaptureViewerComp : public Component,
  216737. public ChangeListener
  216738. {
  216739. public:
  216740. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216741. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  216742. {
  216743. setOpaque (true);
  216744. owner->addChangeListener (this);
  216745. owner->addUser();
  216746. owner->viewerComps.add (this);
  216747. setSize (owner->width, owner->height);
  216748. }
  216749. ~DShowCaptureViewerComp()
  216750. {
  216751. if (owner != 0)
  216752. {
  216753. owner->viewerComps.removeValue (this);
  216754. owner->removeUser();
  216755. owner->removeChangeListener (this);
  216756. }
  216757. }
  216758. void ownerDeleted()
  216759. {
  216760. owner = 0;
  216761. }
  216762. void paint (Graphics& g)
  216763. {
  216764. g.setColour (Colours::black);
  216765. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216766. if (owner != 0)
  216767. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216768. else
  216769. g.fillAll (Colours::black);
  216770. }
  216771. void changeListenerCallback (ChangeBroadcaster*)
  216772. {
  216773. const int64 now = Time::currentTimeMillis();
  216774. if (now >= lastRepaintTime + (1000 / maxFPS))
  216775. {
  216776. lastRepaintTime = now;
  216777. repaint();
  216778. if (owner != 0)
  216779. maxFPS = owner->getPreviewMaxFPS();
  216780. }
  216781. }
  216782. private:
  216783. DShowCameraDeviceInteral* owner;
  216784. int maxFPS;
  216785. int64 lastRepaintTime;
  216786. };
  216787. bool ok;
  216788. int width, height;
  216789. Time firstRecordedTime;
  216790. Array <DShowCaptureViewerComp*> viewerComps;
  216791. private:
  216792. CameraDevice* const owner;
  216793. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216794. ComSmartPtr <IBaseFilter> filter;
  216795. ComSmartPtr <IBaseFilter> smartTee;
  216796. ComSmartPtr <IGraphBuilder> graphBuilder;
  216797. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216798. ComSmartPtr <IMediaControl> mediaControl;
  216799. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216800. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216801. ComSmartPtr <IBaseFilter> asfWriter;
  216802. int activeUsers;
  216803. Array <int> widths, heights;
  216804. DWORD graphRegistrationID;
  216805. CriticalSection imageSwapLock;
  216806. bool imageNeedsFlipping;
  216807. Image loadingImage;
  216808. Image activeImage;
  216809. bool recordNextFrameTime;
  216810. int previewMaxFPS;
  216811. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216812. {
  216813. widths.clear();
  216814. heights.clear();
  216815. int count = 0, size = 0;
  216816. streamConfig->GetNumberOfCapabilities (&count, &size);
  216817. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216818. {
  216819. for (int i = 0; i < count; ++i)
  216820. {
  216821. VIDEO_STREAM_CONFIG_CAPS scc;
  216822. AM_MEDIA_TYPE* config;
  216823. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216824. if (SUCCEEDED (hr))
  216825. {
  216826. const int w = scc.InputSize.cx;
  216827. const int h = scc.InputSize.cy;
  216828. bool duplicate = false;
  216829. for (int j = widths.size(); --j >= 0;)
  216830. {
  216831. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216832. {
  216833. duplicate = true;
  216834. break;
  216835. }
  216836. }
  216837. if (! duplicate)
  216838. {
  216839. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216840. widths.add (w);
  216841. heights.add (h);
  216842. }
  216843. deleteMediaType (config);
  216844. }
  216845. }
  216846. }
  216847. }
  216848. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216849. const int minWidth, const int minHeight,
  216850. const int maxWidth, const int maxHeight)
  216851. {
  216852. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216853. streamConfig->GetNumberOfCapabilities (&count, &size);
  216854. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216855. {
  216856. AM_MEDIA_TYPE* config;
  216857. VIDEO_STREAM_CONFIG_CAPS scc;
  216858. for (int i = 0; i < count; ++i)
  216859. {
  216860. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216861. if (SUCCEEDED (hr))
  216862. {
  216863. if (scc.InputSize.cx >= minWidth
  216864. && scc.InputSize.cy >= minHeight
  216865. && scc.InputSize.cx <= maxWidth
  216866. && scc.InputSize.cy <= maxHeight)
  216867. {
  216868. int area = scc.InputSize.cx * scc.InputSize.cy;
  216869. if (area > bestArea)
  216870. {
  216871. bestIndex = i;
  216872. bestArea = area;
  216873. }
  216874. }
  216875. deleteMediaType (config);
  216876. }
  216877. }
  216878. if (bestIndex >= 0)
  216879. {
  216880. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216881. hr = streamConfig->SetFormat (config);
  216882. deleteMediaType (config);
  216883. return SUCCEEDED (hr);
  216884. }
  216885. }
  216886. return false;
  216887. }
  216888. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216889. {
  216890. ComSmartPtr <IEnumPins> enumerator;
  216891. ComSmartPtr <IPin> pin;
  216892. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216893. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216894. {
  216895. PIN_DIRECTION dir;
  216896. pin->QueryDirection (&dir);
  216897. if (wantedDirection == dir)
  216898. {
  216899. PIN_INFO info;
  216900. zerostruct (info);
  216901. pin->QueryPinInfo (&info);
  216902. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216903. {
  216904. result = pin;
  216905. return true;
  216906. }
  216907. }
  216908. }
  216909. return false;
  216910. }
  216911. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216912. {
  216913. ComSmartPtr <IPin> in, out;
  216914. return getPin (first, PINDIR_OUTPUT, out)
  216915. && getPin (second, PINDIR_INPUT, in)
  216916. && SUCCEEDED (graphBuilder->Connect (out, in));
  216917. }
  216918. bool addGraphToRot()
  216919. {
  216920. ComSmartPtr <IRunningObjectTable> rot;
  216921. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216922. return false;
  216923. ComSmartPtr <IMoniker> moniker;
  216924. WCHAR buffer[128];
  216925. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216926. if (FAILED (hr))
  216927. return false;
  216928. graphRegistrationID = 0;
  216929. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216930. }
  216931. void removeGraphFromRot()
  216932. {
  216933. ComSmartPtr <IRunningObjectTable> rot;
  216934. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216935. rot->Revoke (graphRegistrationID);
  216936. }
  216937. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216938. {
  216939. if (pmt->cbFormat != 0)
  216940. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216941. if (pmt->pUnk != 0)
  216942. pmt->pUnk->Release();
  216943. CoTaskMemFree (pmt);
  216944. }
  216945. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216946. {
  216947. public:
  216948. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216949. : owner (owner_)
  216950. {
  216951. }
  216952. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216953. {
  216954. return E_FAIL;
  216955. }
  216956. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216957. {
  216958. owner.handleFrame (time, buffer, bufferSize);
  216959. return S_OK;
  216960. }
  216961. private:
  216962. DShowCameraDeviceInteral& owner;
  216963. GrabberCallback (const GrabberCallback&);
  216964. GrabberCallback& operator= (const GrabberCallback&);
  216965. };
  216966. ComSmartPtr <GrabberCallback> callback;
  216967. Array <CameraDevice::Listener*> listeners;
  216968. CriticalSection listenerLock;
  216969. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  216970. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  216971. };
  216972. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216973. : name (name_)
  216974. {
  216975. isRecording = false;
  216976. }
  216977. CameraDevice::~CameraDevice()
  216978. {
  216979. stopRecording();
  216980. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216981. internal = 0;
  216982. }
  216983. Component* CameraDevice::createViewerComponent()
  216984. {
  216985. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216986. }
  216987. const String CameraDevice::getFileExtension()
  216988. {
  216989. return ".wmv";
  216990. }
  216991. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216992. {
  216993. stopRecording();
  216994. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216995. d->addUser();
  216996. isRecording = d->createFileCaptureFilter (file, quality);
  216997. }
  216998. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216999. {
  217000. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217001. return d->firstRecordedTime;
  217002. }
  217003. void CameraDevice::stopRecording()
  217004. {
  217005. if (isRecording)
  217006. {
  217007. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217008. d->removeFileCaptureFilter();
  217009. d->removeUser();
  217010. isRecording = false;
  217011. }
  217012. }
  217013. void CameraDevice::addListener (Listener* listenerToAdd)
  217014. {
  217015. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217016. if (listenerToAdd != 0)
  217017. d->addListener (listenerToAdd);
  217018. }
  217019. void CameraDevice::removeListener (Listener* listenerToRemove)
  217020. {
  217021. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217022. if (listenerToRemove != 0)
  217023. d->removeListener (listenerToRemove);
  217024. }
  217025. namespace
  217026. {
  217027. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  217028. const int deviceIndexToOpen,
  217029. String& name)
  217030. {
  217031. int index = 0;
  217032. ComSmartPtr <IBaseFilter> result;
  217033. ComSmartPtr <ICreateDevEnum> pDevEnum;
  217034. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  217035. if (SUCCEEDED (hr))
  217036. {
  217037. ComSmartPtr <IEnumMoniker> enumerator;
  217038. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  217039. if (SUCCEEDED (hr) && enumerator != 0)
  217040. {
  217041. ComSmartPtr <IMoniker> moniker;
  217042. ULONG fetched;
  217043. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  217044. {
  217045. ComSmartPtr <IBaseFilter> captureFilter;
  217046. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  217047. if (SUCCEEDED (hr))
  217048. {
  217049. ComSmartPtr <IPropertyBag> propertyBag;
  217050. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  217051. if (SUCCEEDED (hr))
  217052. {
  217053. VARIANT var;
  217054. var.vt = VT_BSTR;
  217055. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  217056. propertyBag = 0;
  217057. if (SUCCEEDED (hr))
  217058. {
  217059. if (names != 0)
  217060. names->add (var.bstrVal);
  217061. if (index == deviceIndexToOpen)
  217062. {
  217063. name = var.bstrVal;
  217064. result = captureFilter;
  217065. break;
  217066. }
  217067. ++index;
  217068. }
  217069. }
  217070. }
  217071. }
  217072. }
  217073. }
  217074. return result;
  217075. }
  217076. }
  217077. const StringArray CameraDevice::getAvailableDevices()
  217078. {
  217079. StringArray devs;
  217080. String dummy;
  217081. enumerateCameras (&devs, -1, dummy);
  217082. return devs;
  217083. }
  217084. CameraDevice* CameraDevice::openDevice (int index,
  217085. int minWidth, int minHeight,
  217086. int maxWidth, int maxHeight)
  217087. {
  217088. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  217089. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  217090. if (SUCCEEDED (hr))
  217091. {
  217092. String name;
  217093. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  217094. if (filter != 0)
  217095. {
  217096. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  217097. DShowCameraDeviceInteral* const intern
  217098. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  217099. minWidth, minHeight, maxWidth, maxHeight);
  217100. cam->internal = intern;
  217101. if (intern->ok)
  217102. return cam.release();
  217103. }
  217104. }
  217105. return 0;
  217106. }
  217107. #endif
  217108. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  217109. #endif
  217110. // Auto-link the other win32 libs that are needed by library calls..
  217111. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  217112. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217113. // Auto-links to various win32 libs that are needed by library calls..
  217114. #pragma comment(lib, "kernel32.lib")
  217115. #pragma comment(lib, "user32.lib")
  217116. #pragma comment(lib, "shell32.lib")
  217117. #pragma comment(lib, "gdi32.lib")
  217118. #pragma comment(lib, "vfw32.lib")
  217119. #pragma comment(lib, "comdlg32.lib")
  217120. #pragma comment(lib, "winmm.lib")
  217121. #pragma comment(lib, "wininet.lib")
  217122. #pragma comment(lib, "ole32.lib")
  217123. #pragma comment(lib, "oleaut32.lib")
  217124. #pragma comment(lib, "advapi32.lib")
  217125. #pragma comment(lib, "ws2_32.lib")
  217126. #pragma comment(lib, "version.lib")
  217127. #ifdef _NATIVE_WCHAR_T_DEFINED
  217128. #ifdef _DEBUG
  217129. #pragma comment(lib, "comsuppwd.lib")
  217130. #else
  217131. #pragma comment(lib, "comsuppw.lib")
  217132. #endif
  217133. #else
  217134. #ifdef _DEBUG
  217135. #pragma comment(lib, "comsuppd.lib")
  217136. #else
  217137. #pragma comment(lib, "comsupp.lib")
  217138. #endif
  217139. #endif
  217140. #if JUCE_OPENGL
  217141. #pragma comment(lib, "OpenGL32.Lib")
  217142. #pragma comment(lib, "GlU32.Lib")
  217143. #endif
  217144. #if JUCE_QUICKTIME
  217145. #pragma comment (lib, "QTMLClient.lib")
  217146. #endif
  217147. #if JUCE_USE_CAMERA
  217148. #pragma comment (lib, "Strmiids.lib")
  217149. #pragma comment (lib, "wmvcore.lib")
  217150. #endif
  217151. #if JUCE_DIRECT2D
  217152. #pragma comment (lib, "Dwrite.lib")
  217153. #pragma comment (lib, "D2d1.lib")
  217154. #endif
  217155. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217156. #endif
  217157. END_JUCE_NAMESPACE
  217158. #endif
  217159. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217160. #endif
  217161. #if JUCE_LINUX
  217162. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217163. /*
  217164. This file wraps together all the mac-specific code, so that
  217165. we can include all the native headers just once, and compile all our
  217166. platform-specific stuff in one big lump, keeping it out of the way of
  217167. the rest of the codebase.
  217168. */
  217169. #if JUCE_LINUX
  217170. BEGIN_JUCE_NAMESPACE
  217171. #define JUCE_INCLUDED_FILE 1
  217172. // Now include the actual code files..
  217173. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217174. /*
  217175. This file contains posix routines that are common to both the Linux and Mac builds.
  217176. It gets included directly in the cpp files for these platforms.
  217177. */
  217178. CriticalSection::CriticalSection() throw()
  217179. {
  217180. pthread_mutexattr_t atts;
  217181. pthread_mutexattr_init (&atts);
  217182. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217183. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217184. pthread_mutex_init (&internal, &atts);
  217185. }
  217186. CriticalSection::~CriticalSection() throw()
  217187. {
  217188. pthread_mutex_destroy (&internal);
  217189. }
  217190. void CriticalSection::enter() const throw()
  217191. {
  217192. pthread_mutex_lock (&internal);
  217193. }
  217194. bool CriticalSection::tryEnter() const throw()
  217195. {
  217196. return pthread_mutex_trylock (&internal) == 0;
  217197. }
  217198. void CriticalSection::exit() const throw()
  217199. {
  217200. pthread_mutex_unlock (&internal);
  217201. }
  217202. class WaitableEventImpl
  217203. {
  217204. public:
  217205. WaitableEventImpl (const bool manualReset_)
  217206. : triggered (false),
  217207. manualReset (manualReset_)
  217208. {
  217209. pthread_cond_init (&condition, 0);
  217210. pthread_mutexattr_t atts;
  217211. pthread_mutexattr_init (&atts);
  217212. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217213. pthread_mutex_init (&mutex, &atts);
  217214. }
  217215. ~WaitableEventImpl()
  217216. {
  217217. pthread_cond_destroy (&condition);
  217218. pthread_mutex_destroy (&mutex);
  217219. }
  217220. bool wait (const int timeOutMillisecs) throw()
  217221. {
  217222. pthread_mutex_lock (&mutex);
  217223. if (! triggered)
  217224. {
  217225. if (timeOutMillisecs < 0)
  217226. {
  217227. do
  217228. {
  217229. pthread_cond_wait (&condition, &mutex);
  217230. }
  217231. while (! triggered);
  217232. }
  217233. else
  217234. {
  217235. struct timeval now;
  217236. gettimeofday (&now, 0);
  217237. struct timespec time;
  217238. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217239. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217240. if (time.tv_nsec >= 1000000000)
  217241. {
  217242. time.tv_nsec -= 1000000000;
  217243. time.tv_sec++;
  217244. }
  217245. do
  217246. {
  217247. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217248. {
  217249. pthread_mutex_unlock (&mutex);
  217250. return false;
  217251. }
  217252. }
  217253. while (! triggered);
  217254. }
  217255. }
  217256. if (! manualReset)
  217257. triggered = false;
  217258. pthread_mutex_unlock (&mutex);
  217259. return true;
  217260. }
  217261. void signal() throw()
  217262. {
  217263. pthread_mutex_lock (&mutex);
  217264. triggered = true;
  217265. pthread_cond_broadcast (&condition);
  217266. pthread_mutex_unlock (&mutex);
  217267. }
  217268. void reset() throw()
  217269. {
  217270. pthread_mutex_lock (&mutex);
  217271. triggered = false;
  217272. pthread_mutex_unlock (&mutex);
  217273. }
  217274. private:
  217275. pthread_cond_t condition;
  217276. pthread_mutex_t mutex;
  217277. bool triggered;
  217278. const bool manualReset;
  217279. WaitableEventImpl (const WaitableEventImpl&);
  217280. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217281. };
  217282. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217283. : internal (new WaitableEventImpl (manualReset))
  217284. {
  217285. }
  217286. WaitableEvent::~WaitableEvent() throw()
  217287. {
  217288. delete static_cast <WaitableEventImpl*> (internal);
  217289. }
  217290. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217291. {
  217292. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217293. }
  217294. void WaitableEvent::signal() const throw()
  217295. {
  217296. static_cast <WaitableEventImpl*> (internal)->signal();
  217297. }
  217298. void WaitableEvent::reset() const throw()
  217299. {
  217300. static_cast <WaitableEventImpl*> (internal)->reset();
  217301. }
  217302. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217303. {
  217304. struct timespec time;
  217305. time.tv_sec = millisecs / 1000;
  217306. time.tv_nsec = (millisecs % 1000) * 1000000;
  217307. nanosleep (&time, 0);
  217308. }
  217309. const juce_wchar File::separator = '/';
  217310. const String File::separatorString ("/");
  217311. const File File::getCurrentWorkingDirectory()
  217312. {
  217313. HeapBlock<char> heapBuffer;
  217314. char localBuffer [1024];
  217315. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217316. int bufferSize = 4096;
  217317. while (cwd == 0 && errno == ERANGE)
  217318. {
  217319. heapBuffer.malloc (bufferSize);
  217320. cwd = getcwd (heapBuffer, bufferSize - 1);
  217321. bufferSize += 1024;
  217322. }
  217323. return File (String::fromUTF8 (cwd));
  217324. }
  217325. bool File::setAsCurrentWorkingDirectory() const
  217326. {
  217327. return chdir (getFullPathName().toUTF8()) == 0;
  217328. }
  217329. namespace
  217330. {
  217331. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217332. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  217333. #else
  217334. typedef struct stat juce_statStruct;
  217335. #endif
  217336. bool juce_stat (const String& fileName, juce_statStruct& info)
  217337. {
  217338. return fileName.isNotEmpty()
  217339. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217340. && (stat64 (fileName.toUTF8(), &info) == 0);
  217341. #else
  217342. && (stat (fileName.toUTF8(), &info) == 0);
  217343. #endif
  217344. }
  217345. // if this file doesn't exist, find a parent of it that does..
  217346. bool juce_doStatFS (File f, struct statfs& result)
  217347. {
  217348. for (int i = 5; --i >= 0;)
  217349. {
  217350. if (f.exists())
  217351. break;
  217352. f = f.getParentDirectory();
  217353. }
  217354. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217355. }
  217356. }
  217357. bool File::isDirectory() const
  217358. {
  217359. juce_statStruct info;
  217360. return fullPath.isEmpty()
  217361. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217362. }
  217363. bool File::exists() const
  217364. {
  217365. juce_statStruct info;
  217366. return fullPath.isNotEmpty()
  217367. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217368. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  217369. #else
  217370. && (lstat (fullPath.toUTF8(), &info) == 0);
  217371. #endif
  217372. }
  217373. bool File::existsAsFile() const
  217374. {
  217375. return exists() && ! isDirectory();
  217376. }
  217377. int64 File::getSize() const
  217378. {
  217379. juce_statStruct info;
  217380. return juce_stat (fullPath, info) ? info.st_size : 0;
  217381. }
  217382. bool File::hasWriteAccess() const
  217383. {
  217384. if (exists())
  217385. return access (fullPath.toUTF8(), W_OK) == 0;
  217386. if ((! isDirectory()) && fullPath.containsChar (separator))
  217387. return getParentDirectory().hasWriteAccess();
  217388. return false;
  217389. }
  217390. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217391. {
  217392. juce_statStruct info;
  217393. if (! juce_stat (fullPath, info))
  217394. return false;
  217395. info.st_mode &= 0777; // Just permissions
  217396. if (shouldBeReadOnly)
  217397. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217398. else
  217399. // Give everybody write permission?
  217400. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217401. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217402. }
  217403. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217404. {
  217405. modificationTime = 0;
  217406. accessTime = 0;
  217407. creationTime = 0;
  217408. juce_statStruct info;
  217409. if (juce_stat (fullPath, info))
  217410. {
  217411. modificationTime = (int64) info.st_mtime * 1000;
  217412. accessTime = (int64) info.st_atime * 1000;
  217413. creationTime = (int64) info.st_ctime * 1000;
  217414. }
  217415. }
  217416. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217417. {
  217418. struct utimbuf times;
  217419. times.actime = (time_t) (accessTime / 1000);
  217420. times.modtime = (time_t) (modificationTime / 1000);
  217421. return utime (fullPath.toUTF8(), &times) == 0;
  217422. }
  217423. bool File::deleteFile() const
  217424. {
  217425. if (! exists())
  217426. return true;
  217427. else if (isDirectory())
  217428. return rmdir (fullPath.toUTF8()) == 0;
  217429. else
  217430. return remove (fullPath.toUTF8()) == 0;
  217431. }
  217432. bool File::moveInternal (const File& dest) const
  217433. {
  217434. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217435. return true;
  217436. if (hasWriteAccess() && copyInternal (dest))
  217437. {
  217438. if (deleteFile())
  217439. return true;
  217440. dest.deleteFile();
  217441. }
  217442. return false;
  217443. }
  217444. void File::createDirectoryInternal (const String& fileName) const
  217445. {
  217446. mkdir (fileName.toUTF8(), 0777);
  217447. }
  217448. int64 juce_fileSetPosition (void* handle, int64 pos)
  217449. {
  217450. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217451. return pos;
  217452. return -1;
  217453. }
  217454. void FileInputStream::openHandle()
  217455. {
  217456. totalSize = file.getSize();
  217457. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217458. if (f != -1)
  217459. fileHandle = (void*) f;
  217460. }
  217461. void FileInputStream::closeHandle()
  217462. {
  217463. if (fileHandle != 0)
  217464. {
  217465. close ((int) (pointer_sized_int) fileHandle);
  217466. fileHandle = 0;
  217467. }
  217468. }
  217469. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217470. {
  217471. if (fileHandle != 0)
  217472. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217473. return 0;
  217474. }
  217475. void FileOutputStream::openHandle()
  217476. {
  217477. if (file.exists())
  217478. {
  217479. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217480. if (f != -1)
  217481. {
  217482. currentPosition = lseek (f, 0, SEEK_END);
  217483. if (currentPosition >= 0)
  217484. fileHandle = (void*) f;
  217485. else
  217486. close (f);
  217487. }
  217488. }
  217489. else
  217490. {
  217491. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217492. if (f != -1)
  217493. fileHandle = (void*) f;
  217494. }
  217495. }
  217496. void FileOutputStream::closeHandle()
  217497. {
  217498. if (fileHandle != 0)
  217499. {
  217500. close ((int) (pointer_sized_int) fileHandle);
  217501. fileHandle = 0;
  217502. }
  217503. }
  217504. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217505. {
  217506. if (fileHandle != 0)
  217507. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217508. return 0;
  217509. }
  217510. void FileOutputStream::flushInternal()
  217511. {
  217512. if (fileHandle != 0)
  217513. fsync ((int) (pointer_sized_int) fileHandle);
  217514. }
  217515. const File juce_getExecutableFile()
  217516. {
  217517. Dl_info exeInfo;
  217518. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217519. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217520. }
  217521. int64 File::getBytesFreeOnVolume() const
  217522. {
  217523. struct statfs buf;
  217524. if (juce_doStatFS (*this, buf))
  217525. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217526. return 0;
  217527. }
  217528. int64 File::getVolumeTotalSize() const
  217529. {
  217530. struct statfs buf;
  217531. if (juce_doStatFS (*this, buf))
  217532. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217533. return 0;
  217534. }
  217535. const String File::getVolumeLabel() const
  217536. {
  217537. #if JUCE_MAC
  217538. struct VolAttrBuf
  217539. {
  217540. u_int32_t length;
  217541. attrreference_t mountPointRef;
  217542. char mountPointSpace [MAXPATHLEN];
  217543. } attrBuf;
  217544. struct attrlist attrList;
  217545. zerostruct (attrList);
  217546. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217547. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217548. File f (*this);
  217549. for (;;)
  217550. {
  217551. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217552. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217553. (int) attrBuf.mountPointRef.attr_length);
  217554. const File parent (f.getParentDirectory());
  217555. if (f == parent)
  217556. break;
  217557. f = parent;
  217558. }
  217559. #endif
  217560. return String::empty;
  217561. }
  217562. int File::getVolumeSerialNumber() const
  217563. {
  217564. return 0; // xxx
  217565. }
  217566. void juce_runSystemCommand (const String& command)
  217567. {
  217568. int result = system (command.toUTF8());
  217569. (void) result;
  217570. }
  217571. const String juce_getOutputFromCommand (const String& command)
  217572. {
  217573. // slight bodge here, as we just pipe the output into a temp file and read it...
  217574. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217575. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217576. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217577. String result (tempFile.loadFileAsString());
  217578. tempFile.deleteFile();
  217579. return result;
  217580. }
  217581. class InterProcessLock::Pimpl
  217582. {
  217583. public:
  217584. Pimpl (const String& name, const int timeOutMillisecs)
  217585. : handle (0), refCount (1)
  217586. {
  217587. #if JUCE_MAC
  217588. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217589. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217590. #else
  217591. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217592. #endif
  217593. temp.create();
  217594. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217595. if (handle != 0)
  217596. {
  217597. struct flock fl;
  217598. zerostruct (fl);
  217599. fl.l_whence = SEEK_SET;
  217600. fl.l_type = F_WRLCK;
  217601. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217602. for (;;)
  217603. {
  217604. const int result = fcntl (handle, F_SETLK, &fl);
  217605. if (result >= 0)
  217606. return;
  217607. if (errno != EINTR)
  217608. {
  217609. if (timeOutMillisecs == 0
  217610. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217611. break;
  217612. Thread::sleep (10);
  217613. }
  217614. }
  217615. }
  217616. closeFile();
  217617. }
  217618. ~Pimpl()
  217619. {
  217620. closeFile();
  217621. }
  217622. void closeFile()
  217623. {
  217624. if (handle != 0)
  217625. {
  217626. struct flock fl;
  217627. zerostruct (fl);
  217628. fl.l_whence = SEEK_SET;
  217629. fl.l_type = F_UNLCK;
  217630. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217631. {}
  217632. close (handle);
  217633. handle = 0;
  217634. }
  217635. }
  217636. int handle, refCount;
  217637. };
  217638. InterProcessLock::InterProcessLock (const String& name_)
  217639. : name (name_)
  217640. {
  217641. }
  217642. InterProcessLock::~InterProcessLock()
  217643. {
  217644. }
  217645. bool InterProcessLock::enter (const int timeOutMillisecs)
  217646. {
  217647. const ScopedLock sl (lock);
  217648. if (pimpl == 0)
  217649. {
  217650. pimpl = new Pimpl (name, timeOutMillisecs);
  217651. if (pimpl->handle == 0)
  217652. pimpl = 0;
  217653. }
  217654. else
  217655. {
  217656. pimpl->refCount++;
  217657. }
  217658. return pimpl != 0;
  217659. }
  217660. void InterProcessLock::exit()
  217661. {
  217662. const ScopedLock sl (lock);
  217663. // Trying to release the lock too many times!
  217664. jassert (pimpl != 0);
  217665. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217666. pimpl = 0;
  217667. }
  217668. void JUCE_API juce_threadEntryPoint (void*);
  217669. void* threadEntryProc (void* userData)
  217670. {
  217671. JUCE_AUTORELEASEPOOL
  217672. juce_threadEntryPoint (userData);
  217673. return 0;
  217674. }
  217675. void* juce_createThread (void* userData)
  217676. {
  217677. pthread_t handle = 0;
  217678. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217679. {
  217680. pthread_detach (handle);
  217681. return (void*) handle;
  217682. }
  217683. return 0;
  217684. }
  217685. void juce_killThread (void* handle)
  217686. {
  217687. if (handle != 0)
  217688. pthread_cancel ((pthread_t) handle);
  217689. }
  217690. void juce_setCurrentThreadName (const String& /*name*/)
  217691. {
  217692. }
  217693. bool juce_setThreadPriority (void* handle, int priority)
  217694. {
  217695. struct sched_param param;
  217696. int policy;
  217697. priority = jlimit (0, 10, priority);
  217698. if (handle == 0)
  217699. handle = (void*) pthread_self();
  217700. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217701. return false;
  217702. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217703. const int minPriority = sched_get_priority_min (policy);
  217704. const int maxPriority = sched_get_priority_max (policy);
  217705. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217706. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217707. }
  217708. Thread::ThreadID Thread::getCurrentThreadId()
  217709. {
  217710. return (ThreadID) pthread_self();
  217711. }
  217712. void Thread::yield()
  217713. {
  217714. sched_yield();
  217715. }
  217716. /* Remove this macro if you're having problems compiling the cpu affinity
  217717. calls (the API for these has changed about quite a bit in various Linux
  217718. versions, and a lot of distros seem to ship with obsolete versions)
  217719. */
  217720. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217721. #define SUPPORT_AFFINITIES 1
  217722. #endif
  217723. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217724. {
  217725. #if SUPPORT_AFFINITIES
  217726. cpu_set_t affinity;
  217727. CPU_ZERO (&affinity);
  217728. for (int i = 0; i < 32; ++i)
  217729. if ((affinityMask & (1 << i)) != 0)
  217730. CPU_SET (i, &affinity);
  217731. /*
  217732. N.B. If this line causes a compile error, then you've probably not got the latest
  217733. version of glibc installed.
  217734. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217735. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217736. */
  217737. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217738. sched_yield();
  217739. #else
  217740. /* affinities aren't supported because either the appropriate header files weren't found,
  217741. or the SUPPORT_AFFINITIES macro was turned off
  217742. */
  217743. jassertfalse;
  217744. #endif
  217745. }
  217746. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217747. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217748. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217749. // compiled on its own).
  217750. #if JUCE_INCLUDED_FILE
  217751. enum
  217752. {
  217753. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  217754. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  217755. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  217756. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  217757. };
  217758. bool File::copyInternal (const File& dest) const
  217759. {
  217760. FileInputStream in (*this);
  217761. if (dest.deleteFile())
  217762. {
  217763. {
  217764. FileOutputStream out (dest);
  217765. if (out.failedToOpen())
  217766. return false;
  217767. if (out.writeFromInputStream (in, -1) == getSize())
  217768. return true;
  217769. }
  217770. dest.deleteFile();
  217771. }
  217772. return false;
  217773. }
  217774. void File::findFileSystemRoots (Array<File>& destArray)
  217775. {
  217776. destArray.add (File ("/"));
  217777. }
  217778. bool File::isOnCDRomDrive() const
  217779. {
  217780. struct statfs buf;
  217781. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217782. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  217783. }
  217784. bool File::isOnHardDisk() const
  217785. {
  217786. struct statfs buf;
  217787. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217788. {
  217789. switch (buf.f_type)
  217790. {
  217791. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217792. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217793. case U_NFS_SUPER_MAGIC: // Network NFS
  217794. case U_SMB_SUPER_MAGIC: // Network Samba
  217795. return false;
  217796. default:
  217797. // Assume anything else is a hard-disk (but note it could
  217798. // be a RAM disk. There isn't a good way of determining
  217799. // this for sure)
  217800. return true;
  217801. }
  217802. }
  217803. // Assume so if this fails for some reason
  217804. return true;
  217805. }
  217806. bool File::isOnRemovableDrive() const
  217807. {
  217808. jassertfalse; // xxx not implemented for linux!
  217809. return false;
  217810. }
  217811. bool File::isHidden() const
  217812. {
  217813. return getFileName().startsWithChar ('.');
  217814. }
  217815. namespace
  217816. {
  217817. const File juce_readlink (const String& file, const File& defaultFile)
  217818. {
  217819. const int size = 8192;
  217820. HeapBlock<char> buffer;
  217821. buffer.malloc (size + 4);
  217822. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217823. if (numBytes > 0 && numBytes <= size)
  217824. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217825. return defaultFile;
  217826. }
  217827. }
  217828. const File File::getLinkedTarget() const
  217829. {
  217830. return juce_readlink (getFullPathName().toUTF8(), *this);
  217831. }
  217832. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217833. const File File::getSpecialLocation (const SpecialLocationType type)
  217834. {
  217835. switch (type)
  217836. {
  217837. case userHomeDirectory:
  217838. {
  217839. const char* homeDir = getenv ("HOME");
  217840. if (homeDir == 0)
  217841. {
  217842. struct passwd* const pw = getpwuid (getuid());
  217843. if (pw != 0)
  217844. homeDir = pw->pw_dir;
  217845. }
  217846. return File (String::fromUTF8 (homeDir));
  217847. }
  217848. case userDocumentsDirectory:
  217849. case userMusicDirectory:
  217850. case userMoviesDirectory:
  217851. case userApplicationDataDirectory:
  217852. return File ("~");
  217853. case userDesktopDirectory:
  217854. return File ("~/Desktop");
  217855. case commonApplicationDataDirectory:
  217856. return File ("/var");
  217857. case globalApplicationsDirectory:
  217858. return File ("/usr");
  217859. case tempDirectory:
  217860. {
  217861. File tmp ("/var/tmp");
  217862. if (! tmp.isDirectory())
  217863. {
  217864. tmp = "/tmp";
  217865. if (! tmp.isDirectory())
  217866. tmp = File::getCurrentWorkingDirectory();
  217867. }
  217868. return tmp;
  217869. }
  217870. case invokedExecutableFile:
  217871. if (juce_Argv0 != 0)
  217872. return File (String::fromUTF8 (juce_Argv0));
  217873. // deliberate fall-through...
  217874. case currentExecutableFile:
  217875. case currentApplicationFile:
  217876. return juce_getExecutableFile();
  217877. case hostApplicationPath:
  217878. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217879. default:
  217880. jassertfalse; // unknown type?
  217881. break;
  217882. }
  217883. return File::nonexistent;
  217884. }
  217885. const String File::getVersion() const
  217886. {
  217887. return String::empty; // xxx not yet implemented
  217888. }
  217889. bool File::moveToTrash() const
  217890. {
  217891. if (! exists())
  217892. return true;
  217893. File trashCan ("~/.Trash");
  217894. if (! trashCan.isDirectory())
  217895. trashCan = "~/.local/share/Trash/files";
  217896. if (! trashCan.isDirectory())
  217897. return false;
  217898. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217899. getFileExtension()));
  217900. }
  217901. class DirectoryIterator::NativeIterator::Pimpl
  217902. {
  217903. public:
  217904. Pimpl (const File& directory, const String& wildCard_)
  217905. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217906. wildCard (wildCard_),
  217907. dir (opendir (directory.getFullPathName().toUTF8()))
  217908. {
  217909. if (wildCard == "*.*")
  217910. wildCard = "*";
  217911. wildcardUTF8 = wildCard.toUTF8();
  217912. }
  217913. ~Pimpl()
  217914. {
  217915. if (dir != 0)
  217916. closedir (dir);
  217917. }
  217918. bool next (String& filenameFound,
  217919. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217920. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217921. {
  217922. if (dir == 0)
  217923. return false;
  217924. for (;;)
  217925. {
  217926. struct dirent* const de = readdir (dir);
  217927. if (de == 0)
  217928. return false;
  217929. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217930. {
  217931. filenameFound = String::fromUTF8 (de->d_name);
  217932. const String path (parentDir + filenameFound);
  217933. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  217934. {
  217935. struct stat info;
  217936. const bool statOk = juce_stat (path, info);
  217937. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  217938. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  217939. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  217940. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  217941. }
  217942. if (isHidden != 0)
  217943. *isHidden = filenameFound.startsWithChar ('.');
  217944. if (isReadOnly != 0)
  217945. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  217946. return true;
  217947. }
  217948. }
  217949. }
  217950. private:
  217951. String parentDir, wildCard;
  217952. const char* wildcardUTF8;
  217953. DIR* dir;
  217954. Pimpl (const Pimpl&);
  217955. Pimpl& operator= (const Pimpl&);
  217956. };
  217957. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217958. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217959. {
  217960. }
  217961. DirectoryIterator::NativeIterator::~NativeIterator()
  217962. {
  217963. }
  217964. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217965. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217966. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217967. {
  217968. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217969. }
  217970. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217971. {
  217972. String cmdString (fileName.replace (" ", "\\ ",false));
  217973. cmdString << " " << parameters;
  217974. if (URL::isProbablyAWebsiteURL (fileName)
  217975. || cmdString.startsWithIgnoreCase ("file:")
  217976. || URL::isProbablyAnEmailAddress (fileName))
  217977. {
  217978. // create a command that tries to launch a bunch of likely browsers
  217979. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217980. StringArray cmdLines;
  217981. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217982. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217983. cmdString = cmdLines.joinIntoString (" || ");
  217984. }
  217985. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217986. const int cpid = fork();
  217987. if (cpid == 0)
  217988. {
  217989. setsid();
  217990. // Child process
  217991. execve (argv[0], (char**) argv, environ);
  217992. exit (0);
  217993. }
  217994. return cpid >= 0;
  217995. }
  217996. void File::revealToUser() const
  217997. {
  217998. if (isDirectory())
  217999. startAsProcess();
  218000. else if (getParentDirectory().exists())
  218001. getParentDirectory().startAsProcess();
  218002. }
  218003. #endif
  218004. /*** End of inlined file: juce_linux_Files.cpp ***/
  218005. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  218006. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218007. // compiled on its own).
  218008. #if JUCE_INCLUDED_FILE
  218009. struct NamedPipeInternal
  218010. {
  218011. String pipeInName, pipeOutName;
  218012. int pipeIn, pipeOut;
  218013. bool volatile createdPipe, blocked, stopReadOperation;
  218014. static void signalHandler (int) {}
  218015. };
  218016. void NamedPipe::cancelPendingReads()
  218017. {
  218018. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  218019. {
  218020. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218021. intern->stopReadOperation = true;
  218022. char buffer [1] = { 0 };
  218023. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  218024. (void) bytesWritten;
  218025. int timeout = 2000;
  218026. while (intern->blocked && --timeout >= 0)
  218027. Thread::sleep (2);
  218028. intern->stopReadOperation = false;
  218029. }
  218030. }
  218031. void NamedPipe::close()
  218032. {
  218033. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218034. if (intern != 0)
  218035. {
  218036. internal = 0;
  218037. if (intern->pipeIn != -1)
  218038. ::close (intern->pipeIn);
  218039. if (intern->pipeOut != -1)
  218040. ::close (intern->pipeOut);
  218041. if (intern->createdPipe)
  218042. {
  218043. unlink (intern->pipeInName.toUTF8());
  218044. unlink (intern->pipeOutName.toUTF8());
  218045. }
  218046. delete intern;
  218047. }
  218048. }
  218049. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  218050. {
  218051. close();
  218052. NamedPipeInternal* const intern = new NamedPipeInternal();
  218053. internal = intern;
  218054. intern->createdPipe = createPipe;
  218055. intern->blocked = false;
  218056. intern->stopReadOperation = false;
  218057. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  218058. siginterrupt (SIGPIPE, 1);
  218059. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  218060. intern->pipeInName = pipePath + "_in";
  218061. intern->pipeOutName = pipePath + "_out";
  218062. intern->pipeIn = -1;
  218063. intern->pipeOut = -1;
  218064. if (createPipe)
  218065. {
  218066. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  218067. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  218068. {
  218069. delete intern;
  218070. internal = 0;
  218071. return false;
  218072. }
  218073. }
  218074. return true;
  218075. }
  218076. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  218077. {
  218078. int bytesRead = -1;
  218079. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218080. if (intern != 0)
  218081. {
  218082. intern->blocked = true;
  218083. if (intern->pipeIn == -1)
  218084. {
  218085. if (intern->createdPipe)
  218086. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  218087. else
  218088. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  218089. if (intern->pipeIn == -1)
  218090. {
  218091. intern->blocked = false;
  218092. return -1;
  218093. }
  218094. }
  218095. bytesRead = 0;
  218096. char* p = static_cast<char*> (destBuffer);
  218097. while (bytesRead < maxBytesToRead)
  218098. {
  218099. const int bytesThisTime = maxBytesToRead - bytesRead;
  218100. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  218101. if (numRead <= 0 || intern->stopReadOperation)
  218102. {
  218103. bytesRead = -1;
  218104. break;
  218105. }
  218106. bytesRead += numRead;
  218107. p += bytesRead;
  218108. }
  218109. intern->blocked = false;
  218110. }
  218111. return bytesRead;
  218112. }
  218113. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  218114. {
  218115. int bytesWritten = -1;
  218116. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218117. if (intern != 0)
  218118. {
  218119. if (intern->pipeOut == -1)
  218120. {
  218121. if (intern->createdPipe)
  218122. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  218123. else
  218124. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  218125. if (intern->pipeOut == -1)
  218126. {
  218127. return -1;
  218128. }
  218129. }
  218130. const char* p = static_cast<const char*> (sourceBuffer);
  218131. bytesWritten = 0;
  218132. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  218133. while (bytesWritten < numBytesToWrite
  218134. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  218135. {
  218136. const int bytesThisTime = numBytesToWrite - bytesWritten;
  218137. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  218138. if (numWritten <= 0)
  218139. {
  218140. bytesWritten = -1;
  218141. break;
  218142. }
  218143. bytesWritten += numWritten;
  218144. p += bytesWritten;
  218145. }
  218146. }
  218147. return bytesWritten;
  218148. }
  218149. #endif
  218150. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  218151. /*** Start of inlined file: juce_linux_Network.cpp ***/
  218152. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218153. // compiled on its own).
  218154. #if JUCE_INCLUDED_FILE
  218155. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  218156. {
  218157. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  218158. if (s != -1)
  218159. {
  218160. char buf [1024];
  218161. struct ifconf ifc;
  218162. ifc.ifc_len = sizeof (buf);
  218163. ifc.ifc_buf = buf;
  218164. ioctl (s, SIOCGIFCONF, &ifc);
  218165. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  218166. {
  218167. struct ifreq ifr;
  218168. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  218169. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  218170. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  218171. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  218172. {
  218173. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  218174. }
  218175. }
  218176. close (s);
  218177. }
  218178. }
  218179. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218180. const String& emailSubject,
  218181. const String& bodyText,
  218182. const StringArray& filesToAttach)
  218183. {
  218184. jassertfalse; // xxx todo
  218185. return false;
  218186. }
  218187. /** A HTTP input stream that uses sockets.
  218188. */
  218189. class JUCE_HTTPSocketStream
  218190. {
  218191. public:
  218192. JUCE_HTTPSocketStream()
  218193. : readPosition (0),
  218194. socketHandle (-1),
  218195. levelsOfRedirection (0),
  218196. timeoutSeconds (15)
  218197. {
  218198. }
  218199. ~JUCE_HTTPSocketStream()
  218200. {
  218201. closeSocket();
  218202. }
  218203. bool open (const String& url,
  218204. const String& headers,
  218205. const MemoryBlock& postData,
  218206. const bool isPost,
  218207. URL::OpenStreamProgressCallback* callback,
  218208. void* callbackContext,
  218209. int timeOutMs)
  218210. {
  218211. closeSocket();
  218212. uint32 timeOutTime = Time::getMillisecondCounter();
  218213. if (timeOutMs == 0)
  218214. timeOutTime += 60000;
  218215. else if (timeOutMs < 0)
  218216. timeOutTime = 0xffffffff;
  218217. else
  218218. timeOutTime += timeOutMs;
  218219. String hostName, hostPath;
  218220. int hostPort;
  218221. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218222. return false;
  218223. const struct hostent* host = 0;
  218224. int port = 0;
  218225. String proxyName, proxyPath;
  218226. int proxyPort = 0;
  218227. String proxyURL (getenv ("http_proxy"));
  218228. if (proxyURL.startsWithIgnoreCase ("http://"))
  218229. {
  218230. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218231. return false;
  218232. host = gethostbyname (proxyName.toUTF8());
  218233. port = proxyPort;
  218234. }
  218235. else
  218236. {
  218237. host = gethostbyname (hostName.toUTF8());
  218238. port = hostPort;
  218239. }
  218240. if (host == 0)
  218241. return false;
  218242. struct sockaddr_in address;
  218243. zerostruct (address);
  218244. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218245. address.sin_family = host->h_addrtype;
  218246. address.sin_port = htons (port);
  218247. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218248. if (socketHandle == -1)
  218249. return false;
  218250. int receiveBufferSize = 16384;
  218251. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218252. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218253. #if JUCE_MAC
  218254. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218255. #endif
  218256. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218257. {
  218258. closeSocket();
  218259. return false;
  218260. }
  218261. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  218262. hostPath, url, headers, postData, isPost));
  218263. size_t totalHeaderSent = 0;
  218264. while (totalHeaderSent < requestHeader.getSize())
  218265. {
  218266. if (Time::getMillisecondCounter() > timeOutTime)
  218267. {
  218268. closeSocket();
  218269. return false;
  218270. }
  218271. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218272. if (send (socketHandle, ((const char*) requestHeader.getData()) + totalHeaderSent, numToSend, 0)
  218273. != numToSend)
  218274. {
  218275. closeSocket();
  218276. return false;
  218277. }
  218278. totalHeaderSent += numToSend;
  218279. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218280. {
  218281. closeSocket();
  218282. return false;
  218283. }
  218284. }
  218285. const String responseHeader (readResponse (timeOutTime));
  218286. if (responseHeader.isNotEmpty())
  218287. {
  218288. headerLines.clear();
  218289. headerLines.addLines (responseHeader);
  218290. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218291. .substring (0, 3).getIntValue();
  218292. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218293. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218294. String location (findHeaderItem (headerLines, "Location:"));
  218295. if (statusCode >= 300 && statusCode < 400
  218296. && location.isNotEmpty())
  218297. {
  218298. if (! location.startsWithIgnoreCase ("http://"))
  218299. location = "http://" + location;
  218300. if (levelsOfRedirection++ < 3)
  218301. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218302. }
  218303. else
  218304. {
  218305. levelsOfRedirection = 0;
  218306. return true;
  218307. }
  218308. }
  218309. closeSocket();
  218310. return false;
  218311. }
  218312. int read (void* buffer, int bytesToRead)
  218313. {
  218314. fd_set readbits;
  218315. FD_ZERO (&readbits);
  218316. FD_SET (socketHandle, &readbits);
  218317. struct timeval tv;
  218318. tv.tv_sec = timeoutSeconds;
  218319. tv.tv_usec = 0;
  218320. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218321. return 0; // (timeout)
  218322. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218323. readPosition += bytesRead;
  218324. return bytesRead;
  218325. }
  218326. int readPosition;
  218327. StringArray headerLines;
  218328. juce_UseDebuggingNewOperator
  218329. private:
  218330. int socketHandle, levelsOfRedirection;
  218331. const int timeoutSeconds;
  218332. void closeSocket()
  218333. {
  218334. if (socketHandle >= 0)
  218335. close (socketHandle);
  218336. socketHandle = -1;
  218337. }
  218338. const MemoryBlock createRequestHeader (const String& hostName,
  218339. const int hostPort,
  218340. const String& proxyName,
  218341. const int proxyPort,
  218342. const String& hostPath,
  218343. const String& originalURL,
  218344. const String& headers,
  218345. const MemoryBlock& postData,
  218346. const bool isPost)
  218347. {
  218348. String header (isPost ? "POST " : "GET ");
  218349. if (proxyName.isEmpty())
  218350. {
  218351. header << hostPath << " HTTP/1.0\r\nHost: "
  218352. << hostName << ':' << hostPort;
  218353. }
  218354. else
  218355. {
  218356. header << originalURL << " HTTP/1.0\r\nHost: "
  218357. << proxyName << ':' << proxyPort;
  218358. }
  218359. header << "\r\nUser-Agent: JUCE/"
  218360. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218361. << "\r\nConnection: Close\r\nContent-Length: "
  218362. << postData.getSize() << "\r\n"
  218363. << headers << "\r\n";
  218364. MemoryBlock mb;
  218365. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218366. mb.append (postData.getData(), postData.getSize());
  218367. return mb;
  218368. }
  218369. const String readResponse (const uint32 timeOutTime)
  218370. {
  218371. int bytesRead = 0, numConsecutiveLFs = 0;
  218372. MemoryBlock buffer (1024, true);
  218373. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218374. && Time::getMillisecondCounter() <= timeOutTime)
  218375. {
  218376. fd_set readbits;
  218377. FD_ZERO (&readbits);
  218378. FD_SET (socketHandle, &readbits);
  218379. struct timeval tv;
  218380. tv.tv_sec = timeoutSeconds;
  218381. tv.tv_usec = 0;
  218382. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218383. return String::empty; // (timeout)
  218384. buffer.ensureSize (bytesRead + 8, true);
  218385. char* const dest = (char*) buffer.getData() + bytesRead;
  218386. if (recv (socketHandle, dest, 1, 0) == -1)
  218387. return String::empty;
  218388. const char lastByte = *dest;
  218389. ++bytesRead;
  218390. if (lastByte == '\n')
  218391. ++numConsecutiveLFs;
  218392. else if (lastByte != '\r')
  218393. numConsecutiveLFs = 0;
  218394. }
  218395. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218396. if (header.startsWithIgnoreCase ("HTTP/"))
  218397. return header.trimEnd();
  218398. return String::empty;
  218399. }
  218400. static bool decomposeURL (const String& url,
  218401. String& host, String& path, int& port)
  218402. {
  218403. if (! url.startsWithIgnoreCase ("http://"))
  218404. return false;
  218405. const int nextSlash = url.indexOfChar (7, '/');
  218406. int nextColon = url.indexOfChar (7, ':');
  218407. if (nextColon > nextSlash && nextSlash > 0)
  218408. nextColon = -1;
  218409. if (nextColon >= 0)
  218410. {
  218411. host = url.substring (7, nextColon);
  218412. if (nextSlash >= 0)
  218413. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218414. else
  218415. port = url.substring (nextColon + 1).getIntValue();
  218416. }
  218417. else
  218418. {
  218419. port = 80;
  218420. if (nextSlash >= 0)
  218421. host = url.substring (7, nextSlash);
  218422. else
  218423. host = url.substring (7);
  218424. }
  218425. if (nextSlash >= 0)
  218426. path = url.substring (nextSlash);
  218427. else
  218428. path = "/";
  218429. return true;
  218430. }
  218431. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218432. {
  218433. for (int i = 0; i < lines.size(); ++i)
  218434. if (lines[i].startsWithIgnoreCase (itemName))
  218435. return lines[i].substring (itemName.length()).trim();
  218436. return String::empty;
  218437. }
  218438. };
  218439. void* juce_openInternetFile (const String& url,
  218440. const String& headers,
  218441. const MemoryBlock& postData,
  218442. const bool isPost,
  218443. URL::OpenStreamProgressCallback* callback,
  218444. void* callbackContext,
  218445. int timeOutMs)
  218446. {
  218447. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218448. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218449. return s.release();
  218450. return 0;
  218451. }
  218452. void juce_closeInternetFile (void* handle)
  218453. {
  218454. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218455. }
  218456. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218457. {
  218458. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218459. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218460. }
  218461. int64 juce_getInternetFileContentLength (void* handle)
  218462. {
  218463. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218464. if (s != 0)
  218465. {
  218466. //xxx todo
  218467. jassertfalse
  218468. }
  218469. return -1;
  218470. }
  218471. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218472. {
  218473. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218474. if (s != 0)
  218475. {
  218476. for (int i = 0; i < s->headerLines.size(); ++i)
  218477. {
  218478. const String& headersEntry = s->headerLines[i];
  218479. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218480. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218481. const String previousValue (headers [key]);
  218482. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218483. }
  218484. }
  218485. }
  218486. int juce_seekInInternetFile (void* handle, int newPosition)
  218487. {
  218488. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218489. return s != 0 ? s->readPosition : 0;
  218490. }
  218491. #endif
  218492. /*** End of inlined file: juce_linux_Network.cpp ***/
  218493. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218494. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218495. // compiled on its own).
  218496. #if JUCE_INCLUDED_FILE
  218497. void Logger::outputDebugString (const String& text)
  218498. {
  218499. std::cerr << text << std::endl;
  218500. }
  218501. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218502. {
  218503. return Linux;
  218504. }
  218505. const String SystemStats::getOperatingSystemName()
  218506. {
  218507. return "Linux";
  218508. }
  218509. bool SystemStats::isOperatingSystem64Bit()
  218510. {
  218511. #if JUCE_64BIT
  218512. return true;
  218513. #else
  218514. //xxx not sure how to find this out?..
  218515. return false;
  218516. #endif
  218517. }
  218518. namespace LinuxStatsHelpers
  218519. {
  218520. const String getCpuInfo (const char* const key)
  218521. {
  218522. StringArray lines;
  218523. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218524. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218525. if (lines[i].startsWithIgnoreCase (key))
  218526. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218527. return String::empty;
  218528. }
  218529. bool getTimeSinceStartup (timeval* const t) throw()
  218530. {
  218531. if (gettimeofday (t, 0) != 0)
  218532. return false;
  218533. static unsigned int calibrate = 0;
  218534. static bool calibrated = false;
  218535. if (! calibrated)
  218536. {
  218537. calibrated = true;
  218538. struct sysinfo sysi;
  218539. if (sysinfo (&sysi) == 0)
  218540. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218541. }
  218542. t->tv_sec -= calibrate;
  218543. return true;
  218544. }
  218545. }
  218546. const String SystemStats::getCpuVendor()
  218547. {
  218548. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  218549. }
  218550. int SystemStats::getCpuSpeedInMegaherz()
  218551. {
  218552. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  218553. }
  218554. int SystemStats::getMemorySizeInMegabytes()
  218555. {
  218556. struct sysinfo sysi;
  218557. if (sysinfo (&sysi) == 0)
  218558. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218559. return 0;
  218560. }
  218561. int SystemStats::getPageSize()
  218562. {
  218563. return sysconf (_SC_PAGESIZE);
  218564. }
  218565. const String SystemStats::getLogonName()
  218566. {
  218567. const char* user = getenv ("USER");
  218568. if (user == 0)
  218569. {
  218570. struct passwd* const pw = getpwuid (getuid());
  218571. if (pw != 0)
  218572. user = pw->pw_name;
  218573. }
  218574. return String::fromUTF8 (user);
  218575. }
  218576. const String SystemStats::getFullUserName()
  218577. {
  218578. return getLogonName();
  218579. }
  218580. void SystemStats::initialiseStats()
  218581. {
  218582. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  218583. cpuFlags.hasMMX = flags.contains ("mmx");
  218584. cpuFlags.hasSSE = flags.contains ("sse");
  218585. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218586. cpuFlags.has3DNow = flags.contains ("3dnow");
  218587. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  218588. }
  218589. void PlatformUtilities::fpuReset()
  218590. {
  218591. }
  218592. uint32 juce_millisecondsSinceStartup() throw()
  218593. {
  218594. timeval t;
  218595. if (LinuxStatsHelpers::getTimeSinceStartup (&t))
  218596. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218597. return 0;
  218598. }
  218599. int64 Time::getHighResolutionTicks() throw()
  218600. {
  218601. timeval t;
  218602. if (LinuxStatsHelpers::getTimeSinceStartup (&t))
  218603. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218604. return 0;
  218605. }
  218606. int64 Time::getHighResolutionTicksPerSecond() throw()
  218607. {
  218608. return 1000000; // (microseconds)
  218609. }
  218610. double Time::getMillisecondCounterHiRes() throw()
  218611. {
  218612. return getHighResolutionTicks() * 0.001;
  218613. }
  218614. bool Time::setSystemTimeToThisTime() const
  218615. {
  218616. timeval t;
  218617. t.tv_sec = millisSinceEpoch % 1000000;
  218618. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218619. return settimeofday (&t, 0) ? false : true;
  218620. }
  218621. #endif
  218622. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218623. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218624. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218625. // compiled on its own).
  218626. #if JUCE_INCLUDED_FILE
  218627. /*
  218628. Note that a lot of methods that you'd expect to find in this file actually
  218629. live in juce_posix_SharedCode.h!
  218630. */
  218631. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218632. void Process::setPriority (ProcessPriority prior)
  218633. {
  218634. struct sched_param param;
  218635. int policy, maxp, minp;
  218636. const int p = (int) prior;
  218637. if (p <= 1)
  218638. policy = SCHED_OTHER;
  218639. else
  218640. policy = SCHED_RR;
  218641. minp = sched_get_priority_min (policy);
  218642. maxp = sched_get_priority_max (policy);
  218643. if (p < 2)
  218644. param.sched_priority = 0;
  218645. else if (p == 2 )
  218646. // Set to middle of lower realtime priority range
  218647. param.sched_priority = minp + (maxp - minp) / 4;
  218648. else
  218649. // Set to middle of higher realtime priority range
  218650. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218651. pthread_setschedparam (pthread_self(), policy, &param);
  218652. }
  218653. void Process::terminate()
  218654. {
  218655. exit (0);
  218656. }
  218657. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  218658. {
  218659. static char testResult = 0;
  218660. if (testResult == 0)
  218661. {
  218662. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218663. if (testResult >= 0)
  218664. {
  218665. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218666. testResult = 1;
  218667. }
  218668. }
  218669. return testResult < 0;
  218670. }
  218671. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218672. {
  218673. return juce_isRunningUnderDebugger();
  218674. }
  218675. void Process::raisePrivilege()
  218676. {
  218677. // If running suid root, change effective user
  218678. // to root
  218679. if (geteuid() != 0 && getuid() == 0)
  218680. {
  218681. setreuid (geteuid(), getuid());
  218682. setregid (getegid(), getgid());
  218683. }
  218684. }
  218685. void Process::lowerPrivilege()
  218686. {
  218687. // If runing suid root, change effective user
  218688. // back to real user
  218689. if (geteuid() == 0 && getuid() != 0)
  218690. {
  218691. setreuid (geteuid(), getuid());
  218692. setregid (getegid(), getgid());
  218693. }
  218694. }
  218695. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218696. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218697. {
  218698. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218699. }
  218700. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218701. {
  218702. dlclose(handle);
  218703. }
  218704. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218705. {
  218706. return dlsym (libraryHandle, procedureName.toCString());
  218707. }
  218708. #endif
  218709. #endif
  218710. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218711. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218712. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218713. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218714. // compiled on its own).
  218715. #if JUCE_INCLUDED_FILE
  218716. extern Display* display;
  218717. extern Window juce_messageWindowHandle;
  218718. namespace ClipboardHelpers
  218719. {
  218720. static String localClipboardContent;
  218721. static Atom atom_UTF8_STRING;
  218722. static Atom atom_CLIPBOARD;
  218723. static Atom atom_TARGETS;
  218724. static void initSelectionAtoms()
  218725. {
  218726. static bool isInitialised = false;
  218727. if (! isInitialised)
  218728. {
  218729. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218730. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218731. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218732. }
  218733. }
  218734. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218735. // works only for strings shorter than 1000000 bytes
  218736. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218737. {
  218738. String returnData;
  218739. char* clipData;
  218740. Atom actualType;
  218741. int actualFormat;
  218742. unsigned long numItems, bytesLeft;
  218743. if (XGetWindowProperty (display, window, prop,
  218744. 0L /* offset */, 1000000 /* length (max) */, False,
  218745. AnyPropertyType /* format */,
  218746. &actualType, &actualFormat, &numItems, &bytesLeft,
  218747. (unsigned char**) &clipData) == Success)
  218748. {
  218749. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218750. returnData = String::fromUTF8 (clipData, numItems);
  218751. else if (actualType == XA_STRING && actualFormat == 8)
  218752. returnData = String (clipData, numItems);
  218753. if (clipData != 0)
  218754. XFree (clipData);
  218755. jassert (bytesLeft == 0 || numItems == 1000000);
  218756. }
  218757. XDeleteProperty (display, window, prop);
  218758. return returnData;
  218759. }
  218760. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218761. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218762. {
  218763. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218764. // The selection owner will be asked to set the JUCE_SEL property on the
  218765. // juce_messageWindowHandle with the selection content
  218766. XConvertSelection (display, selection, requestedFormat, property_name,
  218767. juce_messageWindowHandle, CurrentTime);
  218768. int count = 50; // will wait at most for 200 ms
  218769. while (--count >= 0)
  218770. {
  218771. XEvent event;
  218772. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218773. {
  218774. if (event.xselection.property == property_name)
  218775. {
  218776. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218777. selectionContent = readWindowProperty (event.xselection.requestor,
  218778. event.xselection.property,
  218779. requestedFormat);
  218780. return true;
  218781. }
  218782. else
  218783. {
  218784. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218785. }
  218786. }
  218787. // not very elegant.. we could do a select() or something like that...
  218788. // however clipboard content requesting is inherently slow on x11, it
  218789. // often takes 50ms or more so...
  218790. Thread::sleep (4);
  218791. }
  218792. return false;
  218793. }
  218794. }
  218795. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218796. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218797. {
  218798. ClipboardHelpers::initSelectionAtoms();
  218799. // the selection content is sent to the target window as a window property
  218800. XSelectionEvent reply;
  218801. reply.type = SelectionNotify;
  218802. reply.display = evt.display;
  218803. reply.requestor = evt.requestor;
  218804. reply.selection = evt.selection;
  218805. reply.target = evt.target;
  218806. reply.property = None; // == "fail"
  218807. reply.time = evt.time;
  218808. HeapBlock <char> data;
  218809. int propertyFormat = 0, numDataItems = 0;
  218810. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218811. {
  218812. if (evt.target == XA_STRING)
  218813. {
  218814. // format data according to system locale
  218815. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218816. data.calloc (numDataItems + 1);
  218817. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218818. propertyFormat = 8; // bits/item
  218819. }
  218820. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218821. {
  218822. // translate to utf8
  218823. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218824. data.calloc (numDataItems + 1);
  218825. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218826. propertyFormat = 8; // bits/item
  218827. }
  218828. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218829. {
  218830. // another application wants to know what we are able to send
  218831. numDataItems = 2;
  218832. propertyFormat = 32; // atoms are 32-bit
  218833. data.calloc (numDataItems * 4);
  218834. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218835. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218836. atoms[1] = XA_STRING;
  218837. }
  218838. }
  218839. else
  218840. {
  218841. DBG ("requested unsupported clipboard");
  218842. }
  218843. if (data != 0)
  218844. {
  218845. const int maxReasonableSelectionSize = 1000000;
  218846. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218847. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218848. {
  218849. XChangeProperty (evt.display, evt.requestor,
  218850. evt.property, evt.target,
  218851. propertyFormat /* 8 or 32 */, PropModeReplace,
  218852. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218853. reply.property = evt.property; // " == success"
  218854. }
  218855. }
  218856. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218857. }
  218858. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218859. {
  218860. ClipboardHelpers::initSelectionAtoms();
  218861. ClipboardHelpers::localClipboardContent = clipText;
  218862. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218863. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218864. }
  218865. const String SystemClipboard::getTextFromClipboard()
  218866. {
  218867. ClipboardHelpers::initSelectionAtoms();
  218868. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218869. level" clipboard that is supposed to be filled by ctrl-C
  218870. etc). When a clipboard manager is running, the content of this
  218871. selection is preserved even when the original selection owner
  218872. exits.
  218873. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218874. filled by good old x11 apps such as xterm)
  218875. */
  218876. String content;
  218877. Atom selection = XA_PRIMARY;
  218878. Window selectionOwner = None;
  218879. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218880. {
  218881. selection = ClipboardHelpers::atom_CLIPBOARD;
  218882. selectionOwner = XGetSelectionOwner (display, selection);
  218883. }
  218884. if (selectionOwner != None)
  218885. {
  218886. if (selectionOwner == juce_messageWindowHandle)
  218887. {
  218888. content = ClipboardHelpers::localClipboardContent;
  218889. }
  218890. else
  218891. {
  218892. // first try: we want an utf8 string
  218893. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218894. if (! ok)
  218895. {
  218896. // second chance, ask for a good old locale-dependent string ..
  218897. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218898. }
  218899. }
  218900. }
  218901. return content;
  218902. }
  218903. #endif
  218904. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218905. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218906. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218907. // compiled on its own).
  218908. #if JUCE_INCLUDED_FILE
  218909. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218910. #define JUCE_DEBUG_XERRORS 1
  218911. #endif
  218912. Display* display = 0;
  218913. Window juce_messageWindowHandle = None;
  218914. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218915. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218916. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218917. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218918. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218919. class InternalMessageQueue
  218920. {
  218921. public:
  218922. InternalMessageQueue()
  218923. : bytesInSocket (0),
  218924. totalEventCount (0)
  218925. {
  218926. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218927. (void) ret; jassert (ret == 0);
  218928. //setNonBlocking (fd[0]);
  218929. //setNonBlocking (fd[1]);
  218930. }
  218931. ~InternalMessageQueue()
  218932. {
  218933. close (fd[0]);
  218934. close (fd[1]);
  218935. clearSingletonInstance();
  218936. }
  218937. void postMessage (Message* msg)
  218938. {
  218939. const int maxBytesInSocketQueue = 128;
  218940. ScopedLock sl (lock);
  218941. queue.add (msg);
  218942. if (bytesInSocket < maxBytesInSocketQueue)
  218943. {
  218944. ++bytesInSocket;
  218945. ScopedUnlock ul (lock);
  218946. const unsigned char x = 0xff;
  218947. size_t bytesWritten = write (fd[0], &x, 1);
  218948. (void) bytesWritten;
  218949. }
  218950. }
  218951. bool isEmpty() const
  218952. {
  218953. ScopedLock sl (lock);
  218954. return queue.size() == 0;
  218955. }
  218956. bool dispatchNextEvent()
  218957. {
  218958. // This alternates between giving priority to XEvents or internal messages,
  218959. // to keep everything running smoothly..
  218960. if ((++totalEventCount & 1) != 0)
  218961. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218962. else
  218963. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218964. }
  218965. // Wait for an event (either XEvent, or an internal Message)
  218966. bool sleepUntilEvent (const int timeoutMs)
  218967. {
  218968. if (! isEmpty())
  218969. return true;
  218970. if (display != 0)
  218971. {
  218972. ScopedXLock xlock;
  218973. if (XPending (display))
  218974. return true;
  218975. }
  218976. struct timeval tv;
  218977. tv.tv_sec = 0;
  218978. tv.tv_usec = timeoutMs * 1000;
  218979. int fd0 = getWaitHandle();
  218980. int fdmax = fd0;
  218981. fd_set readset;
  218982. FD_ZERO (&readset);
  218983. FD_SET (fd0, &readset);
  218984. if (display != 0)
  218985. {
  218986. ScopedXLock xlock;
  218987. int fd1 = XConnectionNumber (display);
  218988. FD_SET (fd1, &readset);
  218989. fdmax = jmax (fd0, fd1);
  218990. }
  218991. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218992. return (ret > 0); // ret <= 0 if error or timeout
  218993. }
  218994. struct MessageThreadFuncCall
  218995. {
  218996. enum { uniqueID = 0x73774623 };
  218997. MessageCallbackFunction* func;
  218998. void* parameter;
  218999. void* result;
  219000. CriticalSection lock;
  219001. WaitableEvent event;
  219002. };
  219003. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  219004. private:
  219005. CriticalSection lock;
  219006. OwnedArray <Message> queue;
  219007. int fd[2];
  219008. int bytesInSocket;
  219009. int totalEventCount;
  219010. int getWaitHandle() const throw() { return fd[1]; }
  219011. static bool setNonBlocking (int handle)
  219012. {
  219013. int socketFlags = fcntl (handle, F_GETFL, 0);
  219014. if (socketFlags == -1)
  219015. return false;
  219016. socketFlags |= O_NONBLOCK;
  219017. return fcntl (handle, F_SETFL, socketFlags) == 0;
  219018. }
  219019. static bool dispatchNextXEvent()
  219020. {
  219021. if (display == 0)
  219022. return false;
  219023. XEvent evt;
  219024. {
  219025. ScopedXLock xlock;
  219026. if (! XPending (display))
  219027. return false;
  219028. XNextEvent (display, &evt);
  219029. }
  219030. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  219031. juce_handleSelectionRequest (evt.xselectionrequest);
  219032. else if (evt.xany.window != juce_messageWindowHandle)
  219033. juce_windowMessageReceive (&evt);
  219034. return true;
  219035. }
  219036. Message* popNextMessage()
  219037. {
  219038. ScopedLock sl (lock);
  219039. if (bytesInSocket > 0)
  219040. {
  219041. --bytesInSocket;
  219042. ScopedUnlock ul (lock);
  219043. unsigned char x;
  219044. size_t numBytes = read (fd[1], &x, 1);
  219045. (void) numBytes;
  219046. }
  219047. return queue.removeAndReturn (0);
  219048. }
  219049. bool dispatchNextInternalMessage()
  219050. {
  219051. ScopedPointer <Message> msg (popNextMessage());
  219052. if (msg == 0)
  219053. return false;
  219054. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  219055. {
  219056. // Handle callback message
  219057. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  219058. call->result = (*(call->func)) (call->parameter);
  219059. call->event.signal();
  219060. }
  219061. else
  219062. {
  219063. // Handle "normal" messages
  219064. MessageManager::getInstance()->deliverMessage (msg.release());
  219065. }
  219066. return true;
  219067. }
  219068. };
  219069. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  219070. namespace LinuxErrorHandling
  219071. {
  219072. static bool errorOccurred = false;
  219073. static bool keyboardBreakOccurred = false;
  219074. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  219075. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  219076. // Usually happens when client-server connection is broken
  219077. static int ioErrorHandler (Display* display)
  219078. {
  219079. DBG ("ERROR: connection to X server broken.. terminating.");
  219080. if (JUCEApplication::isStandaloneApp())
  219081. MessageManager::getInstance()->stopDispatchLoop();
  219082. errorOccurred = true;
  219083. return 0;
  219084. }
  219085. // A protocol error has occurred
  219086. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  219087. {
  219088. #if JUCE_DEBUG_XERRORS
  219089. char errorStr[64] = { 0 };
  219090. char requestStr[64] = { 0 };
  219091. XGetErrorText (display, event->error_code, errorStr, 64);
  219092. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  219093. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  219094. #endif
  219095. return 0;
  219096. }
  219097. static void installXErrorHandlers()
  219098. {
  219099. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  219100. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  219101. }
  219102. static void removeXErrorHandlers()
  219103. {
  219104. if (JUCEApplication::isStandaloneApp())
  219105. {
  219106. XSetIOErrorHandler (oldIOErrorHandler);
  219107. oldIOErrorHandler = 0;
  219108. XSetErrorHandler (oldErrorHandler);
  219109. oldErrorHandler = 0;
  219110. }
  219111. }
  219112. static void keyboardBreakSignalHandler (int sig)
  219113. {
  219114. if (sig == SIGINT)
  219115. keyboardBreakOccurred = true;
  219116. }
  219117. static void installKeyboardBreakHandler()
  219118. {
  219119. struct sigaction saction;
  219120. sigset_t maskSet;
  219121. sigemptyset (&maskSet);
  219122. saction.sa_handler = keyboardBreakSignalHandler;
  219123. saction.sa_mask = maskSet;
  219124. saction.sa_flags = 0;
  219125. sigaction (SIGINT, &saction, 0);
  219126. }
  219127. }
  219128. void MessageManager::doPlatformSpecificInitialisation()
  219129. {
  219130. if (JUCEApplication::isStandaloneApp())
  219131. {
  219132. // Initialise xlib for multiple thread support
  219133. static bool initThreadCalled = false;
  219134. if (! initThreadCalled)
  219135. {
  219136. if (! XInitThreads())
  219137. {
  219138. // This is fatal! Print error and closedown
  219139. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  219140. Process::terminate();
  219141. return;
  219142. }
  219143. initThreadCalled = true;
  219144. }
  219145. LinuxErrorHandling::installXErrorHandlers();
  219146. LinuxErrorHandling::installKeyboardBreakHandler();
  219147. }
  219148. // Create the internal message queue
  219149. InternalMessageQueue::getInstance();
  219150. // Try to connect to a display
  219151. String displayName (getenv ("DISPLAY"));
  219152. if (displayName.isEmpty())
  219153. displayName = ":0.0";
  219154. display = XOpenDisplay (displayName.toCString());
  219155. if (display != 0) // This is not fatal! we can run headless.
  219156. {
  219157. // Create a context to store user data associated with Windows we create in WindowDriver
  219158. windowHandleXContext = XUniqueContext();
  219159. // We're only interested in client messages for this window, which are always sent
  219160. XSetWindowAttributes swa;
  219161. swa.event_mask = NoEventMask;
  219162. // Create our message window (this will never be mapped)
  219163. const int screen = DefaultScreen (display);
  219164. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  219165. 0, 0, 1, 1, 0, 0, InputOnly,
  219166. DefaultVisual (display, screen),
  219167. CWEventMask, &swa);
  219168. }
  219169. }
  219170. void MessageManager::doPlatformSpecificShutdown()
  219171. {
  219172. InternalMessageQueue::deleteInstance();
  219173. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  219174. {
  219175. XDestroyWindow (display, juce_messageWindowHandle);
  219176. XCloseDisplay (display);
  219177. juce_messageWindowHandle = 0;
  219178. display = 0;
  219179. LinuxErrorHandling::removeXErrorHandlers();
  219180. }
  219181. }
  219182. bool juce_postMessageToSystemQueue (Message* message)
  219183. {
  219184. if (LinuxErrorHandling::errorOccurred)
  219185. return false;
  219186. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219187. return true;
  219188. }
  219189. void MessageManager::broadcastMessage (const String& value)
  219190. {
  219191. /* TODO */
  219192. }
  219193. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  219194. {
  219195. if (LinuxErrorHandling::errorOccurred)
  219196. return 0;
  219197. if (isThisTheMessageThread())
  219198. return func (parameter);
  219199. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219200. messageCallContext.func = func;
  219201. messageCallContext.parameter = parameter;
  219202. InternalMessageQueue::getInstanceWithoutCreating()
  219203. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219204. 0, 0, &messageCallContext));
  219205. // Wait for it to complete before continuing
  219206. messageCallContext.event.wait();
  219207. return messageCallContext.result;
  219208. }
  219209. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219210. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219211. {
  219212. while (! LinuxErrorHandling::errorOccurred)
  219213. {
  219214. if (LinuxErrorHandling::keyboardBreakOccurred)
  219215. {
  219216. LinuxErrorHandling::errorOccurred = true;
  219217. if (JUCEApplication::isStandaloneApp())
  219218. Process::terminate();
  219219. break;
  219220. }
  219221. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219222. return true;
  219223. if (returnIfNoPendingMessages)
  219224. break;
  219225. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219226. }
  219227. return false;
  219228. }
  219229. #endif
  219230. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219231. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219232. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219233. // compiled on its own).
  219234. #if JUCE_INCLUDED_FILE
  219235. class FreeTypeFontFace
  219236. {
  219237. public:
  219238. enum FontStyle
  219239. {
  219240. Plain = 0,
  219241. Bold = 1,
  219242. Italic = 2
  219243. };
  219244. FreeTypeFontFace (const String& familyName)
  219245. : hasSerif (false),
  219246. monospaced (false)
  219247. {
  219248. family = familyName;
  219249. }
  219250. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219251. {
  219252. if (names [(int) style].fileName.isEmpty())
  219253. {
  219254. names [(int) style].fileName = name;
  219255. names [(int) style].faceIndex = faceIndex;
  219256. }
  219257. }
  219258. const String& getFamilyName() const throw() { return family; }
  219259. const String& getFileName (const int style, int& faceIndex) const throw()
  219260. {
  219261. faceIndex = names[style].faceIndex;
  219262. return names[style].fileName;
  219263. }
  219264. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219265. bool getMonospaced() const throw() { return monospaced; }
  219266. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219267. bool getSerif() const throw() { return hasSerif; }
  219268. private:
  219269. String family;
  219270. struct FontNameIndex
  219271. {
  219272. String fileName;
  219273. int faceIndex;
  219274. };
  219275. FontNameIndex names[4];
  219276. bool hasSerif, monospaced;
  219277. };
  219278. class FreeTypeInterface : public DeletedAtShutdown
  219279. {
  219280. public:
  219281. FreeTypeInterface()
  219282. : ftLib (0),
  219283. lastFace (0),
  219284. lastBold (false),
  219285. lastItalic (false)
  219286. {
  219287. if (FT_Init_FreeType (&ftLib) != 0)
  219288. {
  219289. ftLib = 0;
  219290. DBG ("Failed to initialize FreeType");
  219291. }
  219292. StringArray fontDirs;
  219293. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219294. fontDirs.removeEmptyStrings (true);
  219295. if (fontDirs.size() == 0)
  219296. {
  219297. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  219298. if (fontsInfo != 0)
  219299. {
  219300. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219301. {
  219302. fontDirs.add (e->getAllSubText().trim());
  219303. }
  219304. }
  219305. }
  219306. if (fontDirs.size() == 0)
  219307. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219308. for (int i = 0; i < fontDirs.size(); ++i)
  219309. enumerateFaces (fontDirs[i]);
  219310. }
  219311. ~FreeTypeInterface()
  219312. {
  219313. if (lastFace != 0)
  219314. FT_Done_Face (lastFace);
  219315. if (ftLib != 0)
  219316. FT_Done_FreeType (ftLib);
  219317. clearSingletonInstance();
  219318. }
  219319. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219320. {
  219321. for (int i = 0; i < faces.size(); i++)
  219322. if (faces[i]->getFamilyName() == familyName)
  219323. return faces[i];
  219324. if (! create)
  219325. return 0;
  219326. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219327. faces.add (newFace);
  219328. return newFace;
  219329. }
  219330. // Enumerate all font faces available in a given directory
  219331. void enumerateFaces (const String& path)
  219332. {
  219333. File dirPath (path);
  219334. if (path.isEmpty() || ! dirPath.isDirectory())
  219335. return;
  219336. DirectoryIterator di (dirPath, true);
  219337. while (di.next())
  219338. {
  219339. File possible (di.getFile());
  219340. if (possible.hasFileExtension ("ttf")
  219341. || possible.hasFileExtension ("pfb")
  219342. || possible.hasFileExtension ("pcf"))
  219343. {
  219344. FT_Face face;
  219345. int faceIndex = 0;
  219346. int numFaces = 0;
  219347. do
  219348. {
  219349. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219350. faceIndex, &face) == 0)
  219351. {
  219352. if (faceIndex == 0)
  219353. numFaces = face->num_faces;
  219354. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219355. {
  219356. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219357. int style = (int) FreeTypeFontFace::Plain;
  219358. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219359. style |= (int) FreeTypeFontFace::Bold;
  219360. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219361. style |= (int) FreeTypeFontFace::Italic;
  219362. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219363. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219364. // Surely there must be a better way to do this?
  219365. const String name (face->family_name);
  219366. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219367. || name.containsIgnoreCase ("Verdana")
  219368. || name.containsIgnoreCase ("Arial")));
  219369. }
  219370. FT_Done_Face (face);
  219371. }
  219372. ++faceIndex;
  219373. }
  219374. while (faceIndex < numFaces);
  219375. }
  219376. }
  219377. }
  219378. // Create a FreeType face object for a given font
  219379. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219380. {
  219381. FT_Face face = 0;
  219382. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219383. {
  219384. face = lastFace;
  219385. }
  219386. else
  219387. {
  219388. if (lastFace != 0)
  219389. {
  219390. FT_Done_Face (lastFace);
  219391. lastFace = 0;
  219392. }
  219393. lastFontName = fontName;
  219394. lastBold = bold;
  219395. lastItalic = italic;
  219396. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219397. if (ftFace != 0)
  219398. {
  219399. int style = (int) FreeTypeFontFace::Plain;
  219400. if (bold)
  219401. style |= (int) FreeTypeFontFace::Bold;
  219402. if (italic)
  219403. style |= (int) FreeTypeFontFace::Italic;
  219404. int faceIndex;
  219405. String fileName (ftFace->getFileName (style, faceIndex));
  219406. if (fileName.isEmpty())
  219407. {
  219408. style ^= (int) FreeTypeFontFace::Bold;
  219409. fileName = ftFace->getFileName (style, faceIndex);
  219410. if (fileName.isEmpty())
  219411. {
  219412. style ^= (int) FreeTypeFontFace::Bold;
  219413. style ^= (int) FreeTypeFontFace::Italic;
  219414. fileName = ftFace->getFileName (style, faceIndex);
  219415. if (! fileName.length())
  219416. {
  219417. style ^= (int) FreeTypeFontFace::Bold;
  219418. fileName = ftFace->getFileName (style, faceIndex);
  219419. }
  219420. }
  219421. }
  219422. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219423. {
  219424. face = lastFace;
  219425. // If there isn't a unicode charmap then select the first one.
  219426. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219427. FT_Set_Charmap (face, face->charmaps[0]);
  219428. }
  219429. }
  219430. }
  219431. return face;
  219432. }
  219433. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219434. {
  219435. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219436. const float height = (float) (face->ascender - face->descender);
  219437. const float scaleX = 1.0f / height;
  219438. const float scaleY = -1.0f / height;
  219439. Path destShape;
  219440. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219441. || face->glyph->format != ft_glyph_format_outline)
  219442. {
  219443. return false;
  219444. }
  219445. const FT_Outline* const outline = &face->glyph->outline;
  219446. const short* const contours = outline->contours;
  219447. const char* const tags = outline->tags;
  219448. FT_Vector* const points = outline->points;
  219449. for (int c = 0; c < outline->n_contours; c++)
  219450. {
  219451. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219452. const int endPoint = contours[c];
  219453. for (int p = startPoint; p <= endPoint; p++)
  219454. {
  219455. const float x = scaleX * points[p].x;
  219456. const float y = scaleY * points[p].y;
  219457. if (p == startPoint)
  219458. {
  219459. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219460. {
  219461. float x2 = scaleX * points [endPoint].x;
  219462. float y2 = scaleY * points [endPoint].y;
  219463. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219464. {
  219465. x2 = (x + x2) * 0.5f;
  219466. y2 = (y + y2) * 0.5f;
  219467. }
  219468. destShape.startNewSubPath (x2, y2);
  219469. }
  219470. else
  219471. {
  219472. destShape.startNewSubPath (x, y);
  219473. }
  219474. }
  219475. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219476. {
  219477. if (p != startPoint)
  219478. destShape.lineTo (x, y);
  219479. }
  219480. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219481. {
  219482. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219483. float x2 = scaleX * points [nextIndex].x;
  219484. float y2 = scaleY * points [nextIndex].y;
  219485. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219486. {
  219487. x2 = (x + x2) * 0.5f;
  219488. y2 = (y + y2) * 0.5f;
  219489. }
  219490. else
  219491. {
  219492. ++p;
  219493. }
  219494. destShape.quadraticTo (x, y, x2, y2);
  219495. }
  219496. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219497. {
  219498. if (p >= endPoint)
  219499. return false;
  219500. const int next1 = p + 1;
  219501. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219502. const float x2 = scaleX * points [next1].x;
  219503. const float y2 = scaleY * points [next1].y;
  219504. const float x3 = scaleX * points [next2].x;
  219505. const float y3 = scaleY * points [next2].y;
  219506. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219507. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219508. return false;
  219509. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219510. p += 2;
  219511. }
  219512. }
  219513. destShape.closeSubPath();
  219514. }
  219515. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219516. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219517. addKerning (face, dest, character, glyphIndex);
  219518. return true;
  219519. }
  219520. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219521. {
  219522. const float height = (float) (face->ascender - face->descender);
  219523. uint32 rightGlyphIndex;
  219524. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219525. while (rightGlyphIndex != 0)
  219526. {
  219527. FT_Vector kerning;
  219528. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219529. {
  219530. if (kerning.x != 0)
  219531. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219532. }
  219533. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219534. }
  219535. }
  219536. // Add a glyph to a font
  219537. bool addGlyphToFont (const uint32 character, const String& fontName,
  219538. bool bold, bool italic, CustomTypeface& dest)
  219539. {
  219540. FT_Face face = createFT_Face (fontName, bold, italic);
  219541. return face != 0 && addGlyph (face, dest, character);
  219542. }
  219543. void getFamilyNames (StringArray& familyNames) const
  219544. {
  219545. for (int i = 0; i < faces.size(); i++)
  219546. familyNames.add (faces[i]->getFamilyName());
  219547. }
  219548. void getMonospacedNames (StringArray& monoSpaced) const
  219549. {
  219550. for (int i = 0; i < faces.size(); i++)
  219551. if (faces[i]->getMonospaced())
  219552. monoSpaced.add (faces[i]->getFamilyName());
  219553. }
  219554. void getSerifNames (StringArray& serif) const
  219555. {
  219556. for (int i = 0; i < faces.size(); i++)
  219557. if (faces[i]->getSerif())
  219558. serif.add (faces[i]->getFamilyName());
  219559. }
  219560. void getSansSerifNames (StringArray& sansSerif) const
  219561. {
  219562. for (int i = 0; i < faces.size(); i++)
  219563. if (! faces[i]->getSerif())
  219564. sansSerif.add (faces[i]->getFamilyName());
  219565. }
  219566. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219567. private:
  219568. FT_Library ftLib;
  219569. FT_Face lastFace;
  219570. String lastFontName;
  219571. bool lastBold, lastItalic;
  219572. OwnedArray<FreeTypeFontFace> faces;
  219573. };
  219574. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219575. class FreetypeTypeface : public CustomTypeface
  219576. {
  219577. public:
  219578. FreetypeTypeface (const Font& font)
  219579. {
  219580. FT_Face face = FreeTypeInterface::getInstance()
  219581. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219582. if (face == 0)
  219583. {
  219584. #if JUCE_DEBUG
  219585. String msg ("Failed to create typeface: ");
  219586. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219587. DBG (msg);
  219588. #endif
  219589. }
  219590. else
  219591. {
  219592. setCharacteristics (font.getTypefaceName(),
  219593. face->ascender / (float) (face->ascender - face->descender),
  219594. font.isBold(), font.isItalic(),
  219595. L' ');
  219596. }
  219597. }
  219598. bool loadGlyphIfPossible (juce_wchar character)
  219599. {
  219600. return FreeTypeInterface::getInstance()
  219601. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219602. }
  219603. };
  219604. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219605. {
  219606. return new FreetypeTypeface (font);
  219607. }
  219608. const StringArray Font::findAllTypefaceNames()
  219609. {
  219610. StringArray s;
  219611. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219612. s.sort (true);
  219613. return s;
  219614. }
  219615. namespace
  219616. {
  219617. const String pickBestFont (const StringArray& names,
  219618. const char* const choicesString)
  219619. {
  219620. StringArray choices;
  219621. choices.addTokens (String (choicesString), ",", String::empty);
  219622. choices.trim();
  219623. choices.removeEmptyStrings();
  219624. int i, j;
  219625. for (j = 0; j < choices.size(); ++j)
  219626. if (names.contains (choices[j], true))
  219627. return choices[j];
  219628. for (j = 0; j < choices.size(); ++j)
  219629. for (i = 0; i < names.size(); i++)
  219630. if (names[i].startsWithIgnoreCase (choices[j]))
  219631. return names[i];
  219632. for (j = 0; j < choices.size(); ++j)
  219633. for (i = 0; i < names.size(); i++)
  219634. if (names[i].containsIgnoreCase (choices[j]))
  219635. return names[i];
  219636. return names[0];
  219637. }
  219638. const String linux_getDefaultSansSerifFontName()
  219639. {
  219640. StringArray allFonts;
  219641. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219642. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219643. }
  219644. const String linux_getDefaultSerifFontName()
  219645. {
  219646. StringArray allFonts;
  219647. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219648. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219649. }
  219650. const String linux_getDefaultMonospacedFontName()
  219651. {
  219652. StringArray allFonts;
  219653. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219654. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219655. }
  219656. }
  219657. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  219658. {
  219659. defaultSans = linux_getDefaultSansSerifFontName();
  219660. defaultSerif = linux_getDefaultSerifFontName();
  219661. defaultFixed = linux_getDefaultMonospacedFontName();
  219662. }
  219663. #endif
  219664. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219665. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219666. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219667. // compiled on its own).
  219668. #if JUCE_INCLUDED_FILE
  219669. // These are defined in juce_linux_Messaging.cpp
  219670. extern Display* display;
  219671. extern XContext windowHandleXContext;
  219672. namespace Atoms
  219673. {
  219674. enum ProtocolItems
  219675. {
  219676. TAKE_FOCUS = 0,
  219677. DELETE_WINDOW = 1,
  219678. PING = 2
  219679. };
  219680. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219681. ActiveWin, Pid, WindowType, WindowState,
  219682. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219683. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219684. XdndActionDescription, XdndActionCopy,
  219685. allowedActions[5],
  219686. allowedMimeTypes[2];
  219687. const unsigned long DndVersion = 3;
  219688. static void initialiseAtoms()
  219689. {
  219690. static bool atomsInitialised = false;
  219691. if (! atomsInitialised)
  219692. {
  219693. atomsInitialised = true;
  219694. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219695. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219696. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219697. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219698. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219699. State = XInternAtom (display, "WM_STATE", True);
  219700. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219701. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219702. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219703. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219704. XdndAware = XInternAtom (display, "XdndAware", False);
  219705. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219706. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219707. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219708. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219709. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219710. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219711. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219712. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219713. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219714. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219715. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219716. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219717. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219718. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219719. allowedActions[1] = XdndActionCopy;
  219720. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219721. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219722. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219723. }
  219724. }
  219725. }
  219726. namespace Keys
  219727. {
  219728. enum MouseButtons
  219729. {
  219730. NoButton = 0,
  219731. LeftButton = 1,
  219732. MiddleButton = 2,
  219733. RightButton = 3,
  219734. WheelUp = 4,
  219735. WheelDown = 5
  219736. };
  219737. static int AltMask = 0;
  219738. static int NumLockMask = 0;
  219739. static bool numLock = false;
  219740. static bool capsLock = false;
  219741. static char keyStates [32];
  219742. static const int extendedKeyModifier = 0x10000000;
  219743. }
  219744. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219745. {
  219746. int keysym;
  219747. if (keyCode & Keys::extendedKeyModifier)
  219748. {
  219749. keysym = 0xff00 | (keyCode & 0xff);
  219750. }
  219751. else
  219752. {
  219753. keysym = keyCode;
  219754. if (keysym == (XK_Tab & 0xff)
  219755. || keysym == (XK_Return & 0xff)
  219756. || keysym == (XK_Escape & 0xff)
  219757. || keysym == (XK_BackSpace & 0xff))
  219758. {
  219759. keysym |= 0xff00;
  219760. }
  219761. }
  219762. ScopedXLock xlock;
  219763. const int keycode = XKeysymToKeycode (display, keysym);
  219764. const int keybyte = keycode >> 3;
  219765. const int keybit = (1 << (keycode & 7));
  219766. return (Keys::keyStates [keybyte] & keybit) != 0;
  219767. }
  219768. #if JUCE_USE_XSHM
  219769. namespace XSHMHelpers
  219770. {
  219771. static int trappedErrorCode = 0;
  219772. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219773. {
  219774. trappedErrorCode = err->error_code;
  219775. return 0;
  219776. }
  219777. static bool isShmAvailable() throw()
  219778. {
  219779. static bool isChecked = false;
  219780. static bool isAvailable = false;
  219781. if (! isChecked)
  219782. {
  219783. isChecked = true;
  219784. int major, minor;
  219785. Bool pixmaps;
  219786. ScopedXLock xlock;
  219787. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219788. {
  219789. trappedErrorCode = 0;
  219790. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219791. XShmSegmentInfo segmentInfo;
  219792. zerostruct (segmentInfo);
  219793. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219794. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219795. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219796. xImage->bytes_per_line * xImage->height,
  219797. IPC_CREAT | 0777)) >= 0)
  219798. {
  219799. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219800. if (segmentInfo.shmaddr != (void*) -1)
  219801. {
  219802. segmentInfo.readOnly = False;
  219803. xImage->data = segmentInfo.shmaddr;
  219804. XSync (display, False);
  219805. if (XShmAttach (display, &segmentInfo) != 0)
  219806. {
  219807. XSync (display, False);
  219808. XShmDetach (display, &segmentInfo);
  219809. isAvailable = true;
  219810. }
  219811. }
  219812. XFlush (display);
  219813. XDestroyImage (xImage);
  219814. shmdt (segmentInfo.shmaddr);
  219815. }
  219816. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219817. XSetErrorHandler (oldHandler);
  219818. if (trappedErrorCode != 0)
  219819. isAvailable = false;
  219820. }
  219821. }
  219822. return isAvailable;
  219823. }
  219824. }
  219825. #endif
  219826. #if JUCE_USE_XRENDER
  219827. namespace XRender
  219828. {
  219829. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219830. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219831. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219832. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219833. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219834. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219835. static tXRenderFindFormat xRenderFindFormat = 0;
  219836. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219837. static bool isAvailable()
  219838. {
  219839. static bool hasLoaded = false;
  219840. if (! hasLoaded)
  219841. {
  219842. ScopedXLock xlock;
  219843. hasLoaded = true;
  219844. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219845. if (h != 0)
  219846. {
  219847. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219848. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219849. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219850. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219851. }
  219852. if (xRenderQueryVersion != 0
  219853. && xRenderFindStandardFormat != 0
  219854. && xRenderFindFormat != 0
  219855. && xRenderFindVisualFormat != 0)
  219856. {
  219857. int major, minor;
  219858. if (xRenderQueryVersion (display, &major, &minor))
  219859. return true;
  219860. }
  219861. xRenderQueryVersion = 0;
  219862. }
  219863. return xRenderQueryVersion != 0;
  219864. }
  219865. static XRenderPictFormat* findPictureFormat()
  219866. {
  219867. ScopedXLock xlock;
  219868. XRenderPictFormat* pictFormat = 0;
  219869. if (isAvailable())
  219870. {
  219871. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219872. if (pictFormat == 0)
  219873. {
  219874. XRenderPictFormat desiredFormat;
  219875. desiredFormat.type = PictTypeDirect;
  219876. desiredFormat.depth = 32;
  219877. desiredFormat.direct.alphaMask = 0xff;
  219878. desiredFormat.direct.redMask = 0xff;
  219879. desiredFormat.direct.greenMask = 0xff;
  219880. desiredFormat.direct.blueMask = 0xff;
  219881. desiredFormat.direct.alpha = 24;
  219882. desiredFormat.direct.red = 16;
  219883. desiredFormat.direct.green = 8;
  219884. desiredFormat.direct.blue = 0;
  219885. pictFormat = xRenderFindFormat (display,
  219886. PictFormatType | PictFormatDepth
  219887. | PictFormatRedMask | PictFormatRed
  219888. | PictFormatGreenMask | PictFormatGreen
  219889. | PictFormatBlueMask | PictFormatBlue
  219890. | PictFormatAlphaMask | PictFormatAlpha,
  219891. &desiredFormat,
  219892. 0);
  219893. }
  219894. }
  219895. return pictFormat;
  219896. }
  219897. }
  219898. #endif
  219899. namespace Visuals
  219900. {
  219901. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219902. {
  219903. ScopedXLock xlock;
  219904. Visual* visual = 0;
  219905. int numVisuals = 0;
  219906. long desiredMask = VisualNoMask;
  219907. XVisualInfo desiredVisual;
  219908. desiredVisual.screen = DefaultScreen (display);
  219909. desiredVisual.depth = desiredDepth;
  219910. desiredMask = VisualScreenMask | VisualDepthMask;
  219911. if (desiredDepth == 32)
  219912. {
  219913. desiredVisual.c_class = TrueColor;
  219914. desiredVisual.red_mask = 0x00FF0000;
  219915. desiredVisual.green_mask = 0x0000FF00;
  219916. desiredVisual.blue_mask = 0x000000FF;
  219917. desiredVisual.bits_per_rgb = 8;
  219918. desiredMask |= VisualClassMask;
  219919. desiredMask |= VisualRedMaskMask;
  219920. desiredMask |= VisualGreenMaskMask;
  219921. desiredMask |= VisualBlueMaskMask;
  219922. desiredMask |= VisualBitsPerRGBMask;
  219923. }
  219924. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219925. desiredMask,
  219926. &desiredVisual,
  219927. &numVisuals);
  219928. if (xvinfos != 0)
  219929. {
  219930. for (int i = 0; i < numVisuals; i++)
  219931. {
  219932. if (xvinfos[i].depth == desiredDepth)
  219933. {
  219934. visual = xvinfos[i].visual;
  219935. break;
  219936. }
  219937. }
  219938. XFree (xvinfos);
  219939. }
  219940. return visual;
  219941. }
  219942. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219943. {
  219944. Visual* visual = 0;
  219945. if (desiredDepth == 32)
  219946. {
  219947. #if JUCE_USE_XSHM
  219948. if (XSHMHelpers::isShmAvailable())
  219949. {
  219950. #if JUCE_USE_XRENDER
  219951. if (XRender::isAvailable())
  219952. {
  219953. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219954. if (pictFormat != 0)
  219955. {
  219956. int numVisuals = 0;
  219957. XVisualInfo desiredVisual;
  219958. desiredVisual.screen = DefaultScreen (display);
  219959. desiredVisual.depth = 32;
  219960. desiredVisual.bits_per_rgb = 8;
  219961. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219962. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219963. &desiredVisual, &numVisuals);
  219964. if (xvinfos != 0)
  219965. {
  219966. for (int i = 0; i < numVisuals; ++i)
  219967. {
  219968. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219969. if (pictVisualFormat != 0
  219970. && pictVisualFormat->type == PictTypeDirect
  219971. && pictVisualFormat->direct.alphaMask)
  219972. {
  219973. visual = xvinfos[i].visual;
  219974. matchedDepth = 32;
  219975. break;
  219976. }
  219977. }
  219978. XFree (xvinfos);
  219979. }
  219980. }
  219981. }
  219982. #endif
  219983. if (visual == 0)
  219984. {
  219985. visual = findVisualWithDepth (32);
  219986. if (visual != 0)
  219987. matchedDepth = 32;
  219988. }
  219989. }
  219990. #endif
  219991. }
  219992. if (visual == 0 && desiredDepth >= 24)
  219993. {
  219994. visual = findVisualWithDepth (24);
  219995. if (visual != 0)
  219996. matchedDepth = 24;
  219997. }
  219998. if (visual == 0 && desiredDepth >= 16)
  219999. {
  220000. visual = findVisualWithDepth (16);
  220001. if (visual != 0)
  220002. matchedDepth = 16;
  220003. }
  220004. return visual;
  220005. }
  220006. }
  220007. class XBitmapImage : public Image::SharedImage
  220008. {
  220009. public:
  220010. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  220011. const bool clearImage, const int imageDepth_, Visual* visual)
  220012. : Image::SharedImage (format_, w, h),
  220013. imageDepth (imageDepth_),
  220014. gc (None)
  220015. {
  220016. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  220017. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  220018. lineStride = ((w * pixelStride + 3) & ~3);
  220019. ScopedXLock xlock;
  220020. #if JUCE_USE_XSHM
  220021. usingXShm = false;
  220022. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  220023. {
  220024. zerostruct (segmentInfo);
  220025. segmentInfo.shmid = -1;
  220026. segmentInfo.shmaddr = (char *) -1;
  220027. segmentInfo.readOnly = False;
  220028. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  220029. if (xImage != 0)
  220030. {
  220031. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  220032. xImage->bytes_per_line * xImage->height,
  220033. IPC_CREAT | 0777)) >= 0)
  220034. {
  220035. if (segmentInfo.shmid != -1)
  220036. {
  220037. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  220038. if (segmentInfo.shmaddr != (void*) -1)
  220039. {
  220040. segmentInfo.readOnly = False;
  220041. xImage->data = segmentInfo.shmaddr;
  220042. imageData = (uint8*) segmentInfo.shmaddr;
  220043. if (XShmAttach (display, &segmentInfo) != 0)
  220044. usingXShm = true;
  220045. else
  220046. jassertfalse;
  220047. }
  220048. else
  220049. {
  220050. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220051. }
  220052. }
  220053. }
  220054. }
  220055. }
  220056. if (! usingXShm)
  220057. #endif
  220058. {
  220059. imageDataAllocated.malloc (lineStride * h);
  220060. imageData = imageDataAllocated;
  220061. if (format_ == Image::ARGB && clearImage)
  220062. zeromem (imageData, h * lineStride);
  220063. xImage = (XImage*) juce_calloc (sizeof (XImage));
  220064. xImage->width = w;
  220065. xImage->height = h;
  220066. xImage->xoffset = 0;
  220067. xImage->format = ZPixmap;
  220068. xImage->data = (char*) imageData;
  220069. xImage->byte_order = ImageByteOrder (display);
  220070. xImage->bitmap_unit = BitmapUnit (display);
  220071. xImage->bitmap_bit_order = BitmapBitOrder (display);
  220072. xImage->bitmap_pad = 32;
  220073. xImage->depth = pixelStride * 8;
  220074. xImage->bytes_per_line = lineStride;
  220075. xImage->bits_per_pixel = pixelStride * 8;
  220076. xImage->red_mask = 0x00FF0000;
  220077. xImage->green_mask = 0x0000FF00;
  220078. xImage->blue_mask = 0x000000FF;
  220079. if (imageDepth == 16)
  220080. {
  220081. const int pixelStride = 2;
  220082. const int lineStride = ((w * pixelStride + 3) & ~3);
  220083. imageData16Bit.malloc (lineStride * h);
  220084. xImage->data = imageData16Bit;
  220085. xImage->bitmap_pad = 16;
  220086. xImage->depth = pixelStride * 8;
  220087. xImage->bytes_per_line = lineStride;
  220088. xImage->bits_per_pixel = pixelStride * 8;
  220089. xImage->red_mask = visual->red_mask;
  220090. xImage->green_mask = visual->green_mask;
  220091. xImage->blue_mask = visual->blue_mask;
  220092. }
  220093. if (! XInitImage (xImage))
  220094. jassertfalse;
  220095. }
  220096. }
  220097. ~XBitmapImage()
  220098. {
  220099. ScopedXLock xlock;
  220100. if (gc != None)
  220101. XFreeGC (display, gc);
  220102. #if JUCE_USE_XSHM
  220103. if (usingXShm)
  220104. {
  220105. XShmDetach (display, &segmentInfo);
  220106. XFlush (display);
  220107. XDestroyImage (xImage);
  220108. shmdt (segmentInfo.shmaddr);
  220109. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220110. }
  220111. else
  220112. #endif
  220113. {
  220114. xImage->data = 0;
  220115. XDestroyImage (xImage);
  220116. }
  220117. }
  220118. Image::ImageType getType() const { return Image::NativeImage; }
  220119. LowLevelGraphicsContext* createLowLevelContext()
  220120. {
  220121. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  220122. }
  220123. SharedImage* clone()
  220124. {
  220125. jassertfalse;
  220126. return 0;
  220127. }
  220128. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  220129. {
  220130. ScopedXLock xlock;
  220131. if (gc == None)
  220132. {
  220133. XGCValues gcvalues;
  220134. gcvalues.foreground = None;
  220135. gcvalues.background = None;
  220136. gcvalues.function = GXcopy;
  220137. gcvalues.plane_mask = AllPlanes;
  220138. gcvalues.clip_mask = None;
  220139. gcvalues.graphics_exposures = False;
  220140. gc = XCreateGC (display, window,
  220141. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  220142. &gcvalues);
  220143. }
  220144. if (imageDepth == 16)
  220145. {
  220146. const uint32 rMask = xImage->red_mask;
  220147. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  220148. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  220149. const uint32 gMask = xImage->green_mask;
  220150. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  220151. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  220152. const uint32 bMask = xImage->blue_mask;
  220153. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  220154. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  220155. const Image::BitmapData srcData (Image (this), false);
  220156. for (int y = sy; y < sy + dh; ++y)
  220157. {
  220158. const uint8* p = srcData.getPixelPointer (sx, y);
  220159. for (int x = sx; x < sx + dw; ++x)
  220160. {
  220161. const PixelRGB* const pixel = (const PixelRGB*) p;
  220162. p += srcData.pixelStride;
  220163. XPutPixel (xImage, x, y,
  220164. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  220165. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  220166. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  220167. }
  220168. }
  220169. }
  220170. // blit results to screen.
  220171. #if JUCE_USE_XSHM
  220172. if (usingXShm)
  220173. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  220174. else
  220175. #endif
  220176. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  220177. }
  220178. juce_UseDebuggingNewOperator
  220179. private:
  220180. XImage* xImage;
  220181. const int imageDepth;
  220182. HeapBlock <uint8> imageDataAllocated;
  220183. HeapBlock <char> imageData16Bit;
  220184. GC gc;
  220185. #if JUCE_USE_XSHM
  220186. XShmSegmentInfo segmentInfo;
  220187. bool usingXShm;
  220188. #endif
  220189. static int getShiftNeeded (const uint32 mask) throw()
  220190. {
  220191. for (int i = 32; --i >= 0;)
  220192. if (((mask >> i) & 1) != 0)
  220193. return i - 7;
  220194. jassertfalse;
  220195. return 0;
  220196. }
  220197. };
  220198. class LinuxComponentPeer : public ComponentPeer
  220199. {
  220200. public:
  220201. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220202. : ComponentPeer (component, windowStyleFlags),
  220203. windowH (0),
  220204. parentWindow (0),
  220205. wx (0),
  220206. wy (0),
  220207. ww (0),
  220208. wh (0),
  220209. fullScreen (false),
  220210. mapped (false),
  220211. visual (0),
  220212. depth (0)
  220213. {
  220214. // it's dangerous to create a window on a thread other than the message thread..
  220215. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220216. repainter = new LinuxRepaintManager (this);
  220217. createWindow();
  220218. setTitle (component->getName());
  220219. }
  220220. ~LinuxComponentPeer()
  220221. {
  220222. // it's dangerous to delete a window on a thread other than the message thread..
  220223. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220224. deleteIconPixmaps();
  220225. destroyWindow();
  220226. windowH = 0;
  220227. }
  220228. void* getNativeHandle() const
  220229. {
  220230. return (void*) windowH;
  220231. }
  220232. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220233. {
  220234. XPointer peer = 0;
  220235. ScopedXLock xlock;
  220236. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220237. {
  220238. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220239. peer = 0;
  220240. }
  220241. return (LinuxComponentPeer*) peer;
  220242. }
  220243. void setVisible (bool shouldBeVisible)
  220244. {
  220245. ScopedXLock xlock;
  220246. if (shouldBeVisible)
  220247. XMapWindow (display, windowH);
  220248. else
  220249. XUnmapWindow (display, windowH);
  220250. }
  220251. void setTitle (const String& title)
  220252. {
  220253. setWindowTitle (windowH, title);
  220254. }
  220255. void setPosition (int x, int y)
  220256. {
  220257. setBounds (x, y, ww, wh, false);
  220258. }
  220259. void setSize (int w, int h)
  220260. {
  220261. setBounds (wx, wy, w, h, false);
  220262. }
  220263. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220264. {
  220265. fullScreen = isNowFullScreen;
  220266. if (windowH != 0)
  220267. {
  220268. Component::SafePointer<Component> deletionChecker (component);
  220269. wx = x;
  220270. wy = y;
  220271. ww = jmax (1, w);
  220272. wh = jmax (1, h);
  220273. ScopedXLock xlock;
  220274. // Make sure the Window manager does what we want
  220275. XSizeHints* hints = XAllocSizeHints();
  220276. hints->flags = USSize | USPosition;
  220277. hints->width = ww;
  220278. hints->height = wh;
  220279. hints->x = wx;
  220280. hints->y = wy;
  220281. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220282. {
  220283. hints->min_width = hints->max_width = hints->width;
  220284. hints->min_height = hints->max_height = hints->height;
  220285. hints->flags |= PMinSize | PMaxSize;
  220286. }
  220287. XSetWMNormalHints (display, windowH, hints);
  220288. XFree (hints);
  220289. XMoveResizeWindow (display, windowH,
  220290. wx - windowBorder.getLeft(),
  220291. wy - windowBorder.getTop(), ww, wh);
  220292. if (deletionChecker != 0)
  220293. {
  220294. updateBorderSize();
  220295. handleMovedOrResized();
  220296. }
  220297. }
  220298. }
  220299. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220300. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220301. const Point<int> localToGlobal (const Point<int>& relativePosition)
  220302. {
  220303. return relativePosition + getScreenPosition();
  220304. }
  220305. const Point<int> globalToLocal (const Point<int>& screenPosition)
  220306. {
  220307. return screenPosition - getScreenPosition();
  220308. }
  220309. void setAlpha (float newAlpha)
  220310. {
  220311. //xxx todo!
  220312. }
  220313. void setMinimised (bool shouldBeMinimised)
  220314. {
  220315. if (shouldBeMinimised)
  220316. {
  220317. Window root = RootWindow (display, DefaultScreen (display));
  220318. XClientMessageEvent clientMsg;
  220319. clientMsg.display = display;
  220320. clientMsg.window = windowH;
  220321. clientMsg.type = ClientMessage;
  220322. clientMsg.format = 32;
  220323. clientMsg.message_type = Atoms::ChangeState;
  220324. clientMsg.data.l[0] = IconicState;
  220325. ScopedXLock xlock;
  220326. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220327. }
  220328. else
  220329. {
  220330. setVisible (true);
  220331. }
  220332. }
  220333. bool isMinimised() const
  220334. {
  220335. bool minimised = false;
  220336. unsigned char* stateProp;
  220337. unsigned long nitems, bytesLeft;
  220338. Atom actualType;
  220339. int actualFormat;
  220340. ScopedXLock xlock;
  220341. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220342. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220343. &stateProp) == Success
  220344. && actualType == Atoms::State
  220345. && actualFormat == 32
  220346. && nitems > 0)
  220347. {
  220348. if (((unsigned long*) stateProp)[0] == IconicState)
  220349. minimised = true;
  220350. XFree (stateProp);
  220351. }
  220352. return minimised;
  220353. }
  220354. void setFullScreen (const bool shouldBeFullScreen)
  220355. {
  220356. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220357. setMinimised (false);
  220358. if (fullScreen != shouldBeFullScreen)
  220359. {
  220360. if (shouldBeFullScreen)
  220361. r = Desktop::getInstance().getMainMonitorArea();
  220362. if (! r.isEmpty())
  220363. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220364. getComponent()->repaint();
  220365. }
  220366. }
  220367. bool isFullScreen() const
  220368. {
  220369. return fullScreen;
  220370. }
  220371. bool isChildWindowOf (Window possibleParent) const
  220372. {
  220373. Window* windowList = 0;
  220374. uint32 windowListSize = 0;
  220375. Window parent, root;
  220376. ScopedXLock xlock;
  220377. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220378. {
  220379. if (windowList != 0)
  220380. XFree (windowList);
  220381. return parent == possibleParent;
  220382. }
  220383. return false;
  220384. }
  220385. bool isFrontWindow() const
  220386. {
  220387. Window* windowList = 0;
  220388. uint32 windowListSize = 0;
  220389. bool result = false;
  220390. ScopedXLock xlock;
  220391. Window parent, root = RootWindow (display, DefaultScreen (display));
  220392. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220393. {
  220394. for (int i = windowListSize; --i >= 0;)
  220395. {
  220396. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220397. if (peer != 0)
  220398. {
  220399. result = (peer == this);
  220400. break;
  220401. }
  220402. }
  220403. }
  220404. if (windowList != 0)
  220405. XFree (windowList);
  220406. return result;
  220407. }
  220408. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220409. {
  220410. if (((unsigned int) position.getX()) >= (unsigned int) ww
  220411. || ((unsigned int) position.getY()) >= (unsigned int) wh)
  220412. return false;
  220413. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  220414. {
  220415. Component* const c = Desktop::getInstance().getComponent (i);
  220416. if (c == getComponent())
  220417. break;
  220418. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  220419. return false;
  220420. }
  220421. if (trueIfInAChildWindow)
  220422. return true;
  220423. ::Window root, child;
  220424. unsigned int bw, depth;
  220425. int wx, wy, w, h;
  220426. ScopedXLock xlock;
  220427. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220428. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220429. &bw, &depth))
  220430. {
  220431. return false;
  220432. }
  220433. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  220434. return false;
  220435. return child == None;
  220436. }
  220437. const BorderSize getFrameSize() const
  220438. {
  220439. return BorderSize();
  220440. }
  220441. bool setAlwaysOnTop (bool alwaysOnTop)
  220442. {
  220443. return false;
  220444. }
  220445. void toFront (bool makeActive)
  220446. {
  220447. if (makeActive)
  220448. {
  220449. setVisible (true);
  220450. grabFocus();
  220451. }
  220452. XEvent ev;
  220453. ev.xclient.type = ClientMessage;
  220454. ev.xclient.serial = 0;
  220455. ev.xclient.send_event = True;
  220456. ev.xclient.message_type = Atoms::ActiveWin;
  220457. ev.xclient.window = windowH;
  220458. ev.xclient.format = 32;
  220459. ev.xclient.data.l[0] = 2;
  220460. ev.xclient.data.l[1] = CurrentTime;
  220461. ev.xclient.data.l[2] = 0;
  220462. ev.xclient.data.l[3] = 0;
  220463. ev.xclient.data.l[4] = 0;
  220464. {
  220465. ScopedXLock xlock;
  220466. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220467. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220468. XWindowAttributes attr;
  220469. XGetWindowAttributes (display, windowH, &attr);
  220470. if (component->isAlwaysOnTop())
  220471. XRaiseWindow (display, windowH);
  220472. XSync (display, False);
  220473. }
  220474. handleBroughtToFront();
  220475. }
  220476. void toBehind (ComponentPeer* other)
  220477. {
  220478. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220479. jassert (otherPeer != 0); // wrong type of window?
  220480. if (otherPeer != 0)
  220481. {
  220482. setMinimised (false);
  220483. Window newStack[] = { otherPeer->windowH, windowH };
  220484. ScopedXLock xlock;
  220485. XRestackWindows (display, newStack, 2);
  220486. }
  220487. }
  220488. bool isFocused() const
  220489. {
  220490. int revert = 0;
  220491. Window focusedWindow = 0;
  220492. ScopedXLock xlock;
  220493. XGetInputFocus (display, &focusedWindow, &revert);
  220494. return focusedWindow == windowH;
  220495. }
  220496. void grabFocus()
  220497. {
  220498. XWindowAttributes atts;
  220499. ScopedXLock xlock;
  220500. if (windowH != 0
  220501. && XGetWindowAttributes (display, windowH, &atts)
  220502. && atts.map_state == IsViewable
  220503. && ! isFocused())
  220504. {
  220505. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220506. isActiveApplication = true;
  220507. }
  220508. }
  220509. void textInputRequired (const Point<int>&)
  220510. {
  220511. }
  220512. void repaint (const Rectangle<int>& area)
  220513. {
  220514. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220515. }
  220516. void performAnyPendingRepaintsNow()
  220517. {
  220518. repainter->performAnyPendingRepaintsNow();
  220519. }
  220520. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220521. {
  220522. ScopedXLock xlock;
  220523. const int width = image.getWidth();
  220524. const int height = image.getHeight();
  220525. HeapBlock <uint32> colour (width * height);
  220526. int index = 0;
  220527. for (int y = 0; y < height; ++y)
  220528. for (int x = 0; x < width; ++x)
  220529. colour[index++] = image.getPixelAt (x, y).getARGB();
  220530. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220531. 0, reinterpret_cast<char*> (colour.getData()),
  220532. width, height, 32, 0);
  220533. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220534. width, height, 24);
  220535. GC gc = XCreateGC (display, pixmap, 0, 0);
  220536. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220537. XFreeGC (display, gc);
  220538. return pixmap;
  220539. }
  220540. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220541. {
  220542. ScopedXLock xlock;
  220543. const int width = image.getWidth();
  220544. const int height = image.getHeight();
  220545. const int stride = (width + 7) >> 3;
  220546. HeapBlock <char> mask;
  220547. mask.calloc (stride * height);
  220548. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220549. for (int y = 0; y < height; ++y)
  220550. {
  220551. for (int x = 0; x < width; ++x)
  220552. {
  220553. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220554. const int offset = y * stride + (x >> 3);
  220555. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220556. mask[offset] |= bit;
  220557. }
  220558. }
  220559. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220560. mask.getData(), width, height, 1, 0, 1);
  220561. }
  220562. void setIcon (const Image& newIcon)
  220563. {
  220564. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220565. HeapBlock <unsigned long> data (dataSize);
  220566. int index = 0;
  220567. data[index++] = newIcon.getWidth();
  220568. data[index++] = newIcon.getHeight();
  220569. for (int y = 0; y < newIcon.getHeight(); ++y)
  220570. for (int x = 0; x < newIcon.getWidth(); ++x)
  220571. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220572. ScopedXLock xlock;
  220573. XChangeProperty (display, windowH,
  220574. XInternAtom (display, "_NET_WM_ICON", False),
  220575. XA_CARDINAL, 32, PropModeReplace,
  220576. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220577. deleteIconPixmaps();
  220578. XWMHints* wmHints = XGetWMHints (display, windowH);
  220579. if (wmHints == 0)
  220580. wmHints = XAllocWMHints();
  220581. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220582. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220583. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220584. XSetWMHints (display, windowH, wmHints);
  220585. XFree (wmHints);
  220586. XSync (display, False);
  220587. }
  220588. void deleteIconPixmaps()
  220589. {
  220590. ScopedXLock xlock;
  220591. XWMHints* wmHints = XGetWMHints (display, windowH);
  220592. if (wmHints != 0)
  220593. {
  220594. if ((wmHints->flags & IconPixmapHint) != 0)
  220595. {
  220596. wmHints->flags &= ~IconPixmapHint;
  220597. XFreePixmap (display, wmHints->icon_pixmap);
  220598. }
  220599. if ((wmHints->flags & IconMaskHint) != 0)
  220600. {
  220601. wmHints->flags &= ~IconMaskHint;
  220602. XFreePixmap (display, wmHints->icon_mask);
  220603. }
  220604. XSetWMHints (display, windowH, wmHints);
  220605. XFree (wmHints);
  220606. }
  220607. }
  220608. void handleWindowMessage (XEvent* event)
  220609. {
  220610. switch (event->xany.type)
  220611. {
  220612. case 2: // 'KeyPress'
  220613. {
  220614. ScopedXLock xlock;
  220615. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220616. updateKeyStates (keyEvent->keycode, true);
  220617. char utf8 [64];
  220618. zeromem (utf8, sizeof (utf8));
  220619. KeySym sym;
  220620. {
  220621. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220622. ::setlocale (LC_ALL, "");
  220623. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220624. ::setlocale (LC_ALL, oldLocale);
  220625. }
  220626. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220627. int keyCode = (int) unicodeChar;
  220628. if (keyCode < 0x20)
  220629. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220630. const ModifierKeys oldMods (currentModifiers);
  220631. bool keyPressed = false;
  220632. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220633. if ((sym & 0xff00) == 0xff00)
  220634. {
  220635. // Translate keypad
  220636. if (sym == XK_KP_Divide)
  220637. keyCode = XK_slash;
  220638. else if (sym == XK_KP_Multiply)
  220639. keyCode = XK_asterisk;
  220640. else if (sym == XK_KP_Subtract)
  220641. keyCode = XK_hyphen;
  220642. else if (sym == XK_KP_Add)
  220643. keyCode = XK_plus;
  220644. else if (sym == XK_KP_Enter)
  220645. keyCode = XK_Return;
  220646. else if (sym == XK_KP_Decimal)
  220647. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220648. else if (sym == XK_KP_0)
  220649. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220650. else if (sym == XK_KP_1)
  220651. keyCode = Keys::numLock ? XK_1 : XK_End;
  220652. else if (sym == XK_KP_2)
  220653. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220654. else if (sym == XK_KP_3)
  220655. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220656. else if (sym == XK_KP_4)
  220657. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220658. else if (sym == XK_KP_5)
  220659. keyCode = XK_5;
  220660. else if (sym == XK_KP_6)
  220661. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220662. else if (sym == XK_KP_7)
  220663. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220664. else if (sym == XK_KP_8)
  220665. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220666. else if (sym == XK_KP_9)
  220667. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220668. switch (sym)
  220669. {
  220670. case XK_Left:
  220671. case XK_Right:
  220672. case XK_Up:
  220673. case XK_Down:
  220674. case XK_Page_Up:
  220675. case XK_Page_Down:
  220676. case XK_End:
  220677. case XK_Home:
  220678. case XK_Delete:
  220679. case XK_Insert:
  220680. keyPressed = true;
  220681. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220682. break;
  220683. case XK_Tab:
  220684. case XK_Return:
  220685. case XK_Escape:
  220686. case XK_BackSpace:
  220687. keyPressed = true;
  220688. keyCode &= 0xff;
  220689. break;
  220690. default:
  220691. {
  220692. if (sym >= XK_F1 && sym <= XK_F16)
  220693. {
  220694. keyPressed = true;
  220695. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220696. }
  220697. break;
  220698. }
  220699. }
  220700. }
  220701. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220702. keyPressed = true;
  220703. if (oldMods != currentModifiers)
  220704. handleModifierKeysChange();
  220705. if (keyDownChange)
  220706. handleKeyUpOrDown (true);
  220707. if (keyPressed)
  220708. handleKeyPress (keyCode, unicodeChar);
  220709. break;
  220710. }
  220711. case KeyRelease:
  220712. {
  220713. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220714. updateKeyStates (keyEvent->keycode, false);
  220715. KeySym sym;
  220716. {
  220717. ScopedXLock xlock;
  220718. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220719. }
  220720. const ModifierKeys oldMods (currentModifiers);
  220721. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220722. if (oldMods != currentModifiers)
  220723. handleModifierKeysChange();
  220724. if (keyDownChange)
  220725. handleKeyUpOrDown (false);
  220726. break;
  220727. }
  220728. case ButtonPress:
  220729. {
  220730. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220731. updateKeyModifiers (buttonPressEvent->state);
  220732. bool buttonMsg = false;
  220733. const int map = pointerMap [buttonPressEvent->button - Button1];
  220734. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220735. {
  220736. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220737. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220738. }
  220739. if (map == Keys::LeftButton)
  220740. {
  220741. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220742. buttonMsg = true;
  220743. }
  220744. else if (map == Keys::RightButton)
  220745. {
  220746. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220747. buttonMsg = true;
  220748. }
  220749. else if (map == Keys::MiddleButton)
  220750. {
  220751. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220752. buttonMsg = true;
  220753. }
  220754. if (buttonMsg)
  220755. {
  220756. toFront (true);
  220757. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220758. getEventTime (buttonPressEvent->time));
  220759. }
  220760. clearLastMousePos();
  220761. break;
  220762. }
  220763. case ButtonRelease:
  220764. {
  220765. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220766. updateKeyModifiers (buttonRelEvent->state);
  220767. const int map = pointerMap [buttonRelEvent->button - Button1];
  220768. if (map == Keys::LeftButton)
  220769. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220770. else if (map == Keys::RightButton)
  220771. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220772. else if (map == Keys::MiddleButton)
  220773. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220774. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220775. getEventTime (buttonRelEvent->time));
  220776. clearLastMousePos();
  220777. break;
  220778. }
  220779. case MotionNotify:
  220780. {
  220781. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220782. updateKeyModifiers (movedEvent->state);
  220783. const Point<int> mousePos (Desktop::getMousePosition());
  220784. if (lastMousePos != mousePos)
  220785. {
  220786. lastMousePos = mousePos;
  220787. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220788. {
  220789. Window wRoot = 0, wParent = 0;
  220790. {
  220791. ScopedXLock xlock;
  220792. unsigned int numChildren;
  220793. Window* wChild = 0;
  220794. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220795. }
  220796. if (wParent != 0
  220797. && wParent != windowH
  220798. && wParent != wRoot)
  220799. {
  220800. parentWindow = wParent;
  220801. updateBounds();
  220802. }
  220803. else
  220804. {
  220805. parentWindow = 0;
  220806. }
  220807. }
  220808. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220809. }
  220810. break;
  220811. }
  220812. case EnterNotify:
  220813. {
  220814. clearLastMousePos();
  220815. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220816. if (! currentModifiers.isAnyMouseButtonDown())
  220817. {
  220818. updateKeyModifiers (enterEvent->state);
  220819. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220820. }
  220821. break;
  220822. }
  220823. case LeaveNotify:
  220824. {
  220825. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220826. // Suppress the normal leave if we've got a pointer grab, or if
  220827. // it's a bogus one caused by clicking a mouse button when running
  220828. // in a Window manager
  220829. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220830. || leaveEvent->mode == NotifyUngrab)
  220831. {
  220832. updateKeyModifiers (leaveEvent->state);
  220833. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220834. }
  220835. break;
  220836. }
  220837. case FocusIn:
  220838. {
  220839. isActiveApplication = true;
  220840. if (isFocused())
  220841. handleFocusGain();
  220842. break;
  220843. }
  220844. case FocusOut:
  220845. {
  220846. isActiveApplication = false;
  220847. if (! isFocused())
  220848. handleFocusLoss();
  220849. break;
  220850. }
  220851. case Expose:
  220852. {
  220853. // Batch together all pending expose events
  220854. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  220855. XEvent nextEvent;
  220856. ScopedXLock xlock;
  220857. if (exposeEvent->window != windowH)
  220858. {
  220859. Window child;
  220860. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220861. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220862. &child);
  220863. }
  220864. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220865. exposeEvent->width, exposeEvent->height));
  220866. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220867. {
  220868. XPeekEvent (display, (XEvent*) &nextEvent);
  220869. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  220870. break;
  220871. XNextEvent (display, (XEvent*) &nextEvent);
  220872. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220873. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220874. nextExposeEvent->width, nextExposeEvent->height));
  220875. }
  220876. break;
  220877. }
  220878. case CirculateNotify:
  220879. case CreateNotify:
  220880. case DestroyNotify:
  220881. // Think we can ignore these
  220882. break;
  220883. case ConfigureNotify:
  220884. {
  220885. updateBounds();
  220886. updateBorderSize();
  220887. handleMovedOrResized();
  220888. // if the native title bar is dragged, need to tell any active menus, etc.
  220889. if ((styleFlags & windowHasTitleBar) != 0
  220890. && component->isCurrentlyBlockedByAnotherModalComponent())
  220891. {
  220892. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220893. if (currentModalComp != 0)
  220894. currentModalComp->inputAttemptWhenModal();
  220895. }
  220896. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  220897. if (confEvent->window == windowH
  220898. && confEvent->above != 0
  220899. && isFrontWindow())
  220900. {
  220901. handleBroughtToFront();
  220902. }
  220903. break;
  220904. }
  220905. case ReparentNotify:
  220906. {
  220907. parentWindow = 0;
  220908. Window wRoot = 0;
  220909. Window* wChild = 0;
  220910. unsigned int numChildren;
  220911. {
  220912. ScopedXLock xlock;
  220913. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220914. }
  220915. if (parentWindow == windowH || parentWindow == wRoot)
  220916. parentWindow = 0;
  220917. updateBounds();
  220918. updateBorderSize();
  220919. handleMovedOrResized();
  220920. break;
  220921. }
  220922. case GravityNotify:
  220923. {
  220924. updateBounds();
  220925. updateBorderSize();
  220926. handleMovedOrResized();
  220927. break;
  220928. }
  220929. case MapNotify:
  220930. mapped = true;
  220931. handleBroughtToFront();
  220932. break;
  220933. case UnmapNotify:
  220934. mapped = false;
  220935. break;
  220936. case MappingNotify:
  220937. {
  220938. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  220939. if (mappingEvent->request != MappingPointer)
  220940. {
  220941. // Deal with modifier/keyboard mapping
  220942. ScopedXLock xlock;
  220943. XRefreshKeyboardMapping (mappingEvent);
  220944. updateModifierMappings();
  220945. }
  220946. break;
  220947. }
  220948. case ClientMessage:
  220949. {
  220950. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  220951. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220952. {
  220953. const Atom atom = (Atom) clientMsg->data.l[0];
  220954. if (atom == Atoms::ProtocolList [Atoms::PING])
  220955. {
  220956. Window root = RootWindow (display, DefaultScreen (display));
  220957. event->xclient.window = root;
  220958. XSendEvent (display, root, False, NoEventMask, event);
  220959. XFlush (display);
  220960. }
  220961. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220962. {
  220963. XWindowAttributes atts;
  220964. ScopedXLock xlock;
  220965. if (clientMsg->window != 0
  220966. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220967. {
  220968. if (atts.map_state == IsViewable)
  220969. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220970. }
  220971. }
  220972. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220973. {
  220974. handleUserClosingWindow();
  220975. }
  220976. }
  220977. else if (clientMsg->message_type == Atoms::XdndEnter)
  220978. {
  220979. handleDragAndDropEnter (clientMsg);
  220980. }
  220981. else if (clientMsg->message_type == Atoms::XdndLeave)
  220982. {
  220983. resetDragAndDrop();
  220984. }
  220985. else if (clientMsg->message_type == Atoms::XdndPosition)
  220986. {
  220987. handleDragAndDropPosition (clientMsg);
  220988. }
  220989. else if (clientMsg->message_type == Atoms::XdndDrop)
  220990. {
  220991. handleDragAndDropDrop (clientMsg);
  220992. }
  220993. else if (clientMsg->message_type == Atoms::XdndStatus)
  220994. {
  220995. handleDragAndDropStatus (clientMsg);
  220996. }
  220997. else if (clientMsg->message_type == Atoms::XdndFinished)
  220998. {
  220999. resetDragAndDrop();
  221000. }
  221001. break;
  221002. }
  221003. case SelectionNotify:
  221004. handleDragAndDropSelection (event);
  221005. break;
  221006. case SelectionClear:
  221007. case SelectionRequest:
  221008. break;
  221009. default:
  221010. #if JUCE_USE_XSHM
  221011. {
  221012. ScopedXLock xlock;
  221013. if (event->xany.type == XShmGetEventBase (display))
  221014. repainter->notifyPaintCompleted();
  221015. }
  221016. #endif
  221017. break;
  221018. }
  221019. }
  221020. void showMouseCursor (Cursor cursor) throw()
  221021. {
  221022. ScopedXLock xlock;
  221023. XDefineCursor (display, windowH, cursor);
  221024. }
  221025. void setTaskBarIcon (const Image& image)
  221026. {
  221027. ScopedXLock xlock;
  221028. taskbarImage = image;
  221029. Screen* const screen = XDefaultScreenOfDisplay (display);
  221030. const int screenNumber = XScreenNumberOfScreen (screen);
  221031. String screenAtom ("_NET_SYSTEM_TRAY_S");
  221032. screenAtom << screenNumber;
  221033. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  221034. XGrabServer (display);
  221035. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  221036. if (managerWin != None)
  221037. XSelectInput (display, managerWin, StructureNotifyMask);
  221038. XUngrabServer (display);
  221039. XFlush (display);
  221040. if (managerWin != None)
  221041. {
  221042. XEvent ev;
  221043. zerostruct (ev);
  221044. ev.xclient.type = ClientMessage;
  221045. ev.xclient.window = managerWin;
  221046. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  221047. ev.xclient.format = 32;
  221048. ev.xclient.data.l[0] = CurrentTime;
  221049. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  221050. ev.xclient.data.l[2] = windowH;
  221051. ev.xclient.data.l[3] = 0;
  221052. ev.xclient.data.l[4] = 0;
  221053. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  221054. XSync (display, False);
  221055. }
  221056. // For older KDE's ...
  221057. long atomData = 1;
  221058. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  221059. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  221060. // For more recent KDE's...
  221061. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  221062. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  221063. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  221064. XSizeHints* hints = XAllocSizeHints();
  221065. hints->flags = PMinSize;
  221066. hints->min_width = 22;
  221067. hints->min_height = 22;
  221068. XSetWMNormalHints (display, windowH, hints);
  221069. XFree (hints);
  221070. }
  221071. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  221072. juce_UseDebuggingNewOperator
  221073. bool dontRepaint;
  221074. static ModifierKeys currentModifiers;
  221075. static bool isActiveApplication;
  221076. private:
  221077. class LinuxRepaintManager : public Timer
  221078. {
  221079. public:
  221080. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  221081. : peer (peer_),
  221082. lastTimeImageUsed (0)
  221083. {
  221084. #if JUCE_USE_XSHM
  221085. shmCompletedDrawing = true;
  221086. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  221087. if (useARGBImagesForRendering)
  221088. {
  221089. ScopedXLock xlock;
  221090. XShmSegmentInfo segmentinfo;
  221091. XImage* const testImage
  221092. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  221093. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  221094. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  221095. XDestroyImage (testImage);
  221096. }
  221097. #endif
  221098. }
  221099. ~LinuxRepaintManager()
  221100. {
  221101. }
  221102. void timerCallback()
  221103. {
  221104. #if JUCE_USE_XSHM
  221105. if (! shmCompletedDrawing)
  221106. return;
  221107. #endif
  221108. if (! regionsNeedingRepaint.isEmpty())
  221109. {
  221110. stopTimer();
  221111. performAnyPendingRepaintsNow();
  221112. }
  221113. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  221114. {
  221115. stopTimer();
  221116. image = Image::null;
  221117. }
  221118. }
  221119. void repaint (const Rectangle<int>& area)
  221120. {
  221121. if (! isTimerRunning())
  221122. startTimer (repaintTimerPeriod);
  221123. regionsNeedingRepaint.add (area);
  221124. }
  221125. void performAnyPendingRepaintsNow()
  221126. {
  221127. #if JUCE_USE_XSHM
  221128. if (! shmCompletedDrawing)
  221129. {
  221130. startTimer (repaintTimerPeriod);
  221131. return;
  221132. }
  221133. #endif
  221134. peer->clearMaskedRegion();
  221135. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  221136. regionsNeedingRepaint.clear();
  221137. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  221138. if (! totalArea.isEmpty())
  221139. {
  221140. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  221141. || image.getHeight() < totalArea.getHeight())
  221142. {
  221143. #if JUCE_USE_XSHM
  221144. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  221145. : Image::RGB,
  221146. #else
  221147. image = Image (new XBitmapImage (Image::RGB,
  221148. #endif
  221149. (totalArea.getWidth() + 31) & ~31,
  221150. (totalArea.getHeight() + 31) & ~31,
  221151. false, peer->depth, peer->visual));
  221152. }
  221153. startTimer (repaintTimerPeriod);
  221154. RectangleList adjustedList (originalRepaintRegion);
  221155. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  221156. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  221157. if (peer->depth == 32)
  221158. {
  221159. RectangleList::Iterator i (originalRepaintRegion);
  221160. while (i.next())
  221161. image.clear (*i.getRectangle() - totalArea.getPosition());
  221162. }
  221163. peer->handlePaint (context);
  221164. if (! peer->maskedRegion.isEmpty())
  221165. originalRepaintRegion.subtract (peer->maskedRegion);
  221166. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  221167. {
  221168. #if JUCE_USE_XSHM
  221169. shmCompletedDrawing = false;
  221170. #endif
  221171. const Rectangle<int>& r = *i.getRectangle();
  221172. static_cast<XBitmapImage*> (image.getSharedImage())
  221173. ->blitToWindow (peer->windowH,
  221174. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221175. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221176. }
  221177. }
  221178. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221179. startTimer (repaintTimerPeriod);
  221180. }
  221181. #if JUCE_USE_XSHM
  221182. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221183. #endif
  221184. private:
  221185. enum { repaintTimerPeriod = 1000 / 100 };
  221186. LinuxComponentPeer* const peer;
  221187. Image image;
  221188. uint32 lastTimeImageUsed;
  221189. RectangleList regionsNeedingRepaint;
  221190. #if JUCE_USE_XSHM
  221191. bool useARGBImagesForRendering, shmCompletedDrawing;
  221192. #endif
  221193. LinuxRepaintManager (const LinuxRepaintManager&);
  221194. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221195. };
  221196. ScopedPointer <LinuxRepaintManager> repainter;
  221197. friend class LinuxRepaintManager;
  221198. Window windowH, parentWindow;
  221199. int wx, wy, ww, wh;
  221200. Image taskbarImage;
  221201. bool fullScreen, mapped;
  221202. Visual* visual;
  221203. int depth;
  221204. BorderSize windowBorder;
  221205. struct MotifWmHints
  221206. {
  221207. unsigned long flags;
  221208. unsigned long functions;
  221209. unsigned long decorations;
  221210. long input_mode;
  221211. unsigned long status;
  221212. };
  221213. static void updateKeyStates (const int keycode, const bool press) throw()
  221214. {
  221215. const int keybyte = keycode >> 3;
  221216. const int keybit = (1 << (keycode & 7));
  221217. if (press)
  221218. Keys::keyStates [keybyte] |= keybit;
  221219. else
  221220. Keys::keyStates [keybyte] &= ~keybit;
  221221. }
  221222. static void updateKeyModifiers (const int status) throw()
  221223. {
  221224. int keyMods = 0;
  221225. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221226. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221227. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221228. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221229. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221230. Keys::capsLock = ((status & LockMask) != 0);
  221231. }
  221232. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221233. {
  221234. int modifier = 0;
  221235. bool isModifier = true;
  221236. switch (sym)
  221237. {
  221238. case XK_Shift_L:
  221239. case XK_Shift_R:
  221240. modifier = ModifierKeys::shiftModifier;
  221241. break;
  221242. case XK_Control_L:
  221243. case XK_Control_R:
  221244. modifier = ModifierKeys::ctrlModifier;
  221245. break;
  221246. case XK_Alt_L:
  221247. case XK_Alt_R:
  221248. modifier = ModifierKeys::altModifier;
  221249. break;
  221250. case XK_Num_Lock:
  221251. if (press)
  221252. Keys::numLock = ! Keys::numLock;
  221253. break;
  221254. case XK_Caps_Lock:
  221255. if (press)
  221256. Keys::capsLock = ! Keys::capsLock;
  221257. break;
  221258. case XK_Scroll_Lock:
  221259. break;
  221260. default:
  221261. isModifier = false;
  221262. break;
  221263. }
  221264. if (modifier != 0)
  221265. {
  221266. if (press)
  221267. currentModifiers = currentModifiers.withFlags (modifier);
  221268. else
  221269. currentModifiers = currentModifiers.withoutFlags (modifier);
  221270. }
  221271. return isModifier;
  221272. }
  221273. // Alt and Num lock are not defined by standard X
  221274. // modifier constants: check what they're mapped to
  221275. static void updateModifierMappings() throw()
  221276. {
  221277. ScopedXLock xlock;
  221278. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221279. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221280. Keys::AltMask = 0;
  221281. Keys::NumLockMask = 0;
  221282. XModifierKeymap* mapping = XGetModifierMapping (display);
  221283. if (mapping)
  221284. {
  221285. for (int i = 0; i < 8; i++)
  221286. {
  221287. if (mapping->modifiermap [i << 1] == altLeftCode)
  221288. Keys::AltMask = 1 << i;
  221289. else if (mapping->modifiermap [i << 1] == numLockCode)
  221290. Keys::NumLockMask = 1 << i;
  221291. }
  221292. XFreeModifiermap (mapping);
  221293. }
  221294. }
  221295. void removeWindowDecorations (Window wndH)
  221296. {
  221297. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221298. if (hints != None)
  221299. {
  221300. MotifWmHints motifHints;
  221301. zerostruct (motifHints);
  221302. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221303. motifHints.decorations = 0;
  221304. ScopedXLock xlock;
  221305. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221306. (unsigned char*) &motifHints, 4);
  221307. }
  221308. hints = XInternAtom (display, "_WIN_HINTS", True);
  221309. if (hints != None)
  221310. {
  221311. long gnomeHints = 0;
  221312. ScopedXLock xlock;
  221313. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221314. (unsigned char*) &gnomeHints, 1);
  221315. }
  221316. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221317. if (hints != None)
  221318. {
  221319. long kwmHints = 2; /*KDE_tinyDecoration*/
  221320. ScopedXLock xlock;
  221321. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221322. (unsigned char*) &kwmHints, 1);
  221323. }
  221324. }
  221325. void addWindowButtons (Window wndH)
  221326. {
  221327. ScopedXLock xlock;
  221328. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221329. if (hints != None)
  221330. {
  221331. MotifWmHints motifHints;
  221332. zerostruct (motifHints);
  221333. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221334. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221335. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221336. if ((styleFlags & windowHasCloseButton) != 0)
  221337. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221338. if ((styleFlags & windowHasMinimiseButton) != 0)
  221339. {
  221340. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221341. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221342. }
  221343. if ((styleFlags & windowHasMaximiseButton) != 0)
  221344. {
  221345. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221346. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221347. }
  221348. if ((styleFlags & windowIsResizable) != 0)
  221349. {
  221350. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221351. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221352. }
  221353. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221354. }
  221355. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221356. if (hints != None)
  221357. {
  221358. int netHints [6];
  221359. int num = 0;
  221360. if ((styleFlags & windowIsResizable) != 0)
  221361. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221362. if ((styleFlags & windowHasMaximiseButton) != 0)
  221363. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221364. if ((styleFlags & windowHasMinimiseButton) != 0)
  221365. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221366. if ((styleFlags & windowHasCloseButton) != 0)
  221367. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221368. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221369. }
  221370. }
  221371. void setWindowType()
  221372. {
  221373. int netHints [2];
  221374. int numHints = 0;
  221375. if ((styleFlags & windowIsTemporary) != 0
  221376. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221377. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221378. else
  221379. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221380. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221381. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221382. (unsigned char*) &netHints, numHints);
  221383. numHints = 0;
  221384. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221385. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221386. if (component->isAlwaysOnTop())
  221387. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221388. if (numHints > 0)
  221389. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221390. (unsigned char*) &netHints, numHints);
  221391. }
  221392. void createWindow()
  221393. {
  221394. ScopedXLock xlock;
  221395. Atoms::initialiseAtoms();
  221396. resetDragAndDrop();
  221397. // Get defaults for various properties
  221398. const int screen = DefaultScreen (display);
  221399. Window root = RootWindow (display, screen);
  221400. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221401. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221402. if (visual == 0)
  221403. {
  221404. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221405. Process::terminate();
  221406. }
  221407. // Create and install a colormap suitable fr our visual
  221408. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221409. XInstallColormap (display, colormap);
  221410. // Set up the window attributes
  221411. XSetWindowAttributes swa;
  221412. swa.border_pixel = 0;
  221413. swa.background_pixmap = None;
  221414. swa.colormap = colormap;
  221415. swa.event_mask = getAllEventsMask();
  221416. windowH = XCreateWindow (display, root,
  221417. 0, 0, 1, 1,
  221418. 0, depth, InputOutput, visual,
  221419. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221420. &swa);
  221421. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221422. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221423. GrabModeAsync, GrabModeAsync, None, None);
  221424. // Set the window context to identify the window handle object
  221425. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221426. {
  221427. // Failed
  221428. jassertfalse;
  221429. Logger::outputDebugString ("Failed to create context information for window.\n");
  221430. XDestroyWindow (display, windowH);
  221431. windowH = 0;
  221432. return;
  221433. }
  221434. // Set window manager hints
  221435. XWMHints* wmHints = XAllocWMHints();
  221436. wmHints->flags = InputHint | StateHint;
  221437. wmHints->input = True; // Locally active input model
  221438. wmHints->initial_state = NormalState;
  221439. XSetWMHints (display, windowH, wmHints);
  221440. XFree (wmHints);
  221441. // Set the window type
  221442. setWindowType();
  221443. // Define decoration
  221444. if ((styleFlags & windowHasTitleBar) == 0)
  221445. removeWindowDecorations (windowH);
  221446. else
  221447. addWindowButtons (windowH);
  221448. // Set window name
  221449. setWindowTitle (windowH, getComponent()->getName());
  221450. // Associate the PID, allowing to be shut down when something goes wrong
  221451. unsigned long pid = getpid();
  221452. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221453. (unsigned char*) &pid, 1);
  221454. // Set window manager protocols
  221455. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221456. (unsigned char*) Atoms::ProtocolList, 2);
  221457. // Set drag and drop flags
  221458. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221459. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221460. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221461. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221462. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221463. (const unsigned char*) "", 0);
  221464. unsigned long dndVersion = Atoms::DndVersion;
  221465. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221466. (const unsigned char*) &dndVersion, 1);
  221467. // Initialise the pointer and keyboard mapping
  221468. // This is not the same as the logical pointer mapping the X server uses:
  221469. // we don't mess with this.
  221470. static bool mappingInitialised = false;
  221471. if (! mappingInitialised)
  221472. {
  221473. mappingInitialised = true;
  221474. const int numButtons = XGetPointerMapping (display, 0, 0);
  221475. if (numButtons == 2)
  221476. {
  221477. pointerMap[0] = Keys::LeftButton;
  221478. pointerMap[1] = Keys::RightButton;
  221479. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221480. }
  221481. else if (numButtons >= 3)
  221482. {
  221483. pointerMap[0] = Keys::LeftButton;
  221484. pointerMap[1] = Keys::MiddleButton;
  221485. pointerMap[2] = Keys::RightButton;
  221486. if (numButtons >= 5)
  221487. {
  221488. pointerMap[3] = Keys::WheelUp;
  221489. pointerMap[4] = Keys::WheelDown;
  221490. }
  221491. }
  221492. updateModifierMappings();
  221493. }
  221494. }
  221495. void destroyWindow()
  221496. {
  221497. ScopedXLock xlock;
  221498. XPointer handlePointer;
  221499. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221500. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221501. XDestroyWindow (display, windowH);
  221502. // Wait for it to complete and then remove any events for this
  221503. // window from the event queue.
  221504. XSync (display, false);
  221505. XEvent event;
  221506. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221507. {}
  221508. }
  221509. static int getAllEventsMask() throw()
  221510. {
  221511. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221512. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221513. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221514. }
  221515. static int64 getEventTime (::Time t)
  221516. {
  221517. static int64 eventTimeOffset = 0x12345678;
  221518. const int64 thisMessageTime = t;
  221519. if (eventTimeOffset == 0x12345678)
  221520. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221521. return eventTimeOffset + thisMessageTime;
  221522. }
  221523. static void setWindowTitle (Window xwin, const String& title)
  221524. {
  221525. XTextProperty nameProperty;
  221526. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221527. ScopedXLock xlock;
  221528. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221529. {
  221530. XSetWMName (display, xwin, &nameProperty);
  221531. XSetWMIconName (display, xwin, &nameProperty);
  221532. XFree (nameProperty.value);
  221533. }
  221534. }
  221535. void updateBorderSize()
  221536. {
  221537. if ((styleFlags & windowHasTitleBar) == 0)
  221538. {
  221539. windowBorder = BorderSize (0);
  221540. }
  221541. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221542. {
  221543. ScopedXLock xlock;
  221544. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221545. if (hints != None)
  221546. {
  221547. unsigned char* data = 0;
  221548. unsigned long nitems, bytesLeft;
  221549. Atom actualType;
  221550. int actualFormat;
  221551. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221552. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221553. &data) == Success)
  221554. {
  221555. const unsigned long* const sizes = (const unsigned long*) data;
  221556. if (actualFormat == 32)
  221557. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221558. (int) sizes[3], (int) sizes[1]);
  221559. XFree (data);
  221560. }
  221561. }
  221562. }
  221563. }
  221564. void updateBounds()
  221565. {
  221566. jassert (windowH != 0);
  221567. if (windowH != 0)
  221568. {
  221569. Window root, child;
  221570. unsigned int bw, depth;
  221571. ScopedXLock xlock;
  221572. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221573. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221574. &bw, &depth))
  221575. {
  221576. wx = wy = ww = wh = 0;
  221577. }
  221578. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221579. {
  221580. wx = wy = 0;
  221581. }
  221582. }
  221583. }
  221584. void resetDragAndDrop()
  221585. {
  221586. dragAndDropFiles.clear();
  221587. lastDropPos = Point<int> (-1, -1);
  221588. dragAndDropCurrentMimeType = 0;
  221589. dragAndDropSourceWindow = 0;
  221590. srcMimeTypeAtomList.clear();
  221591. }
  221592. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221593. {
  221594. msg.type = ClientMessage;
  221595. msg.display = display;
  221596. msg.window = dragAndDropSourceWindow;
  221597. msg.format = 32;
  221598. msg.data.l[0] = windowH;
  221599. ScopedXLock xlock;
  221600. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221601. }
  221602. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221603. {
  221604. XClientMessageEvent msg;
  221605. zerostruct (msg);
  221606. msg.message_type = Atoms::XdndStatus;
  221607. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221608. msg.data.l[4] = dropAction;
  221609. sendDragAndDropMessage (msg);
  221610. }
  221611. void sendDragAndDropLeave()
  221612. {
  221613. XClientMessageEvent msg;
  221614. zerostruct (msg);
  221615. msg.message_type = Atoms::XdndLeave;
  221616. sendDragAndDropMessage (msg);
  221617. }
  221618. void sendDragAndDropFinish()
  221619. {
  221620. XClientMessageEvent msg;
  221621. zerostruct (msg);
  221622. msg.message_type = Atoms::XdndFinished;
  221623. sendDragAndDropMessage (msg);
  221624. }
  221625. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221626. {
  221627. if ((clientMsg->data.l[1] & 1) == 0)
  221628. {
  221629. sendDragAndDropLeave();
  221630. if (dragAndDropFiles.size() > 0)
  221631. handleFileDragExit (dragAndDropFiles);
  221632. dragAndDropFiles.clear();
  221633. }
  221634. }
  221635. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221636. {
  221637. if (dragAndDropSourceWindow == 0)
  221638. return;
  221639. dragAndDropSourceWindow = clientMsg->data.l[0];
  221640. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221641. (int) clientMsg->data.l[2] & 0xffff);
  221642. dropPos -= getScreenPosition();
  221643. if (lastDropPos != dropPos)
  221644. {
  221645. lastDropPos = dropPos;
  221646. dragAndDropTimestamp = clientMsg->data.l[3];
  221647. Atom targetAction = Atoms::XdndActionCopy;
  221648. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221649. {
  221650. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221651. {
  221652. targetAction = Atoms::allowedActions[i];
  221653. break;
  221654. }
  221655. }
  221656. sendDragAndDropStatus (true, targetAction);
  221657. if (dragAndDropFiles.size() == 0)
  221658. updateDraggedFileList (clientMsg);
  221659. if (dragAndDropFiles.size() > 0)
  221660. handleFileDragMove (dragAndDropFiles, dropPos);
  221661. }
  221662. }
  221663. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221664. {
  221665. if (dragAndDropFiles.size() == 0)
  221666. updateDraggedFileList (clientMsg);
  221667. const StringArray files (dragAndDropFiles);
  221668. const Point<int> lastPos (lastDropPos);
  221669. sendDragAndDropFinish();
  221670. resetDragAndDrop();
  221671. if (files.size() > 0)
  221672. handleFileDragDrop (files, lastPos);
  221673. }
  221674. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221675. {
  221676. dragAndDropFiles.clear();
  221677. srcMimeTypeAtomList.clear();
  221678. dragAndDropCurrentMimeType = 0;
  221679. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221680. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221681. {
  221682. dragAndDropSourceWindow = 0;
  221683. return;
  221684. }
  221685. dragAndDropSourceWindow = clientMsg->data.l[0];
  221686. if ((clientMsg->data.l[1] & 1) != 0)
  221687. {
  221688. Atom actual;
  221689. int format;
  221690. unsigned long count = 0, remaining = 0;
  221691. unsigned char* data = 0;
  221692. ScopedXLock xlock;
  221693. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221694. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221695. &count, &remaining, &data);
  221696. if (data != 0)
  221697. {
  221698. if (actual == XA_ATOM && format == 32 && count != 0)
  221699. {
  221700. const unsigned long* const types = (const unsigned long*) data;
  221701. for (unsigned int i = 0; i < count; ++i)
  221702. if (types[i] != None)
  221703. srcMimeTypeAtomList.add (types[i]);
  221704. }
  221705. XFree (data);
  221706. }
  221707. }
  221708. if (srcMimeTypeAtomList.size() == 0)
  221709. {
  221710. for (int i = 2; i < 5; ++i)
  221711. if (clientMsg->data.l[i] != None)
  221712. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221713. if (srcMimeTypeAtomList.size() == 0)
  221714. {
  221715. dragAndDropSourceWindow = 0;
  221716. return;
  221717. }
  221718. }
  221719. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221720. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221721. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221722. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221723. handleDragAndDropPosition (clientMsg);
  221724. }
  221725. void handleDragAndDropSelection (const XEvent* const evt)
  221726. {
  221727. dragAndDropFiles.clear();
  221728. if (evt->xselection.property != 0)
  221729. {
  221730. StringArray lines;
  221731. {
  221732. MemoryBlock dropData;
  221733. for (;;)
  221734. {
  221735. Atom actual;
  221736. uint8* data = 0;
  221737. unsigned long count = 0, remaining = 0;
  221738. int format = 0;
  221739. ScopedXLock xlock;
  221740. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221741. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221742. &format, &count, &remaining, &data) == Success)
  221743. {
  221744. dropData.append (data, count * format / 8);
  221745. XFree (data);
  221746. if (remaining == 0)
  221747. break;
  221748. }
  221749. else
  221750. {
  221751. XFree (data);
  221752. break;
  221753. }
  221754. }
  221755. lines.addLines (dropData.toString());
  221756. }
  221757. for (int i = 0; i < lines.size(); ++i)
  221758. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221759. dragAndDropFiles.trim();
  221760. dragAndDropFiles.removeEmptyStrings();
  221761. }
  221762. }
  221763. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221764. {
  221765. dragAndDropFiles.clear();
  221766. if (dragAndDropSourceWindow != None
  221767. && dragAndDropCurrentMimeType != 0)
  221768. {
  221769. dragAndDropTimestamp = clientMsg->data.l[2];
  221770. ScopedXLock xlock;
  221771. XConvertSelection (display,
  221772. Atoms::XdndSelection,
  221773. dragAndDropCurrentMimeType,
  221774. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221775. windowH,
  221776. dragAndDropTimestamp);
  221777. }
  221778. }
  221779. StringArray dragAndDropFiles;
  221780. int dragAndDropTimestamp;
  221781. Point<int> lastDropPos;
  221782. Atom dragAndDropCurrentMimeType;
  221783. Window dragAndDropSourceWindow;
  221784. Array <Atom> srcMimeTypeAtomList;
  221785. static int pointerMap[5];
  221786. static Point<int> lastMousePos;
  221787. static void clearLastMousePos() throw()
  221788. {
  221789. lastMousePos = Point<int> (0x100000, 0x100000);
  221790. }
  221791. };
  221792. ModifierKeys LinuxComponentPeer::currentModifiers;
  221793. bool LinuxComponentPeer::isActiveApplication = false;
  221794. int LinuxComponentPeer::pointerMap[5];
  221795. Point<int> LinuxComponentPeer::lastMousePos;
  221796. bool Process::isForegroundProcess()
  221797. {
  221798. return LinuxComponentPeer::isActiveApplication;
  221799. }
  221800. void ModifierKeys::updateCurrentModifiers() throw()
  221801. {
  221802. currentModifiers = LinuxComponentPeer::currentModifiers;
  221803. }
  221804. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221805. {
  221806. Window root, child;
  221807. int x, y, winx, winy;
  221808. unsigned int mask;
  221809. int mouseMods = 0;
  221810. ScopedXLock xlock;
  221811. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221812. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221813. {
  221814. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221815. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221816. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221817. }
  221818. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221819. return LinuxComponentPeer::currentModifiers;
  221820. }
  221821. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221822. {
  221823. if (enableOrDisable)
  221824. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221825. }
  221826. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221827. {
  221828. return new LinuxComponentPeer (this, styleFlags);
  221829. }
  221830. // (this callback is hooked up in the messaging code)
  221831. void juce_windowMessageReceive (XEvent* event)
  221832. {
  221833. if (event->xany.window != None)
  221834. {
  221835. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221836. if (ComponentPeer::isValidPeer (peer))
  221837. peer->handleWindowMessage (event);
  221838. }
  221839. else
  221840. {
  221841. switch (event->xany.type)
  221842. {
  221843. case KeymapNotify:
  221844. {
  221845. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221846. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221847. break;
  221848. }
  221849. default:
  221850. break;
  221851. }
  221852. }
  221853. }
  221854. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221855. {
  221856. if (display == 0)
  221857. return;
  221858. #if JUCE_USE_XINERAMA
  221859. int major_opcode, first_event, first_error;
  221860. ScopedXLock xlock;
  221861. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221862. {
  221863. typedef Bool (*tXineramaIsActive) (Display*);
  221864. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221865. static tXineramaIsActive xXineramaIsActive = 0;
  221866. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221867. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221868. {
  221869. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221870. if (h == 0)
  221871. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221872. if (h != 0)
  221873. {
  221874. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221875. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221876. }
  221877. }
  221878. if (xXineramaIsActive != 0
  221879. && xXineramaQueryScreens != 0
  221880. && xXineramaIsActive (display))
  221881. {
  221882. int numMonitors = 0;
  221883. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221884. if (screens != 0)
  221885. {
  221886. for (int i = numMonitors; --i >= 0;)
  221887. {
  221888. int index = screens[i].screen_number;
  221889. if (index >= 0)
  221890. {
  221891. while (monitorCoords.size() < index)
  221892. monitorCoords.add (Rectangle<int>());
  221893. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221894. screens[i].y_org,
  221895. screens[i].width,
  221896. screens[i].height));
  221897. }
  221898. }
  221899. XFree (screens);
  221900. }
  221901. }
  221902. }
  221903. if (monitorCoords.size() == 0)
  221904. #endif
  221905. {
  221906. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221907. if (hints != None)
  221908. {
  221909. const int numMonitors = ScreenCount (display);
  221910. for (int i = 0; i < numMonitors; ++i)
  221911. {
  221912. Window root = RootWindow (display, i);
  221913. unsigned long nitems, bytesLeft;
  221914. Atom actualType;
  221915. int actualFormat;
  221916. unsigned char* data = 0;
  221917. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221918. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221919. &data) == Success)
  221920. {
  221921. const long* const position = (const long*) data;
  221922. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221923. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221924. position[2], position[3]));
  221925. XFree (data);
  221926. }
  221927. }
  221928. }
  221929. if (monitorCoords.size() == 0)
  221930. {
  221931. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221932. DisplayHeight (display, DefaultScreen (display))));
  221933. }
  221934. }
  221935. }
  221936. void Desktop::createMouseInputSources()
  221937. {
  221938. mouseSources.add (new MouseInputSource (0, true));
  221939. }
  221940. bool Desktop::canUseSemiTransparentWindows() throw()
  221941. {
  221942. int matchedDepth = 0;
  221943. const int desiredDepth = 32;
  221944. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221945. && (matchedDepth == desiredDepth);
  221946. }
  221947. const Point<int> Desktop::getMousePosition()
  221948. {
  221949. Window root, child;
  221950. int x, y, winx, winy;
  221951. unsigned int mask;
  221952. ScopedXLock xlock;
  221953. if (XQueryPointer (display,
  221954. RootWindow (display, DefaultScreen (display)),
  221955. &root, &child,
  221956. &x, &y, &winx, &winy, &mask) == False)
  221957. {
  221958. // Pointer not on the default screen
  221959. x = y = -1;
  221960. }
  221961. return Point<int> (x, y);
  221962. }
  221963. void Desktop::setMousePosition (const Point<int>& newPosition)
  221964. {
  221965. ScopedXLock xlock;
  221966. Window root = RootWindow (display, DefaultScreen (display));
  221967. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221968. }
  221969. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  221970. {
  221971. return upright;
  221972. }
  221973. static bool screenSaverAllowed = true;
  221974. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221975. {
  221976. if (screenSaverAllowed != isEnabled)
  221977. {
  221978. screenSaverAllowed = isEnabled;
  221979. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221980. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221981. if (xScreenSaverSuspend == 0)
  221982. {
  221983. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221984. if (h != 0)
  221985. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221986. }
  221987. ScopedXLock xlock;
  221988. if (xScreenSaverSuspend != 0)
  221989. xScreenSaverSuspend (display, ! isEnabled);
  221990. }
  221991. }
  221992. bool Desktop::isScreenSaverEnabled()
  221993. {
  221994. return screenSaverAllowed;
  221995. }
  221996. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221997. {
  221998. ScopedXLock xlock;
  221999. const unsigned int imageW = image.getWidth();
  222000. const unsigned int imageH = image.getHeight();
  222001. #if JUCE_USE_XCURSOR
  222002. {
  222003. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  222004. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  222005. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  222006. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  222007. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  222008. static tXcursorImageCreate xXcursorImageCreate = 0;
  222009. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  222010. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  222011. static bool hasBeenLoaded = false;
  222012. if (! hasBeenLoaded)
  222013. {
  222014. hasBeenLoaded = true;
  222015. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  222016. if (h != 0)
  222017. {
  222018. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  222019. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  222020. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  222021. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  222022. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  222023. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  222024. || ! xXcursorSupportsARGB (display))
  222025. xXcursorSupportsARGB = 0;
  222026. }
  222027. }
  222028. if (xXcursorSupportsARGB != 0)
  222029. {
  222030. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  222031. if (xcImage != 0)
  222032. {
  222033. xcImage->xhot = hotspotX;
  222034. xcImage->yhot = hotspotY;
  222035. XcursorPixel* dest = xcImage->pixels;
  222036. for (int y = 0; y < (int) imageH; ++y)
  222037. for (int x = 0; x < (int) imageW; ++x)
  222038. *dest++ = image.getPixelAt (x, y).getARGB();
  222039. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  222040. xXcursorImageDestroy (xcImage);
  222041. if (result != 0)
  222042. return result;
  222043. }
  222044. }
  222045. }
  222046. #endif
  222047. Window root = RootWindow (display, DefaultScreen (display));
  222048. unsigned int cursorW, cursorH;
  222049. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  222050. return 0;
  222051. Image im (Image::ARGB, cursorW, cursorH, true);
  222052. {
  222053. Graphics g (im);
  222054. if (imageW > cursorW || imageH > cursorH)
  222055. {
  222056. hotspotX = (hotspotX * cursorW) / imageW;
  222057. hotspotY = (hotspotY * cursorH) / imageH;
  222058. g.drawImageWithin (image, 0, 0, imageW, imageH,
  222059. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222060. false);
  222061. }
  222062. else
  222063. {
  222064. g.drawImageAt (image, 0, 0);
  222065. }
  222066. }
  222067. const int stride = (cursorW + 7) >> 3;
  222068. HeapBlock <char> maskPlane, sourcePlane;
  222069. maskPlane.calloc (stride * cursorH);
  222070. sourcePlane.calloc (stride * cursorH);
  222071. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  222072. for (int y = cursorH; --y >= 0;)
  222073. {
  222074. for (int x = cursorW; --x >= 0;)
  222075. {
  222076. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  222077. const int offset = y * stride + (x >> 3);
  222078. const Colour c (im.getPixelAt (x, y));
  222079. if (c.getAlpha() >= 128)
  222080. maskPlane[offset] |= mask;
  222081. if (c.getBrightness() >= 0.5f)
  222082. sourcePlane[offset] |= mask;
  222083. }
  222084. }
  222085. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222086. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222087. XColor white, black;
  222088. black.red = black.green = black.blue = 0;
  222089. white.red = white.green = white.blue = 0xffff;
  222090. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  222091. XFreePixmap (display, sourcePixmap);
  222092. XFreePixmap (display, maskPixmap);
  222093. return result;
  222094. }
  222095. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  222096. {
  222097. ScopedXLock xlock;
  222098. if (cursorHandle != 0)
  222099. XFreeCursor (display, (Cursor) cursorHandle);
  222100. }
  222101. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  222102. {
  222103. unsigned int shape;
  222104. switch (type)
  222105. {
  222106. case NormalCursor: return None; // Use parent cursor
  222107. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  222108. case WaitCursor: shape = XC_watch; break;
  222109. case IBeamCursor: shape = XC_xterm; break;
  222110. case PointingHandCursor: shape = XC_hand2; break;
  222111. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  222112. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  222113. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  222114. case TopEdgeResizeCursor: shape = XC_top_side; break;
  222115. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  222116. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  222117. case RightEdgeResizeCursor: shape = XC_right_side; break;
  222118. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  222119. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  222120. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  222121. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  222122. case CrosshairCursor: shape = XC_crosshair; break;
  222123. case DraggingHandCursor:
  222124. {
  222125. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  222126. 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,
  222127. 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 };
  222128. const int dragHandDataSize = 99;
  222129. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  222130. }
  222131. case CopyingCursor:
  222132. {
  222133. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  222134. 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,
  222135. 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,
  222136. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  222137. const int copyCursorSize = 119;
  222138. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  222139. }
  222140. default:
  222141. jassertfalse;
  222142. return None;
  222143. }
  222144. ScopedXLock xlock;
  222145. return (void*) XCreateFontCursor (display, shape);
  222146. }
  222147. void MouseCursor::showInWindow (ComponentPeer* peer) const
  222148. {
  222149. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  222150. if (lp != 0)
  222151. lp->showMouseCursor ((Cursor) getHandle());
  222152. }
  222153. void MouseCursor::showInAllWindows() const
  222154. {
  222155. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222156. showInWindow (ComponentPeer::getPeer (i));
  222157. }
  222158. const Image juce_createIconForFile (const File& file)
  222159. {
  222160. return Image::null;
  222161. }
  222162. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  222163. {
  222164. return createSoftwareImage (format, width, height, clearImage);
  222165. }
  222166. #if JUCE_OPENGL
  222167. class WindowedGLContext : public OpenGLContext
  222168. {
  222169. public:
  222170. WindowedGLContext (Component* const component,
  222171. const OpenGLPixelFormat& pixelFormat_,
  222172. GLXContext sharedContext)
  222173. : renderContext (0),
  222174. embeddedWindow (0),
  222175. pixelFormat (pixelFormat_),
  222176. swapInterval (0)
  222177. {
  222178. jassert (component != 0);
  222179. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222180. if (peer == 0)
  222181. return;
  222182. ScopedXLock xlock;
  222183. XSync (display, False);
  222184. GLint attribs [64];
  222185. int n = 0;
  222186. attribs[n++] = GLX_RGBA;
  222187. attribs[n++] = GLX_DOUBLEBUFFER;
  222188. attribs[n++] = GLX_RED_SIZE;
  222189. attribs[n++] = pixelFormat.redBits;
  222190. attribs[n++] = GLX_GREEN_SIZE;
  222191. attribs[n++] = pixelFormat.greenBits;
  222192. attribs[n++] = GLX_BLUE_SIZE;
  222193. attribs[n++] = pixelFormat.blueBits;
  222194. attribs[n++] = GLX_ALPHA_SIZE;
  222195. attribs[n++] = pixelFormat.alphaBits;
  222196. attribs[n++] = GLX_DEPTH_SIZE;
  222197. attribs[n++] = pixelFormat.depthBufferBits;
  222198. attribs[n++] = GLX_STENCIL_SIZE;
  222199. attribs[n++] = pixelFormat.stencilBufferBits;
  222200. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222201. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222202. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222203. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222204. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222205. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222206. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222207. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222208. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222209. attribs[n++] = None;
  222210. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222211. if (bestVisual == 0)
  222212. return;
  222213. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222214. Window windowH = (Window) peer->getNativeHandle();
  222215. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222216. XSetWindowAttributes swa;
  222217. swa.colormap = colourMap;
  222218. swa.border_pixel = 0;
  222219. swa.event_mask = ExposureMask | StructureNotifyMask;
  222220. embeddedWindow = XCreateWindow (display, windowH,
  222221. 0, 0, 1, 1, 0,
  222222. bestVisual->depth,
  222223. InputOutput,
  222224. bestVisual->visual,
  222225. CWBorderPixel | CWColormap | CWEventMask,
  222226. &swa);
  222227. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222228. XMapWindow (display, embeddedWindow);
  222229. XFreeColormap (display, colourMap);
  222230. XFree (bestVisual);
  222231. XSync (display, False);
  222232. }
  222233. ~WindowedGLContext()
  222234. {
  222235. ScopedXLock xlock;
  222236. deleteContext();
  222237. XUnmapWindow (display, embeddedWindow);
  222238. XDestroyWindow (display, embeddedWindow);
  222239. }
  222240. void deleteContext()
  222241. {
  222242. makeInactive();
  222243. if (renderContext != 0)
  222244. {
  222245. ScopedXLock xlock;
  222246. glXDestroyContext (display, renderContext);
  222247. renderContext = 0;
  222248. }
  222249. }
  222250. bool makeActive() const throw()
  222251. {
  222252. jassert (renderContext != 0);
  222253. ScopedXLock xlock;
  222254. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222255. && XSync (display, False);
  222256. }
  222257. bool makeInactive() const throw()
  222258. {
  222259. ScopedXLock xlock;
  222260. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222261. }
  222262. bool isActive() const throw()
  222263. {
  222264. ScopedXLock xlock;
  222265. return glXGetCurrentContext() == renderContext;
  222266. }
  222267. const OpenGLPixelFormat getPixelFormat() const
  222268. {
  222269. return pixelFormat;
  222270. }
  222271. void* getRawContext() const throw()
  222272. {
  222273. return renderContext;
  222274. }
  222275. void updateWindowPosition (int x, int y, int w, int h, int)
  222276. {
  222277. ScopedXLock xlock;
  222278. XMoveResizeWindow (display, embeddedWindow,
  222279. x, y, jmax (1, w), jmax (1, h));
  222280. }
  222281. void swapBuffers()
  222282. {
  222283. ScopedXLock xlock;
  222284. glXSwapBuffers (display, embeddedWindow);
  222285. }
  222286. bool setSwapInterval (const int numFramesPerSwap)
  222287. {
  222288. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222289. if (GLXSwapIntervalSGI != 0)
  222290. {
  222291. swapInterval = numFramesPerSwap;
  222292. GLXSwapIntervalSGI (numFramesPerSwap);
  222293. return true;
  222294. }
  222295. return false;
  222296. }
  222297. int getSwapInterval() const
  222298. {
  222299. return swapInterval;
  222300. }
  222301. void repaint()
  222302. {
  222303. }
  222304. juce_UseDebuggingNewOperator
  222305. GLXContext renderContext;
  222306. private:
  222307. Window embeddedWindow;
  222308. OpenGLPixelFormat pixelFormat;
  222309. int swapInterval;
  222310. WindowedGLContext (const WindowedGLContext&);
  222311. WindowedGLContext& operator= (const WindowedGLContext&);
  222312. };
  222313. OpenGLContext* OpenGLComponent::createContext()
  222314. {
  222315. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222316. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222317. return (c->renderContext != 0) ? c.release() : 0;
  222318. }
  222319. void juce_glViewport (const int w, const int h)
  222320. {
  222321. glViewport (0, 0, w, h);
  222322. }
  222323. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222324. OwnedArray <OpenGLPixelFormat>& results)
  222325. {
  222326. results.add (new OpenGLPixelFormat()); // xxx
  222327. }
  222328. #endif
  222329. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222330. {
  222331. jassertfalse; // not implemented!
  222332. return false;
  222333. }
  222334. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222335. {
  222336. jassertfalse; // not implemented!
  222337. return false;
  222338. }
  222339. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222340. {
  222341. if (! isOnDesktop ())
  222342. addToDesktop (0);
  222343. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222344. if (wp != 0)
  222345. {
  222346. wp->setTaskBarIcon (newImage);
  222347. setVisible (true);
  222348. toFront (false);
  222349. repaint();
  222350. }
  222351. }
  222352. void SystemTrayIconComponent::paint (Graphics& g)
  222353. {
  222354. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222355. if (wp != 0)
  222356. {
  222357. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222358. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222359. false);
  222360. }
  222361. }
  222362. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222363. {
  222364. // xxx not yet implemented!
  222365. }
  222366. void PlatformUtilities::beep()
  222367. {
  222368. std::cout << "\a" << std::flush;
  222369. }
  222370. bool AlertWindow::showNativeDialogBox (const String& title,
  222371. const String& bodyText,
  222372. bool isOkCancel)
  222373. {
  222374. // use a non-native one for the time being..
  222375. if (isOkCancel)
  222376. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222377. else
  222378. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222379. return true;
  222380. }
  222381. const int KeyPress::spaceKey = XK_space & 0xff;
  222382. const int KeyPress::returnKey = XK_Return & 0xff;
  222383. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222384. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222385. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222386. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222387. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222388. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222389. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222390. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222391. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222392. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222393. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222394. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222395. const int KeyPress::tabKey = XK_Tab & 0xff;
  222396. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222397. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222398. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222399. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222400. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222401. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222402. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222403. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222404. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222405. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222406. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222407. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222408. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222409. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222410. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222411. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222412. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222413. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222414. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222415. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222416. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222417. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222418. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222419. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222420. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222421. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222422. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222423. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222424. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222425. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222426. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222427. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222428. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222429. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222430. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222431. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222432. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222433. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222434. #endif
  222435. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222436. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222437. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222438. // compiled on its own).
  222439. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222440. namespace
  222441. {
  222442. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222443. {
  222444. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222445. snd_pcm_hw_params_t* hwParams;
  222446. snd_pcm_hw_params_alloca (&hwParams);
  222447. for (int i = 0; ratesToTry[i] != 0; ++i)
  222448. {
  222449. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222450. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222451. {
  222452. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222453. }
  222454. }
  222455. }
  222456. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222457. {
  222458. snd_pcm_hw_params_t *params;
  222459. snd_pcm_hw_params_alloca (&params);
  222460. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222461. {
  222462. snd_pcm_hw_params_get_channels_min (params, minChans);
  222463. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222464. }
  222465. }
  222466. void getDeviceProperties (const String& deviceID,
  222467. unsigned int& minChansOut,
  222468. unsigned int& maxChansOut,
  222469. unsigned int& minChansIn,
  222470. unsigned int& maxChansIn,
  222471. Array <int>& rates)
  222472. {
  222473. if (deviceID.isEmpty())
  222474. return;
  222475. snd_ctl_t* handle;
  222476. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222477. {
  222478. snd_pcm_info_t* info;
  222479. snd_pcm_info_alloca (&info);
  222480. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222481. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222482. snd_pcm_info_set_subdevice (info, 0);
  222483. if (snd_ctl_pcm_info (handle, info) >= 0)
  222484. {
  222485. snd_pcm_t* pcmHandle;
  222486. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222487. {
  222488. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222489. getDeviceSampleRates (pcmHandle, rates);
  222490. snd_pcm_close (pcmHandle);
  222491. }
  222492. }
  222493. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222494. if (snd_ctl_pcm_info (handle, info) >= 0)
  222495. {
  222496. snd_pcm_t* pcmHandle;
  222497. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222498. {
  222499. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222500. if (rates.size() == 0)
  222501. getDeviceSampleRates (pcmHandle, rates);
  222502. snd_pcm_close (pcmHandle);
  222503. }
  222504. }
  222505. snd_ctl_close (handle);
  222506. }
  222507. }
  222508. }
  222509. class ALSADevice
  222510. {
  222511. public:
  222512. ALSADevice (const String& deviceID, bool forInput)
  222513. : handle (0),
  222514. bitDepth (16),
  222515. numChannelsRunning (0),
  222516. latency (0),
  222517. isInput (forInput),
  222518. isInterleaved (true)
  222519. {
  222520. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222521. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222522. SND_PCM_ASYNC));
  222523. }
  222524. ~ALSADevice()
  222525. {
  222526. if (handle != 0)
  222527. snd_pcm_close (handle);
  222528. }
  222529. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222530. {
  222531. if (handle == 0)
  222532. return false;
  222533. snd_pcm_hw_params_t* hwParams;
  222534. snd_pcm_hw_params_alloca (&hwParams);
  222535. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222536. return false;
  222537. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222538. isInterleaved = false;
  222539. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222540. isInterleaved = true;
  222541. else
  222542. {
  222543. jassertfalse;
  222544. return false;
  222545. }
  222546. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  222547. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  222548. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  222549. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  222550. SND_PCM_FORMAT_S32_BE, 32,
  222551. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  222552. SND_PCM_FORMAT_S24_3BE, 24,
  222553. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  222554. SND_PCM_FORMAT_S16_BE, 16 };
  222555. bitDepth = 0;
  222556. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  222557. {
  222558. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222559. {
  222560. bitDepth = formatsToTry [i + 1] & 255;
  222561. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  222562. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  222563. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  222564. break;
  222565. }
  222566. }
  222567. if (bitDepth == 0)
  222568. {
  222569. error = "device doesn't support a compatible PCM format";
  222570. DBG ("ALSA error: " + error + "\n");
  222571. return false;
  222572. }
  222573. int dir = 0;
  222574. unsigned int periods = 4;
  222575. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222576. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222577. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222578. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222579. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222580. || failed (snd_pcm_hw_params (handle, hwParams)))
  222581. {
  222582. return false;
  222583. }
  222584. snd_pcm_uframes_t frames = 0;
  222585. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222586. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222587. latency = 0;
  222588. else
  222589. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222590. snd_pcm_sw_params_t* swParams;
  222591. snd_pcm_sw_params_alloca (&swParams);
  222592. snd_pcm_uframes_t boundary;
  222593. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222594. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222595. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222596. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222597. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222598. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222599. || failed (snd_pcm_sw_params (handle, swParams)))
  222600. {
  222601. return false;
  222602. }
  222603. /*
  222604. #if JUCE_DEBUG
  222605. // enable this to dump the config of the devices that get opened
  222606. snd_output_t* out;
  222607. snd_output_stdio_attach (&out, stderr, 0);
  222608. snd_pcm_hw_params_dump (hwParams, out);
  222609. snd_pcm_sw_params_dump (swParams, out);
  222610. #endif
  222611. */
  222612. numChannelsRunning = numChannels;
  222613. return true;
  222614. }
  222615. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222616. {
  222617. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222618. float** const data = outputChannelBuffer.getArrayOfChannels();
  222619. snd_pcm_sframes_t numDone = 0;
  222620. if (isInterleaved)
  222621. {
  222622. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222623. for (int i = 0; i < numChannelsRunning; ++i)
  222624. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222625. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222626. }
  222627. else
  222628. {
  222629. for (int i = 0; i < numChannelsRunning; ++i)
  222630. converter->convertSamples (data[i], data[i], numSamples);
  222631. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222632. }
  222633. if (failed (numDone))
  222634. {
  222635. if (numDone == -EPIPE)
  222636. {
  222637. if (failed (snd_pcm_prepare (handle)))
  222638. return false;
  222639. }
  222640. else if (numDone != -ESTRPIPE)
  222641. return false;
  222642. }
  222643. return true;
  222644. }
  222645. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222646. {
  222647. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222648. float** const data = inputChannelBuffer.getArrayOfChannels();
  222649. if (isInterleaved)
  222650. {
  222651. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222652. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  222653. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222654. if (failed (num))
  222655. {
  222656. if (num == -EPIPE)
  222657. {
  222658. if (failed (snd_pcm_prepare (handle)))
  222659. return false;
  222660. }
  222661. else if (num != -ESTRPIPE)
  222662. return false;
  222663. }
  222664. for (int i = 0; i < numChannelsRunning; ++i)
  222665. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222666. }
  222667. else
  222668. {
  222669. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222670. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222671. return false;
  222672. for (int i = 0; i < numChannelsRunning; ++i)
  222673. converter->convertSamples (data[i], data[i], numSamples);
  222674. }
  222675. return true;
  222676. }
  222677. juce_UseDebuggingNewOperator
  222678. snd_pcm_t* handle;
  222679. String error;
  222680. int bitDepth, numChannelsRunning, latency;
  222681. private:
  222682. const bool isInput;
  222683. bool isInterleaved;
  222684. MemoryBlock scratch;
  222685. ScopedPointer<AudioData::Converter> converter;
  222686. template <class SampleType>
  222687. struct ConverterHelper
  222688. {
  222689. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222690. {
  222691. if (forInput)
  222692. {
  222693. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222694. if (isLittleEndian)
  222695. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222696. else
  222697. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222698. }
  222699. else
  222700. {
  222701. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222702. if (isLittleEndian)
  222703. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222704. else
  222705. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222706. }
  222707. }
  222708. };
  222709. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222710. {
  222711. switch (bitDepth)
  222712. {
  222713. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222714. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222715. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222716. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222717. default: jassertfalse; break; // unsupported format!
  222718. }
  222719. return 0;
  222720. }
  222721. bool failed (const int errorNum)
  222722. {
  222723. if (errorNum >= 0)
  222724. return false;
  222725. error = snd_strerror (errorNum);
  222726. DBG ("ALSA error: " + error + "\n");
  222727. return true;
  222728. }
  222729. };
  222730. class ALSAThread : public Thread
  222731. {
  222732. public:
  222733. ALSAThread (const String& inputId_,
  222734. const String& outputId_)
  222735. : Thread ("Juce ALSA"),
  222736. sampleRate (0),
  222737. bufferSize (0),
  222738. outputLatency (0),
  222739. inputLatency (0),
  222740. callback (0),
  222741. inputId (inputId_),
  222742. outputId (outputId_),
  222743. numCallbacks (0),
  222744. inputChannelBuffer (1, 1),
  222745. outputChannelBuffer (1, 1)
  222746. {
  222747. initialiseRatesAndChannels();
  222748. }
  222749. ~ALSAThread()
  222750. {
  222751. close();
  222752. }
  222753. void open (BigInteger inputChannels,
  222754. BigInteger outputChannels,
  222755. const double sampleRate_,
  222756. const int bufferSize_)
  222757. {
  222758. close();
  222759. error = String::empty;
  222760. sampleRate = sampleRate_;
  222761. bufferSize = bufferSize_;
  222762. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222763. inputChannelBuffer.clear();
  222764. inputChannelDataForCallback.clear();
  222765. currentInputChans.clear();
  222766. if (inputChannels.getHighestBit() >= 0)
  222767. {
  222768. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222769. {
  222770. if (inputChannels[i])
  222771. {
  222772. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222773. currentInputChans.setBit (i);
  222774. }
  222775. }
  222776. }
  222777. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222778. outputChannelBuffer.clear();
  222779. outputChannelDataForCallback.clear();
  222780. currentOutputChans.clear();
  222781. if (outputChannels.getHighestBit() >= 0)
  222782. {
  222783. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222784. {
  222785. if (outputChannels[i])
  222786. {
  222787. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222788. currentOutputChans.setBit (i);
  222789. }
  222790. }
  222791. }
  222792. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222793. {
  222794. outputDevice = new ALSADevice (outputId, false);
  222795. if (outputDevice->error.isNotEmpty())
  222796. {
  222797. error = outputDevice->error;
  222798. outputDevice = 0;
  222799. return;
  222800. }
  222801. currentOutputChans.setRange (0, minChansOut, true);
  222802. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222803. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222804. bufferSize))
  222805. {
  222806. error = outputDevice->error;
  222807. outputDevice = 0;
  222808. return;
  222809. }
  222810. outputLatency = outputDevice->latency;
  222811. }
  222812. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222813. {
  222814. inputDevice = new ALSADevice (inputId, true);
  222815. if (inputDevice->error.isNotEmpty())
  222816. {
  222817. error = inputDevice->error;
  222818. inputDevice = 0;
  222819. return;
  222820. }
  222821. currentInputChans.setRange (0, minChansIn, true);
  222822. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222823. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222824. bufferSize))
  222825. {
  222826. error = inputDevice->error;
  222827. inputDevice = 0;
  222828. return;
  222829. }
  222830. inputLatency = inputDevice->latency;
  222831. }
  222832. if (outputDevice == 0 && inputDevice == 0)
  222833. {
  222834. error = "no channels";
  222835. return;
  222836. }
  222837. if (outputDevice != 0 && inputDevice != 0)
  222838. {
  222839. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222840. }
  222841. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222842. return;
  222843. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222844. return;
  222845. startThread (9);
  222846. int count = 1000;
  222847. while (numCallbacks == 0)
  222848. {
  222849. sleep (5);
  222850. if (--count < 0 || ! isThreadRunning())
  222851. {
  222852. error = "device didn't start";
  222853. break;
  222854. }
  222855. }
  222856. }
  222857. void close()
  222858. {
  222859. stopThread (6000);
  222860. inputDevice = 0;
  222861. outputDevice = 0;
  222862. inputChannelBuffer.setSize (1, 1);
  222863. outputChannelBuffer.setSize (1, 1);
  222864. numCallbacks = 0;
  222865. }
  222866. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222867. {
  222868. const ScopedLock sl (callbackLock);
  222869. callback = newCallback;
  222870. }
  222871. void run()
  222872. {
  222873. while (! threadShouldExit())
  222874. {
  222875. if (inputDevice != 0)
  222876. {
  222877. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222878. {
  222879. DBG ("ALSA: read failure");
  222880. break;
  222881. }
  222882. }
  222883. if (threadShouldExit())
  222884. break;
  222885. {
  222886. const ScopedLock sl (callbackLock);
  222887. ++numCallbacks;
  222888. if (callback != 0)
  222889. {
  222890. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222891. inputChannelDataForCallback.size(),
  222892. outputChannelDataForCallback.getRawDataPointer(),
  222893. outputChannelDataForCallback.size(),
  222894. bufferSize);
  222895. }
  222896. else
  222897. {
  222898. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222899. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222900. }
  222901. }
  222902. if (outputDevice != 0)
  222903. {
  222904. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222905. if (threadShouldExit())
  222906. break;
  222907. failed (snd_pcm_avail_update (outputDevice->handle));
  222908. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222909. {
  222910. DBG ("ALSA: write failure");
  222911. break;
  222912. }
  222913. }
  222914. }
  222915. }
  222916. int getBitDepth() const throw()
  222917. {
  222918. if (outputDevice != 0)
  222919. return outputDevice->bitDepth;
  222920. if (inputDevice != 0)
  222921. return inputDevice->bitDepth;
  222922. return 16;
  222923. }
  222924. juce_UseDebuggingNewOperator
  222925. String error;
  222926. double sampleRate;
  222927. int bufferSize, outputLatency, inputLatency;
  222928. BigInteger currentInputChans, currentOutputChans;
  222929. Array <int> sampleRates;
  222930. StringArray channelNamesOut, channelNamesIn;
  222931. AudioIODeviceCallback* callback;
  222932. private:
  222933. const String inputId, outputId;
  222934. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222935. int numCallbacks;
  222936. CriticalSection callbackLock;
  222937. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222938. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222939. unsigned int minChansOut, maxChansOut;
  222940. unsigned int minChansIn, maxChansIn;
  222941. bool failed (const int errorNum)
  222942. {
  222943. if (errorNum >= 0)
  222944. return false;
  222945. error = snd_strerror (errorNum);
  222946. DBG ("ALSA error: " + error + "\n");
  222947. return true;
  222948. }
  222949. void initialiseRatesAndChannels()
  222950. {
  222951. sampleRates.clear();
  222952. channelNamesOut.clear();
  222953. channelNamesIn.clear();
  222954. minChansOut = 0;
  222955. maxChansOut = 0;
  222956. minChansIn = 0;
  222957. maxChansIn = 0;
  222958. unsigned int dummy = 0;
  222959. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222960. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222961. unsigned int i;
  222962. for (i = 0; i < maxChansOut; ++i)
  222963. channelNamesOut.add ("channel " + String ((int) i + 1));
  222964. for (i = 0; i < maxChansIn; ++i)
  222965. channelNamesIn.add ("channel " + String ((int) i + 1));
  222966. }
  222967. };
  222968. class ALSAAudioIODevice : public AudioIODevice
  222969. {
  222970. public:
  222971. ALSAAudioIODevice (const String& deviceName,
  222972. const String& inputId_,
  222973. const String& outputId_)
  222974. : AudioIODevice (deviceName, "ALSA"),
  222975. inputId (inputId_),
  222976. outputId (outputId_),
  222977. isOpen_ (false),
  222978. isStarted (false),
  222979. internal (inputId_, outputId_)
  222980. {
  222981. }
  222982. ~ALSAAudioIODevice()
  222983. {
  222984. }
  222985. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222986. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222987. int getNumSampleRates() { return internal.sampleRates.size(); }
  222988. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222989. int getDefaultBufferSize() { return 512; }
  222990. int getNumBufferSizesAvailable() { return 50; }
  222991. int getBufferSizeSamples (int index)
  222992. {
  222993. int n = 16;
  222994. for (int i = 0; i < index; ++i)
  222995. n += n < 64 ? 16
  222996. : (n < 512 ? 32
  222997. : (n < 1024 ? 64
  222998. : (n < 2048 ? 128 : 256)));
  222999. return n;
  223000. }
  223001. const String open (const BigInteger& inputChannels,
  223002. const BigInteger& outputChannels,
  223003. double sampleRate,
  223004. int bufferSizeSamples)
  223005. {
  223006. close();
  223007. if (bufferSizeSamples <= 0)
  223008. bufferSizeSamples = getDefaultBufferSize();
  223009. if (sampleRate <= 0)
  223010. {
  223011. for (int i = 0; i < getNumSampleRates(); ++i)
  223012. {
  223013. if (getSampleRate (i) >= 44100)
  223014. {
  223015. sampleRate = getSampleRate (i);
  223016. break;
  223017. }
  223018. }
  223019. }
  223020. internal.open (inputChannels, outputChannels,
  223021. sampleRate, bufferSizeSamples);
  223022. isOpen_ = internal.error.isEmpty();
  223023. return internal.error;
  223024. }
  223025. void close()
  223026. {
  223027. stop();
  223028. internal.close();
  223029. isOpen_ = false;
  223030. }
  223031. bool isOpen() { return isOpen_; }
  223032. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  223033. const String getLastError() { return internal.error; }
  223034. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  223035. double getCurrentSampleRate() { return internal.sampleRate; }
  223036. int getCurrentBitDepth() { return internal.getBitDepth(); }
  223037. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  223038. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  223039. int getOutputLatencyInSamples() { return internal.outputLatency; }
  223040. int getInputLatencyInSamples() { return internal.inputLatency; }
  223041. void start (AudioIODeviceCallback* callback)
  223042. {
  223043. if (! isOpen_)
  223044. callback = 0;
  223045. if (callback != 0)
  223046. callback->audioDeviceAboutToStart (this);
  223047. internal.setCallback (callback);
  223048. isStarted = (callback != 0);
  223049. }
  223050. void stop()
  223051. {
  223052. AudioIODeviceCallback* const oldCallback = internal.callback;
  223053. start (0);
  223054. if (oldCallback != 0)
  223055. oldCallback->audioDeviceStopped();
  223056. }
  223057. String inputId, outputId;
  223058. private:
  223059. bool isOpen_, isStarted;
  223060. ALSAThread internal;
  223061. };
  223062. class ALSAAudioIODeviceType : public AudioIODeviceType
  223063. {
  223064. public:
  223065. ALSAAudioIODeviceType()
  223066. : AudioIODeviceType ("ALSA"),
  223067. hasScanned (false)
  223068. {
  223069. }
  223070. ~ALSAAudioIODeviceType()
  223071. {
  223072. }
  223073. void scanForDevices()
  223074. {
  223075. if (hasScanned)
  223076. return;
  223077. hasScanned = true;
  223078. inputNames.clear();
  223079. inputIds.clear();
  223080. outputNames.clear();
  223081. outputIds.clear();
  223082. /* void** hints = 0;
  223083. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  223084. {
  223085. for (void** hint = hints; *hint != 0; ++hint)
  223086. {
  223087. const String name (getHint (*hint, "NAME"));
  223088. if (name.isNotEmpty())
  223089. {
  223090. const String ioid (getHint (*hint, "IOID"));
  223091. String desc (getHint (*hint, "DESC"));
  223092. if (desc.isEmpty())
  223093. desc = name;
  223094. desc = desc.replaceCharacters ("\n\r", " ");
  223095. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  223096. if (ioid.isEmpty() || ioid == "Input")
  223097. {
  223098. inputNames.add (desc);
  223099. inputIds.add (name);
  223100. }
  223101. if (ioid.isEmpty() || ioid == "Output")
  223102. {
  223103. outputNames.add (desc);
  223104. outputIds.add (name);
  223105. }
  223106. }
  223107. }
  223108. snd_device_name_free_hint (hints);
  223109. }
  223110. */
  223111. snd_ctl_t* handle = 0;
  223112. snd_ctl_card_info_t* info = 0;
  223113. snd_ctl_card_info_alloca (&info);
  223114. int cardNum = -1;
  223115. while (outputIds.size() + inputIds.size() <= 32)
  223116. {
  223117. snd_card_next (&cardNum);
  223118. if (cardNum < 0)
  223119. break;
  223120. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  223121. {
  223122. if (snd_ctl_card_info (handle, info) >= 0)
  223123. {
  223124. String cardId (snd_ctl_card_info_get_id (info));
  223125. if (cardId.removeCharacters ("0123456789").isEmpty())
  223126. cardId = String (cardNum);
  223127. int device = -1;
  223128. for (;;)
  223129. {
  223130. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  223131. break;
  223132. String id, name;
  223133. id << "hw:" << cardId << ',' << device;
  223134. bool isInput, isOutput;
  223135. if (testDevice (id, isInput, isOutput))
  223136. {
  223137. name << snd_ctl_card_info_get_name (info);
  223138. if (name.isEmpty())
  223139. name = id;
  223140. if (isInput)
  223141. {
  223142. inputNames.add (name);
  223143. inputIds.add (id);
  223144. }
  223145. if (isOutput)
  223146. {
  223147. outputNames.add (name);
  223148. outputIds.add (id);
  223149. }
  223150. }
  223151. }
  223152. }
  223153. snd_ctl_close (handle);
  223154. }
  223155. }
  223156. inputNames.appendNumbersToDuplicates (false, true);
  223157. outputNames.appendNumbersToDuplicates (false, true);
  223158. }
  223159. const StringArray getDeviceNames (bool wantInputNames) const
  223160. {
  223161. jassert (hasScanned); // need to call scanForDevices() before doing this
  223162. return wantInputNames ? inputNames : outputNames;
  223163. }
  223164. int getDefaultDeviceIndex (bool forInput) const
  223165. {
  223166. jassert (hasScanned); // need to call scanForDevices() before doing this
  223167. return 0;
  223168. }
  223169. bool hasSeparateInputsAndOutputs() const { return true; }
  223170. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223171. {
  223172. jassert (hasScanned); // need to call scanForDevices() before doing this
  223173. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  223174. if (d == 0)
  223175. return -1;
  223176. return asInput ? inputIds.indexOf (d->inputId)
  223177. : outputIds.indexOf (d->outputId);
  223178. }
  223179. AudioIODevice* createDevice (const String& outputDeviceName,
  223180. const String& inputDeviceName)
  223181. {
  223182. jassert (hasScanned); // need to call scanForDevices() before doing this
  223183. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223184. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223185. String deviceName (outputIndex >= 0 ? outputDeviceName
  223186. : inputDeviceName);
  223187. if (inputIndex >= 0 || outputIndex >= 0)
  223188. return new ALSAAudioIODevice (deviceName,
  223189. inputIds [inputIndex],
  223190. outputIds [outputIndex]);
  223191. return 0;
  223192. }
  223193. juce_UseDebuggingNewOperator
  223194. private:
  223195. StringArray inputNames, outputNames, inputIds, outputIds;
  223196. bool hasScanned;
  223197. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  223198. {
  223199. unsigned int minChansOut = 0, maxChansOut = 0;
  223200. unsigned int minChansIn = 0, maxChansIn = 0;
  223201. Array <int> rates;
  223202. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  223203. DBG ("ALSA device: " + id
  223204. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  223205. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  223206. + " rates=" + String (rates.size()));
  223207. isInput = maxChansIn > 0;
  223208. isOutput = maxChansOut > 0;
  223209. return (isInput || isOutput) && rates.size() > 0;
  223210. }
  223211. /*static const String getHint (void* hint, const char* type)
  223212. {
  223213. char* const n = snd_device_name_get_hint (hint, type);
  223214. const String s ((const char*) n);
  223215. free (n);
  223216. return s;
  223217. }*/
  223218. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  223219. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  223220. };
  223221. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  223222. {
  223223. return new ALSAAudioIODeviceType();
  223224. }
  223225. #endif
  223226. /*** End of inlined file: juce_linux_Audio.cpp ***/
  223227. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  223228. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223229. // compiled on its own).
  223230. #ifdef JUCE_INCLUDED_FILE
  223231. #if JUCE_JACK
  223232. static void* juce_libjack_handle = 0;
  223233. void* juce_load_jack_function (const char* const name)
  223234. {
  223235. if (juce_libjack_handle == 0)
  223236. return 0;
  223237. return dlsym (juce_libjack_handle, name);
  223238. }
  223239. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223240. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223241. return_type fn_name argument_types { \
  223242. static fn_name##_ptr_t fn = 0; \
  223243. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223244. if (fn) return (*fn)arguments; \
  223245. else return 0; \
  223246. }
  223247. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223248. typedef void (*fn_name##_ptr_t)argument_types; \
  223249. void fn_name argument_types { \
  223250. static fn_name##_ptr_t fn = 0; \
  223251. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223252. if (fn) (*fn)arguments; \
  223253. }
  223254. 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));
  223255. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223256. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223257. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223258. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223259. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223260. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223261. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223262. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223263. 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));
  223264. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223265. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223266. 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));
  223267. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223268. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223269. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223270. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223271. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223272. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223273. #if JUCE_DEBUG
  223274. #define JACK_LOGGING_ENABLED 1
  223275. #endif
  223276. #if JACK_LOGGING_ENABLED
  223277. namespace
  223278. {
  223279. void jack_Log (const String& s)
  223280. {
  223281. std::cerr << s << std::endl;
  223282. }
  223283. void dumpJackErrorMessage (const jack_status_t status)
  223284. {
  223285. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223286. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223287. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223288. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223289. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223290. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223291. }
  223292. }
  223293. #else
  223294. #define dumpJackErrorMessage(a) {}
  223295. #define jack_Log(...) {}
  223296. #endif
  223297. #ifndef JUCE_JACK_CLIENT_NAME
  223298. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223299. #endif
  223300. class JackAudioIODevice : public AudioIODevice
  223301. {
  223302. public:
  223303. JackAudioIODevice (const String& deviceName,
  223304. const String& inputId_,
  223305. const String& outputId_)
  223306. : AudioIODevice (deviceName, "JACK"),
  223307. inputId (inputId_),
  223308. outputId (outputId_),
  223309. isOpen_ (false),
  223310. callback (0),
  223311. totalNumberOfInputChannels (0),
  223312. totalNumberOfOutputChannels (0)
  223313. {
  223314. jassert (deviceName.isNotEmpty());
  223315. jack_status_t status;
  223316. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223317. if (client == 0)
  223318. {
  223319. dumpJackErrorMessage (status);
  223320. }
  223321. else
  223322. {
  223323. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223324. // open input ports
  223325. const StringArray inputChannels (getInputChannelNames());
  223326. for (int i = 0; i < inputChannels.size(); i++)
  223327. {
  223328. String inputName;
  223329. inputName << "in_" << ++totalNumberOfInputChannels;
  223330. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223331. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223332. }
  223333. // open output ports
  223334. const StringArray outputChannels (getOutputChannelNames());
  223335. for (int i = 0; i < outputChannels.size (); i++)
  223336. {
  223337. String outputName;
  223338. outputName << "out_" << ++totalNumberOfOutputChannels;
  223339. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223340. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223341. }
  223342. inChans.calloc (totalNumberOfInputChannels + 2);
  223343. outChans.calloc (totalNumberOfOutputChannels + 2);
  223344. }
  223345. }
  223346. ~JackAudioIODevice()
  223347. {
  223348. close();
  223349. if (client != 0)
  223350. {
  223351. JUCE_NAMESPACE::jack_client_close (client);
  223352. client = 0;
  223353. }
  223354. }
  223355. const StringArray getChannelNames (bool forInput) const
  223356. {
  223357. StringArray names;
  223358. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223359. forInput ? JackPortIsInput : JackPortIsOutput);
  223360. if (ports != 0)
  223361. {
  223362. int j = 0;
  223363. while (ports[j] != 0)
  223364. {
  223365. const String portName (ports [j++]);
  223366. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223367. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223368. }
  223369. free (ports);
  223370. }
  223371. return names;
  223372. }
  223373. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223374. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223375. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223376. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223377. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223378. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223379. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223380. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223381. double sampleRate, int bufferSizeSamples)
  223382. {
  223383. if (client == 0)
  223384. {
  223385. lastError = "No JACK client running";
  223386. return lastError;
  223387. }
  223388. lastError = String::empty;
  223389. close();
  223390. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223391. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223392. JUCE_NAMESPACE::jack_activate (client);
  223393. isOpen_ = true;
  223394. if (! inputChannels.isZero())
  223395. {
  223396. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223397. if (ports != 0)
  223398. {
  223399. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223400. for (int i = 0; i < numInputChannels; ++i)
  223401. {
  223402. const String portName (ports[i]);
  223403. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223404. {
  223405. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223406. if (error != 0)
  223407. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223408. }
  223409. }
  223410. free (ports);
  223411. }
  223412. }
  223413. if (! outputChannels.isZero())
  223414. {
  223415. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223416. if (ports != 0)
  223417. {
  223418. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223419. for (int i = 0; i < numOutputChannels; ++i)
  223420. {
  223421. const String portName (ports[i]);
  223422. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223423. {
  223424. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223425. if (error != 0)
  223426. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223427. }
  223428. }
  223429. free (ports);
  223430. }
  223431. }
  223432. return lastError;
  223433. }
  223434. void close()
  223435. {
  223436. stop();
  223437. if (client != 0)
  223438. {
  223439. JUCE_NAMESPACE::jack_deactivate (client);
  223440. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223441. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223442. }
  223443. isOpen_ = false;
  223444. }
  223445. void start (AudioIODeviceCallback* newCallback)
  223446. {
  223447. if (isOpen_ && newCallback != callback)
  223448. {
  223449. if (newCallback != 0)
  223450. newCallback->audioDeviceAboutToStart (this);
  223451. AudioIODeviceCallback* const oldCallback = callback;
  223452. {
  223453. const ScopedLock sl (callbackLock);
  223454. callback = newCallback;
  223455. }
  223456. if (oldCallback != 0)
  223457. oldCallback->audioDeviceStopped();
  223458. }
  223459. }
  223460. void stop()
  223461. {
  223462. start (0);
  223463. }
  223464. bool isOpen() { return isOpen_; }
  223465. bool isPlaying() { return callback != 0; }
  223466. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223467. double getCurrentSampleRate() { return getSampleRate (0); }
  223468. int getCurrentBitDepth() { return 32; }
  223469. const String getLastError() { return lastError; }
  223470. const BigInteger getActiveOutputChannels() const
  223471. {
  223472. BigInteger outputBits;
  223473. for (int i = 0; i < outputPorts.size(); i++)
  223474. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223475. outputBits.setBit (i);
  223476. return outputBits;
  223477. }
  223478. const BigInteger getActiveInputChannels() const
  223479. {
  223480. BigInteger inputBits;
  223481. for (int i = 0; i < inputPorts.size(); i++)
  223482. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223483. inputBits.setBit (i);
  223484. return inputBits;
  223485. }
  223486. int getOutputLatencyInSamples()
  223487. {
  223488. int latency = 0;
  223489. for (int i = 0; i < outputPorts.size(); i++)
  223490. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223491. return latency;
  223492. }
  223493. int getInputLatencyInSamples()
  223494. {
  223495. int latency = 0;
  223496. for (int i = 0; i < inputPorts.size(); i++)
  223497. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223498. return latency;
  223499. }
  223500. String inputId, outputId;
  223501. private:
  223502. void process (const int numSamples)
  223503. {
  223504. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223505. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223506. {
  223507. jack_default_audio_sample_t* in
  223508. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223509. if (in != 0)
  223510. inChans [numActiveInChans++] = (float*) in;
  223511. }
  223512. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223513. {
  223514. jack_default_audio_sample_t* out
  223515. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223516. if (out != 0)
  223517. outChans [numActiveOutChans++] = (float*) out;
  223518. }
  223519. const ScopedLock sl (callbackLock);
  223520. if (callback != 0)
  223521. {
  223522. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223523. outChans, numActiveOutChans, numSamples);
  223524. }
  223525. else
  223526. {
  223527. for (i = 0; i < numActiveOutChans; ++i)
  223528. zeromem (outChans[i], sizeof (float) * numSamples);
  223529. }
  223530. }
  223531. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223532. {
  223533. if (callbackArgument != 0)
  223534. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223535. return 0;
  223536. }
  223537. static void threadInitCallback (void* callbackArgument)
  223538. {
  223539. jack_Log ("JackAudioIODevice::initialise");
  223540. }
  223541. static void shutdownCallback (void* callbackArgument)
  223542. {
  223543. jack_Log ("JackAudioIODevice::shutdown");
  223544. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223545. if (device != 0)
  223546. {
  223547. device->client = 0;
  223548. device->close();
  223549. }
  223550. }
  223551. static void errorCallback (const char* msg)
  223552. {
  223553. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223554. }
  223555. bool isOpen_;
  223556. jack_client_t* client;
  223557. String lastError;
  223558. AudioIODeviceCallback* callback;
  223559. CriticalSection callbackLock;
  223560. HeapBlock <float*> inChans, outChans;
  223561. int totalNumberOfInputChannels;
  223562. int totalNumberOfOutputChannels;
  223563. Array<void*> inputPorts, outputPorts;
  223564. };
  223565. class JackAudioIODeviceType : public AudioIODeviceType
  223566. {
  223567. public:
  223568. JackAudioIODeviceType()
  223569. : AudioIODeviceType ("JACK"),
  223570. hasScanned (false)
  223571. {
  223572. }
  223573. ~JackAudioIODeviceType()
  223574. {
  223575. }
  223576. void scanForDevices()
  223577. {
  223578. hasScanned = true;
  223579. inputNames.clear();
  223580. inputIds.clear();
  223581. outputNames.clear();
  223582. outputIds.clear();
  223583. if (juce_libjack_handle == 0)
  223584. {
  223585. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223586. if (juce_libjack_handle == 0)
  223587. return;
  223588. }
  223589. // open a dummy client
  223590. jack_status_t status;
  223591. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223592. if (client == 0)
  223593. {
  223594. dumpJackErrorMessage (status);
  223595. }
  223596. else
  223597. {
  223598. // scan for output devices
  223599. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223600. if (ports != 0)
  223601. {
  223602. int j = 0;
  223603. while (ports[j] != 0)
  223604. {
  223605. String clientName (ports[j]);
  223606. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223607. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223608. && ! inputNames.contains (clientName))
  223609. {
  223610. inputNames.add (clientName);
  223611. inputIds.add (ports [j]);
  223612. }
  223613. ++j;
  223614. }
  223615. free (ports);
  223616. }
  223617. // scan for input devices
  223618. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223619. if (ports != 0)
  223620. {
  223621. int j = 0;
  223622. while (ports[j] != 0)
  223623. {
  223624. String clientName (ports[j]);
  223625. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223626. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223627. && ! outputNames.contains (clientName))
  223628. {
  223629. outputNames.add (clientName);
  223630. outputIds.add (ports [j]);
  223631. }
  223632. ++j;
  223633. }
  223634. free (ports);
  223635. }
  223636. JUCE_NAMESPACE::jack_client_close (client);
  223637. }
  223638. }
  223639. const StringArray getDeviceNames (bool wantInputNames) const
  223640. {
  223641. jassert (hasScanned); // need to call scanForDevices() before doing this
  223642. return wantInputNames ? inputNames : outputNames;
  223643. }
  223644. int getDefaultDeviceIndex (bool forInput) const
  223645. {
  223646. jassert (hasScanned); // need to call scanForDevices() before doing this
  223647. return 0;
  223648. }
  223649. bool hasSeparateInputsAndOutputs() const { return true; }
  223650. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223651. {
  223652. jassert (hasScanned); // need to call scanForDevices() before doing this
  223653. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223654. if (d == 0)
  223655. return -1;
  223656. return asInput ? inputIds.indexOf (d->inputId)
  223657. : outputIds.indexOf (d->outputId);
  223658. }
  223659. AudioIODevice* createDevice (const String& outputDeviceName,
  223660. const String& inputDeviceName)
  223661. {
  223662. jassert (hasScanned); // need to call scanForDevices() before doing this
  223663. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223664. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223665. if (inputIndex >= 0 || outputIndex >= 0)
  223666. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223667. : inputDeviceName,
  223668. inputIds [inputIndex],
  223669. outputIds [outputIndex]);
  223670. return 0;
  223671. }
  223672. juce_UseDebuggingNewOperator
  223673. private:
  223674. StringArray inputNames, outputNames, inputIds, outputIds;
  223675. bool hasScanned;
  223676. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223677. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223678. };
  223679. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223680. {
  223681. return new JackAudioIODeviceType();
  223682. }
  223683. #else // if JACK is turned off..
  223684. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223685. #endif
  223686. #endif
  223687. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223688. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223689. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223690. // compiled on its own).
  223691. #if JUCE_INCLUDED_FILE
  223692. #if JUCE_ALSA
  223693. namespace
  223694. {
  223695. snd_seq_t* iterateMidiDevices (const bool forInput,
  223696. StringArray& deviceNamesFound,
  223697. const int deviceIndexToOpen)
  223698. {
  223699. snd_seq_t* returnedHandle = 0;
  223700. snd_seq_t* seqHandle;
  223701. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223702. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223703. {
  223704. snd_seq_system_info_t* systemInfo;
  223705. snd_seq_client_info_t* clientInfo;
  223706. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223707. {
  223708. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223709. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223710. {
  223711. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223712. while (--numClients >= 0 && returnedHandle == 0)
  223713. {
  223714. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223715. {
  223716. snd_seq_port_info_t* portInfo;
  223717. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223718. {
  223719. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223720. const int client = snd_seq_client_info_get_client (clientInfo);
  223721. snd_seq_port_info_set_client (portInfo, client);
  223722. snd_seq_port_info_set_port (portInfo, -1);
  223723. while (--numPorts >= 0)
  223724. {
  223725. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223726. && (snd_seq_port_info_get_capability (portInfo)
  223727. & (forInput ? SND_SEQ_PORT_CAP_READ
  223728. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223729. {
  223730. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223731. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223732. {
  223733. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223734. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223735. if (sourcePort != -1)
  223736. {
  223737. snd_seq_set_client_name (seqHandle,
  223738. forInput ? "Juce Midi Input"
  223739. : "Juce Midi Output");
  223740. const int portId
  223741. = snd_seq_create_simple_port (seqHandle,
  223742. forInput ? "Juce Midi In Port"
  223743. : "Juce Midi Out Port",
  223744. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223745. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223746. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223747. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223748. returnedHandle = seqHandle;
  223749. }
  223750. }
  223751. }
  223752. }
  223753. snd_seq_port_info_free (portInfo);
  223754. }
  223755. }
  223756. }
  223757. snd_seq_client_info_free (clientInfo);
  223758. }
  223759. snd_seq_system_info_free (systemInfo);
  223760. }
  223761. if (returnedHandle == 0)
  223762. snd_seq_close (seqHandle);
  223763. }
  223764. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223765. return returnedHandle;
  223766. }
  223767. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  223768. {
  223769. snd_seq_t* seqHandle = 0;
  223770. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223771. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223772. {
  223773. snd_seq_set_client_name (seqHandle,
  223774. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223775. const int portId
  223776. = snd_seq_create_simple_port (seqHandle,
  223777. forInput ? "in"
  223778. : "out",
  223779. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223780. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223781. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223782. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223783. if (portId < 0)
  223784. {
  223785. snd_seq_close (seqHandle);
  223786. seqHandle = 0;
  223787. }
  223788. }
  223789. return seqHandle;
  223790. }
  223791. }
  223792. class MidiOutputDevice
  223793. {
  223794. public:
  223795. MidiOutputDevice (MidiOutput* const midiOutput_,
  223796. snd_seq_t* const seqHandle_)
  223797. :
  223798. midiOutput (midiOutput_),
  223799. seqHandle (seqHandle_),
  223800. maxEventSize (16 * 1024)
  223801. {
  223802. jassert (seqHandle != 0 && midiOutput != 0);
  223803. snd_midi_event_new (maxEventSize, &midiParser);
  223804. }
  223805. ~MidiOutputDevice()
  223806. {
  223807. snd_midi_event_free (midiParser);
  223808. snd_seq_close (seqHandle);
  223809. }
  223810. void sendMessageNow (const MidiMessage& message)
  223811. {
  223812. if (message.getRawDataSize() > maxEventSize)
  223813. {
  223814. maxEventSize = message.getRawDataSize();
  223815. snd_midi_event_free (midiParser);
  223816. snd_midi_event_new (maxEventSize, &midiParser);
  223817. }
  223818. snd_seq_event_t event;
  223819. snd_seq_ev_clear (&event);
  223820. snd_midi_event_encode (midiParser,
  223821. message.getRawData(),
  223822. message.getRawDataSize(),
  223823. &event);
  223824. snd_midi_event_reset_encode (midiParser);
  223825. snd_seq_ev_set_source (&event, 0);
  223826. snd_seq_ev_set_subs (&event);
  223827. snd_seq_ev_set_direct (&event);
  223828. snd_seq_event_output (seqHandle, &event);
  223829. snd_seq_drain_output (seqHandle);
  223830. }
  223831. juce_UseDebuggingNewOperator
  223832. private:
  223833. MidiOutput* const midiOutput;
  223834. snd_seq_t* const seqHandle;
  223835. snd_midi_event_t* midiParser;
  223836. int maxEventSize;
  223837. };
  223838. const StringArray MidiOutput::getDevices()
  223839. {
  223840. StringArray devices;
  223841. iterateMidiDevices (false, devices, -1);
  223842. return devices;
  223843. }
  223844. int MidiOutput::getDefaultDeviceIndex()
  223845. {
  223846. return 0;
  223847. }
  223848. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223849. {
  223850. MidiOutput* newDevice = 0;
  223851. StringArray devices;
  223852. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223853. if (handle != 0)
  223854. {
  223855. newDevice = new MidiOutput();
  223856. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223857. }
  223858. return newDevice;
  223859. }
  223860. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223861. {
  223862. MidiOutput* newDevice = 0;
  223863. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223864. if (handle != 0)
  223865. {
  223866. newDevice = new MidiOutput();
  223867. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223868. }
  223869. return newDevice;
  223870. }
  223871. MidiOutput::~MidiOutput()
  223872. {
  223873. delete static_cast <MidiOutputDevice*> (internal);
  223874. }
  223875. void MidiOutput::reset()
  223876. {
  223877. }
  223878. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223879. {
  223880. return false;
  223881. }
  223882. void MidiOutput::setVolume (float leftVol, float rightVol)
  223883. {
  223884. }
  223885. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223886. {
  223887. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223888. }
  223889. class MidiInputThread : public Thread
  223890. {
  223891. public:
  223892. MidiInputThread (MidiInput* const midiInput_,
  223893. snd_seq_t* const seqHandle_,
  223894. MidiInputCallback* const callback_)
  223895. : Thread ("Juce MIDI Input"),
  223896. midiInput (midiInput_),
  223897. seqHandle (seqHandle_),
  223898. callback (callback_)
  223899. {
  223900. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223901. }
  223902. ~MidiInputThread()
  223903. {
  223904. snd_seq_close (seqHandle);
  223905. }
  223906. void run()
  223907. {
  223908. const int maxEventSize = 16 * 1024;
  223909. snd_midi_event_t* midiParser;
  223910. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223911. {
  223912. HeapBlock <uint8> buffer (maxEventSize);
  223913. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223914. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223915. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223916. while (! threadShouldExit())
  223917. {
  223918. if (poll (pfd, numPfds, 500) > 0)
  223919. {
  223920. snd_seq_event_t* inputEvent = 0;
  223921. snd_seq_nonblock (seqHandle, 1);
  223922. do
  223923. {
  223924. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223925. {
  223926. // xxx what about SYSEXes that are too big for the buffer?
  223927. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223928. snd_midi_event_reset_decode (midiParser);
  223929. if (numBytes > 0)
  223930. {
  223931. const MidiMessage message ((const uint8*) buffer,
  223932. numBytes,
  223933. Time::getMillisecondCounter() * 0.001);
  223934. callback->handleIncomingMidiMessage (midiInput, message);
  223935. }
  223936. snd_seq_free_event (inputEvent);
  223937. }
  223938. }
  223939. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223940. snd_seq_free_event (inputEvent);
  223941. }
  223942. }
  223943. snd_midi_event_free (midiParser);
  223944. }
  223945. };
  223946. juce_UseDebuggingNewOperator
  223947. private:
  223948. MidiInput* const midiInput;
  223949. snd_seq_t* const seqHandle;
  223950. MidiInputCallback* const callback;
  223951. };
  223952. MidiInput::MidiInput (const String& name_)
  223953. : name (name_),
  223954. internal (0)
  223955. {
  223956. }
  223957. MidiInput::~MidiInput()
  223958. {
  223959. stop();
  223960. delete static_cast <MidiInputThread*> (internal);
  223961. }
  223962. void MidiInput::start()
  223963. {
  223964. static_cast <MidiInputThread*> (internal)->startThread();
  223965. }
  223966. void MidiInput::stop()
  223967. {
  223968. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223969. }
  223970. int MidiInput::getDefaultDeviceIndex()
  223971. {
  223972. return 0;
  223973. }
  223974. const StringArray MidiInput::getDevices()
  223975. {
  223976. StringArray devices;
  223977. iterateMidiDevices (true, devices, -1);
  223978. return devices;
  223979. }
  223980. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223981. {
  223982. MidiInput* newDevice = 0;
  223983. StringArray devices;
  223984. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223985. if (handle != 0)
  223986. {
  223987. newDevice = new MidiInput (devices [deviceIndex]);
  223988. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223989. }
  223990. return newDevice;
  223991. }
  223992. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223993. {
  223994. MidiInput* newDevice = 0;
  223995. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223996. if (handle != 0)
  223997. {
  223998. newDevice = new MidiInput (deviceName);
  223999. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  224000. }
  224001. return newDevice;
  224002. }
  224003. #else
  224004. // (These are just stub functions if ALSA is unavailable...)
  224005. const StringArray MidiOutput::getDevices() { return StringArray(); }
  224006. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  224007. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  224008. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  224009. MidiOutput::~MidiOutput() {}
  224010. void MidiOutput::reset() {}
  224011. bool MidiOutput::getVolume (float&, float&) { return false; }
  224012. void MidiOutput::setVolume (float, float) {}
  224013. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  224014. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  224015. MidiInput::~MidiInput() {}
  224016. void MidiInput::start() {}
  224017. void MidiInput::stop() {}
  224018. int MidiInput::getDefaultDeviceIndex() { return 0; }
  224019. const StringArray MidiInput::getDevices() { return StringArray(); }
  224020. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  224021. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  224022. #endif
  224023. #endif
  224024. /*** End of inlined file: juce_linux_Midi.cpp ***/
  224025. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  224026. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224027. // compiled on its own).
  224028. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  224029. AudioCDReader::AudioCDReader()
  224030. : AudioFormatReader (0, "CD Audio")
  224031. {
  224032. }
  224033. const StringArray AudioCDReader::getAvailableCDNames()
  224034. {
  224035. StringArray names;
  224036. return names;
  224037. }
  224038. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  224039. {
  224040. return 0;
  224041. }
  224042. AudioCDReader::~AudioCDReader()
  224043. {
  224044. }
  224045. void AudioCDReader::refreshTrackLengths()
  224046. {
  224047. }
  224048. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  224049. int64 startSampleInFile, int numSamples)
  224050. {
  224051. return false;
  224052. }
  224053. bool AudioCDReader::isCDStillPresent() const
  224054. {
  224055. return false;
  224056. }
  224057. bool AudioCDReader::isTrackAudio (int trackNum) const
  224058. {
  224059. return false;
  224060. }
  224061. void AudioCDReader::enableIndexScanning (bool b)
  224062. {
  224063. }
  224064. int AudioCDReader::getLastIndex() const
  224065. {
  224066. return 0;
  224067. }
  224068. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  224069. {
  224070. return Array<int>();
  224071. }
  224072. #endif
  224073. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  224074. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  224075. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224076. // compiled on its own).
  224077. #if JUCE_INCLUDED_FILE
  224078. void FileChooser::showPlatformDialog (Array<File>& results,
  224079. const String& title,
  224080. const File& file,
  224081. const String& filters,
  224082. bool isDirectory,
  224083. bool selectsFiles,
  224084. bool isSave,
  224085. bool warnAboutOverwritingExistingFiles,
  224086. bool selectMultipleFiles,
  224087. FilePreviewComponent* previewComponent)
  224088. {
  224089. const String separator (":");
  224090. String command ("zenity --file-selection");
  224091. if (title.isNotEmpty())
  224092. command << " --title=\"" << title << "\"";
  224093. if (file != File::nonexistent)
  224094. command << " --filename=\"" << file.getFullPathName () << "\"";
  224095. if (isDirectory)
  224096. command << " --directory";
  224097. if (isSave)
  224098. command << " --save";
  224099. if (selectMultipleFiles)
  224100. command << " --multiple --separator=\"" << separator << "\"";
  224101. command << " 2>&1";
  224102. MemoryOutputStream result;
  224103. int status = -1;
  224104. FILE* stream = popen (command.toUTF8(), "r");
  224105. if (stream != 0)
  224106. {
  224107. for (;;)
  224108. {
  224109. char buffer [1024];
  224110. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  224111. if (bytesRead <= 0)
  224112. break;
  224113. result.write (buffer, bytesRead);
  224114. }
  224115. status = pclose (stream);
  224116. }
  224117. if (status == 0)
  224118. {
  224119. StringArray tokens;
  224120. if (selectMultipleFiles)
  224121. tokens.addTokens (result.toUTF8(), separator, String::empty);
  224122. else
  224123. tokens.add (result.toUTF8());
  224124. for (int i = 0; i < tokens.size(); i++)
  224125. results.add (File (tokens[i]));
  224126. return;
  224127. }
  224128. //xxx ain't got one!
  224129. jassertfalse;
  224130. }
  224131. #endif
  224132. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  224133. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224134. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224135. // compiled on its own).
  224136. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224137. /*
  224138. Sorry.. This class isn't implemented on Linux!
  224139. */
  224140. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224141. : browser (0),
  224142. blankPageShown (false),
  224143. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224144. {
  224145. setOpaque (true);
  224146. }
  224147. WebBrowserComponent::~WebBrowserComponent()
  224148. {
  224149. }
  224150. void WebBrowserComponent::goToURL (const String& url,
  224151. const StringArray* headers,
  224152. const MemoryBlock* postData)
  224153. {
  224154. lastURL = url;
  224155. lastHeaders.clear();
  224156. if (headers != 0)
  224157. lastHeaders = *headers;
  224158. lastPostData.setSize (0);
  224159. if (postData != 0)
  224160. lastPostData = *postData;
  224161. blankPageShown = false;
  224162. }
  224163. void WebBrowserComponent::stop()
  224164. {
  224165. }
  224166. void WebBrowserComponent::goBack()
  224167. {
  224168. lastURL = String::empty;
  224169. blankPageShown = false;
  224170. }
  224171. void WebBrowserComponent::goForward()
  224172. {
  224173. lastURL = String::empty;
  224174. }
  224175. void WebBrowserComponent::refresh()
  224176. {
  224177. }
  224178. void WebBrowserComponent::paint (Graphics& g)
  224179. {
  224180. g.fillAll (Colours::white);
  224181. }
  224182. void WebBrowserComponent::checkWindowAssociation()
  224183. {
  224184. }
  224185. void WebBrowserComponent::reloadLastURL()
  224186. {
  224187. if (lastURL.isNotEmpty())
  224188. {
  224189. goToURL (lastURL, &lastHeaders, &lastPostData);
  224190. lastURL = String::empty;
  224191. }
  224192. }
  224193. void WebBrowserComponent::parentHierarchyChanged()
  224194. {
  224195. checkWindowAssociation();
  224196. }
  224197. void WebBrowserComponent::resized()
  224198. {
  224199. }
  224200. void WebBrowserComponent::visibilityChanged()
  224201. {
  224202. checkWindowAssociation();
  224203. }
  224204. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224205. {
  224206. return true;
  224207. }
  224208. #endif
  224209. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224210. #endif
  224211. END_JUCE_NAMESPACE
  224212. #endif
  224213. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  224214. #endif
  224215. #if JUCE_MAC || JUCE_IPHONE
  224216. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  224217. /*
  224218. This file wraps together all the mac-specific code, so that
  224219. we can include all the native headers just once, and compile all our
  224220. platform-specific stuff in one big lump, keeping it out of the way of
  224221. the rest of the codebase.
  224222. */
  224223. #if JUCE_MAC || JUCE_IOS
  224224. BEGIN_JUCE_NAMESPACE
  224225. #undef Point
  224226. namespace
  224227. {
  224228. template <class RectType>
  224229. const Rectangle<int> convertToRectInt (const RectType& r)
  224230. {
  224231. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  224232. }
  224233. template <class RectType>
  224234. const Rectangle<float> convertToRectFloat (const RectType& r)
  224235. {
  224236. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  224237. }
  224238. template <class RectType>
  224239. CGRect convertToCGRect (const RectType& r)
  224240. {
  224241. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  224242. }
  224243. }
  224244. #define JUCE_INCLUDED_FILE 1
  224245. // Now include the actual code files..
  224246. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  224247. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  224248. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  224249. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  224250. cross-linked so that when you make a call to a class that you thought was private, it ends up
  224251. actually calling into a similarly named class in the other module's address space.
  224252. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224253. have unique names, and should avoid this problem.
  224254. If you're using the amalgamated version, you can just set this macro to something unique before
  224255. you include juce_amalgamated.cpp.
  224256. */
  224257. #ifndef JUCE_ObjCExtraSuffix
  224258. #define JUCE_ObjCExtraSuffix 3
  224259. #endif
  224260. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224261. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224262. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224263. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224264. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224265. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224266. // compiled on its own).
  224267. #if JUCE_INCLUDED_FILE
  224268. namespace
  224269. {
  224270. const String nsStringToJuce (NSString* s)
  224271. {
  224272. return String::fromUTF8 ([s UTF8String]);
  224273. }
  224274. NSString* juceStringToNS (const String& s)
  224275. {
  224276. return [NSString stringWithUTF8String: s.toUTF8()];
  224277. }
  224278. const String convertUTF16ToString (const UniChar* utf16)
  224279. {
  224280. String s;
  224281. while (*utf16 != 0)
  224282. s += (juce_wchar) *utf16++;
  224283. return s;
  224284. }
  224285. }
  224286. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224287. {
  224288. String result;
  224289. if (cfString != 0)
  224290. {
  224291. CFRange range = { 0, CFStringGetLength (cfString) };
  224292. HeapBlock <UniChar> u (range.length + 1);
  224293. CFStringGetCharacters (cfString, range, u);
  224294. u[range.length] = 0;
  224295. result = convertUTF16ToString (u);
  224296. }
  224297. return result;
  224298. }
  224299. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224300. {
  224301. const int len = s.length();
  224302. HeapBlock <UniChar> temp (len + 2);
  224303. for (int i = 0; i <= len; ++i)
  224304. temp[i] = s[i];
  224305. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224306. }
  224307. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224308. {
  224309. #if JUCE_IOS
  224310. const ScopedAutoReleasePool pool;
  224311. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224312. #else
  224313. UnicodeMapping map;
  224314. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224315. kUnicodeNoSubset,
  224316. kTextEncodingDefaultFormat);
  224317. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224318. kUnicodeCanonicalCompVariant,
  224319. kTextEncodingDefaultFormat);
  224320. map.mappingVersion = kUnicodeUseLatestMapping;
  224321. UnicodeToTextInfo conversionInfo = 0;
  224322. String result;
  224323. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224324. {
  224325. const int len = s.length();
  224326. HeapBlock <UniChar> tempIn, tempOut;
  224327. tempIn.calloc (len + 2);
  224328. tempOut.calloc (len + 2);
  224329. for (int i = 0; i <= len; ++i)
  224330. tempIn[i] = s[i];
  224331. ByteCount bytesRead = 0;
  224332. ByteCount outputBufferSize = 0;
  224333. if (ConvertFromUnicodeToText (conversionInfo,
  224334. len * sizeof (UniChar), tempIn,
  224335. kUnicodeDefaultDirectionMask,
  224336. 0, 0, 0, 0,
  224337. len * sizeof (UniChar), &bytesRead,
  224338. &outputBufferSize, tempOut) == noErr)
  224339. {
  224340. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224341. juce_wchar* t = result;
  224342. unsigned int i;
  224343. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224344. t[i] = (juce_wchar) tempOut[i];
  224345. t[i] = 0;
  224346. }
  224347. DisposeUnicodeToTextInfo (&conversionInfo);
  224348. }
  224349. return result;
  224350. #endif
  224351. }
  224352. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224353. void SystemClipboard::copyTextToClipboard (const String& text)
  224354. {
  224355. #if JUCE_IOS
  224356. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224357. forPasteboardType: @"public.text"];
  224358. #else
  224359. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224360. owner: nil];
  224361. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224362. forType: NSStringPboardType];
  224363. #endif
  224364. }
  224365. const String SystemClipboard::getTextFromClipboard()
  224366. {
  224367. #if JUCE_IOS
  224368. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224369. #else
  224370. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224371. #endif
  224372. return text == 0 ? String::empty
  224373. : nsStringToJuce (text);
  224374. }
  224375. #endif
  224376. #endif
  224377. /*** End of inlined file: juce_mac_Strings.mm ***/
  224378. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224379. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224380. // compiled on its own).
  224381. #if JUCE_INCLUDED_FILE
  224382. namespace SystemStatsHelpers
  224383. {
  224384. static int64 highResTimerFrequency = 0;
  224385. static double highResTimerToMillisecRatio = 0;
  224386. #if JUCE_INTEL
  224387. static void juce_getCpuVendor (char* const v) throw()
  224388. {
  224389. int vendor[4];
  224390. zerostruct (vendor);
  224391. int dummy = 0;
  224392. asm ("mov %%ebx, %%esi \n\t"
  224393. "cpuid \n\t"
  224394. "xchg %%esi, %%ebx"
  224395. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224396. memcpy (v, vendor, 16);
  224397. }
  224398. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224399. {
  224400. unsigned int cpu = 0;
  224401. unsigned int ext = 0;
  224402. unsigned int family = 0;
  224403. unsigned int dummy = 0;
  224404. asm ("mov %%ebx, %%esi \n\t"
  224405. "cpuid \n\t"
  224406. "xchg %%esi, %%ebx"
  224407. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224408. familyModel = family;
  224409. extFeatures = ext;
  224410. return cpu;
  224411. }
  224412. #endif
  224413. }
  224414. void SystemStats::initialiseStats()
  224415. {
  224416. using namespace SystemStatsHelpers;
  224417. static bool initialised = false;
  224418. if (! initialised)
  224419. {
  224420. initialised = true;
  224421. #if JUCE_MAC
  224422. [NSApplication sharedApplication];
  224423. #endif
  224424. #if JUCE_INTEL
  224425. unsigned int familyModel, extFeatures;
  224426. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224427. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224428. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224429. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224430. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224431. #else
  224432. cpuFlags.hasMMX = false;
  224433. cpuFlags.hasSSE = false;
  224434. cpuFlags.hasSSE2 = false;
  224435. cpuFlags.has3DNow = false;
  224436. #endif
  224437. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224438. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224439. #else
  224440. cpuFlags.numCpus = (int) MPProcessors();
  224441. #endif
  224442. mach_timebase_info_data_t timebase;
  224443. (void) mach_timebase_info (&timebase);
  224444. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224445. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224446. String s (SystemStats::getJUCEVersion());
  224447. rlimit lim;
  224448. getrlimit (RLIMIT_NOFILE, &lim);
  224449. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224450. setrlimit (RLIMIT_NOFILE, &lim);
  224451. }
  224452. }
  224453. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224454. {
  224455. return MacOSX;
  224456. }
  224457. const String SystemStats::getOperatingSystemName()
  224458. {
  224459. return "Mac OS X";
  224460. }
  224461. #if ! JUCE_IOS
  224462. int PlatformUtilities::getOSXMinorVersionNumber()
  224463. {
  224464. SInt32 versionMinor = 0;
  224465. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224466. (void) err;
  224467. jassert (err == noErr);
  224468. return (int) versionMinor;
  224469. }
  224470. #endif
  224471. bool SystemStats::isOperatingSystem64Bit()
  224472. {
  224473. #if JUCE_IOS
  224474. return false;
  224475. #elif JUCE_64BIT
  224476. return true;
  224477. #else
  224478. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224479. #endif
  224480. }
  224481. int SystemStats::getMemorySizeInMegabytes()
  224482. {
  224483. uint64 mem = 0;
  224484. size_t memSize = sizeof (mem);
  224485. int mib[] = { CTL_HW, HW_MEMSIZE };
  224486. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224487. return (int) (mem / (1024 * 1024));
  224488. }
  224489. const String SystemStats::getCpuVendor()
  224490. {
  224491. #if JUCE_INTEL
  224492. char v [16];
  224493. SystemStatsHelpers::juce_getCpuVendor (v);
  224494. return String (v, 16);
  224495. #else
  224496. return String::empty;
  224497. #endif
  224498. }
  224499. int SystemStats::getCpuSpeedInMegaherz()
  224500. {
  224501. uint64 speedHz = 0;
  224502. size_t speedSize = sizeof (speedHz);
  224503. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224504. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224505. #if JUCE_BIG_ENDIAN
  224506. if (speedSize == 4)
  224507. speedHz >>= 32;
  224508. #endif
  224509. return (int) (speedHz / 1000000);
  224510. }
  224511. const String SystemStats::getLogonName()
  224512. {
  224513. return nsStringToJuce (NSUserName());
  224514. }
  224515. const String SystemStats::getFullUserName()
  224516. {
  224517. return nsStringToJuce (NSFullUserName());
  224518. }
  224519. uint32 juce_millisecondsSinceStartup() throw()
  224520. {
  224521. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224522. }
  224523. double Time::getMillisecondCounterHiRes() throw()
  224524. {
  224525. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224526. }
  224527. int64 Time::getHighResolutionTicks() throw()
  224528. {
  224529. return (int64) mach_absolute_time();
  224530. }
  224531. int64 Time::getHighResolutionTicksPerSecond() throw()
  224532. {
  224533. return SystemStatsHelpers::highResTimerFrequency;
  224534. }
  224535. bool Time::setSystemTimeToThisTime() const
  224536. {
  224537. jassertfalse;
  224538. return false;
  224539. }
  224540. int SystemStats::getPageSize()
  224541. {
  224542. return (int) NSPageSize();
  224543. }
  224544. void PlatformUtilities::fpuReset()
  224545. {
  224546. }
  224547. #endif
  224548. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224549. /*** Start of inlined file: juce_mac_Network.mm ***/
  224550. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224551. // compiled on its own).
  224552. #if JUCE_INCLUDED_FILE
  224553. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  224554. {
  224555. ifaddrs* addrs = 0;
  224556. if (getifaddrs (&addrs) == 0)
  224557. {
  224558. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  224559. {
  224560. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224561. if (sto->ss_family == AF_LINK)
  224562. {
  224563. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224564. #ifndef IFT_ETHER
  224565. #define IFT_ETHER 6
  224566. #endif
  224567. if (sadd->sdl_type == IFT_ETHER)
  224568. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  224569. }
  224570. }
  224571. freeifaddrs (addrs);
  224572. }
  224573. }
  224574. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224575. const String& emailSubject,
  224576. const String& bodyText,
  224577. const StringArray& filesToAttach)
  224578. {
  224579. #if JUCE_IOS
  224580. //xxx probably need to use MFMailComposeViewController
  224581. jassertfalse;
  224582. return false;
  224583. #else
  224584. const ScopedAutoReleasePool pool;
  224585. String script;
  224586. script << "tell application \"Mail\"\r\n"
  224587. "set newMessage to make new outgoing message with properties {subject:\""
  224588. << emailSubject.replace ("\"", "\\\"")
  224589. << "\", content:\""
  224590. << bodyText.replace ("\"", "\\\"")
  224591. << "\" & return & return}\r\n"
  224592. "tell newMessage\r\n"
  224593. "set visible to true\r\n"
  224594. "set sender to \"sdfsdfsdfewf\"\r\n"
  224595. "make new to recipient at end of to recipients with properties {address:\""
  224596. << targetEmailAddress
  224597. << "\"}\r\n";
  224598. for (int i = 0; i < filesToAttach.size(); ++i)
  224599. {
  224600. script << "tell content\r\n"
  224601. "make new attachment with properties {file name:\""
  224602. << filesToAttach[i].replace ("\"", "\\\"")
  224603. << "\"} at after the last paragraph\r\n"
  224604. "end tell\r\n";
  224605. }
  224606. script << "end tell\r\n"
  224607. "end tell\r\n";
  224608. NSAppleScript* s = [[NSAppleScript alloc]
  224609. initWithSource: juceStringToNS (script)];
  224610. NSDictionary* error = 0;
  224611. const bool ok = [s executeAndReturnError: &error] != nil;
  224612. [s release];
  224613. return ok;
  224614. #endif
  224615. }
  224616. END_JUCE_NAMESPACE
  224617. using namespace JUCE_NAMESPACE;
  224618. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224619. @interface JuceURLConnection : NSObject
  224620. {
  224621. @public
  224622. NSURLRequest* request;
  224623. NSURLConnection* connection;
  224624. NSMutableData* data;
  224625. Thread* runLoopThread;
  224626. bool initialised, hasFailed, hasFinished;
  224627. int position;
  224628. int64 contentLength;
  224629. NSDictionary* headers;
  224630. NSLock* dataLock;
  224631. }
  224632. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224633. - (void) dealloc;
  224634. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224635. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224636. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224637. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224638. - (BOOL) isOpen;
  224639. - (int) read: (char*) dest numBytes: (int) num;
  224640. - (int) readPosition;
  224641. - (void) stop;
  224642. - (void) createConnection;
  224643. @end
  224644. class JuceURLConnectionMessageThread : public Thread
  224645. {
  224646. JuceURLConnection* owner;
  224647. public:
  224648. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224649. : Thread ("http connection"),
  224650. owner (owner_)
  224651. {
  224652. }
  224653. ~JuceURLConnectionMessageThread()
  224654. {
  224655. stopThread (10000);
  224656. }
  224657. void run()
  224658. {
  224659. [owner createConnection];
  224660. while (! threadShouldExit())
  224661. {
  224662. const ScopedAutoReleasePool pool;
  224663. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224664. }
  224665. }
  224666. };
  224667. @implementation JuceURLConnection
  224668. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224669. withCallback: (URL::OpenStreamProgressCallback*) callback
  224670. withContext: (void*) context;
  224671. {
  224672. [super init];
  224673. request = req;
  224674. [request retain];
  224675. data = [[NSMutableData data] retain];
  224676. dataLock = [[NSLock alloc] init];
  224677. connection = 0;
  224678. initialised = false;
  224679. hasFailed = false;
  224680. hasFinished = false;
  224681. contentLength = -1;
  224682. headers = 0;
  224683. runLoopThread = new JuceURLConnectionMessageThread (self);
  224684. runLoopThread->startThread();
  224685. while (runLoopThread->isThreadRunning() && ! initialised)
  224686. {
  224687. if (callback != 0)
  224688. callback (context, -1, (int) [[request HTTPBody] length]);
  224689. Thread::sleep (1);
  224690. }
  224691. return self;
  224692. }
  224693. - (void) dealloc
  224694. {
  224695. [self stop];
  224696. deleteAndZero (runLoopThread);
  224697. [connection release];
  224698. [data release];
  224699. [dataLock release];
  224700. [request release];
  224701. [headers release];
  224702. [super dealloc];
  224703. }
  224704. - (void) createConnection
  224705. {
  224706. NSUInteger oldRetainCount = [self retainCount];
  224707. connection = [[NSURLConnection alloc] initWithRequest: request
  224708. delegate: self];
  224709. if (oldRetainCount == [self retainCount])
  224710. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224711. if (connection == nil)
  224712. runLoopThread->signalThreadShouldExit();
  224713. }
  224714. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224715. {
  224716. (void) conn;
  224717. [dataLock lock];
  224718. [data setLength: 0];
  224719. [dataLock unlock];
  224720. initialised = true;
  224721. contentLength = [response expectedContentLength];
  224722. [headers release];
  224723. headers = 0;
  224724. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224725. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224726. }
  224727. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224728. {
  224729. (void) conn;
  224730. DBG (nsStringToJuce ([error description]));
  224731. hasFailed = true;
  224732. initialised = true;
  224733. if (runLoopThread != 0)
  224734. runLoopThread->signalThreadShouldExit();
  224735. }
  224736. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224737. {
  224738. (void) conn;
  224739. [dataLock lock];
  224740. [data appendData: newData];
  224741. [dataLock unlock];
  224742. initialised = true;
  224743. }
  224744. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224745. {
  224746. (void) conn;
  224747. hasFinished = true;
  224748. initialised = true;
  224749. if (runLoopThread != 0)
  224750. runLoopThread->signalThreadShouldExit();
  224751. }
  224752. - (BOOL) isOpen
  224753. {
  224754. return connection != 0 && ! hasFailed;
  224755. }
  224756. - (int) readPosition
  224757. {
  224758. return position;
  224759. }
  224760. - (int) read: (char*) dest numBytes: (int) numNeeded
  224761. {
  224762. int numDone = 0;
  224763. while (numNeeded > 0)
  224764. {
  224765. int available = jmin (numNeeded, (int) [data length]);
  224766. if (available > 0)
  224767. {
  224768. [dataLock lock];
  224769. [data getBytes: dest length: available];
  224770. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224771. [dataLock unlock];
  224772. numDone += available;
  224773. numNeeded -= available;
  224774. dest += available;
  224775. }
  224776. else
  224777. {
  224778. if (hasFailed || hasFinished)
  224779. break;
  224780. Thread::sleep (1);
  224781. }
  224782. }
  224783. position += numDone;
  224784. return numDone;
  224785. }
  224786. - (void) stop
  224787. {
  224788. [connection cancel];
  224789. if (runLoopThread != 0)
  224790. runLoopThread->stopThread (10000);
  224791. }
  224792. @end
  224793. BEGIN_JUCE_NAMESPACE
  224794. void* juce_openInternetFile (const String& url,
  224795. const String& headers,
  224796. const MemoryBlock& postData,
  224797. const bool isPost,
  224798. URL::OpenStreamProgressCallback* callback,
  224799. void* callbackContext,
  224800. int timeOutMs)
  224801. {
  224802. const ScopedAutoReleasePool pool;
  224803. NSMutableURLRequest* req = [NSMutableURLRequest
  224804. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224805. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224806. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224807. if (req == nil)
  224808. return 0;
  224809. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224810. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224811. StringArray headerLines;
  224812. headerLines.addLines (headers);
  224813. headerLines.removeEmptyStrings (true);
  224814. for (int i = 0; i < headerLines.size(); ++i)
  224815. {
  224816. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224817. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224818. if (key.isNotEmpty() && value.isNotEmpty())
  224819. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224820. }
  224821. if (isPost && postData.getSize() > 0)
  224822. {
  224823. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224824. length: postData.getSize()]];
  224825. }
  224826. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224827. withCallback: callback
  224828. withContext: callbackContext];
  224829. if ([s isOpen])
  224830. return s;
  224831. [s release];
  224832. return 0;
  224833. }
  224834. void juce_closeInternetFile (void* handle)
  224835. {
  224836. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224837. if (s != 0)
  224838. {
  224839. const ScopedAutoReleasePool pool;
  224840. [s stop];
  224841. [s release];
  224842. }
  224843. }
  224844. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224845. {
  224846. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224847. if (s != 0)
  224848. {
  224849. const ScopedAutoReleasePool pool;
  224850. return [s read: (char*) buffer numBytes: bytesToRead];
  224851. }
  224852. return 0;
  224853. }
  224854. int64 juce_getInternetFileContentLength (void* handle)
  224855. {
  224856. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224857. if (s != 0)
  224858. return s->contentLength;
  224859. return -1;
  224860. }
  224861. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224862. {
  224863. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224864. if (s != 0 && s->headers != 0)
  224865. {
  224866. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224867. NSString* key;
  224868. while ((key = [enumerator nextObject]) != nil)
  224869. headers.set (nsStringToJuce (key),
  224870. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224871. }
  224872. }
  224873. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224874. {
  224875. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224876. if (s != 0)
  224877. return [s readPosition];
  224878. return 0;
  224879. }
  224880. #endif
  224881. /*** End of inlined file: juce_mac_Network.mm ***/
  224882. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224883. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224884. // compiled on its own).
  224885. #if JUCE_INCLUDED_FILE
  224886. struct NamedPipeInternal
  224887. {
  224888. String pipeInName, pipeOutName;
  224889. int pipeIn, pipeOut;
  224890. bool volatile createdPipe, blocked, stopReadOperation;
  224891. static void signalHandler (int) {}
  224892. };
  224893. void NamedPipe::cancelPendingReads()
  224894. {
  224895. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224896. {
  224897. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224898. intern->stopReadOperation = true;
  224899. char buffer [1] = { 0 };
  224900. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224901. (void) bytesWritten;
  224902. int timeout = 2000;
  224903. while (intern->blocked && --timeout >= 0)
  224904. Thread::sleep (2);
  224905. intern->stopReadOperation = false;
  224906. }
  224907. }
  224908. void NamedPipe::close()
  224909. {
  224910. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224911. if (intern != 0)
  224912. {
  224913. internal = 0;
  224914. if (intern->pipeIn != -1)
  224915. ::close (intern->pipeIn);
  224916. if (intern->pipeOut != -1)
  224917. ::close (intern->pipeOut);
  224918. if (intern->createdPipe)
  224919. {
  224920. unlink (intern->pipeInName.toUTF8());
  224921. unlink (intern->pipeOutName.toUTF8());
  224922. }
  224923. delete intern;
  224924. }
  224925. }
  224926. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224927. {
  224928. close();
  224929. NamedPipeInternal* const intern = new NamedPipeInternal();
  224930. internal = intern;
  224931. intern->createdPipe = createPipe;
  224932. intern->blocked = false;
  224933. intern->stopReadOperation = false;
  224934. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224935. siginterrupt (SIGPIPE, 1);
  224936. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224937. intern->pipeInName = pipePath + "_in";
  224938. intern->pipeOutName = pipePath + "_out";
  224939. intern->pipeIn = -1;
  224940. intern->pipeOut = -1;
  224941. if (createPipe)
  224942. {
  224943. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224944. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224945. {
  224946. delete intern;
  224947. internal = 0;
  224948. return false;
  224949. }
  224950. }
  224951. return true;
  224952. }
  224953. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224954. {
  224955. int bytesRead = -1;
  224956. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224957. if (intern != 0)
  224958. {
  224959. intern->blocked = true;
  224960. if (intern->pipeIn == -1)
  224961. {
  224962. if (intern->createdPipe)
  224963. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224964. else
  224965. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224966. if (intern->pipeIn == -1)
  224967. {
  224968. intern->blocked = false;
  224969. return -1;
  224970. }
  224971. }
  224972. bytesRead = 0;
  224973. char* p = static_cast<char*> (destBuffer);
  224974. while (bytesRead < maxBytesToRead)
  224975. {
  224976. const int bytesThisTime = maxBytesToRead - bytesRead;
  224977. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224978. if (numRead <= 0 || intern->stopReadOperation)
  224979. {
  224980. bytesRead = -1;
  224981. break;
  224982. }
  224983. bytesRead += numRead;
  224984. p += bytesRead;
  224985. }
  224986. intern->blocked = false;
  224987. }
  224988. return bytesRead;
  224989. }
  224990. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224991. {
  224992. int bytesWritten = -1;
  224993. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224994. if (intern != 0)
  224995. {
  224996. if (intern->pipeOut == -1)
  224997. {
  224998. if (intern->createdPipe)
  224999. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  225000. else
  225001. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  225002. if (intern->pipeOut == -1)
  225003. {
  225004. return -1;
  225005. }
  225006. }
  225007. const char* p = static_cast<const char*> (sourceBuffer);
  225008. bytesWritten = 0;
  225009. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  225010. while (bytesWritten < numBytesToWrite
  225011. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  225012. {
  225013. const int bytesThisTime = numBytesToWrite - bytesWritten;
  225014. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  225015. if (numWritten <= 0)
  225016. {
  225017. bytesWritten = -1;
  225018. break;
  225019. }
  225020. bytesWritten += numWritten;
  225021. p += bytesWritten;
  225022. }
  225023. }
  225024. return bytesWritten;
  225025. }
  225026. #endif
  225027. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  225028. /*** Start of inlined file: juce_mac_Threads.mm ***/
  225029. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225030. // compiled on its own).
  225031. #if JUCE_INCLUDED_FILE
  225032. /*
  225033. Note that a lot of methods that you'd expect to find in this file actually
  225034. live in juce_posix_SharedCode.h!
  225035. */
  225036. bool Process::isForegroundProcess()
  225037. {
  225038. #if JUCE_MAC
  225039. return [NSApp isActive];
  225040. #else
  225041. return true; // xxx change this if more than one app is ever possible on the iPhone!
  225042. #endif
  225043. }
  225044. void Process::raisePrivilege()
  225045. {
  225046. jassertfalse;
  225047. }
  225048. void Process::lowerPrivilege()
  225049. {
  225050. jassertfalse;
  225051. }
  225052. void Process::terminate()
  225053. {
  225054. exit (0);
  225055. }
  225056. void Process::setPriority (ProcessPriority)
  225057. {
  225058. // xxx
  225059. }
  225060. #endif
  225061. /*** End of inlined file: juce_mac_Threads.mm ***/
  225062. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  225063. /*
  225064. This file contains posix routines that are common to both the Linux and Mac builds.
  225065. It gets included directly in the cpp files for these platforms.
  225066. */
  225067. CriticalSection::CriticalSection() throw()
  225068. {
  225069. pthread_mutexattr_t atts;
  225070. pthread_mutexattr_init (&atts);
  225071. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  225072. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225073. pthread_mutex_init (&internal, &atts);
  225074. }
  225075. CriticalSection::~CriticalSection() throw()
  225076. {
  225077. pthread_mutex_destroy (&internal);
  225078. }
  225079. void CriticalSection::enter() const throw()
  225080. {
  225081. pthread_mutex_lock (&internal);
  225082. }
  225083. bool CriticalSection::tryEnter() const throw()
  225084. {
  225085. return pthread_mutex_trylock (&internal) == 0;
  225086. }
  225087. void CriticalSection::exit() const throw()
  225088. {
  225089. pthread_mutex_unlock (&internal);
  225090. }
  225091. class WaitableEventImpl
  225092. {
  225093. public:
  225094. WaitableEventImpl (const bool manualReset_)
  225095. : triggered (false),
  225096. manualReset (manualReset_)
  225097. {
  225098. pthread_cond_init (&condition, 0);
  225099. pthread_mutexattr_t atts;
  225100. pthread_mutexattr_init (&atts);
  225101. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225102. pthread_mutex_init (&mutex, &atts);
  225103. }
  225104. ~WaitableEventImpl()
  225105. {
  225106. pthread_cond_destroy (&condition);
  225107. pthread_mutex_destroy (&mutex);
  225108. }
  225109. bool wait (const int timeOutMillisecs) throw()
  225110. {
  225111. pthread_mutex_lock (&mutex);
  225112. if (! triggered)
  225113. {
  225114. if (timeOutMillisecs < 0)
  225115. {
  225116. do
  225117. {
  225118. pthread_cond_wait (&condition, &mutex);
  225119. }
  225120. while (! triggered);
  225121. }
  225122. else
  225123. {
  225124. struct timeval now;
  225125. gettimeofday (&now, 0);
  225126. struct timespec time;
  225127. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  225128. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  225129. if (time.tv_nsec >= 1000000000)
  225130. {
  225131. time.tv_nsec -= 1000000000;
  225132. time.tv_sec++;
  225133. }
  225134. do
  225135. {
  225136. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  225137. {
  225138. pthread_mutex_unlock (&mutex);
  225139. return false;
  225140. }
  225141. }
  225142. while (! triggered);
  225143. }
  225144. }
  225145. if (! manualReset)
  225146. triggered = false;
  225147. pthread_mutex_unlock (&mutex);
  225148. return true;
  225149. }
  225150. void signal() throw()
  225151. {
  225152. pthread_mutex_lock (&mutex);
  225153. triggered = true;
  225154. pthread_cond_broadcast (&condition);
  225155. pthread_mutex_unlock (&mutex);
  225156. }
  225157. void reset() throw()
  225158. {
  225159. pthread_mutex_lock (&mutex);
  225160. triggered = false;
  225161. pthread_mutex_unlock (&mutex);
  225162. }
  225163. private:
  225164. pthread_cond_t condition;
  225165. pthread_mutex_t mutex;
  225166. bool triggered;
  225167. const bool manualReset;
  225168. WaitableEventImpl (const WaitableEventImpl&);
  225169. WaitableEventImpl& operator= (const WaitableEventImpl&);
  225170. };
  225171. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  225172. : internal (new WaitableEventImpl (manualReset))
  225173. {
  225174. }
  225175. WaitableEvent::~WaitableEvent() throw()
  225176. {
  225177. delete static_cast <WaitableEventImpl*> (internal);
  225178. }
  225179. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  225180. {
  225181. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  225182. }
  225183. void WaitableEvent::signal() const throw()
  225184. {
  225185. static_cast <WaitableEventImpl*> (internal)->signal();
  225186. }
  225187. void WaitableEvent::reset() const throw()
  225188. {
  225189. static_cast <WaitableEventImpl*> (internal)->reset();
  225190. }
  225191. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  225192. {
  225193. struct timespec time;
  225194. time.tv_sec = millisecs / 1000;
  225195. time.tv_nsec = (millisecs % 1000) * 1000000;
  225196. nanosleep (&time, 0);
  225197. }
  225198. const juce_wchar File::separator = '/';
  225199. const String File::separatorString ("/");
  225200. const File File::getCurrentWorkingDirectory()
  225201. {
  225202. HeapBlock<char> heapBuffer;
  225203. char localBuffer [1024];
  225204. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  225205. int bufferSize = 4096;
  225206. while (cwd == 0 && errno == ERANGE)
  225207. {
  225208. heapBuffer.malloc (bufferSize);
  225209. cwd = getcwd (heapBuffer, bufferSize - 1);
  225210. bufferSize += 1024;
  225211. }
  225212. return File (String::fromUTF8 (cwd));
  225213. }
  225214. bool File::setAsCurrentWorkingDirectory() const
  225215. {
  225216. return chdir (getFullPathName().toUTF8()) == 0;
  225217. }
  225218. namespace
  225219. {
  225220. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225221. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  225222. #else
  225223. typedef struct stat juce_statStruct;
  225224. #endif
  225225. bool juce_stat (const String& fileName, juce_statStruct& info)
  225226. {
  225227. return fileName.isNotEmpty()
  225228. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225229. && (stat64 (fileName.toUTF8(), &info) == 0);
  225230. #else
  225231. && (stat (fileName.toUTF8(), &info) == 0);
  225232. #endif
  225233. }
  225234. // if this file doesn't exist, find a parent of it that does..
  225235. bool juce_doStatFS (File f, struct statfs& result)
  225236. {
  225237. for (int i = 5; --i >= 0;)
  225238. {
  225239. if (f.exists())
  225240. break;
  225241. f = f.getParentDirectory();
  225242. }
  225243. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225244. }
  225245. }
  225246. bool File::isDirectory() const
  225247. {
  225248. juce_statStruct info;
  225249. return fullPath.isEmpty()
  225250. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  225251. }
  225252. bool File::exists() const
  225253. {
  225254. juce_statStruct info;
  225255. return fullPath.isNotEmpty()
  225256. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225257. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  225258. #else
  225259. && (lstat (fullPath.toUTF8(), &info) == 0);
  225260. #endif
  225261. }
  225262. bool File::existsAsFile() const
  225263. {
  225264. return exists() && ! isDirectory();
  225265. }
  225266. int64 File::getSize() const
  225267. {
  225268. juce_statStruct info;
  225269. return juce_stat (fullPath, info) ? info.st_size : 0;
  225270. }
  225271. bool File::hasWriteAccess() const
  225272. {
  225273. if (exists())
  225274. return access (fullPath.toUTF8(), W_OK) == 0;
  225275. if ((! isDirectory()) && fullPath.containsChar (separator))
  225276. return getParentDirectory().hasWriteAccess();
  225277. return false;
  225278. }
  225279. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225280. {
  225281. juce_statStruct info;
  225282. if (! juce_stat (fullPath, info))
  225283. return false;
  225284. info.st_mode &= 0777; // Just permissions
  225285. if (shouldBeReadOnly)
  225286. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225287. else
  225288. // Give everybody write permission?
  225289. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225290. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225291. }
  225292. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225293. {
  225294. modificationTime = 0;
  225295. accessTime = 0;
  225296. creationTime = 0;
  225297. juce_statStruct info;
  225298. if (juce_stat (fullPath, info))
  225299. {
  225300. modificationTime = (int64) info.st_mtime * 1000;
  225301. accessTime = (int64) info.st_atime * 1000;
  225302. creationTime = (int64) info.st_ctime * 1000;
  225303. }
  225304. }
  225305. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225306. {
  225307. struct utimbuf times;
  225308. times.actime = (time_t) (accessTime / 1000);
  225309. times.modtime = (time_t) (modificationTime / 1000);
  225310. return utime (fullPath.toUTF8(), &times) == 0;
  225311. }
  225312. bool File::deleteFile() const
  225313. {
  225314. if (! exists())
  225315. return true;
  225316. else if (isDirectory())
  225317. return rmdir (fullPath.toUTF8()) == 0;
  225318. else
  225319. return remove (fullPath.toUTF8()) == 0;
  225320. }
  225321. bool File::moveInternal (const File& dest) const
  225322. {
  225323. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225324. return true;
  225325. if (hasWriteAccess() && copyInternal (dest))
  225326. {
  225327. if (deleteFile())
  225328. return true;
  225329. dest.deleteFile();
  225330. }
  225331. return false;
  225332. }
  225333. void File::createDirectoryInternal (const String& fileName) const
  225334. {
  225335. mkdir (fileName.toUTF8(), 0777);
  225336. }
  225337. int64 juce_fileSetPosition (void* handle, int64 pos)
  225338. {
  225339. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225340. return pos;
  225341. return -1;
  225342. }
  225343. void FileInputStream::openHandle()
  225344. {
  225345. totalSize = file.getSize();
  225346. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225347. if (f != -1)
  225348. fileHandle = (void*) f;
  225349. }
  225350. void FileInputStream::closeHandle()
  225351. {
  225352. if (fileHandle != 0)
  225353. {
  225354. close ((int) (pointer_sized_int) fileHandle);
  225355. fileHandle = 0;
  225356. }
  225357. }
  225358. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225359. {
  225360. if (fileHandle != 0)
  225361. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225362. return 0;
  225363. }
  225364. void FileOutputStream::openHandle()
  225365. {
  225366. if (file.exists())
  225367. {
  225368. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225369. if (f != -1)
  225370. {
  225371. currentPosition = lseek (f, 0, SEEK_END);
  225372. if (currentPosition >= 0)
  225373. fileHandle = (void*) f;
  225374. else
  225375. close (f);
  225376. }
  225377. }
  225378. else
  225379. {
  225380. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225381. if (f != -1)
  225382. fileHandle = (void*) f;
  225383. }
  225384. }
  225385. void FileOutputStream::closeHandle()
  225386. {
  225387. if (fileHandle != 0)
  225388. {
  225389. close ((int) (pointer_sized_int) fileHandle);
  225390. fileHandle = 0;
  225391. }
  225392. }
  225393. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225394. {
  225395. if (fileHandle != 0)
  225396. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225397. return 0;
  225398. }
  225399. void FileOutputStream::flushInternal()
  225400. {
  225401. if (fileHandle != 0)
  225402. fsync ((int) (pointer_sized_int) fileHandle);
  225403. }
  225404. const File juce_getExecutableFile()
  225405. {
  225406. Dl_info exeInfo;
  225407. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225408. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225409. }
  225410. int64 File::getBytesFreeOnVolume() const
  225411. {
  225412. struct statfs buf;
  225413. if (juce_doStatFS (*this, buf))
  225414. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225415. return 0;
  225416. }
  225417. int64 File::getVolumeTotalSize() const
  225418. {
  225419. struct statfs buf;
  225420. if (juce_doStatFS (*this, buf))
  225421. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225422. return 0;
  225423. }
  225424. const String File::getVolumeLabel() const
  225425. {
  225426. #if JUCE_MAC
  225427. struct VolAttrBuf
  225428. {
  225429. u_int32_t length;
  225430. attrreference_t mountPointRef;
  225431. char mountPointSpace [MAXPATHLEN];
  225432. } attrBuf;
  225433. struct attrlist attrList;
  225434. zerostruct (attrList);
  225435. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225436. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225437. File f (*this);
  225438. for (;;)
  225439. {
  225440. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225441. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225442. (int) attrBuf.mountPointRef.attr_length);
  225443. const File parent (f.getParentDirectory());
  225444. if (f == parent)
  225445. break;
  225446. f = parent;
  225447. }
  225448. #endif
  225449. return String::empty;
  225450. }
  225451. int File::getVolumeSerialNumber() const
  225452. {
  225453. return 0; // xxx
  225454. }
  225455. void juce_runSystemCommand (const String& command)
  225456. {
  225457. int result = system (command.toUTF8());
  225458. (void) result;
  225459. }
  225460. const String juce_getOutputFromCommand (const String& command)
  225461. {
  225462. // slight bodge here, as we just pipe the output into a temp file and read it...
  225463. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225464. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225465. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225466. String result (tempFile.loadFileAsString());
  225467. tempFile.deleteFile();
  225468. return result;
  225469. }
  225470. class InterProcessLock::Pimpl
  225471. {
  225472. public:
  225473. Pimpl (const String& name, const int timeOutMillisecs)
  225474. : handle (0), refCount (1)
  225475. {
  225476. #if JUCE_MAC
  225477. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225478. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225479. #else
  225480. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225481. #endif
  225482. temp.create();
  225483. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225484. if (handle != 0)
  225485. {
  225486. struct flock fl;
  225487. zerostruct (fl);
  225488. fl.l_whence = SEEK_SET;
  225489. fl.l_type = F_WRLCK;
  225490. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225491. for (;;)
  225492. {
  225493. const int result = fcntl (handle, F_SETLK, &fl);
  225494. if (result >= 0)
  225495. return;
  225496. if (errno != EINTR)
  225497. {
  225498. if (timeOutMillisecs == 0
  225499. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225500. break;
  225501. Thread::sleep (10);
  225502. }
  225503. }
  225504. }
  225505. closeFile();
  225506. }
  225507. ~Pimpl()
  225508. {
  225509. closeFile();
  225510. }
  225511. void closeFile()
  225512. {
  225513. if (handle != 0)
  225514. {
  225515. struct flock fl;
  225516. zerostruct (fl);
  225517. fl.l_whence = SEEK_SET;
  225518. fl.l_type = F_UNLCK;
  225519. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225520. {}
  225521. close (handle);
  225522. handle = 0;
  225523. }
  225524. }
  225525. int handle, refCount;
  225526. };
  225527. InterProcessLock::InterProcessLock (const String& name_)
  225528. : name (name_)
  225529. {
  225530. }
  225531. InterProcessLock::~InterProcessLock()
  225532. {
  225533. }
  225534. bool InterProcessLock::enter (const int timeOutMillisecs)
  225535. {
  225536. const ScopedLock sl (lock);
  225537. if (pimpl == 0)
  225538. {
  225539. pimpl = new Pimpl (name, timeOutMillisecs);
  225540. if (pimpl->handle == 0)
  225541. pimpl = 0;
  225542. }
  225543. else
  225544. {
  225545. pimpl->refCount++;
  225546. }
  225547. return pimpl != 0;
  225548. }
  225549. void InterProcessLock::exit()
  225550. {
  225551. const ScopedLock sl (lock);
  225552. // Trying to release the lock too many times!
  225553. jassert (pimpl != 0);
  225554. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225555. pimpl = 0;
  225556. }
  225557. void JUCE_API juce_threadEntryPoint (void*);
  225558. void* threadEntryProc (void* userData)
  225559. {
  225560. JUCE_AUTORELEASEPOOL
  225561. juce_threadEntryPoint (userData);
  225562. return 0;
  225563. }
  225564. void* juce_createThread (void* userData)
  225565. {
  225566. pthread_t handle = 0;
  225567. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225568. {
  225569. pthread_detach (handle);
  225570. return (void*) handle;
  225571. }
  225572. return 0;
  225573. }
  225574. void juce_killThread (void* handle)
  225575. {
  225576. if (handle != 0)
  225577. pthread_cancel ((pthread_t) handle);
  225578. }
  225579. void juce_setCurrentThreadName (const String& /*name*/)
  225580. {
  225581. }
  225582. bool juce_setThreadPriority (void* handle, int priority)
  225583. {
  225584. struct sched_param param;
  225585. int policy;
  225586. priority = jlimit (0, 10, priority);
  225587. if (handle == 0)
  225588. handle = (void*) pthread_self();
  225589. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225590. return false;
  225591. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225592. const int minPriority = sched_get_priority_min (policy);
  225593. const int maxPriority = sched_get_priority_max (policy);
  225594. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225595. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225596. }
  225597. Thread::ThreadID Thread::getCurrentThreadId()
  225598. {
  225599. return (ThreadID) pthread_self();
  225600. }
  225601. void Thread::yield()
  225602. {
  225603. sched_yield();
  225604. }
  225605. /* Remove this macro if you're having problems compiling the cpu affinity
  225606. calls (the API for these has changed about quite a bit in various Linux
  225607. versions, and a lot of distros seem to ship with obsolete versions)
  225608. */
  225609. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225610. #define SUPPORT_AFFINITIES 1
  225611. #endif
  225612. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225613. {
  225614. #if SUPPORT_AFFINITIES
  225615. cpu_set_t affinity;
  225616. CPU_ZERO (&affinity);
  225617. for (int i = 0; i < 32; ++i)
  225618. if ((affinityMask & (1 << i)) != 0)
  225619. CPU_SET (i, &affinity);
  225620. /*
  225621. N.B. If this line causes a compile error, then you've probably not got the latest
  225622. version of glibc installed.
  225623. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225624. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225625. */
  225626. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225627. sched_yield();
  225628. #else
  225629. /* affinities aren't supported because either the appropriate header files weren't found,
  225630. or the SUPPORT_AFFINITIES macro was turned off
  225631. */
  225632. jassertfalse;
  225633. #endif
  225634. }
  225635. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225636. /*** Start of inlined file: juce_mac_Files.mm ***/
  225637. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225638. // compiled on its own).
  225639. #if JUCE_INCLUDED_FILE
  225640. /*
  225641. Note that a lot of methods that you'd expect to find in this file actually
  225642. live in juce_posix_SharedCode.h!
  225643. */
  225644. bool File::copyInternal (const File& dest) const
  225645. {
  225646. const ScopedAutoReleasePool pool;
  225647. NSFileManager* fm = [NSFileManager defaultManager];
  225648. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225649. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225650. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225651. toPath: juceStringToNS (dest.getFullPathName())
  225652. error: nil];
  225653. #else
  225654. && [fm copyPath: juceStringToNS (fullPath)
  225655. toPath: juceStringToNS (dest.getFullPathName())
  225656. handler: nil];
  225657. #endif
  225658. }
  225659. void File::findFileSystemRoots (Array<File>& destArray)
  225660. {
  225661. destArray.add (File ("/"));
  225662. }
  225663. namespace
  225664. {
  225665. bool isFileOnDriveType (const File& f, const char* const* types)
  225666. {
  225667. struct statfs buf;
  225668. if (juce_doStatFS (f, buf))
  225669. {
  225670. const String type (buf.f_fstypename);
  225671. while (*types != 0)
  225672. if (type.equalsIgnoreCase (*types++))
  225673. return true;
  225674. }
  225675. return false;
  225676. }
  225677. bool juce_isHiddenFile (const String& path)
  225678. {
  225679. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225680. const ScopedAutoReleasePool pool;
  225681. NSNumber* hidden = nil;
  225682. NSError* err = nil;
  225683. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225684. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225685. && [hidden boolValue];
  225686. #else
  225687. #if JUCE_IOS
  225688. return File (path).getFileName().startsWithChar ('.');
  225689. #else
  225690. FSRef ref;
  225691. LSItemInfoRecord info;
  225692. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225693. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225694. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225695. #endif
  225696. #endif
  225697. }
  225698. #if JUCE_IOS
  225699. const String getIOSSystemLocation (NSSearchPathDirectory type)
  225700. {
  225701. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  225702. objectAtIndex: 0]);
  225703. }
  225704. #endif
  225705. }
  225706. bool File::isOnCDRomDrive() const
  225707. {
  225708. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225709. return isFileOnDriveType (*this, cdTypes);
  225710. }
  225711. bool File::isOnHardDisk() const
  225712. {
  225713. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225714. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225715. }
  225716. bool File::isOnRemovableDrive() const
  225717. {
  225718. #if JUCE_IOS
  225719. return false; // xxx is this possible?
  225720. #else
  225721. const ScopedAutoReleasePool pool;
  225722. BOOL removable = false;
  225723. [[NSWorkspace sharedWorkspace]
  225724. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225725. isRemovable: &removable
  225726. isWritable: nil
  225727. isUnmountable: nil
  225728. description: nil
  225729. type: nil];
  225730. return removable;
  225731. #endif
  225732. }
  225733. bool File::isHidden() const
  225734. {
  225735. return juce_isHiddenFile (getFullPathName());
  225736. }
  225737. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225738. const File File::getSpecialLocation (const SpecialLocationType type)
  225739. {
  225740. const ScopedAutoReleasePool pool;
  225741. String resultPath;
  225742. switch (type)
  225743. {
  225744. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225745. #if JUCE_IOS
  225746. case userDocumentsDirectory: resultPath = getIOSSystemLocation (NSDocumentDirectory); break;
  225747. case userDesktopDirectory: resultPath = getIOSSystemLocation (NSDesktopDirectory); break;
  225748. case tempDirectory:
  225749. {
  225750. File tmp (getIOSSystemLocation (NSCachesDirectory));
  225751. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  225752. tmp.createDirectory();
  225753. return tmp.getFullPathName();
  225754. }
  225755. #else
  225756. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225757. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225758. case tempDirectory:
  225759. {
  225760. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225761. tmp.createDirectory();
  225762. return tmp.getFullPathName();
  225763. }
  225764. #endif
  225765. case userMusicDirectory: resultPath = "~/Music"; break;
  225766. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225767. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225768. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225769. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225770. case invokedExecutableFile:
  225771. if (juce_Argv0 != 0)
  225772. return File (String::fromUTF8 (juce_Argv0));
  225773. // deliberate fall-through...
  225774. case currentExecutableFile:
  225775. return juce_getExecutableFile();
  225776. case currentApplicationFile:
  225777. {
  225778. const File exe (juce_getExecutableFile());
  225779. const File parent (exe.getParentDirectory());
  225780. #if JUCE_IOS
  225781. return parent;
  225782. #else
  225783. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225784. ? parent.getParentDirectory().getParentDirectory()
  225785. : exe;
  225786. #endif
  225787. }
  225788. case hostApplicationPath:
  225789. {
  225790. unsigned int size = 8192;
  225791. HeapBlock<char> buffer;
  225792. buffer.calloc (size + 8);
  225793. _NSGetExecutablePath (buffer.getData(), &size);
  225794. return String::fromUTF8 (buffer, size);
  225795. }
  225796. default:
  225797. jassertfalse; // unknown type?
  225798. break;
  225799. }
  225800. if (resultPath.isNotEmpty())
  225801. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225802. return File::nonexistent;
  225803. }
  225804. const String File::getVersion() const
  225805. {
  225806. const ScopedAutoReleasePool pool;
  225807. String result;
  225808. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225809. if (bundle != 0)
  225810. {
  225811. NSDictionary* info = [bundle infoDictionary];
  225812. if (info != 0)
  225813. {
  225814. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225815. if (name != nil)
  225816. result = nsStringToJuce (name);
  225817. }
  225818. }
  225819. return result;
  225820. }
  225821. const File File::getLinkedTarget() const
  225822. {
  225823. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225824. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225825. #else
  225826. // (the cast here avoids a deprecation warning)
  225827. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225828. #endif
  225829. if (dest != nil)
  225830. return File (nsStringToJuce (dest));
  225831. return *this;
  225832. }
  225833. bool File::moveToTrash() const
  225834. {
  225835. if (! exists())
  225836. return true;
  225837. #if JUCE_IOS
  225838. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225839. #else
  225840. const ScopedAutoReleasePool pool;
  225841. NSString* p = juceStringToNS (getFullPathName());
  225842. return [[NSWorkspace sharedWorkspace]
  225843. performFileOperation: NSWorkspaceRecycleOperation
  225844. source: [p stringByDeletingLastPathComponent]
  225845. destination: @""
  225846. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225847. tag: nil ];
  225848. #endif
  225849. }
  225850. class DirectoryIterator::NativeIterator::Pimpl
  225851. {
  225852. public:
  225853. Pimpl (const File& directory, const String& wildCard_)
  225854. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225855. wildCard (wildCard_),
  225856. enumerator (0)
  225857. {
  225858. const ScopedAutoReleasePool pool;
  225859. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225860. wildcardUTF8 = wildCard.toUTF8();
  225861. }
  225862. ~Pimpl()
  225863. {
  225864. [enumerator release];
  225865. }
  225866. bool next (String& filenameFound,
  225867. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225868. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225869. {
  225870. const ScopedAutoReleasePool pool;
  225871. for (;;)
  225872. {
  225873. NSString* file;
  225874. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225875. return false;
  225876. [enumerator skipDescendents];
  225877. filenameFound = nsStringToJuce (file);
  225878. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225879. continue;
  225880. const String path (parentDir + filenameFound);
  225881. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225882. {
  225883. juce_statStruct info;
  225884. const bool statOk = juce_stat (path, info);
  225885. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225886. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225887. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225888. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225889. }
  225890. if (isHidden != 0)
  225891. *isHidden = juce_isHiddenFile (path);
  225892. if (isReadOnly != 0)
  225893. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225894. return true;
  225895. }
  225896. }
  225897. private:
  225898. String parentDir, wildCard;
  225899. const char* wildcardUTF8;
  225900. NSDirectoryEnumerator* enumerator;
  225901. Pimpl (const Pimpl&);
  225902. Pimpl& operator= (const Pimpl&);
  225903. };
  225904. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225905. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225906. {
  225907. }
  225908. DirectoryIterator::NativeIterator::~NativeIterator()
  225909. {
  225910. }
  225911. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225912. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225913. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225914. {
  225915. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225916. }
  225917. bool juce_launchExecutable (const String& pathAndArguments)
  225918. {
  225919. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225920. const int cpid = fork();
  225921. if (cpid == 0)
  225922. {
  225923. // Child process
  225924. if (execve (argv[0], (char**) argv, 0) < 0)
  225925. exit (0);
  225926. }
  225927. else
  225928. {
  225929. if (cpid < 0)
  225930. return false;
  225931. }
  225932. return true;
  225933. }
  225934. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225935. {
  225936. #if JUCE_IOS
  225937. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225938. #else
  225939. const ScopedAutoReleasePool pool;
  225940. if (parameters.isEmpty())
  225941. {
  225942. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225943. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225944. }
  225945. bool ok = false;
  225946. if (PlatformUtilities::isBundle (fileName))
  225947. {
  225948. NSMutableArray* urls = [NSMutableArray array];
  225949. StringArray docs;
  225950. docs.addTokens (parameters, true);
  225951. for (int i = 0; i < docs.size(); ++i)
  225952. [urls addObject: juceStringToNS (docs[i])];
  225953. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225954. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225955. options: 0
  225956. additionalEventParamDescriptor: nil
  225957. launchIdentifiers: nil];
  225958. }
  225959. else if (File (fileName).exists())
  225960. {
  225961. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  225962. }
  225963. return ok;
  225964. #endif
  225965. }
  225966. void File::revealToUser() const
  225967. {
  225968. #if ! JUCE_IOS
  225969. if (exists())
  225970. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225971. else if (getParentDirectory().exists())
  225972. getParentDirectory().revealToUser();
  225973. #endif
  225974. }
  225975. #if ! JUCE_IOS
  225976. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225977. {
  225978. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225979. }
  225980. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225981. {
  225982. char path [2048];
  225983. zerostruct (path);
  225984. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225985. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225986. return String::empty;
  225987. }
  225988. #endif
  225989. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225990. {
  225991. const ScopedAutoReleasePool pool;
  225992. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225993. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225994. #else
  225995. // (the cast here avoids a deprecation warning)
  225996. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225997. #endif
  225998. return [fileDict fileHFSTypeCode];
  225999. }
  226000. bool PlatformUtilities::isBundle (const String& filename)
  226001. {
  226002. #if JUCE_IOS
  226003. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  226004. #else
  226005. const ScopedAutoReleasePool pool;
  226006. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  226007. #endif
  226008. }
  226009. #endif
  226010. /*** End of inlined file: juce_mac_Files.mm ***/
  226011. #if JUCE_IOS
  226012. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  226013. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226014. // compiled on its own).
  226015. #if JUCE_INCLUDED_FILE
  226016. END_JUCE_NAMESPACE
  226017. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  226018. {
  226019. }
  226020. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  226021. - (void) applicationWillTerminate: (UIApplication*) application;
  226022. @end
  226023. @implementation JuceAppStartupDelegate
  226024. - (void) applicationDidFinishLaunching: (UIApplication*) application
  226025. {
  226026. initialiseJuce_GUI();
  226027. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  226028. exit (0);
  226029. }
  226030. - (void) applicationWillTerminate: (UIApplication*) application
  226031. {
  226032. JUCEApplication::appWillTerminateByForce();
  226033. }
  226034. @end
  226035. BEGIN_JUCE_NAMESPACE
  226036. int juce_iOSMain (int argc, const char* argv[])
  226037. {
  226038. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  226039. }
  226040. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226041. {
  226042. pool = [[NSAutoreleasePool alloc] init];
  226043. }
  226044. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226045. {
  226046. [((NSAutoreleasePool*) pool) release];
  226047. }
  226048. void PlatformUtilities::beep()
  226049. {
  226050. //xxx
  226051. //AudioServicesPlaySystemSound ();
  226052. }
  226053. void PlatformUtilities::addItemToDock (const File& file)
  226054. {
  226055. }
  226056. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226057. END_JUCE_NAMESPACE
  226058. @interface JuceAlertBoxDelegate : NSObject
  226059. {
  226060. @public
  226061. bool clickedOk;
  226062. }
  226063. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  226064. @end
  226065. @implementation JuceAlertBoxDelegate
  226066. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  226067. {
  226068. clickedOk = (buttonIndex == 0);
  226069. alertView.hidden = true;
  226070. }
  226071. @end
  226072. BEGIN_JUCE_NAMESPACE
  226073. // (This function is used directly by other bits of code)
  226074. bool juce_iPhoneShowModalAlert (const String& title,
  226075. const String& bodyText,
  226076. NSString* okButtonText,
  226077. NSString* cancelButtonText)
  226078. {
  226079. const ScopedAutoReleasePool pool;
  226080. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  226081. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  226082. message: juceStringToNS (bodyText)
  226083. delegate: callback
  226084. cancelButtonTitle: okButtonText
  226085. otherButtonTitles: cancelButtonText, nil];
  226086. [alert retain];
  226087. [alert show];
  226088. while (! alert.hidden && alert.superview != nil)
  226089. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  226090. const bool result = callback->clickedOk;
  226091. [alert release];
  226092. [callback release];
  226093. return result;
  226094. }
  226095. bool AlertWindow::showNativeDialogBox (const String& title,
  226096. const String& bodyText,
  226097. bool isOkCancel)
  226098. {
  226099. return juce_iPhoneShowModalAlert (title, bodyText,
  226100. @"OK",
  226101. isOkCancel ? @"Cancel" : nil);
  226102. }
  226103. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  226104. {
  226105. jassertfalse; // no such thing on the iphone!
  226106. return false;
  226107. }
  226108. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  226109. {
  226110. jassertfalse; // no such thing on the iphone!
  226111. return false;
  226112. }
  226113. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226114. {
  226115. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  226116. }
  226117. bool Desktop::isScreenSaverEnabled()
  226118. {
  226119. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  226120. }
  226121. #endif
  226122. #endif
  226123. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  226124. #else
  226125. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  226126. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226127. // compiled on its own).
  226128. #if JUCE_INCLUDED_FILE
  226129. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226130. {
  226131. pool = [[NSAutoreleasePool alloc] init];
  226132. }
  226133. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226134. {
  226135. [((NSAutoreleasePool*) pool) release];
  226136. }
  226137. void PlatformUtilities::beep()
  226138. {
  226139. NSBeep();
  226140. }
  226141. void PlatformUtilities::addItemToDock (const File& file)
  226142. {
  226143. // check that it's not already there...
  226144. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  226145. .containsIgnoreCase (file.getFullPathName()))
  226146. {
  226147. 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>"
  226148. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  226149. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  226150. }
  226151. }
  226152. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226153. bool AlertWindow::showNativeDialogBox (const String& title,
  226154. const String& bodyText,
  226155. bool isOkCancel)
  226156. {
  226157. const ScopedAutoReleasePool pool;
  226158. return NSRunAlertPanel (juceStringToNS (title),
  226159. juceStringToNS (bodyText),
  226160. @"Ok",
  226161. isOkCancel ? @"Cancel" : nil,
  226162. nil) == NSAlertDefaultReturn;
  226163. }
  226164. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  226165. {
  226166. if (files.size() == 0)
  226167. return false;
  226168. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  226169. if (draggingSource == 0)
  226170. {
  226171. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226172. return false;
  226173. }
  226174. Component* sourceComp = draggingSource->getComponentUnderMouse();
  226175. if (sourceComp == 0)
  226176. {
  226177. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226178. return false;
  226179. }
  226180. const ScopedAutoReleasePool pool;
  226181. NSView* view = (NSView*) sourceComp->getWindowHandle();
  226182. if (view == 0)
  226183. return false;
  226184. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  226185. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  226186. owner: nil];
  226187. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  226188. for (int i = 0; i < files.size(); ++i)
  226189. [filesArray addObject: juceStringToNS (files[i])];
  226190. [pboard setPropertyList: filesArray
  226191. forType: NSFilenamesPboardType];
  226192. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  226193. fromView: nil];
  226194. dragPosition.x -= 16;
  226195. dragPosition.y -= 16;
  226196. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  226197. at: dragPosition
  226198. offset: NSMakeSize (0, 0)
  226199. event: [[view window] currentEvent]
  226200. pasteboard: pboard
  226201. source: view
  226202. slideBack: YES];
  226203. return true;
  226204. }
  226205. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  226206. {
  226207. jassertfalse; // not implemented!
  226208. return false;
  226209. }
  226210. bool Desktop::canUseSemiTransparentWindows() throw()
  226211. {
  226212. return true;
  226213. }
  226214. const Point<int> Desktop::getMousePosition()
  226215. {
  226216. const ScopedAutoReleasePool pool;
  226217. const NSPoint p ([NSEvent mouseLocation]);
  226218. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  226219. }
  226220. void Desktop::setMousePosition (const Point<int>& newPosition)
  226221. {
  226222. // this rubbish needs to be done around the warp call, to avoid causing a
  226223. // bizarre glitch..
  226224. CGAssociateMouseAndMouseCursorPosition (false);
  226225. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  226226. CGAssociateMouseAndMouseCursorPosition (true);
  226227. }
  226228. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  226229. {
  226230. return upright;
  226231. }
  226232. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226233. class ScreenSaverDefeater : public Timer,
  226234. public DeletedAtShutdown
  226235. {
  226236. public:
  226237. ScreenSaverDefeater()
  226238. {
  226239. startTimer (10000);
  226240. timerCallback();
  226241. }
  226242. ~ScreenSaverDefeater() {}
  226243. void timerCallback()
  226244. {
  226245. if (Process::isForegroundProcess())
  226246. UpdateSystemActivity (UsrActivity);
  226247. }
  226248. };
  226249. static ScreenSaverDefeater* screenSaverDefeater = 0;
  226250. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226251. {
  226252. if (isEnabled)
  226253. deleteAndZero (screenSaverDefeater);
  226254. else if (screenSaverDefeater == 0)
  226255. screenSaverDefeater = new ScreenSaverDefeater();
  226256. }
  226257. bool Desktop::isScreenSaverEnabled()
  226258. {
  226259. return screenSaverDefeater == 0;
  226260. }
  226261. #else
  226262. static IOPMAssertionID screenSaverDisablerID = 0;
  226263. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226264. {
  226265. if (isEnabled)
  226266. {
  226267. if (screenSaverDisablerID != 0)
  226268. {
  226269. IOPMAssertionRelease (screenSaverDisablerID);
  226270. screenSaverDisablerID = 0;
  226271. }
  226272. }
  226273. else
  226274. {
  226275. if (screenSaverDisablerID == 0)
  226276. {
  226277. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226278. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226279. CFSTR ("Juce"), &screenSaverDisablerID);
  226280. #else
  226281. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226282. &screenSaverDisablerID);
  226283. #endif
  226284. }
  226285. }
  226286. }
  226287. bool Desktop::isScreenSaverEnabled()
  226288. {
  226289. return screenSaverDisablerID == 0;
  226290. }
  226291. #endif
  226292. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226293. {
  226294. const ScopedAutoReleasePool pool;
  226295. monitorCoords.clear();
  226296. NSArray* screens = [NSScreen screens];
  226297. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226298. for (unsigned int i = 0; i < [screens count]; ++i)
  226299. {
  226300. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226301. NSRect r = clipToWorkArea ? [s visibleFrame]
  226302. : [s frame];
  226303. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  226304. monitorCoords.add (convertToRectInt (r));
  226305. }
  226306. jassert (monitorCoords.size() > 0);
  226307. }
  226308. #endif
  226309. #endif
  226310. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226311. #endif
  226312. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226313. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226314. // compiled on its own).
  226315. #if JUCE_INCLUDED_FILE
  226316. void Logger::outputDebugString (const String& text)
  226317. {
  226318. std::cerr << text << std::endl;
  226319. }
  226320. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  226321. {
  226322. static char testResult = 0;
  226323. if (testResult == 0)
  226324. {
  226325. struct kinfo_proc info;
  226326. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226327. size_t sz = sizeof (info);
  226328. sysctl (m, 4, &info, &sz, 0, 0);
  226329. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226330. }
  226331. return testResult > 0;
  226332. }
  226333. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226334. {
  226335. return juce_isRunningUnderDebugger();
  226336. }
  226337. #endif
  226338. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226339. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226340. #if JUCE_IOS
  226341. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226342. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226343. // compiled on its own).
  226344. #if JUCE_INCLUDED_FILE
  226345. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226346. #define SUPPORT_10_4_FONTS 1
  226347. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226348. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226349. #define SUPPORT_ONLY_10_4_FONTS 1
  226350. #endif
  226351. END_JUCE_NAMESPACE
  226352. @interface NSFont (PrivateHack)
  226353. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226354. @end
  226355. BEGIN_JUCE_NAMESPACE
  226356. #endif
  226357. class MacTypeface : public Typeface
  226358. {
  226359. public:
  226360. MacTypeface (const Font& font)
  226361. : Typeface (font.getTypefaceName())
  226362. {
  226363. const ScopedAutoReleasePool pool;
  226364. renderingTransform = CGAffineTransformIdentity;
  226365. bool needsItalicTransform = false;
  226366. #if JUCE_IOS
  226367. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226368. if (font.isItalic() || font.isBold())
  226369. {
  226370. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226371. for (NSString* i in familyFonts)
  226372. {
  226373. const String fn (nsStringToJuce (i));
  226374. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226375. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226376. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226377. || afterDash.containsIgnoreCase ("italic")
  226378. || fn.endsWithIgnoreCase ("oblique")
  226379. || fn.endsWithIgnoreCase ("italic");
  226380. if (probablyBold == font.isBold()
  226381. && probablyItalic == font.isItalic())
  226382. {
  226383. fontName = i;
  226384. needsItalicTransform = false;
  226385. break;
  226386. }
  226387. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226388. {
  226389. fontName = i;
  226390. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226391. }
  226392. }
  226393. if (needsItalicTransform)
  226394. renderingTransform.c = 0.15f;
  226395. }
  226396. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226397. const int ascender = abs (CGFontGetAscent (fontRef));
  226398. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226399. ascent = ascender / totalHeight;
  226400. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226401. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226402. #else
  226403. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226404. if (font.isItalic())
  226405. {
  226406. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226407. toHaveTrait: NSItalicFontMask];
  226408. if (newFont == nsFont)
  226409. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226410. nsFont = newFont;
  226411. }
  226412. if (font.isBold())
  226413. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226414. [nsFont retain];
  226415. ascent = std::abs ((float) [nsFont ascender]);
  226416. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226417. ascent /= totalSize;
  226418. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226419. if (needsItalicTransform)
  226420. {
  226421. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226422. renderingTransform.c = 0.15f;
  226423. }
  226424. #if SUPPORT_ONLY_10_4_FONTS
  226425. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226426. if (atsFont == 0)
  226427. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226428. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226429. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226430. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226431. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226432. #else
  226433. #if SUPPORT_10_4_FONTS
  226434. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226435. {
  226436. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226437. if (atsFont == 0)
  226438. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226439. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226440. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226441. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226442. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226443. }
  226444. else
  226445. #endif
  226446. {
  226447. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226448. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226449. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226450. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226451. }
  226452. #endif
  226453. #endif
  226454. }
  226455. ~MacTypeface()
  226456. {
  226457. #if ! JUCE_IOS
  226458. [nsFont release];
  226459. #endif
  226460. if (fontRef != 0)
  226461. CGFontRelease (fontRef);
  226462. }
  226463. float getAscent() const
  226464. {
  226465. return ascent;
  226466. }
  226467. float getDescent() const
  226468. {
  226469. return 1.0f - ascent;
  226470. }
  226471. float getStringWidth (const String& text)
  226472. {
  226473. if (fontRef == 0 || text.isEmpty())
  226474. return 0;
  226475. const int length = text.length();
  226476. HeapBlock <CGGlyph> glyphs;
  226477. createGlyphsForString (text, length, glyphs);
  226478. float x = 0;
  226479. #if SUPPORT_ONLY_10_4_FONTS
  226480. HeapBlock <NSSize> advances (length);
  226481. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226482. for (int i = 0; i < length; ++i)
  226483. x += advances[i].width;
  226484. #else
  226485. #if SUPPORT_10_4_FONTS
  226486. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226487. {
  226488. HeapBlock <NSSize> advances (length);
  226489. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226490. for (int i = 0; i < length; ++i)
  226491. x += advances[i].width;
  226492. }
  226493. else
  226494. #endif
  226495. {
  226496. HeapBlock <int> advances (length);
  226497. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226498. for (int i = 0; i < length; ++i)
  226499. x += advances[i];
  226500. }
  226501. #endif
  226502. return x * unitsToHeightScaleFactor;
  226503. }
  226504. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226505. {
  226506. xOffsets.add (0);
  226507. if (fontRef == 0 || text.isEmpty())
  226508. return;
  226509. const int length = text.length();
  226510. HeapBlock <CGGlyph> glyphs;
  226511. createGlyphsForString (text, length, glyphs);
  226512. #if SUPPORT_ONLY_10_4_FONTS
  226513. HeapBlock <NSSize> advances (length);
  226514. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226515. int x = 0;
  226516. for (int i = 0; i < length; ++i)
  226517. {
  226518. x += advances[i].width;
  226519. xOffsets.add (x * unitsToHeightScaleFactor);
  226520. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226521. }
  226522. #else
  226523. #if SUPPORT_10_4_FONTS
  226524. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226525. {
  226526. HeapBlock <NSSize> advances (length);
  226527. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226528. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226529. float x = 0;
  226530. for (int i = 0; i < length; ++i)
  226531. {
  226532. x += advances[i].width;
  226533. xOffsets.add (x * unitsToHeightScaleFactor);
  226534. resultGlyphs.add (nsGlyphs[i]);
  226535. }
  226536. }
  226537. else
  226538. #endif
  226539. {
  226540. HeapBlock <int> advances (length);
  226541. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226542. {
  226543. int x = 0;
  226544. for (int i = 0; i < length; ++i)
  226545. {
  226546. x += advances [i];
  226547. xOffsets.add (x * unitsToHeightScaleFactor);
  226548. resultGlyphs.add (glyphs[i]);
  226549. }
  226550. }
  226551. }
  226552. #endif
  226553. }
  226554. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226555. {
  226556. #if JUCE_IOS
  226557. return false;
  226558. #else
  226559. if (nsFont == 0)
  226560. return false;
  226561. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226562. jassert (path.isEmpty());
  226563. const ScopedAutoReleasePool pool;
  226564. NSBezierPath* bez = [NSBezierPath bezierPath];
  226565. [bez moveToPoint: NSMakePoint (0, 0)];
  226566. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226567. inFont: nsFont];
  226568. for (int i = 0; i < [bez elementCount]; ++i)
  226569. {
  226570. NSPoint p[3];
  226571. switch ([bez elementAtIndex: i associatedPoints: p])
  226572. {
  226573. case NSMoveToBezierPathElement:
  226574. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226575. break;
  226576. case NSLineToBezierPathElement:
  226577. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226578. break;
  226579. case NSCurveToBezierPathElement:
  226580. 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);
  226581. break;
  226582. case NSClosePathBezierPathElement:
  226583. path.closeSubPath();
  226584. break;
  226585. default:
  226586. jassertfalse;
  226587. break;
  226588. }
  226589. }
  226590. path.applyTransform (pathTransform);
  226591. return true;
  226592. #endif
  226593. }
  226594. juce_UseDebuggingNewOperator
  226595. CGFontRef fontRef;
  226596. float fontHeightToCGSizeFactor;
  226597. CGAffineTransform renderingTransform;
  226598. private:
  226599. float ascent, unitsToHeightScaleFactor;
  226600. #if JUCE_IOS
  226601. #else
  226602. NSFont* nsFont;
  226603. AffineTransform pathTransform;
  226604. #endif
  226605. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226606. {
  226607. #if SUPPORT_10_4_FONTS
  226608. #if ! SUPPORT_ONLY_10_4_FONTS
  226609. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226610. #endif
  226611. {
  226612. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226613. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226614. for (int i = 0; i < length; ++i)
  226615. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226616. return;
  226617. }
  226618. #endif
  226619. #if ! SUPPORT_ONLY_10_4_FONTS
  226620. if (charToGlyphMapper == 0)
  226621. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226622. glyphs.malloc (length);
  226623. for (int i = 0; i < length; ++i)
  226624. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226625. #endif
  226626. }
  226627. #if ! SUPPORT_ONLY_10_4_FONTS
  226628. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226629. class CharToGlyphMapper
  226630. {
  226631. public:
  226632. CharToGlyphMapper (CGFontRef fontRef)
  226633. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226634. idRangeOffset (0), glyphIndexes (0)
  226635. {
  226636. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226637. if (cmapTable != 0)
  226638. {
  226639. const int numSubtables = getValue16 (cmapTable, 2);
  226640. for (int i = 0; i < numSubtables; ++i)
  226641. {
  226642. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226643. {
  226644. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226645. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226646. {
  226647. const int length = getValue16 (cmapTable, offset + 2);
  226648. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226649. segCount = segCountX2 / 2;
  226650. const int endCodeOffset = offset + 14;
  226651. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226652. const int idDeltaOffset = startCodeOffset + segCountX2;
  226653. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226654. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226655. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226656. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226657. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226658. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226659. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226660. }
  226661. break;
  226662. }
  226663. }
  226664. CFRelease (cmapTable);
  226665. }
  226666. }
  226667. ~CharToGlyphMapper()
  226668. {
  226669. if (endCode != 0)
  226670. {
  226671. CFRelease (endCode);
  226672. CFRelease (startCode);
  226673. CFRelease (idDelta);
  226674. CFRelease (idRangeOffset);
  226675. CFRelease (glyphIndexes);
  226676. }
  226677. }
  226678. int getGlyphForCharacter (const juce_wchar c) const
  226679. {
  226680. for (int i = 0; i < segCount; ++i)
  226681. {
  226682. if (getValue16 (endCode, i * 2) >= c)
  226683. {
  226684. const int start = getValue16 (startCode, i * 2);
  226685. if (start > c)
  226686. break;
  226687. const int delta = getValue16 (idDelta, i * 2);
  226688. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226689. if (rangeOffset == 0)
  226690. return delta + c;
  226691. else
  226692. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226693. }
  226694. }
  226695. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226696. return jmax (-1, (int) c - 29);
  226697. }
  226698. private:
  226699. int segCount;
  226700. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226701. static uint16 getValue16 (CFDataRef data, const int index)
  226702. {
  226703. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226704. }
  226705. static uint32 getValue32 (CFDataRef data, const int index)
  226706. {
  226707. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226708. }
  226709. };
  226710. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226711. #endif
  226712. MacTypeface (const MacTypeface&);
  226713. MacTypeface& operator= (const MacTypeface&);
  226714. };
  226715. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226716. {
  226717. return new MacTypeface (font);
  226718. }
  226719. const StringArray Font::findAllTypefaceNames()
  226720. {
  226721. StringArray names;
  226722. const ScopedAutoReleasePool pool;
  226723. #if JUCE_IOS
  226724. NSArray* fonts = [UIFont familyNames];
  226725. #else
  226726. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226727. #endif
  226728. for (unsigned int i = 0; i < [fonts count]; ++i)
  226729. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226730. names.sort (true);
  226731. return names;
  226732. }
  226733. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  226734. {
  226735. #if JUCE_IOS
  226736. defaultSans = "Helvetica";
  226737. defaultSerif = "Times New Roman";
  226738. defaultFixed = "Courier New";
  226739. #else
  226740. defaultSans = "Lucida Grande";
  226741. defaultSerif = "Times New Roman";
  226742. defaultFixed = "Monaco";
  226743. #endif
  226744. defaultFallback = "Arial Unicode MS";
  226745. }
  226746. #endif
  226747. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226748. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226749. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226750. // compiled on its own).
  226751. #if JUCE_INCLUDED_FILE
  226752. class CoreGraphicsImage : public Image::SharedImage
  226753. {
  226754. public:
  226755. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226756. : Image::SharedImage (format_, width_, height_)
  226757. {
  226758. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226759. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226760. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226761. imageData = imageDataAllocated;
  226762. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226763. : CGColorSpaceCreateDeviceRGB();
  226764. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226765. colourSpace, getCGImageFlags (format_));
  226766. CGColorSpaceRelease (colourSpace);
  226767. }
  226768. ~CoreGraphicsImage()
  226769. {
  226770. CGContextRelease (context);
  226771. }
  226772. Image::ImageType getType() const { return Image::NativeImage; }
  226773. LowLevelGraphicsContext* createLowLevelContext();
  226774. SharedImage* clone()
  226775. {
  226776. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226777. memcpy (im->imageData, imageData, lineStride * height);
  226778. return im;
  226779. }
  226780. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226781. {
  226782. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226783. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226784. {
  226785. return CGBitmapContextCreateImage (nativeImage->context);
  226786. }
  226787. else
  226788. {
  226789. const Image::BitmapData srcData (juceImage, false);
  226790. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226791. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226792. 8, srcData.pixelStride * 8, srcData.lineStride,
  226793. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226794. 0, true, kCGRenderingIntentDefault);
  226795. CGDataProviderRelease (provider);
  226796. return imageRef;
  226797. }
  226798. }
  226799. #if JUCE_MAC
  226800. static NSImage* createNSImage (const Image& image)
  226801. {
  226802. const ScopedAutoReleasePool pool;
  226803. NSImage* im = [[NSImage alloc] init];
  226804. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226805. [im lockFocus];
  226806. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226807. CGImageRef imageRef = createImage (image, false, colourSpace);
  226808. CGColorSpaceRelease (colourSpace);
  226809. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226810. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226811. CGImageRelease (imageRef);
  226812. [im unlockFocus];
  226813. return im;
  226814. }
  226815. #endif
  226816. CGContextRef context;
  226817. HeapBlock<uint8> imageDataAllocated;
  226818. private:
  226819. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226820. {
  226821. #if JUCE_BIG_ENDIAN
  226822. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226823. #else
  226824. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226825. #endif
  226826. }
  226827. };
  226828. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226829. {
  226830. #if USE_COREGRAPHICS_RENDERING
  226831. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226832. #else
  226833. return createSoftwareImage (format, width, height, clearImage);
  226834. #endif
  226835. }
  226836. class CoreGraphicsContext : public LowLevelGraphicsContext
  226837. {
  226838. public:
  226839. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226840. : context (context_),
  226841. flipHeight (flipHeight_),
  226842. lastClipRectIsValid (false),
  226843. state (new SavedState()),
  226844. numGradientLookupEntries (0)
  226845. {
  226846. CGContextRetain (context);
  226847. CGContextSaveGState(context);
  226848. CGContextSetShouldSmoothFonts (context, true);
  226849. CGContextSetShouldAntialias (context, true);
  226850. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226851. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226852. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226853. gradientCallbacks.version = 0;
  226854. gradientCallbacks.evaluate = gradientCallback;
  226855. gradientCallbacks.releaseInfo = 0;
  226856. setFont (Font());
  226857. }
  226858. ~CoreGraphicsContext()
  226859. {
  226860. CGContextRestoreGState (context);
  226861. CGContextRelease (context);
  226862. CGColorSpaceRelease (rgbColourSpace);
  226863. CGColorSpaceRelease (greyColourSpace);
  226864. }
  226865. bool isVectorDevice() const { return false; }
  226866. void setOrigin (int x, int y)
  226867. {
  226868. CGContextTranslateCTM (context, x, -y);
  226869. if (lastClipRectIsValid)
  226870. lastClipRect.translate (-x, -y);
  226871. }
  226872. void addTransform (const AffineTransform& transform)
  226873. {
  226874. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  226875. .translated (0, flipHeight)
  226876. .followedBy (transform)
  226877. .translated (0, -flipHeight)
  226878. .scaled (1.0f, -1.0f));
  226879. lastClipRectIsValid = false;
  226880. }
  226881. bool clipToRectangle (const Rectangle<int>& r)
  226882. {
  226883. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226884. if (lastClipRectIsValid)
  226885. {
  226886. // This is actually incorrect, because the actual clip region may be complex, and
  226887. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226888. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226889. // when calculating the resultant clip bounds, and makes the same mistake!
  226890. lastClipRect = lastClipRect.getIntersection (r);
  226891. return ! lastClipRect.isEmpty();
  226892. }
  226893. return ! isClipEmpty();
  226894. }
  226895. bool clipToRectangleList (const RectangleList& clipRegion)
  226896. {
  226897. if (clipRegion.isEmpty())
  226898. {
  226899. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226900. lastClipRectIsValid = true;
  226901. lastClipRect = Rectangle<int>();
  226902. return false;
  226903. }
  226904. else
  226905. {
  226906. const int numRects = clipRegion.getNumRectangles();
  226907. HeapBlock <CGRect> rects (numRects);
  226908. for (int i = 0; i < numRects; ++i)
  226909. {
  226910. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226911. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226912. }
  226913. CGContextClipToRects (context, rects, numRects);
  226914. lastClipRectIsValid = false;
  226915. return ! isClipEmpty();
  226916. }
  226917. }
  226918. void excludeClipRectangle (const Rectangle<int>& r)
  226919. {
  226920. RectangleList remaining (getClipBounds());
  226921. remaining.subtract (r);
  226922. clipToRectangleList (remaining);
  226923. lastClipRectIsValid = false;
  226924. }
  226925. void clipToPath (const Path& path, const AffineTransform& transform)
  226926. {
  226927. createPath (path, transform);
  226928. CGContextClip (context);
  226929. lastClipRectIsValid = false;
  226930. }
  226931. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226932. {
  226933. if (! transform.isSingularity())
  226934. {
  226935. Image singleChannelImage (sourceImage);
  226936. if (sourceImage.getFormat() != Image::SingleChannel)
  226937. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226938. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226939. flip();
  226940. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226941. applyTransform (t);
  226942. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226943. CGContextClipToMask (context, r, image);
  226944. applyTransform (t.inverted());
  226945. flip();
  226946. CGImageRelease (image);
  226947. lastClipRectIsValid = false;
  226948. }
  226949. }
  226950. bool clipRegionIntersects (const Rectangle<int>& r)
  226951. {
  226952. return getClipBounds().intersects (r);
  226953. }
  226954. const Rectangle<int> getClipBounds() const
  226955. {
  226956. if (! lastClipRectIsValid)
  226957. {
  226958. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226959. lastClipRectIsValid = true;
  226960. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226961. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226962. roundToInt (bounds.size.width),
  226963. roundToInt (bounds.size.height));
  226964. }
  226965. return lastClipRect;
  226966. }
  226967. bool isClipEmpty() const
  226968. {
  226969. return getClipBounds().isEmpty();
  226970. }
  226971. void saveState()
  226972. {
  226973. CGContextSaveGState (context);
  226974. stateStack.add (new SavedState (*state));
  226975. }
  226976. void restoreState()
  226977. {
  226978. CGContextRestoreGState (context);
  226979. SavedState* const top = stateStack.getLast();
  226980. if (top != 0)
  226981. {
  226982. state = top;
  226983. stateStack.removeLast (1, false);
  226984. lastClipRectIsValid = false;
  226985. }
  226986. else
  226987. {
  226988. jassertfalse; // trying to pop with an empty stack!
  226989. }
  226990. }
  226991. void setFill (const FillType& fillType)
  226992. {
  226993. state->fillType = fillType;
  226994. if (fillType.isColour())
  226995. {
  226996. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226997. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226998. CGContextSetAlpha (context, 1.0f);
  226999. }
  227000. }
  227001. void setOpacity (float newOpacity)
  227002. {
  227003. state->fillType.setOpacity (newOpacity);
  227004. setFill (state->fillType);
  227005. }
  227006. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  227007. {
  227008. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  227009. ? kCGInterpolationLow
  227010. : kCGInterpolationHigh);
  227011. }
  227012. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  227013. {
  227014. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  227015. }
  227016. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  227017. {
  227018. if (replaceExistingContents)
  227019. {
  227020. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  227021. CGContextClearRect (context, cgRect);
  227022. #else
  227023. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227024. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  227025. CGContextClearRect (context, cgRect);
  227026. else
  227027. #endif
  227028. CGContextSetBlendMode (context, kCGBlendModeCopy);
  227029. #endif
  227030. fillCGRect (cgRect, false);
  227031. CGContextSetBlendMode (context, kCGBlendModeNormal);
  227032. }
  227033. else
  227034. {
  227035. if (state->fillType.isColour())
  227036. {
  227037. CGContextFillRect (context, cgRect);
  227038. }
  227039. else if (state->fillType.isGradient())
  227040. {
  227041. CGContextSaveGState (context);
  227042. CGContextClipToRect (context, cgRect);
  227043. drawGradient();
  227044. CGContextRestoreGState (context);
  227045. }
  227046. else
  227047. {
  227048. CGContextSaveGState (context);
  227049. CGContextClipToRect (context, cgRect);
  227050. drawImage (state->fillType.image, state->fillType.transform, true);
  227051. CGContextRestoreGState (context);
  227052. }
  227053. }
  227054. }
  227055. void fillPath (const Path& path, const AffineTransform& transform)
  227056. {
  227057. CGContextSaveGState (context);
  227058. if (state->fillType.isColour())
  227059. {
  227060. flip();
  227061. applyTransform (transform);
  227062. createPath (path);
  227063. if (path.isUsingNonZeroWinding())
  227064. CGContextFillPath (context);
  227065. else
  227066. CGContextEOFillPath (context);
  227067. }
  227068. else
  227069. {
  227070. createPath (path, transform);
  227071. if (path.isUsingNonZeroWinding())
  227072. CGContextClip (context);
  227073. else
  227074. CGContextEOClip (context);
  227075. if (state->fillType.isGradient())
  227076. drawGradient();
  227077. else
  227078. drawImage (state->fillType.image, state->fillType.transform, true);
  227079. }
  227080. CGContextRestoreGState (context);
  227081. }
  227082. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  227083. {
  227084. const int iw = sourceImage.getWidth();
  227085. const int ih = sourceImage.getHeight();
  227086. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  227087. CGContextSaveGState (context);
  227088. CGContextSetAlpha (context, state->fillType.getOpacity());
  227089. flip();
  227090. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  227091. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  227092. if (fillEntireClipAsTiles)
  227093. {
  227094. #if JUCE_IOS
  227095. CGContextDrawTiledImage (context, imageRect, image);
  227096. #else
  227097. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  227098. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  227099. // if it's doing a transformation - it's quicker to just draw lots of images manually
  227100. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  227101. CGContextDrawTiledImage (context, imageRect, image);
  227102. else
  227103. #endif
  227104. {
  227105. // Fallback to manually doing a tiled fill on 10.4
  227106. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  227107. int x = 0, y = 0;
  227108. while (x > clip.origin.x) x -= iw;
  227109. while (y > clip.origin.y) y -= ih;
  227110. const int right = (int) (clip.origin.x + clip.size.width);
  227111. const int bottom = (int) (clip.origin.y + clip.size.height);
  227112. while (y < bottom)
  227113. {
  227114. for (int x2 = x; x2 < right; x2 += iw)
  227115. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  227116. y += ih;
  227117. }
  227118. }
  227119. #endif
  227120. }
  227121. else
  227122. {
  227123. CGContextDrawImage (context, imageRect, image);
  227124. }
  227125. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  227126. CGContextRestoreGState (context);
  227127. }
  227128. void drawLine (const Line<float>& line)
  227129. {
  227130. if (state->fillType.isColour())
  227131. {
  227132. CGContextSetLineCap (context, kCGLineCapSquare);
  227133. CGContextSetLineWidth (context, 1.0f);
  227134. CGContextSetRGBStrokeColor (context,
  227135. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  227136. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  227137. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  227138. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  227139. CGContextStrokeLineSegments (context, cgLine, 1);
  227140. }
  227141. else
  227142. {
  227143. Path p;
  227144. p.addLineSegment (line, 1.0f);
  227145. fillPath (p, AffineTransform::identity);
  227146. }
  227147. }
  227148. void drawVerticalLine (const int x, float top, float bottom)
  227149. {
  227150. if (state->fillType.isColour())
  227151. {
  227152. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227153. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  227154. #else
  227155. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227156. // the x co-ord slightly to trick it..
  227157. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  227158. #endif
  227159. }
  227160. else
  227161. {
  227162. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  227163. }
  227164. }
  227165. void drawHorizontalLine (const int y, float left, float right)
  227166. {
  227167. if (state->fillType.isColour())
  227168. {
  227169. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227170. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  227171. #else
  227172. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227173. // the x co-ord slightly to trick it..
  227174. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  227175. #endif
  227176. }
  227177. else
  227178. {
  227179. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  227180. }
  227181. }
  227182. void setFont (const Font& newFont)
  227183. {
  227184. if (state->font != newFont)
  227185. {
  227186. state->fontRef = 0;
  227187. state->font = newFont;
  227188. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227189. if (mf != 0)
  227190. {
  227191. state->fontRef = mf->fontRef;
  227192. CGContextSetFont (context, state->fontRef);
  227193. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227194. state->fontTransform = mf->renderingTransform;
  227195. state->fontTransform.a *= state->font.getHorizontalScale();
  227196. CGContextSetTextMatrix (context, state->fontTransform);
  227197. }
  227198. }
  227199. }
  227200. const Font getFont()
  227201. {
  227202. return state->font;
  227203. }
  227204. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227205. {
  227206. if (state->fontRef != 0 && state->fillType.isColour())
  227207. {
  227208. if (transform.isOnlyTranslation())
  227209. {
  227210. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  227211. CGGlyph g = glyphNumber;
  227212. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227213. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227214. }
  227215. else
  227216. {
  227217. CGContextSaveGState (context);
  227218. flip();
  227219. applyTransform (transform);
  227220. CGAffineTransform t = state->fontTransform;
  227221. t.d = -t.d;
  227222. CGContextSetTextMatrix (context, t);
  227223. CGGlyph g = glyphNumber;
  227224. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227225. CGContextRestoreGState (context);
  227226. }
  227227. }
  227228. else
  227229. {
  227230. Path p;
  227231. Font& f = state->font;
  227232. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227233. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227234. .followedBy (transform));
  227235. }
  227236. }
  227237. private:
  227238. CGContextRef context;
  227239. const CGFloat flipHeight;
  227240. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227241. CGFunctionCallbacks gradientCallbacks;
  227242. mutable Rectangle<int> lastClipRect;
  227243. mutable bool lastClipRectIsValid;
  227244. struct SavedState
  227245. {
  227246. SavedState()
  227247. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227248. {
  227249. }
  227250. SavedState (const SavedState& other)
  227251. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227252. fontTransform (other.fontTransform)
  227253. {
  227254. }
  227255. ~SavedState()
  227256. {
  227257. }
  227258. FillType fillType;
  227259. Font font;
  227260. CGFontRef fontRef;
  227261. CGAffineTransform fontTransform;
  227262. };
  227263. ScopedPointer <SavedState> state;
  227264. OwnedArray <SavedState> stateStack;
  227265. HeapBlock <PixelARGB> gradientLookupTable;
  227266. int numGradientLookupEntries;
  227267. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227268. {
  227269. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227270. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227271. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227272. colour.unpremultiply();
  227273. outData[0] = colour.getRed() / 255.0f;
  227274. outData[1] = colour.getGreen() / 255.0f;
  227275. outData[2] = colour.getBlue() / 255.0f;
  227276. outData[3] = colour.getAlpha() / 255.0f;
  227277. }
  227278. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227279. {
  227280. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227281. --numGradientLookupEntries;
  227282. CGShadingRef result = 0;
  227283. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227284. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227285. if (gradient.isRadial)
  227286. {
  227287. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227288. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227289. function, true, true);
  227290. }
  227291. else
  227292. {
  227293. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227294. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227295. function, true, true);
  227296. }
  227297. CGFunctionRelease (function);
  227298. return result;
  227299. }
  227300. void drawGradient()
  227301. {
  227302. flip();
  227303. applyTransform (state->fillType.transform);
  227304. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227305. // you draw a gradient with high quality interp enabled).
  227306. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227307. CGContextSetAlpha (context, state->fillType.getOpacity());
  227308. CGContextDrawShading (context, shading);
  227309. CGShadingRelease (shading);
  227310. }
  227311. void createPath (const Path& path) const
  227312. {
  227313. CGContextBeginPath (context);
  227314. Path::Iterator i (path);
  227315. while (i.next())
  227316. {
  227317. switch (i.elementType)
  227318. {
  227319. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227320. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227321. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227322. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227323. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227324. default: jassertfalse; break;
  227325. }
  227326. }
  227327. }
  227328. void createPath (const Path& path, const AffineTransform& transform) const
  227329. {
  227330. CGContextBeginPath (context);
  227331. Path::Iterator i (path);
  227332. while (i.next())
  227333. {
  227334. switch (i.elementType)
  227335. {
  227336. case Path::Iterator::startNewSubPath:
  227337. transform.transformPoint (i.x1, i.y1);
  227338. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227339. break;
  227340. case Path::Iterator::lineTo:
  227341. transform.transformPoint (i.x1, i.y1);
  227342. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227343. break;
  227344. case Path::Iterator::quadraticTo:
  227345. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227346. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227347. break;
  227348. case Path::Iterator::cubicTo:
  227349. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227350. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227351. break;
  227352. case Path::Iterator::closePath:
  227353. CGContextClosePath (context); break;
  227354. default:
  227355. jassertfalse;
  227356. break;
  227357. }
  227358. }
  227359. }
  227360. void flip() const
  227361. {
  227362. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227363. }
  227364. void applyTransform (const AffineTransform& transform) const
  227365. {
  227366. CGAffineTransform t;
  227367. t.a = transform.mat00;
  227368. t.b = transform.mat10;
  227369. t.c = transform.mat01;
  227370. t.d = transform.mat11;
  227371. t.tx = transform.mat02;
  227372. t.ty = transform.mat12;
  227373. CGContextConcatCTM (context, t);
  227374. }
  227375. CoreGraphicsContext (const CoreGraphicsContext&);
  227376. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227377. };
  227378. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227379. {
  227380. return new CoreGraphicsContext (context, height);
  227381. }
  227382. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227383. const Image juce_loadWithCoreImage (InputStream& input)
  227384. {
  227385. MemoryBlock data;
  227386. input.readIntoMemoryBlock (data, -1);
  227387. #if JUCE_IOS
  227388. JUCE_AUTORELEASEPOOL
  227389. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  227390. length: data.getSize()
  227391. freeWhenDone: NO]];
  227392. if (image != nil)
  227393. {
  227394. CGImageRef loadedImage = image.CGImage;
  227395. #else
  227396. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227397. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227398. CGDataProviderRelease (provider);
  227399. if (imageSource != 0)
  227400. {
  227401. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227402. CFRelease (imageSource);
  227403. #endif
  227404. if (loadedImage != 0)
  227405. {
  227406. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  227407. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  227408. && alphaInfo != kCGImageAlphaNoneSkipLast
  227409. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  227410. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  227411. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227412. hasAlphaChan, Image::NativeImage);
  227413. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227414. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227415. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227416. CGContextFlush (cgImage->context);
  227417. #if ! JUCE_IOS
  227418. CFRelease (loadedImage);
  227419. #endif
  227420. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  227421. // to find out whether the file they just loaded the image from had an alpha channel or not.
  227422. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  227423. return image;
  227424. }
  227425. }
  227426. return Image::null;
  227427. }
  227428. #endif
  227429. #endif
  227430. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227431. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227432. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227433. // compiled on its own).
  227434. #if JUCE_INCLUDED_FILE
  227435. class UIViewComponentPeer;
  227436. END_JUCE_NAMESPACE
  227437. #define JuceUIView MakeObjCClassName(JuceUIView)
  227438. @interface JuceUIView : UIView <UITextViewDelegate>
  227439. {
  227440. @public
  227441. UIViewComponentPeer* owner;
  227442. UITextView* hiddenTextView;
  227443. }
  227444. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227445. - (void) dealloc;
  227446. - (void) drawRect: (CGRect) r;
  227447. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227448. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227449. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227450. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227451. - (BOOL) becomeFirstResponder;
  227452. - (BOOL) resignFirstResponder;
  227453. - (BOOL) canBecomeFirstResponder;
  227454. - (void) asyncRepaint: (id) rect;
  227455. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227456. @end
  227457. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  227458. @interface JuceUIViewController : UIViewController
  227459. {
  227460. }
  227461. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  227462. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  227463. @end
  227464. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227465. @interface JuceUIWindow : UIWindow
  227466. {
  227467. @private
  227468. UIViewComponentPeer* owner;
  227469. bool isZooming;
  227470. }
  227471. - (void) setOwner: (UIViewComponentPeer*) owner;
  227472. - (void) becomeKeyWindow;
  227473. @end
  227474. BEGIN_JUCE_NAMESPACE
  227475. class UIViewComponentPeer : public ComponentPeer,
  227476. public FocusChangeListener
  227477. {
  227478. public:
  227479. UIViewComponentPeer (Component* const component,
  227480. const int windowStyleFlags,
  227481. UIView* viewToAttachTo);
  227482. ~UIViewComponentPeer();
  227483. void* getNativeHandle() const;
  227484. void setVisible (bool shouldBeVisible);
  227485. void setTitle (const String& title);
  227486. void setPosition (int x, int y);
  227487. void setSize (int w, int h);
  227488. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227489. const Rectangle<int> getBounds() const;
  227490. const Rectangle<int> getBounds (const bool global) const;
  227491. const Point<int> getScreenPosition() const;
  227492. const Point<int> localToGlobal (const Point<int>& relativePosition);
  227493. const Point<int> globalToLocal (const Point<int>& screenPosition);
  227494. void setAlpha (float newAlpha);
  227495. void setMinimised (bool shouldBeMinimised);
  227496. bool isMinimised() const;
  227497. void setFullScreen (bool shouldBeFullScreen);
  227498. bool isFullScreen() const;
  227499. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227500. const BorderSize getFrameSize() const;
  227501. bool setAlwaysOnTop (bool alwaysOnTop);
  227502. void toFront (bool makeActiveWindow);
  227503. void toBehind (ComponentPeer* other);
  227504. void setIcon (const Image& newIcon);
  227505. virtual void drawRect (CGRect r);
  227506. virtual bool canBecomeKeyWindow();
  227507. virtual bool windowShouldClose();
  227508. virtual void redirectMovedOrResized();
  227509. virtual CGRect constrainRect (CGRect r);
  227510. virtual void viewFocusGain();
  227511. virtual void viewFocusLoss();
  227512. bool isFocused() const;
  227513. void grabFocus();
  227514. void textInputRequired (const Point<int>& position);
  227515. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227516. void updateHiddenTextContent (TextInputTarget* target);
  227517. void globalFocusChanged (Component*);
  227518. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  227519. virtual void displayRotated();
  227520. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227521. void repaint (const Rectangle<int>& area);
  227522. void performAnyPendingRepaintsNow();
  227523. juce_UseDebuggingNewOperator
  227524. UIWindow* window;
  227525. JuceUIView* view;
  227526. JuceUIViewController* controller;
  227527. bool isSharedWindow, fullScreen, insideDrawRect;
  227528. static ModifierKeys currentModifiers;
  227529. static int64 getMouseTime (UIEvent* e)
  227530. {
  227531. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227532. + (int64) ([e timestamp] * 1000.0);
  227533. }
  227534. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  227535. {
  227536. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227537. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227538. {
  227539. case UIInterfaceOrientationPortrait:
  227540. return r;
  227541. case UIInterfaceOrientationPortraitUpsideDown:
  227542. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227543. r.getWidth(), r.getHeight());
  227544. case UIInterfaceOrientationLandscapeLeft:
  227545. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  227546. r.getHeight(), r.getWidth());
  227547. case UIInterfaceOrientationLandscapeRight:
  227548. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  227549. r.getHeight(), r.getWidth());
  227550. default: jassertfalse; // unknown orientation!
  227551. }
  227552. return r;
  227553. }
  227554. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  227555. {
  227556. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227557. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227558. {
  227559. case UIInterfaceOrientationPortrait:
  227560. return r;
  227561. case UIInterfaceOrientationPortraitUpsideDown:
  227562. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227563. r.getWidth(), r.getHeight());
  227564. case UIInterfaceOrientationLandscapeLeft:
  227565. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  227566. r.getHeight(), r.getWidth());
  227567. case UIInterfaceOrientationLandscapeRight:
  227568. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  227569. r.getHeight(), r.getWidth());
  227570. default: jassertfalse; // unknown orientation!
  227571. }
  227572. return r;
  227573. }
  227574. Array <UITouch*> currentTouches;
  227575. };
  227576. END_JUCE_NAMESPACE
  227577. @implementation JuceUIViewController
  227578. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  227579. {
  227580. JuceUIView* juceView = (JuceUIView*) [self view];
  227581. jassert (juceView != 0 && juceView->owner != 0);
  227582. return juceView->owner->shouldRotate (interfaceOrientation);
  227583. }
  227584. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  227585. {
  227586. JuceUIView* juceView = (JuceUIView*) [self view];
  227587. jassert (juceView != 0 && juceView->owner != 0);
  227588. juceView->owner->displayRotated();
  227589. }
  227590. @end
  227591. @implementation JuceUIView
  227592. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227593. withFrame: (CGRect) frame
  227594. {
  227595. [super initWithFrame: frame];
  227596. owner = owner_;
  227597. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227598. [self addSubview: hiddenTextView];
  227599. hiddenTextView.delegate = self;
  227600. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227601. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227602. return self;
  227603. }
  227604. - (void) dealloc
  227605. {
  227606. [hiddenTextView removeFromSuperview];
  227607. [hiddenTextView release];
  227608. [super dealloc];
  227609. }
  227610. - (void) drawRect: (CGRect) r
  227611. {
  227612. if (owner != 0)
  227613. owner->drawRect (r);
  227614. }
  227615. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227616. {
  227617. return false;
  227618. }
  227619. ModifierKeys UIViewComponentPeer::currentModifiers;
  227620. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227621. {
  227622. return UIViewComponentPeer::currentModifiers;
  227623. }
  227624. void ModifierKeys::updateCurrentModifiers() throw()
  227625. {
  227626. currentModifiers = UIViewComponentPeer::currentModifiers;
  227627. }
  227628. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227629. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227630. {
  227631. if (owner != 0)
  227632. owner->handleTouches (event, true, false, false);
  227633. }
  227634. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227635. {
  227636. if (owner != 0)
  227637. owner->handleTouches (event, false, false, false);
  227638. }
  227639. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227640. {
  227641. if (owner != 0)
  227642. owner->handleTouches (event, false, true, false);
  227643. }
  227644. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227645. {
  227646. if (owner != 0)
  227647. owner->handleTouches (event, false, true, true);
  227648. [self touchesEnded: touches withEvent: event];
  227649. }
  227650. - (BOOL) becomeFirstResponder
  227651. {
  227652. if (owner != 0)
  227653. owner->viewFocusGain();
  227654. return true;
  227655. }
  227656. - (BOOL) resignFirstResponder
  227657. {
  227658. if (owner != 0)
  227659. owner->viewFocusLoss();
  227660. return true;
  227661. }
  227662. - (BOOL) canBecomeFirstResponder
  227663. {
  227664. return owner != 0 && owner->canBecomeKeyWindow();
  227665. }
  227666. - (void) asyncRepaint: (id) rect
  227667. {
  227668. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227669. [self setNeedsDisplayInRect: *r];
  227670. }
  227671. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227672. {
  227673. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227674. nsStringToJuce (text));
  227675. }
  227676. @end
  227677. @implementation JuceUIWindow
  227678. - (void) setOwner: (UIViewComponentPeer*) owner_
  227679. {
  227680. owner = owner_;
  227681. isZooming = false;
  227682. }
  227683. - (void) becomeKeyWindow
  227684. {
  227685. [super becomeKeyWindow];
  227686. if (owner != 0)
  227687. owner->grabFocus();
  227688. }
  227689. @end
  227690. BEGIN_JUCE_NAMESPACE
  227691. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227692. const int windowStyleFlags,
  227693. UIView* viewToAttachTo)
  227694. : ComponentPeer (component, windowStyleFlags),
  227695. window (0),
  227696. view (0), controller (0),
  227697. isSharedWindow (viewToAttachTo != 0),
  227698. fullScreen (false),
  227699. insideDrawRect (false)
  227700. {
  227701. CGRect r = convertToCGRect (component->getLocalBounds());
  227702. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227703. if (isSharedWindow)
  227704. {
  227705. window = [viewToAttachTo window];
  227706. [viewToAttachTo addSubview: view];
  227707. setVisible (component->isVisible());
  227708. }
  227709. else
  227710. {
  227711. controller = [[JuceUIViewController alloc] init];
  227712. controller.view = view;
  227713. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  227714. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227715. window = [[JuceUIWindow alloc] init];
  227716. window.frame = r;
  227717. window.opaque = component->isOpaque();
  227718. view.opaque = component->isOpaque();
  227719. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227720. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227721. [((JuceUIWindow*) window) setOwner: this];
  227722. if (component->isAlwaysOnTop())
  227723. window.windowLevel = UIWindowLevelAlert;
  227724. [window addSubview: view];
  227725. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227726. view.hidden = ! component->isVisible();
  227727. window.hidden = ! component->isVisible();
  227728. view.multipleTouchEnabled = YES;
  227729. }
  227730. setTitle (component->getName());
  227731. Desktop::getInstance().addFocusChangeListener (this);
  227732. }
  227733. UIViewComponentPeer::~UIViewComponentPeer()
  227734. {
  227735. Desktop::getInstance().removeFocusChangeListener (this);
  227736. view->owner = 0;
  227737. [view removeFromSuperview];
  227738. [view release];
  227739. [controller release];
  227740. if (! isSharedWindow)
  227741. {
  227742. [((JuceUIWindow*) window) setOwner: 0];
  227743. [window release];
  227744. }
  227745. }
  227746. void* UIViewComponentPeer::getNativeHandle() const
  227747. {
  227748. return view;
  227749. }
  227750. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227751. {
  227752. view.hidden = ! shouldBeVisible;
  227753. if (! isSharedWindow)
  227754. window.hidden = ! shouldBeVisible;
  227755. }
  227756. void UIViewComponentPeer::setTitle (const String& title)
  227757. {
  227758. // xxx is this possible?
  227759. }
  227760. void UIViewComponentPeer::setPosition (int x, int y)
  227761. {
  227762. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227763. }
  227764. void UIViewComponentPeer::setSize (int w, int h)
  227765. {
  227766. setBounds (component->getX(), component->getY(), w, h, false);
  227767. }
  227768. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227769. {
  227770. fullScreen = isNowFullScreen;
  227771. w = jmax (0, w);
  227772. h = jmax (0, h);
  227773. if (isSharedWindow)
  227774. {
  227775. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  227776. if ([view frame].size.width != r.size.width
  227777. || [view frame].size.height != r.size.height)
  227778. [view setNeedsDisplay];
  227779. view.frame = r;
  227780. }
  227781. else
  227782. {
  227783. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  227784. window.frame = convertToCGRect (bounds);
  227785. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  227786. handleMovedOrResized();
  227787. }
  227788. }
  227789. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227790. {
  227791. CGRect r = [view frame];
  227792. if (global && [view window] != 0)
  227793. {
  227794. r = [view convertRect: r toView: nil];
  227795. CGRect wr = [[view window] frame];
  227796. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  227797. r.origin.x = windowBounds.getX();
  227798. r.origin.y = windowBounds.getY();
  227799. }
  227800. return convertToRectInt (r);
  227801. }
  227802. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227803. {
  227804. return getBounds (! isSharedWindow);
  227805. }
  227806. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227807. {
  227808. return getBounds (true).getPosition();
  227809. }
  227810. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  227811. {
  227812. return relativePosition + getScreenPosition();
  227813. }
  227814. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  227815. {
  227816. return screenPosition - getScreenPosition();
  227817. }
  227818. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227819. {
  227820. if (constrainer != 0)
  227821. {
  227822. CGRect current = [window frame];
  227823. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227824. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227825. Rectangle<int> pos (convertToRectInt (r));
  227826. Rectangle<int> original (convertToRectInt (current));
  227827. constrainer->checkBounds (pos, original,
  227828. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227829. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227830. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227831. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227832. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227833. r.origin.x = pos.getX();
  227834. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227835. r.size.width = pos.getWidth();
  227836. r.size.height = pos.getHeight();
  227837. }
  227838. return r;
  227839. }
  227840. void UIViewComponentPeer::setAlpha (float newAlpha)
  227841. {
  227842. [[view window] setAlpha: (CGFloat) newAlpha];
  227843. }
  227844. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227845. {
  227846. }
  227847. bool UIViewComponentPeer::isMinimised() const
  227848. {
  227849. return false;
  227850. }
  227851. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227852. {
  227853. if (! isSharedWindow)
  227854. {
  227855. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  227856. : lastNonFullscreenBounds);
  227857. if ((! shouldBeFullScreen) && r.isEmpty())
  227858. r = getBounds();
  227859. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227860. if (! r.isEmpty())
  227861. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227862. component->repaint();
  227863. }
  227864. }
  227865. bool UIViewComponentPeer::isFullScreen() const
  227866. {
  227867. return fullScreen;
  227868. }
  227869. namespace
  227870. {
  227871. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  227872. {
  227873. switch (interfaceOrientation)
  227874. {
  227875. case UIInterfaceOrientationPortrait: return Desktop::upright;
  227876. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  227877. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  227878. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  227879. default: jassertfalse; // unknown orientation!
  227880. }
  227881. return Desktop::upright;
  227882. }
  227883. }
  227884. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  227885. {
  227886. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  227887. }
  227888. void UIViewComponentPeer::displayRotated()
  227889. {
  227890. const Rectangle<int> oldArea (component->getBounds());
  227891. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  227892. Desktop::getInstance().refreshMonitorSizes();
  227893. if (fullScreen)
  227894. {
  227895. fullScreen = false;
  227896. setFullScreen (true);
  227897. }
  227898. else
  227899. {
  227900. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  227901. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  227902. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  227903. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  227904. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  227905. setBounds ((int) (l * newDesktop.getWidth()),
  227906. (int) (t * newDesktop.getHeight()),
  227907. (int) ((r - l) * newDesktop.getWidth()),
  227908. (int) ((b - t) * newDesktop.getHeight()),
  227909. false);
  227910. }
  227911. }
  227912. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227913. {
  227914. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227915. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227916. return false;
  227917. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  227918. withEvent: nil];
  227919. if (trueIfInAChildWindow)
  227920. return v != nil;
  227921. return v == view;
  227922. }
  227923. const BorderSize UIViewComponentPeer::getFrameSize() const
  227924. {
  227925. return BorderSize();
  227926. }
  227927. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227928. {
  227929. if (! isSharedWindow)
  227930. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227931. return true;
  227932. }
  227933. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227934. {
  227935. if (isSharedWindow)
  227936. [[view superview] bringSubviewToFront: view];
  227937. if (window != 0 && component->isVisible())
  227938. [window makeKeyAndVisible];
  227939. }
  227940. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227941. {
  227942. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227943. jassert (otherPeer != 0); // wrong type of window?
  227944. if (otherPeer != 0)
  227945. {
  227946. if (isSharedWindow)
  227947. {
  227948. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227949. }
  227950. else
  227951. {
  227952. jassertfalse; // don't know how to do this
  227953. }
  227954. }
  227955. }
  227956. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227957. {
  227958. // to do..
  227959. }
  227960. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227961. {
  227962. NSArray* touches = [[event touchesForView: view] allObjects];
  227963. for (unsigned int i = 0; i < [touches count]; ++i)
  227964. {
  227965. UITouch* touch = [touches objectAtIndex: i];
  227966. CGPoint p = [touch locationInView: view];
  227967. const Point<int> pos ((int) p.x, (int) p.y);
  227968. juce_lastMousePos = pos + getScreenPosition();
  227969. const int64 time = getMouseTime (event);
  227970. int touchIndex = currentTouches.indexOf (touch);
  227971. if (touchIndex < 0)
  227972. {
  227973. touchIndex = currentTouches.size();
  227974. currentTouches.add (touch);
  227975. }
  227976. if (isDown)
  227977. {
  227978. currentModifiers = currentModifiers.withoutMouseButtons();
  227979. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227980. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227981. }
  227982. else if (isUp)
  227983. {
  227984. currentModifiers = currentModifiers.withoutMouseButtons();
  227985. currentTouches.remove (touchIndex);
  227986. }
  227987. if (isCancel)
  227988. currentTouches.clear();
  227989. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227990. }
  227991. }
  227992. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227993. void UIViewComponentPeer::viewFocusGain()
  227994. {
  227995. if (currentlyFocusedPeer != this)
  227996. {
  227997. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227998. currentlyFocusedPeer->handleFocusLoss();
  227999. currentlyFocusedPeer = this;
  228000. handleFocusGain();
  228001. }
  228002. }
  228003. void UIViewComponentPeer::viewFocusLoss()
  228004. {
  228005. if (currentlyFocusedPeer == this)
  228006. {
  228007. currentlyFocusedPeer = 0;
  228008. handleFocusLoss();
  228009. }
  228010. }
  228011. void juce_HandleProcessFocusChange()
  228012. {
  228013. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  228014. {
  228015. if (Process::isForegroundProcess())
  228016. {
  228017. currentlyFocusedPeer->handleFocusGain();
  228018. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  228019. }
  228020. else
  228021. {
  228022. currentlyFocusedPeer->handleFocusLoss();
  228023. // turn kiosk mode off if we lose focus..
  228024. Desktop::getInstance().setKioskModeComponent (0);
  228025. }
  228026. }
  228027. }
  228028. bool UIViewComponentPeer::isFocused() const
  228029. {
  228030. return isSharedWindow ? this == currentlyFocusedPeer
  228031. : (window != 0 && [window isKeyWindow]);
  228032. }
  228033. void UIViewComponentPeer::grabFocus()
  228034. {
  228035. if (window != 0)
  228036. {
  228037. [window makeKeyWindow];
  228038. viewFocusGain();
  228039. }
  228040. }
  228041. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  228042. {
  228043. }
  228044. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  228045. {
  228046. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  228047. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  228048. }
  228049. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  228050. {
  228051. TextInputTarget* const target = findCurrentTextInputTarget();
  228052. if (target != 0)
  228053. {
  228054. const Range<int> currentSelection (target->getHighlightedRegion());
  228055. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  228056. if (currentSelection.isEmpty())
  228057. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  228058. target->insertTextAtCaret (text);
  228059. updateHiddenTextContent (target);
  228060. }
  228061. return NO;
  228062. }
  228063. void UIViewComponentPeer::globalFocusChanged (Component*)
  228064. {
  228065. TextInputTarget* const target = findCurrentTextInputTarget();
  228066. if (target != 0)
  228067. {
  228068. Component* comp = dynamic_cast<Component*> (target);
  228069. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  228070. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  228071. updateHiddenTextContent (target);
  228072. [view->hiddenTextView becomeFirstResponder];
  228073. }
  228074. else
  228075. {
  228076. [view->hiddenTextView resignFirstResponder];
  228077. }
  228078. }
  228079. void UIViewComponentPeer::drawRect (CGRect r)
  228080. {
  228081. if (r.size.width < 1.0f || r.size.height < 1.0f)
  228082. return;
  228083. CGContextRef cg = UIGraphicsGetCurrentContext();
  228084. if (! component->isOpaque())
  228085. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  228086. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  228087. CoreGraphicsContext g (cg, view.bounds.size.height);
  228088. insideDrawRect = true;
  228089. handlePaint (g);
  228090. insideDrawRect = false;
  228091. }
  228092. bool UIViewComponentPeer::canBecomeKeyWindow()
  228093. {
  228094. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  228095. }
  228096. bool UIViewComponentPeer::windowShouldClose()
  228097. {
  228098. if (! isValidPeer (this))
  228099. return YES;
  228100. handleUserClosingWindow();
  228101. return NO;
  228102. }
  228103. void UIViewComponentPeer::redirectMovedOrResized()
  228104. {
  228105. handleMovedOrResized();
  228106. }
  228107. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  228108. {
  228109. }
  228110. class AsyncRepaintMessage : public CallbackMessage
  228111. {
  228112. public:
  228113. UIViewComponentPeer* const peer;
  228114. const Rectangle<int> rect;
  228115. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  228116. : peer (peer_), rect (rect_)
  228117. {
  228118. }
  228119. void messageCallback()
  228120. {
  228121. if (ComponentPeer::isValidPeer (peer))
  228122. peer->repaint (rect);
  228123. }
  228124. };
  228125. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  228126. {
  228127. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  228128. {
  228129. (new AsyncRepaintMessage (this, area))->post();
  228130. }
  228131. else
  228132. {
  228133. [view setNeedsDisplayInRect: convertToCGRect (area)];
  228134. }
  228135. }
  228136. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  228137. {
  228138. }
  228139. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  228140. {
  228141. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  228142. }
  228143. const Image juce_createIconForFile (const File& file)
  228144. {
  228145. return Image::null;
  228146. }
  228147. void Desktop::createMouseInputSources()
  228148. {
  228149. for (int i = 0; i < 10; ++i)
  228150. mouseSources.add (new MouseInputSource (i, false));
  228151. }
  228152. bool Desktop::canUseSemiTransparentWindows() throw()
  228153. {
  228154. return true;
  228155. }
  228156. const Point<int> Desktop::getMousePosition()
  228157. {
  228158. return juce_lastMousePos;
  228159. }
  228160. void Desktop::setMousePosition (const Point<int>&)
  228161. {
  228162. }
  228163. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  228164. {
  228165. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  228166. }
  228167. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  228168. {
  228169. const ScopedAutoReleasePool pool;
  228170. monitorCoords.clear();
  228171. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  228172. : [[UIScreen mainScreen] bounds];
  228173. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  228174. }
  228175. const int KeyPress::spaceKey = ' ';
  228176. const int KeyPress::returnKey = 0x0d;
  228177. const int KeyPress::escapeKey = 0x1b;
  228178. const int KeyPress::backspaceKey = 0x7f;
  228179. const int KeyPress::leftKey = 0x1000;
  228180. const int KeyPress::rightKey = 0x1001;
  228181. const int KeyPress::upKey = 0x1002;
  228182. const int KeyPress::downKey = 0x1003;
  228183. const int KeyPress::pageUpKey = 0x1004;
  228184. const int KeyPress::pageDownKey = 0x1005;
  228185. const int KeyPress::endKey = 0x1006;
  228186. const int KeyPress::homeKey = 0x1007;
  228187. const int KeyPress::deleteKey = 0x1008;
  228188. const int KeyPress::insertKey = -1;
  228189. const int KeyPress::tabKey = 9;
  228190. const int KeyPress::F1Key = 0x2001;
  228191. const int KeyPress::F2Key = 0x2002;
  228192. const int KeyPress::F3Key = 0x2003;
  228193. const int KeyPress::F4Key = 0x2004;
  228194. const int KeyPress::F5Key = 0x2005;
  228195. const int KeyPress::F6Key = 0x2006;
  228196. const int KeyPress::F7Key = 0x2007;
  228197. const int KeyPress::F8Key = 0x2008;
  228198. const int KeyPress::F9Key = 0x2009;
  228199. const int KeyPress::F10Key = 0x200a;
  228200. const int KeyPress::F11Key = 0x200b;
  228201. const int KeyPress::F12Key = 0x200c;
  228202. const int KeyPress::F13Key = 0x200d;
  228203. const int KeyPress::F14Key = 0x200e;
  228204. const int KeyPress::F15Key = 0x200f;
  228205. const int KeyPress::F16Key = 0x2010;
  228206. const int KeyPress::numberPad0 = 0x30020;
  228207. const int KeyPress::numberPad1 = 0x30021;
  228208. const int KeyPress::numberPad2 = 0x30022;
  228209. const int KeyPress::numberPad3 = 0x30023;
  228210. const int KeyPress::numberPad4 = 0x30024;
  228211. const int KeyPress::numberPad5 = 0x30025;
  228212. const int KeyPress::numberPad6 = 0x30026;
  228213. const int KeyPress::numberPad7 = 0x30027;
  228214. const int KeyPress::numberPad8 = 0x30028;
  228215. const int KeyPress::numberPad9 = 0x30029;
  228216. const int KeyPress::numberPadAdd = 0x3002a;
  228217. const int KeyPress::numberPadSubtract = 0x3002b;
  228218. const int KeyPress::numberPadMultiply = 0x3002c;
  228219. const int KeyPress::numberPadDivide = 0x3002d;
  228220. const int KeyPress::numberPadSeparator = 0x3002e;
  228221. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228222. const int KeyPress::numberPadEquals = 0x30030;
  228223. const int KeyPress::numberPadDelete = 0x30031;
  228224. const int KeyPress::playKey = 0x30000;
  228225. const int KeyPress::stopKey = 0x30001;
  228226. const int KeyPress::fastForwardKey = 0x30002;
  228227. const int KeyPress::rewindKey = 0x30003;
  228228. #endif
  228229. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  228230. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  228231. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228232. // compiled on its own).
  228233. #if JUCE_INCLUDED_FILE
  228234. struct CallbackMessagePayload
  228235. {
  228236. MessageCallbackFunction* function;
  228237. void* parameter;
  228238. void* volatile result;
  228239. bool volatile hasBeenExecuted;
  228240. };
  228241. END_JUCE_NAMESPACE
  228242. @interface JuceCustomMessageHandler : NSObject
  228243. {
  228244. }
  228245. - (void) performCallback: (id) info;
  228246. @end
  228247. @implementation JuceCustomMessageHandler
  228248. - (void) performCallback: (id) info
  228249. {
  228250. if ([info isKindOfClass: [NSData class]])
  228251. {
  228252. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  228253. if (pl != 0)
  228254. {
  228255. pl->result = (*pl->function) (pl->parameter);
  228256. pl->hasBeenExecuted = true;
  228257. }
  228258. }
  228259. else
  228260. {
  228261. jassertfalse; // should never get here!
  228262. }
  228263. }
  228264. @end
  228265. BEGIN_JUCE_NAMESPACE
  228266. void MessageManager::runDispatchLoop()
  228267. {
  228268. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228269. runDispatchLoopUntil (-1);
  228270. }
  228271. void MessageManager::stopDispatchLoop()
  228272. {
  228273. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  228274. exit (0); // iPhone apps get no mercy..
  228275. }
  228276. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  228277. {
  228278. const ScopedAutoReleasePool pool;
  228279. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228280. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  228281. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  228282. while (! quitMessagePosted)
  228283. {
  228284. const ScopedAutoReleasePool pool;
  228285. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228286. beforeDate: endDate];
  228287. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  228288. break;
  228289. }
  228290. return ! quitMessagePosted;
  228291. }
  228292. namespace iOSMessageLoopHelpers
  228293. {
  228294. static CFRunLoopRef runLoop = 0;
  228295. static CFRunLoopSourceRef runLoopSource = 0;
  228296. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  228297. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  228298. void runLoopSourceCallback (void*)
  228299. {
  228300. if (pendingMessages != 0)
  228301. {
  228302. int numDispatched = 0;
  228303. do
  228304. {
  228305. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  228306. if (nextMessage == 0)
  228307. return;
  228308. const ScopedAutoReleasePool pool;
  228309. MessageManager::getInstance()->deliverMessage (nextMessage);
  228310. } while (++numDispatched <= 4);
  228311. CFRunLoopSourceSignal (runLoopSource);
  228312. CFRunLoopWakeUp (runLoop);
  228313. }
  228314. }
  228315. }
  228316. void MessageManager::doPlatformSpecificInitialisation()
  228317. {
  228318. using namespace iOSMessageLoopHelpers;
  228319. pendingMessages = new OwnedArray <Message, CriticalSection>();
  228320. runLoop = CFRunLoopGetCurrent();
  228321. CFRunLoopSourceContext sourceContext;
  228322. zerostruct (sourceContext);
  228323. sourceContext.perform = runLoopSourceCallback;
  228324. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  228325. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  228326. if (juceCustomMessageHandler == 0)
  228327. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  228328. }
  228329. void MessageManager::doPlatformSpecificShutdown()
  228330. {
  228331. using namespace iOSMessageLoopHelpers;
  228332. CFRunLoopSourceInvalidate (runLoopSource);
  228333. CFRelease (runLoopSource);
  228334. runLoopSource = 0;
  228335. deleteAndZero (pendingMessages);
  228336. if (juceCustomMessageHandler != 0)
  228337. {
  228338. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  228339. [juceCustomMessageHandler release];
  228340. juceCustomMessageHandler = 0;
  228341. }
  228342. }
  228343. bool juce_postMessageToSystemQueue (Message* message)
  228344. {
  228345. using namespace iOSMessageLoopHelpers;
  228346. if (pendingMessages != 0)
  228347. {
  228348. pendingMessages->add (message);
  228349. CFRunLoopSourceSignal (runLoopSource);
  228350. CFRunLoopWakeUp (runLoop);
  228351. }
  228352. return true;
  228353. }
  228354. void MessageManager::broadcastMessage (const String& value)
  228355. {
  228356. }
  228357. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  228358. {
  228359. using namespace iOSMessageLoopHelpers;
  228360. if (isThisTheMessageThread())
  228361. {
  228362. return (*callback) (data);
  228363. }
  228364. else
  228365. {
  228366. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  228367. // deadlock because the message manager is blocked from running, so can never
  228368. // call your function..
  228369. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  228370. const ScopedAutoReleasePool pool;
  228371. CallbackMessagePayload cmp;
  228372. cmp.function = callback;
  228373. cmp.parameter = data;
  228374. cmp.result = 0;
  228375. cmp.hasBeenExecuted = false;
  228376. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  228377. withObject: [NSData dataWithBytesNoCopy: &cmp
  228378. length: sizeof (cmp)
  228379. freeWhenDone: NO]
  228380. waitUntilDone: YES];
  228381. return cmp.result;
  228382. }
  228383. }
  228384. #endif
  228385. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  228386. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  228387. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228388. // compiled on its own).
  228389. #if JUCE_INCLUDED_FILE
  228390. #if JUCE_MAC
  228391. END_JUCE_NAMESPACE
  228392. using namespace JUCE_NAMESPACE;
  228393. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  228394. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228395. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  228396. #else
  228397. @interface JuceFileChooserDelegate : NSObject
  228398. #endif
  228399. {
  228400. StringArray* filters;
  228401. }
  228402. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  228403. - (void) dealloc;
  228404. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  228405. @end
  228406. @implementation JuceFileChooserDelegate
  228407. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  228408. {
  228409. [super init];
  228410. filters = filters_;
  228411. return self;
  228412. }
  228413. - (void) dealloc
  228414. {
  228415. delete filters;
  228416. [super dealloc];
  228417. }
  228418. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  228419. {
  228420. (void) sender;
  228421. const File f (nsStringToJuce (filename));
  228422. for (int i = filters->size(); --i >= 0;)
  228423. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228424. return true;
  228425. return f.isDirectory();
  228426. }
  228427. @end
  228428. BEGIN_JUCE_NAMESPACE
  228429. void FileChooser::showPlatformDialog (Array<File>& results,
  228430. const String& title,
  228431. const File& currentFileOrDirectory,
  228432. const String& filter,
  228433. bool selectsDirectory,
  228434. bool selectsFiles,
  228435. bool isSaveDialogue,
  228436. bool warnAboutOverwritingExistingFiles,
  228437. bool selectMultipleFiles,
  228438. FilePreviewComponent* extraInfoComponent)
  228439. {
  228440. const ScopedAutoReleasePool pool;
  228441. StringArray* filters = new StringArray();
  228442. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228443. filters->trim();
  228444. filters->removeEmptyStrings();
  228445. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228446. [delegate autorelease];
  228447. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228448. : [NSOpenPanel openPanel];
  228449. [panel setTitle: juceStringToNS (title)];
  228450. if (! isSaveDialogue)
  228451. {
  228452. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228453. [openPanel setCanChooseDirectories: selectsDirectory];
  228454. [openPanel setCanChooseFiles: selectsFiles];
  228455. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228456. }
  228457. [panel setDelegate: delegate];
  228458. if (isSaveDialogue || selectsDirectory)
  228459. [panel setCanCreateDirectories: YES];
  228460. String directory, filename;
  228461. if (currentFileOrDirectory.isDirectory())
  228462. {
  228463. directory = currentFileOrDirectory.getFullPathName();
  228464. }
  228465. else
  228466. {
  228467. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228468. filename = currentFileOrDirectory.getFileName();
  228469. }
  228470. if ([panel runModalForDirectory: juceStringToNS (directory)
  228471. file: juceStringToNS (filename)]
  228472. == NSOKButton)
  228473. {
  228474. if (isSaveDialogue)
  228475. {
  228476. results.add (File (nsStringToJuce ([panel filename])));
  228477. }
  228478. else
  228479. {
  228480. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228481. NSArray* urls = [openPanel filenames];
  228482. for (unsigned int i = 0; i < [urls count]; ++i)
  228483. {
  228484. NSString* f = [urls objectAtIndex: i];
  228485. results.add (File (nsStringToJuce (f)));
  228486. }
  228487. }
  228488. }
  228489. [panel setDelegate: nil];
  228490. }
  228491. #else
  228492. void FileChooser::showPlatformDialog (Array<File>& results,
  228493. const String& title,
  228494. const File& currentFileOrDirectory,
  228495. const String& filter,
  228496. bool selectsDirectory,
  228497. bool selectsFiles,
  228498. bool isSaveDialogue,
  228499. bool warnAboutOverwritingExistingFiles,
  228500. bool selectMultipleFiles,
  228501. FilePreviewComponent* extraInfoComponent)
  228502. {
  228503. const ScopedAutoReleasePool pool;
  228504. jassertfalse; //xxx to do
  228505. }
  228506. #endif
  228507. #endif
  228508. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228509. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228510. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228511. // compiled on its own).
  228512. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228513. #if JUCE_MAC
  228514. END_JUCE_NAMESPACE
  228515. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228516. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228517. {
  228518. CriticalSection* contextLock;
  228519. bool needsUpdate;
  228520. }
  228521. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228522. - (bool) makeActive;
  228523. - (void) makeInactive;
  228524. - (void) reshape;
  228525. @end
  228526. @implementation ThreadSafeNSOpenGLView
  228527. - (id) initWithFrame: (NSRect) frameRect
  228528. pixelFormat: (NSOpenGLPixelFormat*) format
  228529. {
  228530. contextLock = new CriticalSection();
  228531. self = [super initWithFrame: frameRect pixelFormat: format];
  228532. if (self != nil)
  228533. [[NSNotificationCenter defaultCenter] addObserver: self
  228534. selector: @selector (_surfaceNeedsUpdate:)
  228535. name: NSViewGlobalFrameDidChangeNotification
  228536. object: self];
  228537. return self;
  228538. }
  228539. - (void) dealloc
  228540. {
  228541. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228542. delete contextLock;
  228543. [super dealloc];
  228544. }
  228545. - (bool) makeActive
  228546. {
  228547. const ScopedLock sl (*contextLock);
  228548. if ([self openGLContext] == 0)
  228549. return false;
  228550. [[self openGLContext] makeCurrentContext];
  228551. if (needsUpdate)
  228552. {
  228553. [super update];
  228554. needsUpdate = false;
  228555. }
  228556. return true;
  228557. }
  228558. - (void) makeInactive
  228559. {
  228560. const ScopedLock sl (*contextLock);
  228561. [NSOpenGLContext clearCurrentContext];
  228562. }
  228563. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228564. {
  228565. const ScopedLock sl (*contextLock);
  228566. needsUpdate = true;
  228567. }
  228568. - (void) update
  228569. {
  228570. const ScopedLock sl (*contextLock);
  228571. needsUpdate = true;
  228572. }
  228573. - (void) reshape
  228574. {
  228575. const ScopedLock sl (*contextLock);
  228576. needsUpdate = true;
  228577. }
  228578. @end
  228579. BEGIN_JUCE_NAMESPACE
  228580. class WindowedGLContext : public OpenGLContext
  228581. {
  228582. public:
  228583. WindowedGLContext (Component* const component,
  228584. const OpenGLPixelFormat& pixelFormat_,
  228585. NSOpenGLContext* sharedContext)
  228586. : renderContext (0),
  228587. pixelFormat (pixelFormat_)
  228588. {
  228589. jassert (component != 0);
  228590. NSOpenGLPixelFormatAttribute attribs [64];
  228591. int n = 0;
  228592. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228593. attribs[n++] = NSOpenGLPFAAccelerated;
  228594. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228595. attribs[n++] = NSOpenGLPFAColorSize;
  228596. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228597. pixelFormat.greenBits,
  228598. pixelFormat.blueBits);
  228599. attribs[n++] = NSOpenGLPFAAlphaSize;
  228600. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228601. attribs[n++] = NSOpenGLPFADepthSize;
  228602. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228603. attribs[n++] = NSOpenGLPFAStencilSize;
  228604. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228605. attribs[n++] = NSOpenGLPFAAccumSize;
  228606. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228607. pixelFormat.accumulationBufferGreenBits,
  228608. pixelFormat.accumulationBufferBlueBits,
  228609. pixelFormat.accumulationBufferAlphaBits);
  228610. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228611. attribs[n++] = NSOpenGLPFASampleBuffers;
  228612. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228613. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228614. attribs[n++] = NSOpenGLPFANoRecovery;
  228615. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228616. NSOpenGLPixelFormat* format
  228617. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228618. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228619. pixelFormat: format];
  228620. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228621. shareContext: sharedContext] autorelease];
  228622. const GLint swapInterval = 1;
  228623. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228624. [view setOpenGLContext: renderContext];
  228625. [format release];
  228626. viewHolder = new NSViewComponentInternal (view, component);
  228627. }
  228628. ~WindowedGLContext()
  228629. {
  228630. deleteContext();
  228631. viewHolder = 0;
  228632. }
  228633. void deleteContext()
  228634. {
  228635. makeInactive();
  228636. [renderContext clearDrawable];
  228637. [renderContext setView: nil];
  228638. [view setOpenGLContext: nil];
  228639. renderContext = nil;
  228640. }
  228641. bool makeActive() const throw()
  228642. {
  228643. jassert (renderContext != 0);
  228644. if ([renderContext view] != view)
  228645. [renderContext setView: view];
  228646. [view makeActive];
  228647. return isActive();
  228648. }
  228649. bool makeInactive() const throw()
  228650. {
  228651. [view makeInactive];
  228652. return true;
  228653. }
  228654. bool isActive() const throw()
  228655. {
  228656. return [NSOpenGLContext currentContext] == renderContext;
  228657. }
  228658. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228659. void* getRawContext() const throw() { return renderContext; }
  228660. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228661. {
  228662. }
  228663. void swapBuffers()
  228664. {
  228665. [renderContext flushBuffer];
  228666. }
  228667. bool setSwapInterval (const int numFramesPerSwap)
  228668. {
  228669. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228670. forParameter: NSOpenGLCPSwapInterval];
  228671. return true;
  228672. }
  228673. int getSwapInterval() const
  228674. {
  228675. GLint numFrames = 0;
  228676. [renderContext getValues: &numFrames
  228677. forParameter: NSOpenGLCPSwapInterval];
  228678. return numFrames;
  228679. }
  228680. void repaint()
  228681. {
  228682. // we need to invalidate the juce view that holds this gl view, to make it
  228683. // cause a repaint callback
  228684. NSView* v = (NSView*) viewHolder->view;
  228685. NSRect r = [v frame];
  228686. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228687. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228688. // repaint message, thus never causing our paint() callback, and never repainting
  228689. // the comp. So invalidating just a little bit around the edge helps..
  228690. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228691. }
  228692. void* getNativeWindowHandle() const { return viewHolder->view; }
  228693. juce_UseDebuggingNewOperator
  228694. NSOpenGLContext* renderContext;
  228695. ThreadSafeNSOpenGLView* view;
  228696. private:
  228697. OpenGLPixelFormat pixelFormat;
  228698. ScopedPointer <NSViewComponentInternal> viewHolder;
  228699. WindowedGLContext (const WindowedGLContext&);
  228700. WindowedGLContext& operator= (const WindowedGLContext&);
  228701. };
  228702. OpenGLContext* OpenGLComponent::createContext()
  228703. {
  228704. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228705. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228706. return (c->renderContext != 0) ? c.release() : 0;
  228707. }
  228708. void* OpenGLComponent::getNativeWindowHandle() const
  228709. {
  228710. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228711. : 0;
  228712. }
  228713. void juce_glViewport (const int w, const int h)
  228714. {
  228715. glViewport (0, 0, w, h);
  228716. }
  228717. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228718. OwnedArray <OpenGLPixelFormat>& results)
  228719. {
  228720. /* GLint attribs [64];
  228721. int n = 0;
  228722. attribs[n++] = AGL_RGBA;
  228723. attribs[n++] = AGL_DOUBLEBUFFER;
  228724. attribs[n++] = AGL_ACCELERATED;
  228725. attribs[n++] = AGL_NO_RECOVERY;
  228726. attribs[n++] = AGL_NONE;
  228727. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228728. while (p != 0)
  228729. {
  228730. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228731. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228732. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228733. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228734. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228735. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228736. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228737. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228738. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228739. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228740. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228741. results.add (pf);
  228742. p = aglNextPixelFormat (p);
  228743. }*/
  228744. //jassertfalse // can't see how you do this in cocoa!
  228745. }
  228746. #else
  228747. END_JUCE_NAMESPACE
  228748. @interface JuceGLView : UIView
  228749. {
  228750. }
  228751. + (Class) layerClass;
  228752. @end
  228753. @implementation JuceGLView
  228754. + (Class) layerClass
  228755. {
  228756. return [CAEAGLLayer class];
  228757. }
  228758. @end
  228759. BEGIN_JUCE_NAMESPACE
  228760. class GLESContext : public OpenGLContext
  228761. {
  228762. public:
  228763. GLESContext (UIViewComponentPeer* peer,
  228764. Component* const component_,
  228765. const OpenGLPixelFormat& pixelFormat_,
  228766. const GLESContext* const sharedContext,
  228767. NSUInteger apiType)
  228768. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228769. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228770. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228771. {
  228772. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228773. view.opaque = YES;
  228774. view.hidden = NO;
  228775. view.backgroundColor = [UIColor blackColor];
  228776. view.userInteractionEnabled = NO;
  228777. glLayer = (CAEAGLLayer*) [view layer];
  228778. [peer->view addSubview: view];
  228779. if (sharedContext != 0)
  228780. context = [[EAGLContext alloc] initWithAPI: apiType
  228781. sharegroup: [sharedContext->context sharegroup]];
  228782. else
  228783. context = [[EAGLContext alloc] initWithAPI: apiType];
  228784. createGLBuffers();
  228785. }
  228786. ~GLESContext()
  228787. {
  228788. deleteContext();
  228789. [view removeFromSuperview];
  228790. [view release];
  228791. freeGLBuffers();
  228792. }
  228793. void deleteContext()
  228794. {
  228795. makeInactive();
  228796. [context release];
  228797. context = nil;
  228798. }
  228799. bool makeActive() const throw()
  228800. {
  228801. jassert (context != 0);
  228802. [EAGLContext setCurrentContext: context];
  228803. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228804. return true;
  228805. }
  228806. void swapBuffers()
  228807. {
  228808. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228809. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228810. }
  228811. bool makeInactive() const throw()
  228812. {
  228813. return [EAGLContext setCurrentContext: nil];
  228814. }
  228815. bool isActive() const throw()
  228816. {
  228817. return [EAGLContext currentContext] == context;
  228818. }
  228819. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228820. void* getRawContext() const throw() { return glLayer; }
  228821. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228822. {
  228823. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228824. if (lastWidth != w || lastHeight != h)
  228825. {
  228826. lastWidth = w;
  228827. lastHeight = h;
  228828. freeGLBuffers();
  228829. createGLBuffers();
  228830. }
  228831. }
  228832. bool setSwapInterval (const int numFramesPerSwap)
  228833. {
  228834. numFrames = numFramesPerSwap;
  228835. return true;
  228836. }
  228837. int getSwapInterval() const
  228838. {
  228839. return numFrames;
  228840. }
  228841. void repaint()
  228842. {
  228843. }
  228844. void createGLBuffers()
  228845. {
  228846. makeActive();
  228847. glGenFramebuffersOES (1, &frameBufferHandle);
  228848. glGenRenderbuffersOES (1, &colorBufferHandle);
  228849. glGenRenderbuffersOES (1, &depthBufferHandle);
  228850. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228851. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228852. GLint width, height;
  228853. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228854. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228855. if (useDepthBuffer)
  228856. {
  228857. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228858. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228859. }
  228860. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228861. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228862. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228863. if (useDepthBuffer)
  228864. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228865. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228866. }
  228867. void freeGLBuffers()
  228868. {
  228869. if (frameBufferHandle != 0)
  228870. {
  228871. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228872. frameBufferHandle = 0;
  228873. }
  228874. if (colorBufferHandle != 0)
  228875. {
  228876. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228877. colorBufferHandle = 0;
  228878. }
  228879. if (depthBufferHandle != 0)
  228880. {
  228881. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228882. depthBufferHandle = 0;
  228883. }
  228884. }
  228885. juce_UseDebuggingNewOperator
  228886. private:
  228887. Component::SafePointer<Component> component;
  228888. OpenGLPixelFormat pixelFormat;
  228889. JuceGLView* view;
  228890. CAEAGLLayer* glLayer;
  228891. EAGLContext* context;
  228892. bool useDepthBuffer;
  228893. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228894. int numFrames;
  228895. int lastWidth, lastHeight;
  228896. GLESContext (const GLESContext&);
  228897. GLESContext& operator= (const GLESContext&);
  228898. };
  228899. OpenGLContext* OpenGLComponent::createContext()
  228900. {
  228901. ScopedAutoReleasePool pool;
  228902. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228903. if (peer != 0)
  228904. return new GLESContext (peer, this, preferredPixelFormat,
  228905. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228906. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228907. return 0;
  228908. }
  228909. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228910. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228911. {
  228912. }
  228913. void juce_glViewport (const int w, const int h)
  228914. {
  228915. glViewport (0, 0, w, h);
  228916. }
  228917. #endif
  228918. #endif
  228919. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228920. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228921. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228922. // compiled on its own).
  228923. #if JUCE_INCLUDED_FILE
  228924. #if JUCE_MAC
  228925. namespace MouseCursorHelpers
  228926. {
  228927. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228928. {
  228929. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228930. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228931. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228932. [im release];
  228933. return c;
  228934. }
  228935. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228936. {
  228937. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228938. BufferedInputStream buf (fileStream, 4096);
  228939. PNGImageFormat pngFormat;
  228940. Image im (pngFormat.decodeImage (buf));
  228941. if (im.isValid())
  228942. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228943. jassertfalse;
  228944. return 0;
  228945. }
  228946. }
  228947. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228948. {
  228949. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228950. }
  228951. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228952. {
  228953. const ScopedAutoReleasePool pool;
  228954. NSCursor* c = 0;
  228955. switch (type)
  228956. {
  228957. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228958. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228959. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228960. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228961. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228962. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228963. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228964. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228965. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228966. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228967. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228968. case UpDownResizeCursor:
  228969. case TopEdgeResizeCursor:
  228970. case BottomEdgeResizeCursor:
  228971. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228972. case TopLeftCornerResizeCursor:
  228973. case BottomRightCornerResizeCursor:
  228974. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228975. case TopRightCornerResizeCursor:
  228976. case BottomLeftCornerResizeCursor:
  228977. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228978. case UpDownLeftRightResizeCursor:
  228979. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228980. default:
  228981. jassertfalse;
  228982. break;
  228983. }
  228984. [c retain];
  228985. return c;
  228986. }
  228987. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228988. {
  228989. [((NSCursor*) cursorHandle) release];
  228990. }
  228991. void MouseCursor::showInAllWindows() const
  228992. {
  228993. showInWindow (0);
  228994. }
  228995. void MouseCursor::showInWindow (ComponentPeer*) const
  228996. {
  228997. NSCursor* c = (NSCursor*) getHandle();
  228998. if (c == 0)
  228999. c = [NSCursor arrowCursor];
  229000. [c set];
  229001. }
  229002. #else
  229003. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  229004. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  229005. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  229006. void MouseCursor::showInAllWindows() const {}
  229007. void MouseCursor::showInWindow (ComponentPeer*) const {}
  229008. #endif
  229009. #endif
  229010. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  229011. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229012. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229013. // compiled on its own).
  229014. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  229015. #if JUCE_MAC
  229016. END_JUCE_NAMESPACE
  229017. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  229018. @interface DownloadClickDetector : NSObject
  229019. {
  229020. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  229021. }
  229022. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  229023. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  229024. request: (NSURLRequest*) request
  229025. frame: (WebFrame*) frame
  229026. decisionListener: (id<WebPolicyDecisionListener>) listener;
  229027. @end
  229028. @implementation DownloadClickDetector
  229029. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  229030. {
  229031. [super init];
  229032. ownerComponent = ownerComponent_;
  229033. return self;
  229034. }
  229035. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  229036. request: (NSURLRequest*) request
  229037. frame: (WebFrame*) frame
  229038. decisionListener: (id <WebPolicyDecisionListener>) listener
  229039. {
  229040. (void) sender;
  229041. (void) request;
  229042. (void) frame;
  229043. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  229044. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  229045. [listener use];
  229046. else
  229047. [listener ignore];
  229048. }
  229049. @end
  229050. BEGIN_JUCE_NAMESPACE
  229051. class WebBrowserComponentInternal : public NSViewComponent
  229052. {
  229053. public:
  229054. WebBrowserComponentInternal (WebBrowserComponent* owner)
  229055. {
  229056. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  229057. frameName: @""
  229058. groupName: @""];
  229059. setView (webView);
  229060. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  229061. [webView setPolicyDelegate: clickListener];
  229062. }
  229063. ~WebBrowserComponentInternal()
  229064. {
  229065. [webView setPolicyDelegate: nil];
  229066. [clickListener release];
  229067. setView (0);
  229068. }
  229069. void goToURL (const String& url,
  229070. const StringArray* headers,
  229071. const MemoryBlock* postData)
  229072. {
  229073. NSMutableURLRequest* r
  229074. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  229075. cachePolicy: NSURLRequestUseProtocolCachePolicy
  229076. timeoutInterval: 30.0];
  229077. if (postData != 0 && postData->getSize() > 0)
  229078. {
  229079. [r setHTTPMethod: @"POST"];
  229080. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  229081. length: postData->getSize()]];
  229082. }
  229083. if (headers != 0)
  229084. {
  229085. for (int i = 0; i < headers->size(); ++i)
  229086. {
  229087. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  229088. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  229089. [r setValue: juceStringToNS (headerValue)
  229090. forHTTPHeaderField: juceStringToNS (headerName)];
  229091. }
  229092. }
  229093. stop();
  229094. [[webView mainFrame] loadRequest: r];
  229095. }
  229096. void goBack()
  229097. {
  229098. [webView goBack];
  229099. }
  229100. void goForward()
  229101. {
  229102. [webView goForward];
  229103. }
  229104. void stop()
  229105. {
  229106. [webView stopLoading: nil];
  229107. }
  229108. void refresh()
  229109. {
  229110. [webView reload: nil];
  229111. }
  229112. void mouseMove (const MouseEvent&)
  229113. {
  229114. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  229115. // them work is to push them via this non-public method..
  229116. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  229117. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  229118. }
  229119. private:
  229120. WebView* webView;
  229121. DownloadClickDetector* clickListener;
  229122. };
  229123. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229124. : browser (0),
  229125. blankPageShown (false),
  229126. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  229127. {
  229128. setOpaque (true);
  229129. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  229130. }
  229131. WebBrowserComponent::~WebBrowserComponent()
  229132. {
  229133. deleteAndZero (browser);
  229134. }
  229135. void WebBrowserComponent::goToURL (const String& url,
  229136. const StringArray* headers,
  229137. const MemoryBlock* postData)
  229138. {
  229139. lastURL = url;
  229140. lastHeaders.clear();
  229141. if (headers != 0)
  229142. lastHeaders = *headers;
  229143. lastPostData.setSize (0);
  229144. if (postData != 0)
  229145. lastPostData = *postData;
  229146. blankPageShown = false;
  229147. browser->goToURL (url, headers, postData);
  229148. }
  229149. void WebBrowserComponent::stop()
  229150. {
  229151. browser->stop();
  229152. }
  229153. void WebBrowserComponent::goBack()
  229154. {
  229155. lastURL = String::empty;
  229156. blankPageShown = false;
  229157. browser->goBack();
  229158. }
  229159. void WebBrowserComponent::goForward()
  229160. {
  229161. lastURL = String::empty;
  229162. browser->goForward();
  229163. }
  229164. void WebBrowserComponent::refresh()
  229165. {
  229166. browser->refresh();
  229167. }
  229168. void WebBrowserComponent::paint (Graphics&)
  229169. {
  229170. }
  229171. void WebBrowserComponent::checkWindowAssociation()
  229172. {
  229173. if (isShowing())
  229174. {
  229175. if (blankPageShown)
  229176. goBack();
  229177. }
  229178. else
  229179. {
  229180. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  229181. {
  229182. // when the component becomes invisible, some stuff like flash
  229183. // carries on playing audio, so we need to force it onto a blank
  229184. // page to avoid this, (and send it back when it's made visible again).
  229185. blankPageShown = true;
  229186. browser->goToURL ("about:blank", 0, 0);
  229187. }
  229188. }
  229189. }
  229190. void WebBrowserComponent::reloadLastURL()
  229191. {
  229192. if (lastURL.isNotEmpty())
  229193. {
  229194. goToURL (lastURL, &lastHeaders, &lastPostData);
  229195. lastURL = String::empty;
  229196. }
  229197. }
  229198. void WebBrowserComponent::parentHierarchyChanged()
  229199. {
  229200. checkWindowAssociation();
  229201. }
  229202. void WebBrowserComponent::resized()
  229203. {
  229204. browser->setSize (getWidth(), getHeight());
  229205. }
  229206. void WebBrowserComponent::visibilityChanged()
  229207. {
  229208. checkWindowAssociation();
  229209. }
  229210. bool WebBrowserComponent::pageAboutToLoad (const String&)
  229211. {
  229212. return true;
  229213. }
  229214. #else
  229215. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229216. {
  229217. }
  229218. WebBrowserComponent::~WebBrowserComponent()
  229219. {
  229220. }
  229221. void WebBrowserComponent::goToURL (const String& url,
  229222. const StringArray* headers,
  229223. const MemoryBlock* postData)
  229224. {
  229225. }
  229226. void WebBrowserComponent::stop()
  229227. {
  229228. }
  229229. void WebBrowserComponent::goBack()
  229230. {
  229231. }
  229232. void WebBrowserComponent::goForward()
  229233. {
  229234. }
  229235. void WebBrowserComponent::refresh()
  229236. {
  229237. }
  229238. void WebBrowserComponent::paint (Graphics& g)
  229239. {
  229240. }
  229241. void WebBrowserComponent::checkWindowAssociation()
  229242. {
  229243. }
  229244. void WebBrowserComponent::reloadLastURL()
  229245. {
  229246. }
  229247. void WebBrowserComponent::parentHierarchyChanged()
  229248. {
  229249. }
  229250. void WebBrowserComponent::resized()
  229251. {
  229252. }
  229253. void WebBrowserComponent::visibilityChanged()
  229254. {
  229255. }
  229256. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  229257. {
  229258. return true;
  229259. }
  229260. #endif
  229261. #endif
  229262. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229263. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  229264. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229265. // compiled on its own).
  229266. #if JUCE_INCLUDED_FILE
  229267. class IPhoneAudioIODevice : public AudioIODevice
  229268. {
  229269. public:
  229270. IPhoneAudioIODevice (const String& deviceName)
  229271. : AudioIODevice (deviceName, "Audio"),
  229272. actualBufferSize (0),
  229273. isRunning (false),
  229274. audioUnit (0),
  229275. callback (0),
  229276. floatData (1, 2)
  229277. {
  229278. numInputChannels = 2;
  229279. numOutputChannels = 2;
  229280. preferredBufferSize = 0;
  229281. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  229282. updateDeviceInfo();
  229283. }
  229284. ~IPhoneAudioIODevice()
  229285. {
  229286. close();
  229287. }
  229288. const StringArray getOutputChannelNames()
  229289. {
  229290. StringArray s;
  229291. s.add ("Left");
  229292. s.add ("Right");
  229293. return s;
  229294. }
  229295. const StringArray getInputChannelNames()
  229296. {
  229297. StringArray s;
  229298. if (audioInputIsAvailable)
  229299. {
  229300. s.add ("Left");
  229301. s.add ("Right");
  229302. }
  229303. return s;
  229304. }
  229305. int getNumSampleRates()
  229306. {
  229307. return 1;
  229308. }
  229309. double getSampleRate (int index)
  229310. {
  229311. return sampleRate;
  229312. }
  229313. int getNumBufferSizesAvailable()
  229314. {
  229315. return 1;
  229316. }
  229317. int getBufferSizeSamples (int index)
  229318. {
  229319. return getDefaultBufferSize();
  229320. }
  229321. int getDefaultBufferSize()
  229322. {
  229323. return 1024;
  229324. }
  229325. const String open (const BigInteger& inputChannels,
  229326. const BigInteger& outputChannels,
  229327. double sampleRate,
  229328. int bufferSize)
  229329. {
  229330. close();
  229331. lastError = String::empty;
  229332. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  229333. // xxx set up channel mapping
  229334. activeOutputChans = outputChannels;
  229335. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  229336. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  229337. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  229338. activeInputChans = inputChannels;
  229339. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  229340. numInputChannels = activeInputChans.countNumberOfSetBits();
  229341. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  229342. AudioSessionSetActive (true);
  229343. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  229344. : kAudioSessionCategory_MediaPlayback;
  229345. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  229346. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  229347. fixAudioRouteIfSetToReceiver();
  229348. updateDeviceInfo();
  229349. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229350. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  229351. actualBufferSize = preferredBufferSize;
  229352. prepareFloatBuffers();
  229353. isRunning = true;
  229354. propertyChanged (0, 0, 0); // creates and starts the AU
  229355. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  229356. return lastError;
  229357. }
  229358. void close()
  229359. {
  229360. if (isRunning)
  229361. {
  229362. isRunning = false;
  229363. AudioSessionSetActive (false);
  229364. if (audioUnit != 0)
  229365. {
  229366. AudioComponentInstanceDispose (audioUnit);
  229367. audioUnit = 0;
  229368. }
  229369. }
  229370. }
  229371. bool isOpen()
  229372. {
  229373. return isRunning;
  229374. }
  229375. int getCurrentBufferSizeSamples()
  229376. {
  229377. return actualBufferSize;
  229378. }
  229379. double getCurrentSampleRate()
  229380. {
  229381. return sampleRate;
  229382. }
  229383. int getCurrentBitDepth()
  229384. {
  229385. return 16;
  229386. }
  229387. const BigInteger getActiveOutputChannels() const
  229388. {
  229389. return activeOutputChans;
  229390. }
  229391. const BigInteger getActiveInputChannels() const
  229392. {
  229393. return activeInputChans;
  229394. }
  229395. int getOutputLatencyInSamples()
  229396. {
  229397. return 0; //xxx
  229398. }
  229399. int getInputLatencyInSamples()
  229400. {
  229401. return 0; //xxx
  229402. }
  229403. void start (AudioIODeviceCallback* callback_)
  229404. {
  229405. if (isRunning && callback != callback_)
  229406. {
  229407. if (callback_ != 0)
  229408. callback_->audioDeviceAboutToStart (this);
  229409. const ScopedLock sl (callbackLock);
  229410. callback = callback_;
  229411. }
  229412. }
  229413. void stop()
  229414. {
  229415. if (isRunning)
  229416. {
  229417. AudioIODeviceCallback* lastCallback;
  229418. {
  229419. const ScopedLock sl (callbackLock);
  229420. lastCallback = callback;
  229421. callback = 0;
  229422. }
  229423. if (lastCallback != 0)
  229424. lastCallback->audioDeviceStopped();
  229425. }
  229426. }
  229427. bool isPlaying()
  229428. {
  229429. return isRunning && callback != 0;
  229430. }
  229431. const String getLastError()
  229432. {
  229433. return lastError;
  229434. }
  229435. private:
  229436. CriticalSection callbackLock;
  229437. Float64 sampleRate;
  229438. int numInputChannels, numOutputChannels;
  229439. int preferredBufferSize;
  229440. int actualBufferSize;
  229441. bool isRunning;
  229442. String lastError;
  229443. AudioStreamBasicDescription format;
  229444. AudioUnit audioUnit;
  229445. UInt32 audioInputIsAvailable;
  229446. AudioIODeviceCallback* callback;
  229447. BigInteger activeOutputChans, activeInputChans;
  229448. AudioSampleBuffer floatData;
  229449. float* inputChannels[3];
  229450. float* outputChannels[3];
  229451. bool monoInputChannelNumber, monoOutputChannelNumber;
  229452. void prepareFloatBuffers()
  229453. {
  229454. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229455. zerostruct (inputChannels);
  229456. zerostruct (outputChannels);
  229457. for (int i = 0; i < numInputChannels; ++i)
  229458. inputChannels[i] = floatData.getSampleData (i);
  229459. for (int i = 0; i < numOutputChannels; ++i)
  229460. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229461. }
  229462. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229463. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229464. {
  229465. OSStatus err = noErr;
  229466. if (audioInputIsAvailable)
  229467. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229468. const ScopedLock sl (callbackLock);
  229469. if (callback != 0)
  229470. {
  229471. if (audioInputIsAvailable && numInputChannels > 0)
  229472. {
  229473. short* shortData = (short*) ioData->mBuffers[0].mData;
  229474. if (numInputChannels >= 2)
  229475. {
  229476. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229477. {
  229478. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229479. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229480. }
  229481. }
  229482. else
  229483. {
  229484. if (monoInputChannelNumber > 0)
  229485. ++shortData;
  229486. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229487. {
  229488. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229489. ++shortData;
  229490. }
  229491. }
  229492. }
  229493. else
  229494. {
  229495. for (int i = numInputChannels; --i >= 0;)
  229496. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229497. }
  229498. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229499. outputChannels, numOutputChannels,
  229500. (int) inNumberFrames);
  229501. short* shortData = (short*) ioData->mBuffers[0].mData;
  229502. int n = 0;
  229503. if (numOutputChannels >= 2)
  229504. {
  229505. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229506. {
  229507. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229508. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229509. }
  229510. }
  229511. else if (numOutputChannels == 1)
  229512. {
  229513. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229514. {
  229515. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229516. shortData [n++] = s;
  229517. shortData [n++] = s;
  229518. }
  229519. }
  229520. else
  229521. {
  229522. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229523. }
  229524. }
  229525. else
  229526. {
  229527. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229528. }
  229529. return err;
  229530. }
  229531. void updateDeviceInfo()
  229532. {
  229533. UInt32 size = sizeof (sampleRate);
  229534. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229535. size = sizeof (audioInputIsAvailable);
  229536. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229537. }
  229538. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229539. {
  229540. if (! isRunning)
  229541. return;
  229542. if (inPropertyValue != 0)
  229543. {
  229544. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229545. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229546. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229547. SInt32 routeChangeReason;
  229548. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229549. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229550. fixAudioRouteIfSetToReceiver();
  229551. }
  229552. updateDeviceInfo();
  229553. createAudioUnit();
  229554. AudioSessionSetActive (true);
  229555. if (audioUnit != 0)
  229556. {
  229557. UInt32 formatSize = sizeof (format);
  229558. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229559. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229560. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229561. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229562. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229563. AudioOutputUnitStart (audioUnit);
  229564. }
  229565. }
  229566. void interruptionListener (UInt32 inInterruption)
  229567. {
  229568. /*if (inInterruption == kAudioSessionBeginInterruption)
  229569. {
  229570. isRunning = false;
  229571. AudioOutputUnitStop (audioUnit);
  229572. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229573. "This could have been interrupted by another application or by unplugging a headset",
  229574. @"Resume",
  229575. @"Cancel"))
  229576. {
  229577. isRunning = true;
  229578. propertyChanged (0, 0, 0);
  229579. }
  229580. }*/
  229581. if (inInterruption == kAudioSessionEndInterruption)
  229582. {
  229583. isRunning = true;
  229584. AudioSessionSetActive (true);
  229585. AudioOutputUnitStart (audioUnit);
  229586. }
  229587. }
  229588. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229589. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229590. {
  229591. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229592. }
  229593. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229594. {
  229595. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229596. }
  229597. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229598. {
  229599. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229600. }
  229601. void resetFormat (const int numChannels)
  229602. {
  229603. memset (&format, 0, sizeof (format));
  229604. format.mFormatID = kAudioFormatLinearPCM;
  229605. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229606. format.mBitsPerChannel = 8 * sizeof (short);
  229607. format.mChannelsPerFrame = 2;
  229608. format.mFramesPerPacket = 1;
  229609. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229610. }
  229611. bool createAudioUnit()
  229612. {
  229613. if (audioUnit != 0)
  229614. {
  229615. AudioComponentInstanceDispose (audioUnit);
  229616. audioUnit = 0;
  229617. }
  229618. resetFormat (2);
  229619. AudioComponentDescription desc;
  229620. desc.componentType = kAudioUnitType_Output;
  229621. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229622. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229623. desc.componentFlags = 0;
  229624. desc.componentFlagsMask = 0;
  229625. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229626. AudioComponentInstanceNew (comp, &audioUnit);
  229627. if (audioUnit == 0)
  229628. return false;
  229629. const UInt32 one = 1;
  229630. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229631. AudioChannelLayout layout;
  229632. layout.mChannelBitmap = 0;
  229633. layout.mNumberChannelDescriptions = 0;
  229634. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229635. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229636. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229637. AURenderCallbackStruct inputProc;
  229638. inputProc.inputProc = processStatic;
  229639. inputProc.inputProcRefCon = this;
  229640. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229641. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229642. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229643. AudioUnitInitialize (audioUnit);
  229644. return true;
  229645. }
  229646. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229647. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229648. static void fixAudioRouteIfSetToReceiver()
  229649. {
  229650. CFStringRef audioRoute = 0;
  229651. UInt32 propertySize = sizeof (audioRoute);
  229652. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229653. {
  229654. NSString* route = (NSString*) audioRoute;
  229655. //DBG ("audio route: " + nsStringToJuce (route));
  229656. if ([route hasPrefix: @"Receiver"])
  229657. {
  229658. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229659. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229660. }
  229661. CFRelease (audioRoute);
  229662. }
  229663. }
  229664. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229665. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229666. };
  229667. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229668. {
  229669. public:
  229670. IPhoneAudioIODeviceType()
  229671. : AudioIODeviceType ("iPhone Audio")
  229672. {
  229673. }
  229674. ~IPhoneAudioIODeviceType()
  229675. {
  229676. }
  229677. void scanForDevices()
  229678. {
  229679. }
  229680. const StringArray getDeviceNames (bool wantInputNames) const
  229681. {
  229682. StringArray s;
  229683. s.add ("iPhone Audio");
  229684. return s;
  229685. }
  229686. int getDefaultDeviceIndex (bool forInput) const
  229687. {
  229688. return 0;
  229689. }
  229690. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229691. {
  229692. return device != 0 ? 0 : -1;
  229693. }
  229694. bool hasSeparateInputsAndOutputs() const { return false; }
  229695. AudioIODevice* createDevice (const String& outputDeviceName,
  229696. const String& inputDeviceName)
  229697. {
  229698. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229699. {
  229700. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229701. : inputDeviceName);
  229702. }
  229703. return 0;
  229704. }
  229705. juce_UseDebuggingNewOperator
  229706. private:
  229707. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229708. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229709. };
  229710. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229711. {
  229712. return new IPhoneAudioIODeviceType();
  229713. }
  229714. #endif
  229715. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229716. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229717. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229718. // compiled on its own).
  229719. #if JUCE_INCLUDED_FILE
  229720. #if JUCE_MAC
  229721. namespace CoreMidiHelpers
  229722. {
  229723. static bool logError (const OSStatus err, const int lineNum)
  229724. {
  229725. if (err == noErr)
  229726. return true;
  229727. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229728. jassertfalse;
  229729. return false;
  229730. }
  229731. #undef CHECK_ERROR
  229732. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229733. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229734. {
  229735. String result;
  229736. CFStringRef str = 0;
  229737. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229738. if (str != 0)
  229739. {
  229740. result = PlatformUtilities::cfStringToJuceString (str);
  229741. CFRelease (str);
  229742. str = 0;
  229743. }
  229744. MIDIEntityRef entity = 0;
  229745. MIDIEndpointGetEntity (endpoint, &entity);
  229746. if (entity == 0)
  229747. return result; // probably virtual
  229748. if (result.isEmpty())
  229749. {
  229750. // endpoint name has zero length - try the entity
  229751. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229752. if (str != 0)
  229753. {
  229754. result += PlatformUtilities::cfStringToJuceString (str);
  229755. CFRelease (str);
  229756. str = 0;
  229757. }
  229758. }
  229759. // now consider the device's name
  229760. MIDIDeviceRef device = 0;
  229761. MIDIEntityGetDevice (entity, &device);
  229762. if (device == 0)
  229763. return result;
  229764. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229765. if (str != 0)
  229766. {
  229767. const String s (PlatformUtilities::cfStringToJuceString (str));
  229768. CFRelease (str);
  229769. // if an external device has only one entity, throw away
  229770. // the endpoint name and just use the device name
  229771. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229772. {
  229773. result = s;
  229774. }
  229775. else if (! result.startsWithIgnoreCase (s))
  229776. {
  229777. // prepend the device name to the entity name
  229778. result = (s + " " + result).trimEnd();
  229779. }
  229780. }
  229781. return result;
  229782. }
  229783. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229784. {
  229785. String result;
  229786. // Does the endpoint have connections?
  229787. CFDataRef connections = 0;
  229788. int numConnections = 0;
  229789. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229790. if (connections != 0)
  229791. {
  229792. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229793. if (numConnections > 0)
  229794. {
  229795. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229796. for (int i = 0; i < numConnections; ++i, ++pid)
  229797. {
  229798. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229799. MIDIObjectRef connObject;
  229800. MIDIObjectType connObjectType;
  229801. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229802. if (err == noErr)
  229803. {
  229804. String s;
  229805. if (connObjectType == kMIDIObjectType_ExternalSource
  229806. || connObjectType == kMIDIObjectType_ExternalDestination)
  229807. {
  229808. // Connected to an external device's endpoint (10.3 and later).
  229809. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229810. }
  229811. else
  229812. {
  229813. // Connected to an external device (10.2) (or something else, catch-all)
  229814. CFStringRef str = 0;
  229815. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229816. if (str != 0)
  229817. {
  229818. s = PlatformUtilities::cfStringToJuceString (str);
  229819. CFRelease (str);
  229820. }
  229821. }
  229822. if (s.isNotEmpty())
  229823. {
  229824. if (result.isNotEmpty())
  229825. result += ", ";
  229826. result += s;
  229827. }
  229828. }
  229829. }
  229830. }
  229831. CFRelease (connections);
  229832. }
  229833. if (result.isNotEmpty())
  229834. return result;
  229835. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229836. return getEndpointName (endpoint, false);
  229837. }
  229838. static MIDIClientRef getGlobalMidiClient()
  229839. {
  229840. static MIDIClientRef globalMidiClient = 0;
  229841. if (globalMidiClient == 0)
  229842. {
  229843. String name ("JUCE");
  229844. if (JUCEApplication::getInstance() != 0)
  229845. name = JUCEApplication::getInstance()->getApplicationName();
  229846. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229847. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229848. CFRelease (appName);
  229849. }
  229850. return globalMidiClient;
  229851. }
  229852. class MidiPortAndEndpoint
  229853. {
  229854. public:
  229855. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229856. : port (port_), endPoint (endPoint_)
  229857. {
  229858. }
  229859. ~MidiPortAndEndpoint()
  229860. {
  229861. if (port != 0)
  229862. MIDIPortDispose (port);
  229863. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229864. MIDIEndpointDispose (endPoint);
  229865. }
  229866. void send (const MIDIPacketList* const packets)
  229867. {
  229868. if (port != 0)
  229869. MIDISend (port, endPoint, packets);
  229870. else
  229871. MIDIReceived (endPoint, packets);
  229872. }
  229873. MIDIPortRef port;
  229874. MIDIEndpointRef endPoint;
  229875. };
  229876. class MidiPortAndCallback;
  229877. static CriticalSection callbackLock;
  229878. static Array<MidiPortAndCallback*> activeCallbacks;
  229879. class MidiPortAndCallback
  229880. {
  229881. public:
  229882. MidiPortAndCallback (MidiInputCallback& callback_)
  229883. : input (0), active (false), callback (callback_), concatenator (2048)
  229884. {
  229885. }
  229886. ~MidiPortAndCallback()
  229887. {
  229888. active = false;
  229889. {
  229890. const ScopedLock sl (callbackLock);
  229891. activeCallbacks.removeValue (this);
  229892. }
  229893. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229894. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229895. }
  229896. void handlePackets (const MIDIPacketList* const pktlist)
  229897. {
  229898. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229899. const ScopedLock sl (callbackLock);
  229900. if (activeCallbacks.contains (this) && active)
  229901. {
  229902. const MIDIPacket* packet = &pktlist->packet[0];
  229903. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229904. {
  229905. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229906. input, callback);
  229907. packet = MIDIPacketNext (packet);
  229908. }
  229909. }
  229910. }
  229911. MidiInput* input;
  229912. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229913. volatile bool active;
  229914. private:
  229915. MidiInputCallback& callback;
  229916. MidiDataConcatenator concatenator;
  229917. };
  229918. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229919. {
  229920. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229921. }
  229922. }
  229923. const StringArray MidiOutput::getDevices()
  229924. {
  229925. StringArray s;
  229926. const ItemCount num = MIDIGetNumberOfDestinations();
  229927. for (ItemCount i = 0; i < num; ++i)
  229928. {
  229929. MIDIEndpointRef dest = MIDIGetDestination (i);
  229930. if (dest != 0)
  229931. {
  229932. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229933. if (name.isEmpty())
  229934. name = "<error>";
  229935. s.add (name);
  229936. }
  229937. else
  229938. {
  229939. s.add ("<error>");
  229940. }
  229941. }
  229942. return s;
  229943. }
  229944. int MidiOutput::getDefaultDeviceIndex()
  229945. {
  229946. return 0;
  229947. }
  229948. MidiOutput* MidiOutput::openDevice (int index)
  229949. {
  229950. MidiOutput* mo = 0;
  229951. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229952. {
  229953. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229954. CFStringRef pname;
  229955. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229956. {
  229957. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229958. MIDIPortRef port;
  229959. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229960. {
  229961. mo = new MidiOutput();
  229962. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229963. }
  229964. CFRelease (pname);
  229965. }
  229966. }
  229967. return mo;
  229968. }
  229969. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229970. {
  229971. MidiOutput* mo = 0;
  229972. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229973. MIDIEndpointRef endPoint;
  229974. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229975. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229976. {
  229977. mo = new MidiOutput();
  229978. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229979. }
  229980. CFRelease (name);
  229981. return mo;
  229982. }
  229983. MidiOutput::~MidiOutput()
  229984. {
  229985. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229986. }
  229987. void MidiOutput::reset()
  229988. {
  229989. }
  229990. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229991. {
  229992. return false;
  229993. }
  229994. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229995. {
  229996. }
  229997. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229998. {
  229999. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  230000. if (message.isSysEx())
  230001. {
  230002. const int maxPacketSize = 256;
  230003. int pos = 0, bytesLeft = message.getRawDataSize();
  230004. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  230005. HeapBlock <MIDIPacketList> packets;
  230006. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  230007. packets->numPackets = numPackets;
  230008. MIDIPacket* p = packets->packet;
  230009. for (int i = 0; i < numPackets; ++i)
  230010. {
  230011. p->timeStamp = 0;
  230012. p->length = jmin (maxPacketSize, bytesLeft);
  230013. memcpy (p->data, message.getRawData() + pos, p->length);
  230014. pos += p->length;
  230015. bytesLeft -= p->length;
  230016. p = MIDIPacketNext (p);
  230017. }
  230018. mpe->send (packets);
  230019. }
  230020. else
  230021. {
  230022. MIDIPacketList packets;
  230023. packets.numPackets = 1;
  230024. packets.packet[0].timeStamp = 0;
  230025. packets.packet[0].length = message.getRawDataSize();
  230026. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  230027. mpe->send (&packets);
  230028. }
  230029. }
  230030. const StringArray MidiInput::getDevices()
  230031. {
  230032. StringArray s;
  230033. const ItemCount num = MIDIGetNumberOfSources();
  230034. for (ItemCount i = 0; i < num; ++i)
  230035. {
  230036. MIDIEndpointRef source = MIDIGetSource (i);
  230037. if (source != 0)
  230038. {
  230039. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  230040. if (name.isEmpty())
  230041. name = "<error>";
  230042. s.add (name);
  230043. }
  230044. else
  230045. {
  230046. s.add ("<error>");
  230047. }
  230048. }
  230049. return s;
  230050. }
  230051. int MidiInput::getDefaultDeviceIndex()
  230052. {
  230053. return 0;
  230054. }
  230055. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  230056. {
  230057. jassert (callback != 0);
  230058. using namespace CoreMidiHelpers;
  230059. MidiInput* newInput = 0;
  230060. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  230061. {
  230062. MIDIEndpointRef endPoint = MIDIGetSource (index);
  230063. if (endPoint != 0)
  230064. {
  230065. CFStringRef name;
  230066. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  230067. {
  230068. MIDIClientRef client = getGlobalMidiClient();
  230069. if (client != 0)
  230070. {
  230071. MIDIPortRef port;
  230072. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  230073. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  230074. {
  230075. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  230076. {
  230077. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  230078. newInput = new MidiInput (getDevices() [index]);
  230079. mpc->input = newInput;
  230080. newInput->internal = mpc;
  230081. const ScopedLock sl (callbackLock);
  230082. activeCallbacks.add (mpc.release());
  230083. }
  230084. else
  230085. {
  230086. CHECK_ERROR (MIDIPortDispose (port));
  230087. }
  230088. }
  230089. }
  230090. }
  230091. CFRelease (name);
  230092. }
  230093. }
  230094. return newInput;
  230095. }
  230096. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  230097. {
  230098. jassert (callback != 0);
  230099. using namespace CoreMidiHelpers;
  230100. MidiInput* mi = 0;
  230101. MIDIClientRef client = getGlobalMidiClient();
  230102. if (client != 0)
  230103. {
  230104. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  230105. mpc->active = false;
  230106. MIDIEndpointRef endPoint;
  230107. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  230108. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  230109. {
  230110. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  230111. mi = new MidiInput (deviceName);
  230112. mpc->input = mi;
  230113. mi->internal = mpc;
  230114. const ScopedLock sl (callbackLock);
  230115. activeCallbacks.add (mpc.release());
  230116. }
  230117. CFRelease (name);
  230118. }
  230119. return mi;
  230120. }
  230121. MidiInput::MidiInput (const String& name_)
  230122. : name (name_)
  230123. {
  230124. }
  230125. MidiInput::~MidiInput()
  230126. {
  230127. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  230128. }
  230129. void MidiInput::start()
  230130. {
  230131. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  230132. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  230133. }
  230134. void MidiInput::stop()
  230135. {
  230136. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  230137. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  230138. }
  230139. #undef CHECK_ERROR
  230140. #else // Stubs for iOS...
  230141. MidiOutput::~MidiOutput() {}
  230142. void MidiOutput::reset() {}
  230143. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  230144. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  230145. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  230146. const StringArray MidiOutput::getDevices() { return StringArray(); }
  230147. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  230148. const StringArray MidiInput::getDevices() { return StringArray(); }
  230149. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  230150. #endif
  230151. #endif
  230152. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  230153. #else
  230154. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  230155. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230156. // compiled on its own).
  230157. #if JUCE_INCLUDED_FILE
  230158. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230159. #define SUPPORT_10_4_FONTS 1
  230160. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  230161. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230162. #define SUPPORT_ONLY_10_4_FONTS 1
  230163. #endif
  230164. END_JUCE_NAMESPACE
  230165. @interface NSFont (PrivateHack)
  230166. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  230167. @end
  230168. BEGIN_JUCE_NAMESPACE
  230169. #endif
  230170. class MacTypeface : public Typeface
  230171. {
  230172. public:
  230173. MacTypeface (const Font& font)
  230174. : Typeface (font.getTypefaceName())
  230175. {
  230176. const ScopedAutoReleasePool pool;
  230177. renderingTransform = CGAffineTransformIdentity;
  230178. bool needsItalicTransform = false;
  230179. #if JUCE_IOS
  230180. NSString* fontName = juceStringToNS (font.getTypefaceName());
  230181. if (font.isItalic() || font.isBold())
  230182. {
  230183. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  230184. for (NSString* i in familyFonts)
  230185. {
  230186. const String fn (nsStringToJuce (i));
  230187. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  230188. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  230189. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  230190. || afterDash.containsIgnoreCase ("italic")
  230191. || fn.endsWithIgnoreCase ("oblique")
  230192. || fn.endsWithIgnoreCase ("italic");
  230193. if (probablyBold == font.isBold()
  230194. && probablyItalic == font.isItalic())
  230195. {
  230196. fontName = i;
  230197. needsItalicTransform = false;
  230198. break;
  230199. }
  230200. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  230201. {
  230202. fontName = i;
  230203. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  230204. }
  230205. }
  230206. if (needsItalicTransform)
  230207. renderingTransform.c = 0.15f;
  230208. }
  230209. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  230210. const int ascender = abs (CGFontGetAscent (fontRef));
  230211. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  230212. ascent = ascender / totalHeight;
  230213. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230214. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  230215. #else
  230216. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  230217. if (font.isItalic())
  230218. {
  230219. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  230220. toHaveTrait: NSItalicFontMask];
  230221. if (newFont == nsFont)
  230222. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  230223. nsFont = newFont;
  230224. }
  230225. if (font.isBold())
  230226. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  230227. [nsFont retain];
  230228. ascent = std::abs ((float) [nsFont ascender]);
  230229. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  230230. ascent /= totalSize;
  230231. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  230232. if (needsItalicTransform)
  230233. {
  230234. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  230235. renderingTransform.c = 0.15f;
  230236. }
  230237. #if SUPPORT_ONLY_10_4_FONTS
  230238. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230239. if (atsFont == 0)
  230240. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230241. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230242. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230243. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230244. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230245. #else
  230246. #if SUPPORT_10_4_FONTS
  230247. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230248. {
  230249. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230250. if (atsFont == 0)
  230251. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230252. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230253. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230254. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230255. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230256. }
  230257. else
  230258. #endif
  230259. {
  230260. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  230261. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  230262. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230263. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  230264. }
  230265. #endif
  230266. #endif
  230267. }
  230268. ~MacTypeface()
  230269. {
  230270. #if ! JUCE_IOS
  230271. [nsFont release];
  230272. #endif
  230273. if (fontRef != 0)
  230274. CGFontRelease (fontRef);
  230275. }
  230276. float getAscent() const
  230277. {
  230278. return ascent;
  230279. }
  230280. float getDescent() const
  230281. {
  230282. return 1.0f - ascent;
  230283. }
  230284. float getStringWidth (const String& text)
  230285. {
  230286. if (fontRef == 0 || text.isEmpty())
  230287. return 0;
  230288. const int length = text.length();
  230289. HeapBlock <CGGlyph> glyphs;
  230290. createGlyphsForString (text, length, glyphs);
  230291. float x = 0;
  230292. #if SUPPORT_ONLY_10_4_FONTS
  230293. HeapBlock <NSSize> advances (length);
  230294. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230295. for (int i = 0; i < length; ++i)
  230296. x += advances[i].width;
  230297. #else
  230298. #if SUPPORT_10_4_FONTS
  230299. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230300. {
  230301. HeapBlock <NSSize> advances (length);
  230302. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  230303. for (int i = 0; i < length; ++i)
  230304. x += advances[i].width;
  230305. }
  230306. else
  230307. #endif
  230308. {
  230309. HeapBlock <int> advances (length);
  230310. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230311. for (int i = 0; i < length; ++i)
  230312. x += advances[i];
  230313. }
  230314. #endif
  230315. return x * unitsToHeightScaleFactor;
  230316. }
  230317. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  230318. {
  230319. xOffsets.add (0);
  230320. if (fontRef == 0 || text.isEmpty())
  230321. return;
  230322. const int length = text.length();
  230323. HeapBlock <CGGlyph> glyphs;
  230324. createGlyphsForString (text, length, glyphs);
  230325. #if SUPPORT_ONLY_10_4_FONTS
  230326. HeapBlock <NSSize> advances (length);
  230327. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230328. int x = 0;
  230329. for (int i = 0; i < length; ++i)
  230330. {
  230331. x += advances[i].width;
  230332. xOffsets.add (x * unitsToHeightScaleFactor);
  230333. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230334. }
  230335. #else
  230336. #if SUPPORT_10_4_FONTS
  230337. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230338. {
  230339. HeapBlock <NSSize> advances (length);
  230340. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230341. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230342. float x = 0;
  230343. for (int i = 0; i < length; ++i)
  230344. {
  230345. x += advances[i].width;
  230346. xOffsets.add (x * unitsToHeightScaleFactor);
  230347. resultGlyphs.add (nsGlyphs[i]);
  230348. }
  230349. }
  230350. else
  230351. #endif
  230352. {
  230353. HeapBlock <int> advances (length);
  230354. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230355. {
  230356. int x = 0;
  230357. for (int i = 0; i < length; ++i)
  230358. {
  230359. x += advances [i];
  230360. xOffsets.add (x * unitsToHeightScaleFactor);
  230361. resultGlyphs.add (glyphs[i]);
  230362. }
  230363. }
  230364. }
  230365. #endif
  230366. }
  230367. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230368. {
  230369. #if JUCE_IOS
  230370. return false;
  230371. #else
  230372. if (nsFont == 0)
  230373. return false;
  230374. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230375. jassert (path.isEmpty());
  230376. const ScopedAutoReleasePool pool;
  230377. NSBezierPath* bez = [NSBezierPath bezierPath];
  230378. [bez moveToPoint: NSMakePoint (0, 0)];
  230379. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230380. inFont: nsFont];
  230381. for (int i = 0; i < [bez elementCount]; ++i)
  230382. {
  230383. NSPoint p[3];
  230384. switch ([bez elementAtIndex: i associatedPoints: p])
  230385. {
  230386. case NSMoveToBezierPathElement:
  230387. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230388. break;
  230389. case NSLineToBezierPathElement:
  230390. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230391. break;
  230392. case NSCurveToBezierPathElement:
  230393. 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);
  230394. break;
  230395. case NSClosePathBezierPathElement:
  230396. path.closeSubPath();
  230397. break;
  230398. default:
  230399. jassertfalse;
  230400. break;
  230401. }
  230402. }
  230403. path.applyTransform (pathTransform);
  230404. return true;
  230405. #endif
  230406. }
  230407. juce_UseDebuggingNewOperator
  230408. CGFontRef fontRef;
  230409. float fontHeightToCGSizeFactor;
  230410. CGAffineTransform renderingTransform;
  230411. private:
  230412. float ascent, unitsToHeightScaleFactor;
  230413. #if JUCE_IOS
  230414. #else
  230415. NSFont* nsFont;
  230416. AffineTransform pathTransform;
  230417. #endif
  230418. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230419. {
  230420. #if SUPPORT_10_4_FONTS
  230421. #if ! SUPPORT_ONLY_10_4_FONTS
  230422. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230423. #endif
  230424. {
  230425. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230426. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230427. for (int i = 0; i < length; ++i)
  230428. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230429. return;
  230430. }
  230431. #endif
  230432. #if ! SUPPORT_ONLY_10_4_FONTS
  230433. if (charToGlyphMapper == 0)
  230434. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230435. glyphs.malloc (length);
  230436. for (int i = 0; i < length; ++i)
  230437. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230438. #endif
  230439. }
  230440. #if ! SUPPORT_ONLY_10_4_FONTS
  230441. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230442. class CharToGlyphMapper
  230443. {
  230444. public:
  230445. CharToGlyphMapper (CGFontRef fontRef)
  230446. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230447. idRangeOffset (0), glyphIndexes (0)
  230448. {
  230449. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230450. if (cmapTable != 0)
  230451. {
  230452. const int numSubtables = getValue16 (cmapTable, 2);
  230453. for (int i = 0; i < numSubtables; ++i)
  230454. {
  230455. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230456. {
  230457. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230458. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230459. {
  230460. const int length = getValue16 (cmapTable, offset + 2);
  230461. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230462. segCount = segCountX2 / 2;
  230463. const int endCodeOffset = offset + 14;
  230464. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230465. const int idDeltaOffset = startCodeOffset + segCountX2;
  230466. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230467. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230468. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230469. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230470. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230471. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230472. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230473. }
  230474. break;
  230475. }
  230476. }
  230477. CFRelease (cmapTable);
  230478. }
  230479. }
  230480. ~CharToGlyphMapper()
  230481. {
  230482. if (endCode != 0)
  230483. {
  230484. CFRelease (endCode);
  230485. CFRelease (startCode);
  230486. CFRelease (idDelta);
  230487. CFRelease (idRangeOffset);
  230488. CFRelease (glyphIndexes);
  230489. }
  230490. }
  230491. int getGlyphForCharacter (const juce_wchar c) const
  230492. {
  230493. for (int i = 0; i < segCount; ++i)
  230494. {
  230495. if (getValue16 (endCode, i * 2) >= c)
  230496. {
  230497. const int start = getValue16 (startCode, i * 2);
  230498. if (start > c)
  230499. break;
  230500. const int delta = getValue16 (idDelta, i * 2);
  230501. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230502. if (rangeOffset == 0)
  230503. return delta + c;
  230504. else
  230505. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230506. }
  230507. }
  230508. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230509. return jmax (-1, (int) c - 29);
  230510. }
  230511. private:
  230512. int segCount;
  230513. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230514. static uint16 getValue16 (CFDataRef data, const int index)
  230515. {
  230516. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230517. }
  230518. static uint32 getValue32 (CFDataRef data, const int index)
  230519. {
  230520. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230521. }
  230522. };
  230523. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230524. #endif
  230525. MacTypeface (const MacTypeface&);
  230526. MacTypeface& operator= (const MacTypeface&);
  230527. };
  230528. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230529. {
  230530. return new MacTypeface (font);
  230531. }
  230532. const StringArray Font::findAllTypefaceNames()
  230533. {
  230534. StringArray names;
  230535. const ScopedAutoReleasePool pool;
  230536. #if JUCE_IOS
  230537. NSArray* fonts = [UIFont familyNames];
  230538. #else
  230539. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230540. #endif
  230541. for (unsigned int i = 0; i < [fonts count]; ++i)
  230542. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230543. names.sort (true);
  230544. return names;
  230545. }
  230546. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  230547. {
  230548. #if JUCE_IOS
  230549. defaultSans = "Helvetica";
  230550. defaultSerif = "Times New Roman";
  230551. defaultFixed = "Courier New";
  230552. #else
  230553. defaultSans = "Lucida Grande";
  230554. defaultSerif = "Times New Roman";
  230555. defaultFixed = "Monaco";
  230556. #endif
  230557. defaultFallback = "Arial Unicode MS";
  230558. }
  230559. #endif
  230560. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230561. // (must go before juce_mac_CoreGraphicsContext.mm)
  230562. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230563. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230564. // compiled on its own).
  230565. #if JUCE_INCLUDED_FILE
  230566. class CoreGraphicsImage : public Image::SharedImage
  230567. {
  230568. public:
  230569. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230570. : Image::SharedImage (format_, width_, height_)
  230571. {
  230572. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230573. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230574. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230575. imageData = imageDataAllocated;
  230576. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230577. : CGColorSpaceCreateDeviceRGB();
  230578. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230579. colourSpace, getCGImageFlags (format_));
  230580. CGColorSpaceRelease (colourSpace);
  230581. }
  230582. ~CoreGraphicsImage()
  230583. {
  230584. CGContextRelease (context);
  230585. }
  230586. Image::ImageType getType() const { return Image::NativeImage; }
  230587. LowLevelGraphicsContext* createLowLevelContext();
  230588. SharedImage* clone()
  230589. {
  230590. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230591. memcpy (im->imageData, imageData, lineStride * height);
  230592. return im;
  230593. }
  230594. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230595. {
  230596. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230597. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230598. {
  230599. return CGBitmapContextCreateImage (nativeImage->context);
  230600. }
  230601. else
  230602. {
  230603. const Image::BitmapData srcData (juceImage, false);
  230604. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230605. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230606. 8, srcData.pixelStride * 8, srcData.lineStride,
  230607. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230608. 0, true, kCGRenderingIntentDefault);
  230609. CGDataProviderRelease (provider);
  230610. return imageRef;
  230611. }
  230612. }
  230613. #if JUCE_MAC
  230614. static NSImage* createNSImage (const Image& image)
  230615. {
  230616. const ScopedAutoReleasePool pool;
  230617. NSImage* im = [[NSImage alloc] init];
  230618. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230619. [im lockFocus];
  230620. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230621. CGImageRef imageRef = createImage (image, false, colourSpace);
  230622. CGColorSpaceRelease (colourSpace);
  230623. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230624. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230625. CGImageRelease (imageRef);
  230626. [im unlockFocus];
  230627. return im;
  230628. }
  230629. #endif
  230630. CGContextRef context;
  230631. HeapBlock<uint8> imageDataAllocated;
  230632. private:
  230633. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230634. {
  230635. #if JUCE_BIG_ENDIAN
  230636. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230637. #else
  230638. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230639. #endif
  230640. }
  230641. };
  230642. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230643. {
  230644. #if USE_COREGRAPHICS_RENDERING
  230645. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230646. #else
  230647. return createSoftwareImage (format, width, height, clearImage);
  230648. #endif
  230649. }
  230650. class CoreGraphicsContext : public LowLevelGraphicsContext
  230651. {
  230652. public:
  230653. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230654. : context (context_),
  230655. flipHeight (flipHeight_),
  230656. lastClipRectIsValid (false),
  230657. state (new SavedState()),
  230658. numGradientLookupEntries (0)
  230659. {
  230660. CGContextRetain (context);
  230661. CGContextSaveGState(context);
  230662. CGContextSetShouldSmoothFonts (context, true);
  230663. CGContextSetShouldAntialias (context, true);
  230664. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230665. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230666. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230667. gradientCallbacks.version = 0;
  230668. gradientCallbacks.evaluate = gradientCallback;
  230669. gradientCallbacks.releaseInfo = 0;
  230670. setFont (Font());
  230671. }
  230672. ~CoreGraphicsContext()
  230673. {
  230674. CGContextRestoreGState (context);
  230675. CGContextRelease (context);
  230676. CGColorSpaceRelease (rgbColourSpace);
  230677. CGColorSpaceRelease (greyColourSpace);
  230678. }
  230679. bool isVectorDevice() const { return false; }
  230680. void setOrigin (int x, int y)
  230681. {
  230682. CGContextTranslateCTM (context, x, -y);
  230683. if (lastClipRectIsValid)
  230684. lastClipRect.translate (-x, -y);
  230685. }
  230686. void addTransform (const AffineTransform& transform)
  230687. {
  230688. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  230689. .translated (0, flipHeight)
  230690. .followedBy (transform)
  230691. .translated (0, -flipHeight)
  230692. .scaled (1.0f, -1.0f));
  230693. lastClipRectIsValid = false;
  230694. }
  230695. bool clipToRectangle (const Rectangle<int>& r)
  230696. {
  230697. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230698. if (lastClipRectIsValid)
  230699. {
  230700. // This is actually incorrect, because the actual clip region may be complex, and
  230701. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230702. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230703. // when calculating the resultant clip bounds, and makes the same mistake!
  230704. lastClipRect = lastClipRect.getIntersection (r);
  230705. return ! lastClipRect.isEmpty();
  230706. }
  230707. return ! isClipEmpty();
  230708. }
  230709. bool clipToRectangleList (const RectangleList& clipRegion)
  230710. {
  230711. if (clipRegion.isEmpty())
  230712. {
  230713. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230714. lastClipRectIsValid = true;
  230715. lastClipRect = Rectangle<int>();
  230716. return false;
  230717. }
  230718. else
  230719. {
  230720. const int numRects = clipRegion.getNumRectangles();
  230721. HeapBlock <CGRect> rects (numRects);
  230722. for (int i = 0; i < numRects; ++i)
  230723. {
  230724. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230725. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230726. }
  230727. CGContextClipToRects (context, rects, numRects);
  230728. lastClipRectIsValid = false;
  230729. return ! isClipEmpty();
  230730. }
  230731. }
  230732. void excludeClipRectangle (const Rectangle<int>& r)
  230733. {
  230734. RectangleList remaining (getClipBounds());
  230735. remaining.subtract (r);
  230736. clipToRectangleList (remaining);
  230737. lastClipRectIsValid = false;
  230738. }
  230739. void clipToPath (const Path& path, const AffineTransform& transform)
  230740. {
  230741. createPath (path, transform);
  230742. CGContextClip (context);
  230743. lastClipRectIsValid = false;
  230744. }
  230745. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230746. {
  230747. if (! transform.isSingularity())
  230748. {
  230749. Image singleChannelImage (sourceImage);
  230750. if (sourceImage.getFormat() != Image::SingleChannel)
  230751. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230752. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230753. flip();
  230754. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230755. applyTransform (t);
  230756. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230757. CGContextClipToMask (context, r, image);
  230758. applyTransform (t.inverted());
  230759. flip();
  230760. CGImageRelease (image);
  230761. lastClipRectIsValid = false;
  230762. }
  230763. }
  230764. bool clipRegionIntersects (const Rectangle<int>& r)
  230765. {
  230766. return getClipBounds().intersects (r);
  230767. }
  230768. const Rectangle<int> getClipBounds() const
  230769. {
  230770. if (! lastClipRectIsValid)
  230771. {
  230772. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230773. lastClipRectIsValid = true;
  230774. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230775. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230776. roundToInt (bounds.size.width),
  230777. roundToInt (bounds.size.height));
  230778. }
  230779. return lastClipRect;
  230780. }
  230781. bool isClipEmpty() const
  230782. {
  230783. return getClipBounds().isEmpty();
  230784. }
  230785. void saveState()
  230786. {
  230787. CGContextSaveGState (context);
  230788. stateStack.add (new SavedState (*state));
  230789. }
  230790. void restoreState()
  230791. {
  230792. CGContextRestoreGState (context);
  230793. SavedState* const top = stateStack.getLast();
  230794. if (top != 0)
  230795. {
  230796. state = top;
  230797. stateStack.removeLast (1, false);
  230798. lastClipRectIsValid = false;
  230799. }
  230800. else
  230801. {
  230802. jassertfalse; // trying to pop with an empty stack!
  230803. }
  230804. }
  230805. void setFill (const FillType& fillType)
  230806. {
  230807. state->fillType = fillType;
  230808. if (fillType.isColour())
  230809. {
  230810. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230811. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230812. CGContextSetAlpha (context, 1.0f);
  230813. }
  230814. }
  230815. void setOpacity (float newOpacity)
  230816. {
  230817. state->fillType.setOpacity (newOpacity);
  230818. setFill (state->fillType);
  230819. }
  230820. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230821. {
  230822. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230823. ? kCGInterpolationLow
  230824. : kCGInterpolationHigh);
  230825. }
  230826. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230827. {
  230828. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230829. }
  230830. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230831. {
  230832. if (replaceExistingContents)
  230833. {
  230834. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230835. CGContextClearRect (context, cgRect);
  230836. #else
  230837. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230838. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230839. CGContextClearRect (context, cgRect);
  230840. else
  230841. #endif
  230842. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230843. #endif
  230844. fillCGRect (cgRect, false);
  230845. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230846. }
  230847. else
  230848. {
  230849. if (state->fillType.isColour())
  230850. {
  230851. CGContextFillRect (context, cgRect);
  230852. }
  230853. else if (state->fillType.isGradient())
  230854. {
  230855. CGContextSaveGState (context);
  230856. CGContextClipToRect (context, cgRect);
  230857. drawGradient();
  230858. CGContextRestoreGState (context);
  230859. }
  230860. else
  230861. {
  230862. CGContextSaveGState (context);
  230863. CGContextClipToRect (context, cgRect);
  230864. drawImage (state->fillType.image, state->fillType.transform, true);
  230865. CGContextRestoreGState (context);
  230866. }
  230867. }
  230868. }
  230869. void fillPath (const Path& path, const AffineTransform& transform)
  230870. {
  230871. CGContextSaveGState (context);
  230872. if (state->fillType.isColour())
  230873. {
  230874. flip();
  230875. applyTransform (transform);
  230876. createPath (path);
  230877. if (path.isUsingNonZeroWinding())
  230878. CGContextFillPath (context);
  230879. else
  230880. CGContextEOFillPath (context);
  230881. }
  230882. else
  230883. {
  230884. createPath (path, transform);
  230885. if (path.isUsingNonZeroWinding())
  230886. CGContextClip (context);
  230887. else
  230888. CGContextEOClip (context);
  230889. if (state->fillType.isGradient())
  230890. drawGradient();
  230891. else
  230892. drawImage (state->fillType.image, state->fillType.transform, true);
  230893. }
  230894. CGContextRestoreGState (context);
  230895. }
  230896. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230897. {
  230898. const int iw = sourceImage.getWidth();
  230899. const int ih = sourceImage.getHeight();
  230900. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230901. CGContextSaveGState (context);
  230902. CGContextSetAlpha (context, state->fillType.getOpacity());
  230903. flip();
  230904. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230905. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230906. if (fillEntireClipAsTiles)
  230907. {
  230908. #if JUCE_IOS
  230909. CGContextDrawTiledImage (context, imageRect, image);
  230910. #else
  230911. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230912. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230913. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230914. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230915. CGContextDrawTiledImage (context, imageRect, image);
  230916. else
  230917. #endif
  230918. {
  230919. // Fallback to manually doing a tiled fill on 10.4
  230920. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230921. int x = 0, y = 0;
  230922. while (x > clip.origin.x) x -= iw;
  230923. while (y > clip.origin.y) y -= ih;
  230924. const int right = (int) (clip.origin.x + clip.size.width);
  230925. const int bottom = (int) (clip.origin.y + clip.size.height);
  230926. while (y < bottom)
  230927. {
  230928. for (int x2 = x; x2 < right; x2 += iw)
  230929. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230930. y += ih;
  230931. }
  230932. }
  230933. #endif
  230934. }
  230935. else
  230936. {
  230937. CGContextDrawImage (context, imageRect, image);
  230938. }
  230939. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230940. CGContextRestoreGState (context);
  230941. }
  230942. void drawLine (const Line<float>& line)
  230943. {
  230944. if (state->fillType.isColour())
  230945. {
  230946. CGContextSetLineCap (context, kCGLineCapSquare);
  230947. CGContextSetLineWidth (context, 1.0f);
  230948. CGContextSetRGBStrokeColor (context,
  230949. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230950. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230951. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230952. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230953. CGContextStrokeLineSegments (context, cgLine, 1);
  230954. }
  230955. else
  230956. {
  230957. Path p;
  230958. p.addLineSegment (line, 1.0f);
  230959. fillPath (p, AffineTransform::identity);
  230960. }
  230961. }
  230962. void drawVerticalLine (const int x, float top, float bottom)
  230963. {
  230964. if (state->fillType.isColour())
  230965. {
  230966. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230967. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230968. #else
  230969. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230970. // the x co-ord slightly to trick it..
  230971. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230972. #endif
  230973. }
  230974. else
  230975. {
  230976. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230977. }
  230978. }
  230979. void drawHorizontalLine (const int y, float left, float right)
  230980. {
  230981. if (state->fillType.isColour())
  230982. {
  230983. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230984. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230985. #else
  230986. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230987. // the x co-ord slightly to trick it..
  230988. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230989. #endif
  230990. }
  230991. else
  230992. {
  230993. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230994. }
  230995. }
  230996. void setFont (const Font& newFont)
  230997. {
  230998. if (state->font != newFont)
  230999. {
  231000. state->fontRef = 0;
  231001. state->font = newFont;
  231002. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  231003. if (mf != 0)
  231004. {
  231005. state->fontRef = mf->fontRef;
  231006. CGContextSetFont (context, state->fontRef);
  231007. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  231008. state->fontTransform = mf->renderingTransform;
  231009. state->fontTransform.a *= state->font.getHorizontalScale();
  231010. CGContextSetTextMatrix (context, state->fontTransform);
  231011. }
  231012. }
  231013. }
  231014. const Font getFont()
  231015. {
  231016. return state->font;
  231017. }
  231018. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  231019. {
  231020. if (state->fontRef != 0 && state->fillType.isColour())
  231021. {
  231022. if (transform.isOnlyTranslation())
  231023. {
  231024. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  231025. CGGlyph g = glyphNumber;
  231026. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  231027. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  231028. }
  231029. else
  231030. {
  231031. CGContextSaveGState (context);
  231032. flip();
  231033. applyTransform (transform);
  231034. CGAffineTransform t = state->fontTransform;
  231035. t.d = -t.d;
  231036. CGContextSetTextMatrix (context, t);
  231037. CGGlyph g = glyphNumber;
  231038. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  231039. CGContextRestoreGState (context);
  231040. }
  231041. }
  231042. else
  231043. {
  231044. Path p;
  231045. Font& f = state->font;
  231046. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  231047. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  231048. .followedBy (transform));
  231049. }
  231050. }
  231051. private:
  231052. CGContextRef context;
  231053. const CGFloat flipHeight;
  231054. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  231055. CGFunctionCallbacks gradientCallbacks;
  231056. mutable Rectangle<int> lastClipRect;
  231057. mutable bool lastClipRectIsValid;
  231058. struct SavedState
  231059. {
  231060. SavedState()
  231061. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  231062. {
  231063. }
  231064. SavedState (const SavedState& other)
  231065. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  231066. fontTransform (other.fontTransform)
  231067. {
  231068. }
  231069. ~SavedState()
  231070. {
  231071. }
  231072. FillType fillType;
  231073. Font font;
  231074. CGFontRef fontRef;
  231075. CGAffineTransform fontTransform;
  231076. };
  231077. ScopedPointer <SavedState> state;
  231078. OwnedArray <SavedState> stateStack;
  231079. HeapBlock <PixelARGB> gradientLookupTable;
  231080. int numGradientLookupEntries;
  231081. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  231082. {
  231083. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  231084. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  231085. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  231086. colour.unpremultiply();
  231087. outData[0] = colour.getRed() / 255.0f;
  231088. outData[1] = colour.getGreen() / 255.0f;
  231089. outData[2] = colour.getBlue() / 255.0f;
  231090. outData[3] = colour.getAlpha() / 255.0f;
  231091. }
  231092. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  231093. {
  231094. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  231095. --numGradientLookupEntries;
  231096. CGShadingRef result = 0;
  231097. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  231098. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  231099. if (gradient.isRadial)
  231100. {
  231101. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  231102. p1, gradient.point1.getDistanceFrom (gradient.point2),
  231103. function, true, true);
  231104. }
  231105. else
  231106. {
  231107. result = CGShadingCreateAxial (rgbColourSpace, p1,
  231108. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  231109. function, true, true);
  231110. }
  231111. CGFunctionRelease (function);
  231112. return result;
  231113. }
  231114. void drawGradient()
  231115. {
  231116. flip();
  231117. applyTransform (state->fillType.transform);
  231118. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  231119. // you draw a gradient with high quality interp enabled).
  231120. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  231121. CGContextSetAlpha (context, state->fillType.getOpacity());
  231122. CGContextDrawShading (context, shading);
  231123. CGShadingRelease (shading);
  231124. }
  231125. void createPath (const Path& path) const
  231126. {
  231127. CGContextBeginPath (context);
  231128. Path::Iterator i (path);
  231129. while (i.next())
  231130. {
  231131. switch (i.elementType)
  231132. {
  231133. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  231134. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  231135. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  231136. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  231137. case Path::Iterator::closePath: CGContextClosePath (context); break;
  231138. default: jassertfalse; break;
  231139. }
  231140. }
  231141. }
  231142. void createPath (const Path& path, const AffineTransform& transform) const
  231143. {
  231144. CGContextBeginPath (context);
  231145. Path::Iterator i (path);
  231146. while (i.next())
  231147. {
  231148. switch (i.elementType)
  231149. {
  231150. case Path::Iterator::startNewSubPath:
  231151. transform.transformPoint (i.x1, i.y1);
  231152. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  231153. break;
  231154. case Path::Iterator::lineTo:
  231155. transform.transformPoint (i.x1, i.y1);
  231156. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  231157. break;
  231158. case Path::Iterator::quadraticTo:
  231159. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  231160. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  231161. break;
  231162. case Path::Iterator::cubicTo:
  231163. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  231164. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  231165. break;
  231166. case Path::Iterator::closePath:
  231167. CGContextClosePath (context); break;
  231168. default:
  231169. jassertfalse;
  231170. break;
  231171. }
  231172. }
  231173. }
  231174. void flip() const
  231175. {
  231176. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  231177. }
  231178. void applyTransform (const AffineTransform& transform) const
  231179. {
  231180. CGAffineTransform t;
  231181. t.a = transform.mat00;
  231182. t.b = transform.mat10;
  231183. t.c = transform.mat01;
  231184. t.d = transform.mat11;
  231185. t.tx = transform.mat02;
  231186. t.ty = transform.mat12;
  231187. CGContextConcatCTM (context, t);
  231188. }
  231189. CoreGraphicsContext (const CoreGraphicsContext&);
  231190. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  231191. };
  231192. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  231193. {
  231194. return new CoreGraphicsContext (context, height);
  231195. }
  231196. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  231197. const Image juce_loadWithCoreImage (InputStream& input)
  231198. {
  231199. MemoryBlock data;
  231200. input.readIntoMemoryBlock (data, -1);
  231201. #if JUCE_IOS
  231202. JUCE_AUTORELEASEPOOL
  231203. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  231204. length: data.getSize()
  231205. freeWhenDone: NO]];
  231206. if (image != nil)
  231207. {
  231208. CGImageRef loadedImage = image.CGImage;
  231209. #else
  231210. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  231211. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  231212. CGDataProviderRelease (provider);
  231213. if (imageSource != 0)
  231214. {
  231215. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  231216. CFRelease (imageSource);
  231217. #endif
  231218. if (loadedImage != 0)
  231219. {
  231220. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  231221. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  231222. && alphaInfo != kCGImageAlphaNoneSkipLast
  231223. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  231224. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  231225. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  231226. hasAlphaChan, Image::NativeImage);
  231227. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  231228. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  231229. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  231230. CGContextFlush (cgImage->context);
  231231. #if ! JUCE_IOS
  231232. CFRelease (loadedImage);
  231233. #endif
  231234. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  231235. // to find out whether the file they just loaded the image from had an alpha channel or not.
  231236. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  231237. return image;
  231238. }
  231239. }
  231240. return Image::null;
  231241. }
  231242. #endif
  231243. #endif
  231244. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  231245. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231246. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231247. // compiled on its own).
  231248. #if JUCE_INCLUDED_FILE
  231249. class NSViewComponentPeer;
  231250. END_JUCE_NAMESPACE
  231251. @interface NSEvent (JuceDeviceDelta)
  231252. - (float) deviceDeltaX;
  231253. - (float) deviceDeltaY;
  231254. @end
  231255. #define JuceNSView MakeObjCClassName(JuceNSView)
  231256. @interface JuceNSView : NSView<NSTextInput>
  231257. {
  231258. @public
  231259. NSViewComponentPeer* owner;
  231260. NSNotificationCenter* notificationCenter;
  231261. String* stringBeingComposed;
  231262. bool textWasInserted;
  231263. }
  231264. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  231265. - (void) dealloc;
  231266. - (BOOL) isOpaque;
  231267. - (void) drawRect: (NSRect) r;
  231268. - (void) mouseDown: (NSEvent*) ev;
  231269. - (void) asyncMouseDown: (NSEvent*) ev;
  231270. - (void) mouseUp: (NSEvent*) ev;
  231271. - (void) asyncMouseUp: (NSEvent*) ev;
  231272. - (void) mouseDragged: (NSEvent*) ev;
  231273. - (void) mouseMoved: (NSEvent*) ev;
  231274. - (void) mouseEntered: (NSEvent*) ev;
  231275. - (void) mouseExited: (NSEvent*) ev;
  231276. - (void) rightMouseDown: (NSEvent*) ev;
  231277. - (void) rightMouseDragged: (NSEvent*) ev;
  231278. - (void) rightMouseUp: (NSEvent*) ev;
  231279. - (void) otherMouseDown: (NSEvent*) ev;
  231280. - (void) otherMouseDragged: (NSEvent*) ev;
  231281. - (void) otherMouseUp: (NSEvent*) ev;
  231282. - (void) scrollWheel: (NSEvent*) ev;
  231283. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  231284. - (void) frameChanged: (NSNotification*) n;
  231285. - (void) viewDidMoveToWindow;
  231286. - (void) keyDown: (NSEvent*) ev;
  231287. - (void) keyUp: (NSEvent*) ev;
  231288. // NSTextInput Methods
  231289. - (void) insertText: (id) aString;
  231290. - (void) doCommandBySelector: (SEL) aSelector;
  231291. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  231292. - (void) unmarkText;
  231293. - (BOOL) hasMarkedText;
  231294. - (long) conversationIdentifier;
  231295. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  231296. - (NSRange) markedRange;
  231297. - (NSRange) selectedRange;
  231298. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  231299. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  231300. - (NSArray*) validAttributesForMarkedText;
  231301. - (void) flagsChanged: (NSEvent*) ev;
  231302. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231303. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  231304. #endif
  231305. - (BOOL) becomeFirstResponder;
  231306. - (BOOL) resignFirstResponder;
  231307. - (BOOL) acceptsFirstResponder;
  231308. - (void) asyncRepaint: (id) rect;
  231309. - (NSArray*) getSupportedDragTypes;
  231310. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  231311. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  231312. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  231313. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  231314. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  231315. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  231316. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  231317. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  231318. @end
  231319. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  231320. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231321. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  231322. #else
  231323. @interface JuceNSWindow : NSWindow
  231324. #endif
  231325. {
  231326. @private
  231327. NSViewComponentPeer* owner;
  231328. bool isZooming;
  231329. }
  231330. - (void) setOwner: (NSViewComponentPeer*) owner;
  231331. - (BOOL) canBecomeKeyWindow;
  231332. - (void) becomeKeyWindow;
  231333. - (BOOL) windowShouldClose: (id) window;
  231334. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  231335. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  231336. - (void) zoom: (id) sender;
  231337. @end
  231338. BEGIN_JUCE_NAMESPACE
  231339. class NSViewComponentPeer : public ComponentPeer
  231340. {
  231341. public:
  231342. NSViewComponentPeer (Component* const component,
  231343. const int windowStyleFlags,
  231344. NSView* viewToAttachTo);
  231345. ~NSViewComponentPeer();
  231346. void* getNativeHandle() const;
  231347. void setVisible (bool shouldBeVisible);
  231348. void setTitle (const String& title);
  231349. void setPosition (int x, int y);
  231350. void setSize (int w, int h);
  231351. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  231352. const Rectangle<int> getBounds (const bool global) const;
  231353. const Rectangle<int> getBounds() const;
  231354. const Point<int> getScreenPosition() const;
  231355. const Point<int> localToGlobal (const Point<int>& relativePosition);
  231356. const Point<int> globalToLocal (const Point<int>& screenPosition);
  231357. void setAlpha (float newAlpha);
  231358. void setMinimised (bool shouldBeMinimised);
  231359. bool isMinimised() const;
  231360. void setFullScreen (bool shouldBeFullScreen);
  231361. bool isFullScreen() const;
  231362. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231363. const BorderSize getFrameSize() const;
  231364. bool setAlwaysOnTop (bool alwaysOnTop);
  231365. void toFront (bool makeActiveWindow);
  231366. void toBehind (ComponentPeer* other);
  231367. void setIcon (const Image& newIcon);
  231368. const StringArray getAvailableRenderingEngines();
  231369. int getCurrentRenderingEngine() throw();
  231370. void setCurrentRenderingEngine (int index);
  231371. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231372. for example having more than one juce plugin loaded into a host, then when a
  231373. method is called, the actual code that runs might actually be in a different module
  231374. than the one you expect... So any calls to library functions or statics that are
  231375. made inside obj-c methods will probably end up getting executed in a different DLL's
  231376. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231377. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231378. virtual methods of an object that's known to live inside the right module's space.
  231379. */
  231380. virtual void redirectMouseDown (NSEvent* ev);
  231381. virtual void redirectMouseUp (NSEvent* ev);
  231382. virtual void redirectMouseDrag (NSEvent* ev);
  231383. virtual void redirectMouseMove (NSEvent* ev);
  231384. virtual void redirectMouseEnter (NSEvent* ev);
  231385. virtual void redirectMouseExit (NSEvent* ev);
  231386. virtual void redirectMouseWheel (NSEvent* ev);
  231387. void sendMouseEvent (NSEvent* ev);
  231388. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231389. virtual bool redirectKeyDown (NSEvent* ev);
  231390. virtual bool redirectKeyUp (NSEvent* ev);
  231391. virtual void redirectModKeyChange (NSEvent* ev);
  231392. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231393. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231394. #endif
  231395. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231396. virtual bool isOpaque();
  231397. virtual void drawRect (NSRect r);
  231398. virtual bool canBecomeKeyWindow();
  231399. virtual bool windowShouldClose();
  231400. virtual void redirectMovedOrResized();
  231401. virtual void viewMovedToWindow();
  231402. virtual NSRect constrainRect (NSRect r);
  231403. static void showArrowCursorIfNeeded();
  231404. static void updateModifiers (NSEvent* e);
  231405. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231406. static int getKeyCodeFromEvent (NSEvent* ev)
  231407. {
  231408. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231409. int keyCode = unmodified[0];
  231410. if (keyCode == 0x19) // (backwards-tab)
  231411. keyCode = '\t';
  231412. else if (keyCode == 0x03) // (enter)
  231413. keyCode = '\r';
  231414. else
  231415. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231416. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231417. {
  231418. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231419. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231420. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231421. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231422. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231423. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231424. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231425. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231426. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231427. if (keyCode == numPadConversions [i])
  231428. keyCode = numPadConversions [i + 1];
  231429. }
  231430. return keyCode;
  231431. }
  231432. static int64 getMouseTime (NSEvent* e)
  231433. {
  231434. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231435. + (int64) ([e timestamp] * 1000.0);
  231436. }
  231437. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231438. {
  231439. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231440. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231441. }
  231442. static int getModifierForButtonNumber (const NSInteger num)
  231443. {
  231444. return num == 0 ? ModifierKeys::leftButtonModifier
  231445. : (num == 1 ? ModifierKeys::rightButtonModifier
  231446. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231447. }
  231448. virtual void viewFocusGain();
  231449. virtual void viewFocusLoss();
  231450. bool isFocused() const;
  231451. void grabFocus();
  231452. void textInputRequired (const Point<int>& position);
  231453. void repaint (const Rectangle<int>& area);
  231454. void performAnyPendingRepaintsNow();
  231455. juce_UseDebuggingNewOperator
  231456. NSWindow* window;
  231457. JuceNSView* view;
  231458. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231459. static ModifierKeys currentModifiers;
  231460. static ComponentPeer* currentlyFocusedPeer;
  231461. static Array<int> keysCurrentlyDown;
  231462. };
  231463. END_JUCE_NAMESPACE
  231464. @implementation JuceNSView
  231465. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231466. withFrame: (NSRect) frame
  231467. {
  231468. [super initWithFrame: frame];
  231469. owner = owner_;
  231470. stringBeingComposed = 0;
  231471. textWasInserted = false;
  231472. notificationCenter = [NSNotificationCenter defaultCenter];
  231473. [notificationCenter addObserver: self
  231474. selector: @selector (frameChanged:)
  231475. name: NSViewFrameDidChangeNotification
  231476. object: self];
  231477. if (! owner_->isSharedWindow)
  231478. {
  231479. [notificationCenter addObserver: self
  231480. selector: @selector (frameChanged:)
  231481. name: NSWindowDidMoveNotification
  231482. object: owner_->window];
  231483. }
  231484. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231485. return self;
  231486. }
  231487. - (void) dealloc
  231488. {
  231489. [notificationCenter removeObserver: self];
  231490. delete stringBeingComposed;
  231491. [super dealloc];
  231492. }
  231493. - (void) drawRect: (NSRect) r
  231494. {
  231495. if (owner != 0)
  231496. owner->drawRect (r);
  231497. }
  231498. - (BOOL) isOpaque
  231499. {
  231500. return owner == 0 || owner->isOpaque();
  231501. }
  231502. - (void) mouseDown: (NSEvent*) ev
  231503. {
  231504. if (JUCEApplication::isStandaloneApp())
  231505. [self asyncMouseDown: ev];
  231506. else
  231507. // In some host situations, the host will stop modal loops from working
  231508. // correctly if they're called from a mouse event, so we'll trigger
  231509. // the event asynchronously..
  231510. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231511. withObject: ev
  231512. waitUntilDone: NO];
  231513. }
  231514. - (void) asyncMouseDown: (NSEvent*) ev
  231515. {
  231516. if (owner != 0)
  231517. owner->redirectMouseDown (ev);
  231518. }
  231519. - (void) mouseUp: (NSEvent*) ev
  231520. {
  231521. if (! JUCEApplication::isStandaloneApp())
  231522. [self asyncMouseUp: ev];
  231523. else
  231524. // In some host situations, the host will stop modal loops from working
  231525. // correctly if they're called from a mouse event, so we'll trigger
  231526. // the event asynchronously..
  231527. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231528. withObject: ev
  231529. waitUntilDone: NO];
  231530. }
  231531. - (void) asyncMouseUp: (NSEvent*) ev
  231532. {
  231533. if (owner != 0)
  231534. owner->redirectMouseUp (ev);
  231535. }
  231536. - (void) mouseDragged: (NSEvent*) ev
  231537. {
  231538. if (owner != 0)
  231539. owner->redirectMouseDrag (ev);
  231540. }
  231541. - (void) mouseMoved: (NSEvent*) ev
  231542. {
  231543. if (owner != 0)
  231544. owner->redirectMouseMove (ev);
  231545. }
  231546. - (void) mouseEntered: (NSEvent*) ev
  231547. {
  231548. if (owner != 0)
  231549. owner->redirectMouseEnter (ev);
  231550. }
  231551. - (void) mouseExited: (NSEvent*) ev
  231552. {
  231553. if (owner != 0)
  231554. owner->redirectMouseExit (ev);
  231555. }
  231556. - (void) rightMouseDown: (NSEvent*) ev
  231557. {
  231558. [self mouseDown: ev];
  231559. }
  231560. - (void) rightMouseDragged: (NSEvent*) ev
  231561. {
  231562. [self mouseDragged: ev];
  231563. }
  231564. - (void) rightMouseUp: (NSEvent*) ev
  231565. {
  231566. [self mouseUp: ev];
  231567. }
  231568. - (void) otherMouseDown: (NSEvent*) ev
  231569. {
  231570. [self mouseDown: ev];
  231571. }
  231572. - (void) otherMouseDragged: (NSEvent*) ev
  231573. {
  231574. [self mouseDragged: ev];
  231575. }
  231576. - (void) otherMouseUp: (NSEvent*) ev
  231577. {
  231578. [self mouseUp: ev];
  231579. }
  231580. - (void) scrollWheel: (NSEvent*) ev
  231581. {
  231582. if (owner != 0)
  231583. owner->redirectMouseWheel (ev);
  231584. }
  231585. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231586. {
  231587. (void) ev;
  231588. return YES;
  231589. }
  231590. - (void) frameChanged: (NSNotification*) n
  231591. {
  231592. (void) n;
  231593. if (owner != 0)
  231594. owner->redirectMovedOrResized();
  231595. }
  231596. - (void) viewDidMoveToWindow
  231597. {
  231598. if (owner != 0)
  231599. owner->viewMovedToWindow();
  231600. }
  231601. - (void) asyncRepaint: (id) rect
  231602. {
  231603. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231604. [self setNeedsDisplayInRect: *r];
  231605. }
  231606. - (void) keyDown: (NSEvent*) ev
  231607. {
  231608. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231609. textWasInserted = false;
  231610. if (target != 0)
  231611. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231612. else
  231613. deleteAndZero (stringBeingComposed);
  231614. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231615. [super keyDown: ev];
  231616. }
  231617. - (void) keyUp: (NSEvent*) ev
  231618. {
  231619. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231620. [super keyUp: ev];
  231621. }
  231622. - (void) insertText: (id) aString
  231623. {
  231624. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231625. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231626. if ([newText length] > 0)
  231627. {
  231628. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231629. if (target != 0)
  231630. {
  231631. target->insertTextAtCaret (nsStringToJuce (newText));
  231632. textWasInserted = true;
  231633. }
  231634. }
  231635. deleteAndZero (stringBeingComposed);
  231636. }
  231637. - (void) doCommandBySelector: (SEL) aSelector
  231638. {
  231639. (void) aSelector;
  231640. }
  231641. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231642. {
  231643. (void) selectionRange;
  231644. if (stringBeingComposed == 0)
  231645. stringBeingComposed = new String();
  231646. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231647. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231648. if (target != 0)
  231649. {
  231650. const Range<int> currentHighlight (target->getHighlightedRegion());
  231651. target->insertTextAtCaret (*stringBeingComposed);
  231652. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231653. textWasInserted = true;
  231654. }
  231655. }
  231656. - (void) unmarkText
  231657. {
  231658. if (stringBeingComposed != 0)
  231659. {
  231660. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231661. if (target != 0)
  231662. {
  231663. target->insertTextAtCaret (*stringBeingComposed);
  231664. textWasInserted = true;
  231665. }
  231666. }
  231667. deleteAndZero (stringBeingComposed);
  231668. }
  231669. - (BOOL) hasMarkedText
  231670. {
  231671. return stringBeingComposed != 0;
  231672. }
  231673. - (long) conversationIdentifier
  231674. {
  231675. return (long) (pointer_sized_int) self;
  231676. }
  231677. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231678. {
  231679. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231680. if (target != 0)
  231681. {
  231682. const Range<int> r ((int) theRange.location,
  231683. (int) (theRange.location + theRange.length));
  231684. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231685. }
  231686. return nil;
  231687. }
  231688. - (NSRange) markedRange
  231689. {
  231690. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231691. : NSMakeRange (NSNotFound, 0);
  231692. }
  231693. - (NSRange) selectedRange
  231694. {
  231695. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231696. if (target != 0)
  231697. {
  231698. const Range<int> highlight (target->getHighlightedRegion());
  231699. if (! highlight.isEmpty())
  231700. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231701. }
  231702. return NSMakeRange (NSNotFound, 0);
  231703. }
  231704. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231705. {
  231706. (void) theRange;
  231707. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231708. if (comp == 0)
  231709. return NSMakeRect (0, 0, 0, 0);
  231710. const Rectangle<int> bounds (comp->getScreenBounds());
  231711. return NSMakeRect (bounds.getX(),
  231712. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231713. bounds.getWidth(),
  231714. bounds.getHeight());
  231715. }
  231716. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231717. {
  231718. (void) thePoint;
  231719. return NSNotFound;
  231720. }
  231721. - (NSArray*) validAttributesForMarkedText
  231722. {
  231723. return [NSArray array];
  231724. }
  231725. - (void) flagsChanged: (NSEvent*) ev
  231726. {
  231727. if (owner != 0)
  231728. owner->redirectModKeyChange (ev);
  231729. }
  231730. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231731. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231732. {
  231733. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231734. return true;
  231735. return [super performKeyEquivalent: ev];
  231736. }
  231737. #endif
  231738. - (BOOL) becomeFirstResponder
  231739. {
  231740. if (owner != 0)
  231741. owner->viewFocusGain();
  231742. return true;
  231743. }
  231744. - (BOOL) resignFirstResponder
  231745. {
  231746. if (owner != 0)
  231747. owner->viewFocusLoss();
  231748. return true;
  231749. }
  231750. - (BOOL) acceptsFirstResponder
  231751. {
  231752. return owner != 0 && owner->canBecomeKeyWindow();
  231753. }
  231754. - (NSArray*) getSupportedDragTypes
  231755. {
  231756. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231757. }
  231758. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231759. {
  231760. return owner != 0 && owner->sendDragCallback (type, sender);
  231761. }
  231762. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231763. {
  231764. if ([self sendDragCallback: 0 sender: sender])
  231765. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231766. else
  231767. return NSDragOperationNone;
  231768. }
  231769. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231770. {
  231771. if ([self sendDragCallback: 0 sender: sender])
  231772. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231773. else
  231774. return NSDragOperationNone;
  231775. }
  231776. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231777. {
  231778. [self sendDragCallback: 1 sender: sender];
  231779. }
  231780. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231781. {
  231782. [self sendDragCallback: 1 sender: sender];
  231783. }
  231784. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231785. {
  231786. (void) sender;
  231787. return YES;
  231788. }
  231789. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231790. {
  231791. return [self sendDragCallback: 2 sender: sender];
  231792. }
  231793. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231794. {
  231795. (void) sender;
  231796. }
  231797. @end
  231798. @implementation JuceNSWindow
  231799. - (void) setOwner: (NSViewComponentPeer*) owner_
  231800. {
  231801. owner = owner_;
  231802. isZooming = false;
  231803. }
  231804. - (BOOL) canBecomeKeyWindow
  231805. {
  231806. return owner != 0 && owner->canBecomeKeyWindow();
  231807. }
  231808. - (void) becomeKeyWindow
  231809. {
  231810. [super becomeKeyWindow];
  231811. if (owner != 0)
  231812. owner->grabFocus();
  231813. }
  231814. - (BOOL) windowShouldClose: (id) window
  231815. {
  231816. (void) window;
  231817. return owner == 0 || owner->windowShouldClose();
  231818. }
  231819. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231820. {
  231821. (void) screen;
  231822. if (owner != 0)
  231823. frameRect = owner->constrainRect (frameRect);
  231824. return frameRect;
  231825. }
  231826. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231827. {
  231828. (void) window;
  231829. if (isZooming)
  231830. return proposedFrameSize;
  231831. NSRect frameRect = [self frame];
  231832. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231833. frameRect.size = proposedFrameSize;
  231834. if (owner != 0)
  231835. frameRect = owner->constrainRect (frameRect);
  231836. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231837. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231838. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231839. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231840. return frameRect.size;
  231841. }
  231842. - (void) zoom: (id) sender
  231843. {
  231844. isZooming = true;
  231845. [super zoom: sender];
  231846. isZooming = false;
  231847. }
  231848. - (void) windowWillMove: (NSNotification*) notification
  231849. {
  231850. (void) notification;
  231851. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231852. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231853. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231854. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231855. }
  231856. @end
  231857. BEGIN_JUCE_NAMESPACE
  231858. ModifierKeys NSViewComponentPeer::currentModifiers;
  231859. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231860. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231861. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231862. {
  231863. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231864. return true;
  231865. if (keyCode >= 'A' && keyCode <= 'Z'
  231866. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231867. return true;
  231868. if (keyCode >= 'a' && keyCode <= 'z'
  231869. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231870. return true;
  231871. return false;
  231872. }
  231873. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231874. {
  231875. int m = 0;
  231876. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231877. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231878. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231879. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231880. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231881. }
  231882. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231883. {
  231884. updateModifiers (ev);
  231885. int keyCode = getKeyCodeFromEvent (ev);
  231886. if (keyCode != 0)
  231887. {
  231888. if (isKeyDown)
  231889. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231890. else
  231891. keysCurrentlyDown.removeValue (keyCode);
  231892. }
  231893. }
  231894. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231895. {
  231896. return NSViewComponentPeer::currentModifiers;
  231897. }
  231898. void ModifierKeys::updateCurrentModifiers() throw()
  231899. {
  231900. currentModifiers = NSViewComponentPeer::currentModifiers;
  231901. }
  231902. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231903. const int windowStyleFlags,
  231904. NSView* viewToAttachTo)
  231905. : ComponentPeer (component_, windowStyleFlags),
  231906. window (0),
  231907. view (0),
  231908. isSharedWindow (viewToAttachTo != 0),
  231909. fullScreen (false),
  231910. insideDrawRect (false),
  231911. #if USE_COREGRAPHICS_RENDERING
  231912. usingCoreGraphics (true),
  231913. #else
  231914. usingCoreGraphics (false),
  231915. #endif
  231916. recursiveToFrontCall (false)
  231917. {
  231918. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231919. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231920. [view setPostsFrameChangedNotifications: YES];
  231921. if (isSharedWindow)
  231922. {
  231923. window = [viewToAttachTo window];
  231924. [viewToAttachTo addSubview: view];
  231925. }
  231926. else
  231927. {
  231928. r.origin.x = (float) component->getX();
  231929. r.origin.y = (float) component->getY();
  231930. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231931. unsigned int style = 0;
  231932. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231933. style = NSBorderlessWindowMask;
  231934. else
  231935. style = NSTitledWindowMask;
  231936. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231937. style |= NSMiniaturizableWindowMask;
  231938. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231939. style |= NSClosableWindowMask;
  231940. if ((windowStyleFlags & windowIsResizable) != 0)
  231941. style |= NSResizableWindowMask;
  231942. window = [[JuceNSWindow alloc] initWithContentRect: r
  231943. styleMask: style
  231944. backing: NSBackingStoreBuffered
  231945. defer: YES];
  231946. [((JuceNSWindow*) window) setOwner: this];
  231947. [window orderOut: nil];
  231948. [window setDelegate: (JuceNSWindow*) window];
  231949. [window setOpaque: component->isOpaque()];
  231950. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231951. if (component->isAlwaysOnTop())
  231952. [window setLevel: NSFloatingWindowLevel];
  231953. [window setContentView: view];
  231954. [window setAutodisplay: YES];
  231955. [window setAcceptsMouseMovedEvents: YES];
  231956. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231957. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231958. [window setReleasedWhenClosed: YES];
  231959. [window retain];
  231960. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231961. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231962. }
  231963. const float alpha = component->getAlpha();
  231964. if (alpha < 1.0f)
  231965. setAlpha (alpha);
  231966. setTitle (component->getName());
  231967. }
  231968. NSViewComponentPeer::~NSViewComponentPeer()
  231969. {
  231970. view->owner = 0;
  231971. [view removeFromSuperview];
  231972. [view release];
  231973. if (! isSharedWindow)
  231974. {
  231975. [((JuceNSWindow*) window) setOwner: 0];
  231976. [window close];
  231977. [window release];
  231978. }
  231979. }
  231980. void* NSViewComponentPeer::getNativeHandle() const
  231981. {
  231982. return view;
  231983. }
  231984. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231985. {
  231986. if (isSharedWindow)
  231987. {
  231988. [view setHidden: ! shouldBeVisible];
  231989. }
  231990. else
  231991. {
  231992. if (shouldBeVisible)
  231993. {
  231994. [window orderFront: nil];
  231995. handleBroughtToFront();
  231996. }
  231997. else
  231998. {
  231999. [window orderOut: nil];
  232000. }
  232001. }
  232002. }
  232003. void NSViewComponentPeer::setTitle (const String& title)
  232004. {
  232005. const ScopedAutoReleasePool pool;
  232006. if (! isSharedWindow)
  232007. [window setTitle: juceStringToNS (title)];
  232008. }
  232009. void NSViewComponentPeer::setPosition (int x, int y)
  232010. {
  232011. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  232012. }
  232013. void NSViewComponentPeer::setSize (int w, int h)
  232014. {
  232015. setBounds (component->getX(), component->getY(), w, h, false);
  232016. }
  232017. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  232018. {
  232019. fullScreen = isNowFullScreen;
  232020. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  232021. if (isSharedWindow)
  232022. {
  232023. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232024. if ([view frame].size.width != r.size.width
  232025. || [view frame].size.height != r.size.height)
  232026. [view setNeedsDisplay: true];
  232027. [view setFrame: r];
  232028. }
  232029. else
  232030. {
  232031. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  232032. [window setFrame: [window frameRectForContentRect: r]
  232033. display: true];
  232034. }
  232035. }
  232036. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  232037. {
  232038. NSRect r = [view frame];
  232039. if (global && [view window] != 0)
  232040. {
  232041. r = [view convertRect: r toView: nil];
  232042. NSRect wr = [[view window] frame];
  232043. r.origin.x += wr.origin.x;
  232044. r.origin.y += wr.origin.y;
  232045. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232046. }
  232047. else
  232048. {
  232049. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  232050. }
  232051. return Rectangle<int> (convertToRectInt (r));
  232052. }
  232053. const Rectangle<int> NSViewComponentPeer::getBounds() const
  232054. {
  232055. return getBounds (! isSharedWindow);
  232056. }
  232057. const Point<int> NSViewComponentPeer::getScreenPosition() const
  232058. {
  232059. return getBounds (true).getPosition();
  232060. }
  232061. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  232062. {
  232063. return relativePosition + getScreenPosition();
  232064. }
  232065. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  232066. {
  232067. return screenPosition - getScreenPosition();
  232068. }
  232069. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  232070. {
  232071. if (constrainer != 0)
  232072. {
  232073. NSRect current = [window frame];
  232074. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  232075. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232076. Rectangle<int> pos (convertToRectInt (r));
  232077. Rectangle<int> original (convertToRectInt (current));
  232078. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  232079. if ([window inLiveResize])
  232080. #else
  232081. if ([window respondsToSelector: @selector (inLiveResize)]
  232082. && [window performSelector: @selector (inLiveResize)])
  232083. #endif
  232084. {
  232085. constrainer->checkBounds (pos, original,
  232086. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  232087. false, false, true, true);
  232088. }
  232089. else
  232090. {
  232091. constrainer->checkBounds (pos, original,
  232092. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  232093. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  232094. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  232095. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  232096. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  232097. }
  232098. r.origin.x = pos.getX();
  232099. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  232100. r.size.width = pos.getWidth();
  232101. r.size.height = pos.getHeight();
  232102. }
  232103. return r;
  232104. }
  232105. void NSViewComponentPeer::setAlpha (float newAlpha)
  232106. {
  232107. if (! isSharedWindow)
  232108. [window setAlphaValue: (CGFloat) newAlpha];
  232109. else
  232110. [view setAlphaValue: (CGFloat) newAlpha];
  232111. }
  232112. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  232113. {
  232114. if (! isSharedWindow)
  232115. {
  232116. if (shouldBeMinimised)
  232117. [window miniaturize: nil];
  232118. else
  232119. [window deminiaturize: nil];
  232120. }
  232121. }
  232122. bool NSViewComponentPeer::isMinimised() const
  232123. {
  232124. return window != 0 && [window isMiniaturized];
  232125. }
  232126. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  232127. {
  232128. if (! isSharedWindow)
  232129. {
  232130. Rectangle<int> r (lastNonFullscreenBounds);
  232131. setMinimised (false);
  232132. if (fullScreen != shouldBeFullScreen)
  232133. {
  232134. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  232135. {
  232136. fullScreen = true;
  232137. [window performZoom: nil];
  232138. }
  232139. else
  232140. {
  232141. if (shouldBeFullScreen)
  232142. r = Desktop::getInstance().getMainMonitorArea();
  232143. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  232144. if (r != getComponent()->getBounds() && ! r.isEmpty())
  232145. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  232146. }
  232147. }
  232148. }
  232149. }
  232150. bool NSViewComponentPeer::isFullScreen() const
  232151. {
  232152. return fullScreen;
  232153. }
  232154. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  232155. {
  232156. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  232157. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  232158. return false;
  232159. NSPoint p;
  232160. p.x = (float) position.getX();
  232161. p.y = (float) position.getY();
  232162. NSView* v = [view hitTest: p];
  232163. if (trueIfInAChildWindow)
  232164. return v != nil;
  232165. return v == view;
  232166. }
  232167. const BorderSize NSViewComponentPeer::getFrameSize() const
  232168. {
  232169. BorderSize b;
  232170. if (! isSharedWindow)
  232171. {
  232172. NSRect v = [view convertRect: [view frame] toView: nil];
  232173. NSRect w = [window frame];
  232174. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  232175. b.setBottom ((int) v.origin.y);
  232176. b.setLeft ((int) v.origin.x);
  232177. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  232178. }
  232179. return b;
  232180. }
  232181. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  232182. {
  232183. if (! isSharedWindow)
  232184. {
  232185. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  232186. : NSNormalWindowLevel];
  232187. }
  232188. return true;
  232189. }
  232190. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  232191. {
  232192. if (isSharedWindow)
  232193. {
  232194. [[view superview] addSubview: view
  232195. positioned: NSWindowAbove
  232196. relativeTo: nil];
  232197. }
  232198. if (window != 0 && component->isVisible())
  232199. {
  232200. if (makeActiveWindow)
  232201. [window makeKeyAndOrderFront: nil];
  232202. else
  232203. [window orderFront: nil];
  232204. if (! recursiveToFrontCall)
  232205. {
  232206. recursiveToFrontCall = true;
  232207. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232208. handleBroughtToFront();
  232209. recursiveToFrontCall = false;
  232210. }
  232211. }
  232212. }
  232213. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  232214. {
  232215. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  232216. jassert (otherPeer != 0); // wrong type of window?
  232217. if (otherPeer != 0)
  232218. {
  232219. if (isSharedWindow)
  232220. {
  232221. [[view superview] addSubview: view
  232222. positioned: NSWindowBelow
  232223. relativeTo: otherPeer->view];
  232224. }
  232225. else
  232226. {
  232227. [window orderWindow: NSWindowBelow
  232228. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  232229. : nil ];
  232230. }
  232231. }
  232232. }
  232233. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  232234. {
  232235. // to do..
  232236. }
  232237. void NSViewComponentPeer::viewFocusGain()
  232238. {
  232239. if (currentlyFocusedPeer != this)
  232240. {
  232241. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  232242. currentlyFocusedPeer->handleFocusLoss();
  232243. currentlyFocusedPeer = this;
  232244. handleFocusGain();
  232245. }
  232246. }
  232247. void NSViewComponentPeer::viewFocusLoss()
  232248. {
  232249. if (currentlyFocusedPeer == this)
  232250. {
  232251. currentlyFocusedPeer = 0;
  232252. handleFocusLoss();
  232253. }
  232254. }
  232255. void juce_HandleProcessFocusChange()
  232256. {
  232257. NSViewComponentPeer::keysCurrentlyDown.clear();
  232258. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  232259. {
  232260. if (Process::isForegroundProcess())
  232261. {
  232262. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  232263. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  232264. }
  232265. else
  232266. {
  232267. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  232268. // turn kiosk mode off if we lose focus..
  232269. Desktop::getInstance().setKioskModeComponent (0);
  232270. }
  232271. }
  232272. }
  232273. bool NSViewComponentPeer::isFocused() const
  232274. {
  232275. return isSharedWindow ? this == currentlyFocusedPeer
  232276. : (window != 0 && [window isKeyWindow]);
  232277. }
  232278. void NSViewComponentPeer::grabFocus()
  232279. {
  232280. if (window != 0)
  232281. {
  232282. [window makeKeyWindow];
  232283. [window makeFirstResponder: view];
  232284. viewFocusGain();
  232285. }
  232286. }
  232287. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  232288. {
  232289. }
  232290. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  232291. {
  232292. String unicode (nsStringToJuce ([ev characters]));
  232293. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  232294. int keyCode = getKeyCodeFromEvent (ev);
  232295. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  232296. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  232297. if (unicode.isNotEmpty() || keyCode != 0)
  232298. {
  232299. if (isKeyDown)
  232300. {
  232301. bool used = false;
  232302. while (unicode.length() > 0)
  232303. {
  232304. juce_wchar textCharacter = unicode[0];
  232305. unicode = unicode.substring (1);
  232306. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232307. textCharacter = 0;
  232308. used = handleKeyUpOrDown (true) || used;
  232309. used = handleKeyPress (keyCode, textCharacter) || used;
  232310. }
  232311. return used;
  232312. }
  232313. else
  232314. {
  232315. if (handleKeyUpOrDown (false))
  232316. return true;
  232317. }
  232318. }
  232319. return false;
  232320. }
  232321. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  232322. {
  232323. updateKeysDown (ev, true);
  232324. bool used = handleKeyEvent (ev, true);
  232325. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232326. {
  232327. // for command keys, the key-up event is thrown away, so simulate one..
  232328. updateKeysDown (ev, false);
  232329. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  232330. }
  232331. // (If we're running modally, don't allow unused keystrokes to be passed
  232332. // along to other blocked views..)
  232333. if (Component::getCurrentlyModalComponent() != 0)
  232334. used = true;
  232335. return used;
  232336. }
  232337. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  232338. {
  232339. updateKeysDown (ev, false);
  232340. return handleKeyEvent (ev, false)
  232341. || Component::getCurrentlyModalComponent() != 0;
  232342. }
  232343. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  232344. {
  232345. keysCurrentlyDown.clear();
  232346. handleKeyUpOrDown (true);
  232347. updateModifiers (ev);
  232348. handleModifierKeysChange();
  232349. }
  232350. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232351. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  232352. {
  232353. if ([ev type] == NSKeyDown)
  232354. return redirectKeyDown (ev);
  232355. else if ([ev type] == NSKeyUp)
  232356. return redirectKeyUp (ev);
  232357. return false;
  232358. }
  232359. #endif
  232360. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  232361. {
  232362. updateModifiers (ev);
  232363. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  232364. }
  232365. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  232366. {
  232367. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232368. sendMouseEvent (ev);
  232369. }
  232370. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  232371. {
  232372. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232373. sendMouseEvent (ev);
  232374. showArrowCursorIfNeeded();
  232375. }
  232376. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232377. {
  232378. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232379. sendMouseEvent (ev);
  232380. }
  232381. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232382. {
  232383. currentModifiers = currentModifiers.withoutMouseButtons();
  232384. sendMouseEvent (ev);
  232385. showArrowCursorIfNeeded();
  232386. }
  232387. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232388. {
  232389. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232390. currentModifiers = currentModifiers.withoutMouseButtons();
  232391. sendMouseEvent (ev);
  232392. }
  232393. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232394. {
  232395. currentModifiers = currentModifiers.withoutMouseButtons();
  232396. sendMouseEvent (ev);
  232397. }
  232398. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232399. {
  232400. updateModifiers (ev);
  232401. float x = 0, y = 0;
  232402. @try
  232403. {
  232404. x = [ev deviceDeltaX] * 0.5f;
  232405. y = [ev deviceDeltaY] * 0.5f;
  232406. }
  232407. @catch (...)
  232408. {}
  232409. if (x == 0 && y == 0)
  232410. {
  232411. x = [ev deltaX] * 10.0f;
  232412. y = [ev deltaY] * 10.0f;
  232413. }
  232414. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232415. }
  232416. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232417. {
  232418. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232419. if (mouse.getComponentUnderMouse() == 0
  232420. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232421. {
  232422. [[NSCursor arrowCursor] set];
  232423. }
  232424. }
  232425. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232426. {
  232427. NSString* bestType
  232428. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232429. if (bestType == nil)
  232430. return false;
  232431. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232432. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232433. StringArray files;
  232434. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232435. if (list == nil)
  232436. return false;
  232437. if ([list isKindOfClass: [NSArray class]])
  232438. {
  232439. NSArray* items = (NSArray*) list;
  232440. for (unsigned int i = 0; i < [items count]; ++i)
  232441. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232442. }
  232443. if (files.size() == 0)
  232444. return false;
  232445. if (type == 0)
  232446. handleFileDragMove (files, pos);
  232447. else if (type == 1)
  232448. handleFileDragExit (files);
  232449. else if (type == 2)
  232450. handleFileDragDrop (files, pos);
  232451. return true;
  232452. }
  232453. bool NSViewComponentPeer::isOpaque()
  232454. {
  232455. return component == 0 || component->isOpaque();
  232456. }
  232457. void NSViewComponentPeer::drawRect (NSRect r)
  232458. {
  232459. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232460. return;
  232461. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232462. if (! component->isOpaque())
  232463. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232464. #if USE_COREGRAPHICS_RENDERING
  232465. if (usingCoreGraphics)
  232466. {
  232467. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232468. insideDrawRect = true;
  232469. handlePaint (context);
  232470. insideDrawRect = false;
  232471. }
  232472. else
  232473. #endif
  232474. {
  232475. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232476. (int) (r.size.width + 0.5f),
  232477. (int) (r.size.height + 0.5f),
  232478. ! getComponent()->isOpaque());
  232479. const int xOffset = -roundToInt (r.origin.x);
  232480. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232481. const NSRect* rects = 0;
  232482. NSInteger numRects = 0;
  232483. [view getRectsBeingDrawn: &rects count: &numRects];
  232484. const Rectangle<int> clipBounds (temp.getBounds());
  232485. RectangleList clip;
  232486. for (int i = 0; i < numRects; ++i)
  232487. {
  232488. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232489. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232490. roundToInt (rects[i].size.width),
  232491. roundToInt (rects[i].size.height))));
  232492. }
  232493. if (! clip.isEmpty())
  232494. {
  232495. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232496. insideDrawRect = true;
  232497. handlePaint (context);
  232498. insideDrawRect = false;
  232499. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232500. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232501. CGColorSpaceRelease (colourSpace);
  232502. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232503. CGImageRelease (image);
  232504. }
  232505. }
  232506. }
  232507. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232508. {
  232509. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232510. #if USE_COREGRAPHICS_RENDERING
  232511. s.add ("CoreGraphics Renderer");
  232512. #endif
  232513. return s;
  232514. }
  232515. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232516. {
  232517. return usingCoreGraphics ? 1 : 0;
  232518. }
  232519. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232520. {
  232521. #if USE_COREGRAPHICS_RENDERING
  232522. if (usingCoreGraphics != (index > 0))
  232523. {
  232524. usingCoreGraphics = index > 0;
  232525. [view setNeedsDisplay: true];
  232526. }
  232527. #endif
  232528. }
  232529. bool NSViewComponentPeer::canBecomeKeyWindow()
  232530. {
  232531. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232532. }
  232533. bool NSViewComponentPeer::windowShouldClose()
  232534. {
  232535. if (! isValidPeer (this))
  232536. return YES;
  232537. handleUserClosingWindow();
  232538. return NO;
  232539. }
  232540. void NSViewComponentPeer::redirectMovedOrResized()
  232541. {
  232542. handleMovedOrResized();
  232543. }
  232544. void NSViewComponentPeer::viewMovedToWindow()
  232545. {
  232546. if (isSharedWindow)
  232547. window = [view window];
  232548. }
  232549. void Desktop::createMouseInputSources()
  232550. {
  232551. mouseSources.add (new MouseInputSource (0, true));
  232552. }
  232553. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232554. {
  232555. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232556. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232557. // is apparently still available in 64-bit apps..
  232558. if (enableOrDisable)
  232559. {
  232560. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232561. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232562. }
  232563. else
  232564. {
  232565. SetSystemUIMode (kUIModeNormal, 0);
  232566. }
  232567. }
  232568. class AsyncRepaintMessage : public CallbackMessage
  232569. {
  232570. public:
  232571. NSViewComponentPeer* const peer;
  232572. const Rectangle<int> rect;
  232573. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232574. : peer (peer_), rect (rect_)
  232575. {
  232576. }
  232577. void messageCallback()
  232578. {
  232579. if (ComponentPeer::isValidPeer (peer))
  232580. peer->repaint (rect);
  232581. }
  232582. };
  232583. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232584. {
  232585. if (insideDrawRect)
  232586. {
  232587. (new AsyncRepaintMessage (this, area))->post();
  232588. }
  232589. else
  232590. {
  232591. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232592. (float) area.getWidth(), (float) area.getHeight())];
  232593. }
  232594. }
  232595. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232596. {
  232597. [view displayIfNeeded];
  232598. }
  232599. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232600. {
  232601. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232602. }
  232603. const Image juce_createIconForFile (const File& file)
  232604. {
  232605. const ScopedAutoReleasePool pool;
  232606. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232607. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232608. [NSGraphicsContext saveGraphicsState];
  232609. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232610. [image drawAtPoint: NSMakePoint (0, 0)
  232611. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232612. operation: NSCompositeSourceOver fraction: 1.0f];
  232613. [[NSGraphicsContext currentContext] flushGraphics];
  232614. [NSGraphicsContext restoreGraphicsState];
  232615. return Image (result);
  232616. }
  232617. const int KeyPress::spaceKey = ' ';
  232618. const int KeyPress::returnKey = 0x0d;
  232619. const int KeyPress::escapeKey = 0x1b;
  232620. const int KeyPress::backspaceKey = 0x7f;
  232621. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232622. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232623. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232624. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232625. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232626. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232627. const int KeyPress::endKey = NSEndFunctionKey;
  232628. const int KeyPress::homeKey = NSHomeFunctionKey;
  232629. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232630. const int KeyPress::insertKey = -1;
  232631. const int KeyPress::tabKey = 9;
  232632. const int KeyPress::F1Key = NSF1FunctionKey;
  232633. const int KeyPress::F2Key = NSF2FunctionKey;
  232634. const int KeyPress::F3Key = NSF3FunctionKey;
  232635. const int KeyPress::F4Key = NSF4FunctionKey;
  232636. const int KeyPress::F5Key = NSF5FunctionKey;
  232637. const int KeyPress::F6Key = NSF6FunctionKey;
  232638. const int KeyPress::F7Key = NSF7FunctionKey;
  232639. const int KeyPress::F8Key = NSF8FunctionKey;
  232640. const int KeyPress::F9Key = NSF9FunctionKey;
  232641. const int KeyPress::F10Key = NSF10FunctionKey;
  232642. const int KeyPress::F11Key = NSF1FunctionKey;
  232643. const int KeyPress::F12Key = NSF12FunctionKey;
  232644. const int KeyPress::F13Key = NSF13FunctionKey;
  232645. const int KeyPress::F14Key = NSF14FunctionKey;
  232646. const int KeyPress::F15Key = NSF15FunctionKey;
  232647. const int KeyPress::F16Key = NSF16FunctionKey;
  232648. const int KeyPress::numberPad0 = 0x30020;
  232649. const int KeyPress::numberPad1 = 0x30021;
  232650. const int KeyPress::numberPad2 = 0x30022;
  232651. const int KeyPress::numberPad3 = 0x30023;
  232652. const int KeyPress::numberPad4 = 0x30024;
  232653. const int KeyPress::numberPad5 = 0x30025;
  232654. const int KeyPress::numberPad6 = 0x30026;
  232655. const int KeyPress::numberPad7 = 0x30027;
  232656. const int KeyPress::numberPad8 = 0x30028;
  232657. const int KeyPress::numberPad9 = 0x30029;
  232658. const int KeyPress::numberPadAdd = 0x3002a;
  232659. const int KeyPress::numberPadSubtract = 0x3002b;
  232660. const int KeyPress::numberPadMultiply = 0x3002c;
  232661. const int KeyPress::numberPadDivide = 0x3002d;
  232662. const int KeyPress::numberPadSeparator = 0x3002e;
  232663. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232664. const int KeyPress::numberPadEquals = 0x30030;
  232665. const int KeyPress::numberPadDelete = 0x30031;
  232666. const int KeyPress::playKey = 0x30000;
  232667. const int KeyPress::stopKey = 0x30001;
  232668. const int KeyPress::fastForwardKey = 0x30002;
  232669. const int KeyPress::rewindKey = 0x30003;
  232670. #endif
  232671. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232672. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232673. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232674. // compiled on its own).
  232675. #if JUCE_INCLUDED_FILE
  232676. #if JUCE_MAC
  232677. namespace MouseCursorHelpers
  232678. {
  232679. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232680. {
  232681. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232682. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232683. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232684. [im release];
  232685. return c;
  232686. }
  232687. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232688. {
  232689. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232690. BufferedInputStream buf (fileStream, 4096);
  232691. PNGImageFormat pngFormat;
  232692. Image im (pngFormat.decodeImage (buf));
  232693. if (im.isValid())
  232694. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232695. jassertfalse;
  232696. return 0;
  232697. }
  232698. }
  232699. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232700. {
  232701. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232702. }
  232703. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232704. {
  232705. const ScopedAutoReleasePool pool;
  232706. NSCursor* c = 0;
  232707. switch (type)
  232708. {
  232709. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232710. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232711. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232712. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232713. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232714. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232715. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232716. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232717. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232718. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232719. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232720. case UpDownResizeCursor:
  232721. case TopEdgeResizeCursor:
  232722. case BottomEdgeResizeCursor:
  232723. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232724. case TopLeftCornerResizeCursor:
  232725. case BottomRightCornerResizeCursor:
  232726. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232727. case TopRightCornerResizeCursor:
  232728. case BottomLeftCornerResizeCursor:
  232729. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232730. case UpDownLeftRightResizeCursor:
  232731. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232732. default:
  232733. jassertfalse;
  232734. break;
  232735. }
  232736. [c retain];
  232737. return c;
  232738. }
  232739. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232740. {
  232741. [((NSCursor*) cursorHandle) release];
  232742. }
  232743. void MouseCursor::showInAllWindows() const
  232744. {
  232745. showInWindow (0);
  232746. }
  232747. void MouseCursor::showInWindow (ComponentPeer*) const
  232748. {
  232749. NSCursor* c = (NSCursor*) getHandle();
  232750. if (c == 0)
  232751. c = [NSCursor arrowCursor];
  232752. [c set];
  232753. }
  232754. #else
  232755. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232756. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232757. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232758. void MouseCursor::showInAllWindows() const {}
  232759. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232760. #endif
  232761. #endif
  232762. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232763. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232764. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232765. // compiled on its own).
  232766. #if JUCE_INCLUDED_FILE
  232767. class NSViewComponentInternal : public ComponentMovementWatcher
  232768. {
  232769. Component* const owner;
  232770. NSViewComponentPeer* currentPeer;
  232771. bool wasShowing;
  232772. public:
  232773. NSView* const view;
  232774. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232775. : ComponentMovementWatcher (owner_),
  232776. owner (owner_),
  232777. currentPeer (0),
  232778. wasShowing (false),
  232779. view (view_)
  232780. {
  232781. [view_ retain];
  232782. if (owner_->isShowing())
  232783. componentPeerChanged();
  232784. }
  232785. ~NSViewComponentInternal()
  232786. {
  232787. [view removeFromSuperview];
  232788. [view release];
  232789. }
  232790. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232791. {
  232792. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232793. // The ComponentMovementWatcher version of this method avoids calling
  232794. // us when the top-level comp is resized, but for an NSView we need to know this
  232795. // because with inverted co-ords, we need to update the position even if the
  232796. // top-left pos hasn't changed
  232797. if (comp.isOnDesktop() && wasResized)
  232798. componentMovedOrResized (wasMoved, wasResized);
  232799. }
  232800. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232801. {
  232802. Component* const topComp = owner->getTopLevelComponent();
  232803. if (topComp->getPeer() != 0)
  232804. {
  232805. const Point<int> pos (topComp->getLocalPoint (owner, Point<int>()));
  232806. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  232807. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232808. [view setFrame: r];
  232809. }
  232810. }
  232811. void componentPeerChanged()
  232812. {
  232813. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232814. if (currentPeer != peer)
  232815. {
  232816. if ([view superview] != nil)
  232817. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  232818. // override the call and use it as a sign that they're being deleted, which breaks everything..
  232819. currentPeer = peer;
  232820. if (peer != 0)
  232821. {
  232822. [peer->view addSubview: view];
  232823. componentMovedOrResized (false, false);
  232824. }
  232825. }
  232826. [view setHidden: ! owner->isShowing()];
  232827. }
  232828. void componentVisibilityChanged (Component&)
  232829. {
  232830. componentPeerChanged();
  232831. }
  232832. const Rectangle<int> getViewBounds() const
  232833. {
  232834. NSRect r = [view frame];
  232835. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  232836. }
  232837. juce_UseDebuggingNewOperator
  232838. private:
  232839. NSViewComponentInternal (const NSViewComponentInternal&);
  232840. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  232841. };
  232842. NSViewComponent::NSViewComponent()
  232843. {
  232844. }
  232845. NSViewComponent::~NSViewComponent()
  232846. {
  232847. }
  232848. void NSViewComponent::setView (void* view)
  232849. {
  232850. if (view != getView())
  232851. {
  232852. if (view != 0)
  232853. info = new NSViewComponentInternal ((NSView*) view, this);
  232854. else
  232855. info = 0;
  232856. }
  232857. }
  232858. void* NSViewComponent::getView() const
  232859. {
  232860. return info == 0 ? 0 : info->view;
  232861. }
  232862. void NSViewComponent::resizeToFitView()
  232863. {
  232864. if (info != 0)
  232865. setBounds (info->getViewBounds());
  232866. }
  232867. void NSViewComponent::paint (Graphics&)
  232868. {
  232869. }
  232870. #endif
  232871. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232872. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232873. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232874. // compiled on its own).
  232875. #if JUCE_INCLUDED_FILE
  232876. AppleRemoteDevice::AppleRemoteDevice()
  232877. : device (0),
  232878. queue (0),
  232879. remoteId (0)
  232880. {
  232881. }
  232882. AppleRemoteDevice::~AppleRemoteDevice()
  232883. {
  232884. stop();
  232885. }
  232886. namespace
  232887. {
  232888. io_object_t getAppleRemoteDevice()
  232889. {
  232890. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232891. io_iterator_t iter = 0;
  232892. io_object_t iod = 0;
  232893. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232894. && iter != 0)
  232895. {
  232896. iod = IOIteratorNext (iter);
  232897. }
  232898. IOObjectRelease (iter);
  232899. return iod;
  232900. }
  232901. bool createAppleRemoteInterface (io_object_t iod, void** device)
  232902. {
  232903. jassert (*device == 0);
  232904. io_name_t classname;
  232905. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232906. {
  232907. IOCFPlugInInterface** cfPlugInInterface = 0;
  232908. SInt32 score = 0;
  232909. if (IOCreatePlugInInterfaceForService (iod,
  232910. kIOHIDDeviceUserClientTypeID,
  232911. kIOCFPlugInInterfaceID,
  232912. &cfPlugInInterface,
  232913. &score) == kIOReturnSuccess)
  232914. {
  232915. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232916. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232917. device);
  232918. (void) hr;
  232919. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232920. }
  232921. }
  232922. return *device != 0;
  232923. }
  232924. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232925. {
  232926. if (result == kIOReturnSuccess)
  232927. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232928. }
  232929. }
  232930. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232931. {
  232932. if (queue != 0)
  232933. return true;
  232934. stop();
  232935. bool result = false;
  232936. io_object_t iod = getAppleRemoteDevice();
  232937. if (iod != 0)
  232938. {
  232939. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232940. result = true;
  232941. else
  232942. stop();
  232943. IOObjectRelease (iod);
  232944. }
  232945. return result;
  232946. }
  232947. void AppleRemoteDevice::stop()
  232948. {
  232949. if (queue != 0)
  232950. {
  232951. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232952. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232953. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232954. queue = 0;
  232955. }
  232956. if (device != 0)
  232957. {
  232958. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232959. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232960. device = 0;
  232961. }
  232962. }
  232963. bool AppleRemoteDevice::isActive() const
  232964. {
  232965. return queue != 0;
  232966. }
  232967. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232968. {
  232969. Array <int> cookies;
  232970. CFArrayRef elements;
  232971. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232972. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232973. return false;
  232974. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232975. {
  232976. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232977. // get the cookie
  232978. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232979. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232980. continue;
  232981. long number;
  232982. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232983. continue;
  232984. cookies.add ((int) number);
  232985. }
  232986. CFRelease (elements);
  232987. if ((*(IOHIDDeviceInterface**) device)
  232988. ->open ((IOHIDDeviceInterface**) device,
  232989. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232990. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232991. {
  232992. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232993. if (queue != 0)
  232994. {
  232995. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232996. for (int i = 0; i < cookies.size(); ++i)
  232997. {
  232998. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232999. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  233000. }
  233001. CFRunLoopSourceRef eventSource;
  233002. if ((*(IOHIDQueueInterface**) queue)
  233003. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  233004. {
  233005. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  233006. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  233007. {
  233008. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  233009. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  233010. return true;
  233011. }
  233012. }
  233013. }
  233014. }
  233015. return false;
  233016. }
  233017. void AppleRemoteDevice::handleCallbackInternal()
  233018. {
  233019. int totalValues = 0;
  233020. AbsoluteTime nullTime = { 0, 0 };
  233021. char cookies [12];
  233022. int numCookies = 0;
  233023. while (numCookies < numElementsInArray (cookies))
  233024. {
  233025. IOHIDEventStruct e;
  233026. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  233027. break;
  233028. if ((int) e.elementCookie == 19)
  233029. {
  233030. remoteId = e.value;
  233031. buttonPressed (switched, false);
  233032. }
  233033. else
  233034. {
  233035. totalValues += e.value;
  233036. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  233037. }
  233038. }
  233039. cookies [numCookies++] = 0;
  233040. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  233041. static const char buttonPatterns[] =
  233042. {
  233043. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  233044. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  233045. 0x1f, 0x1d, 0x1c, 0x12, 0,
  233046. 0x1f, 0x1e, 0x1c, 0x12, 0,
  233047. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  233048. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  233049. 0x1f, 0x12, 0x04, 0x02, 0,
  233050. 0x1f, 0x12, 0x03, 0x02, 0,
  233051. 0x1f, 0x12, 0x1f, 0x12, 0,
  233052. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  233053. 19, 0
  233054. };
  233055. int buttonNum = (int) menuButton;
  233056. int i = 0;
  233057. while (i < numElementsInArray (buttonPatterns))
  233058. {
  233059. if (strcmp (cookies, buttonPatterns + i) == 0)
  233060. {
  233061. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  233062. break;
  233063. }
  233064. i += (int) strlen (buttonPatterns + i) + 1;
  233065. ++buttonNum;
  233066. }
  233067. }
  233068. #endif
  233069. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  233070. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  233071. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233072. // compiled on its own).
  233073. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  233074. #if JUCE_MAC
  233075. END_JUCE_NAMESPACE
  233076. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  233077. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  233078. {
  233079. CriticalSection* contextLock;
  233080. bool needsUpdate;
  233081. }
  233082. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  233083. - (bool) makeActive;
  233084. - (void) makeInactive;
  233085. - (void) reshape;
  233086. @end
  233087. @implementation ThreadSafeNSOpenGLView
  233088. - (id) initWithFrame: (NSRect) frameRect
  233089. pixelFormat: (NSOpenGLPixelFormat*) format
  233090. {
  233091. contextLock = new CriticalSection();
  233092. self = [super initWithFrame: frameRect pixelFormat: format];
  233093. if (self != nil)
  233094. [[NSNotificationCenter defaultCenter] addObserver: self
  233095. selector: @selector (_surfaceNeedsUpdate:)
  233096. name: NSViewGlobalFrameDidChangeNotification
  233097. object: self];
  233098. return self;
  233099. }
  233100. - (void) dealloc
  233101. {
  233102. [[NSNotificationCenter defaultCenter] removeObserver: self];
  233103. delete contextLock;
  233104. [super dealloc];
  233105. }
  233106. - (bool) makeActive
  233107. {
  233108. const ScopedLock sl (*contextLock);
  233109. if ([self openGLContext] == 0)
  233110. return false;
  233111. [[self openGLContext] makeCurrentContext];
  233112. if (needsUpdate)
  233113. {
  233114. [super update];
  233115. needsUpdate = false;
  233116. }
  233117. return true;
  233118. }
  233119. - (void) makeInactive
  233120. {
  233121. const ScopedLock sl (*contextLock);
  233122. [NSOpenGLContext clearCurrentContext];
  233123. }
  233124. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  233125. {
  233126. const ScopedLock sl (*contextLock);
  233127. needsUpdate = true;
  233128. }
  233129. - (void) update
  233130. {
  233131. const ScopedLock sl (*contextLock);
  233132. needsUpdate = true;
  233133. }
  233134. - (void) reshape
  233135. {
  233136. const ScopedLock sl (*contextLock);
  233137. needsUpdate = true;
  233138. }
  233139. @end
  233140. BEGIN_JUCE_NAMESPACE
  233141. class WindowedGLContext : public OpenGLContext
  233142. {
  233143. public:
  233144. WindowedGLContext (Component* const component,
  233145. const OpenGLPixelFormat& pixelFormat_,
  233146. NSOpenGLContext* sharedContext)
  233147. : renderContext (0),
  233148. pixelFormat (pixelFormat_)
  233149. {
  233150. jassert (component != 0);
  233151. NSOpenGLPixelFormatAttribute attribs [64];
  233152. int n = 0;
  233153. attribs[n++] = NSOpenGLPFADoubleBuffer;
  233154. attribs[n++] = NSOpenGLPFAAccelerated;
  233155. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  233156. attribs[n++] = NSOpenGLPFAColorSize;
  233157. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  233158. pixelFormat.greenBits,
  233159. pixelFormat.blueBits);
  233160. attribs[n++] = NSOpenGLPFAAlphaSize;
  233161. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  233162. attribs[n++] = NSOpenGLPFADepthSize;
  233163. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  233164. attribs[n++] = NSOpenGLPFAStencilSize;
  233165. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  233166. attribs[n++] = NSOpenGLPFAAccumSize;
  233167. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  233168. pixelFormat.accumulationBufferGreenBits,
  233169. pixelFormat.accumulationBufferBlueBits,
  233170. pixelFormat.accumulationBufferAlphaBits);
  233171. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  233172. attribs[n++] = NSOpenGLPFASampleBuffers;
  233173. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  233174. attribs[n++] = NSOpenGLPFAClosestPolicy;
  233175. attribs[n++] = NSOpenGLPFANoRecovery;
  233176. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  233177. NSOpenGLPixelFormat* format
  233178. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  233179. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233180. pixelFormat: format];
  233181. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  233182. shareContext: sharedContext] autorelease];
  233183. const GLint swapInterval = 1;
  233184. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  233185. [view setOpenGLContext: renderContext];
  233186. [format release];
  233187. viewHolder = new NSViewComponentInternal (view, component);
  233188. }
  233189. ~WindowedGLContext()
  233190. {
  233191. deleteContext();
  233192. viewHolder = 0;
  233193. }
  233194. void deleteContext()
  233195. {
  233196. makeInactive();
  233197. [renderContext clearDrawable];
  233198. [renderContext setView: nil];
  233199. [view setOpenGLContext: nil];
  233200. renderContext = nil;
  233201. }
  233202. bool makeActive() const throw()
  233203. {
  233204. jassert (renderContext != 0);
  233205. if ([renderContext view] != view)
  233206. [renderContext setView: view];
  233207. [view makeActive];
  233208. return isActive();
  233209. }
  233210. bool makeInactive() const throw()
  233211. {
  233212. [view makeInactive];
  233213. return true;
  233214. }
  233215. bool isActive() const throw()
  233216. {
  233217. return [NSOpenGLContext currentContext] == renderContext;
  233218. }
  233219. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233220. void* getRawContext() const throw() { return renderContext; }
  233221. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233222. {
  233223. }
  233224. void swapBuffers()
  233225. {
  233226. [renderContext flushBuffer];
  233227. }
  233228. bool setSwapInterval (const int numFramesPerSwap)
  233229. {
  233230. [renderContext setValues: (const GLint*) &numFramesPerSwap
  233231. forParameter: NSOpenGLCPSwapInterval];
  233232. return true;
  233233. }
  233234. int getSwapInterval() const
  233235. {
  233236. GLint numFrames = 0;
  233237. [renderContext getValues: &numFrames
  233238. forParameter: NSOpenGLCPSwapInterval];
  233239. return numFrames;
  233240. }
  233241. void repaint()
  233242. {
  233243. // we need to invalidate the juce view that holds this gl view, to make it
  233244. // cause a repaint callback
  233245. NSView* v = (NSView*) viewHolder->view;
  233246. NSRect r = [v frame];
  233247. // bit of a bodge here.. if we only invalidate the area of the gl component,
  233248. // it's completely covered by the NSOpenGLView, so the OS throws away the
  233249. // repaint message, thus never causing our paint() callback, and never repainting
  233250. // the comp. So invalidating just a little bit around the edge helps..
  233251. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  233252. }
  233253. void* getNativeWindowHandle() const { return viewHolder->view; }
  233254. juce_UseDebuggingNewOperator
  233255. NSOpenGLContext* renderContext;
  233256. ThreadSafeNSOpenGLView* view;
  233257. private:
  233258. OpenGLPixelFormat pixelFormat;
  233259. ScopedPointer <NSViewComponentInternal> viewHolder;
  233260. WindowedGLContext (const WindowedGLContext&);
  233261. WindowedGLContext& operator= (const WindowedGLContext&);
  233262. };
  233263. OpenGLContext* OpenGLComponent::createContext()
  233264. {
  233265. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  233266. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  233267. return (c->renderContext != 0) ? c.release() : 0;
  233268. }
  233269. void* OpenGLComponent::getNativeWindowHandle() const
  233270. {
  233271. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  233272. : 0;
  233273. }
  233274. void juce_glViewport (const int w, const int h)
  233275. {
  233276. glViewport (0, 0, w, h);
  233277. }
  233278. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233279. OwnedArray <OpenGLPixelFormat>& results)
  233280. {
  233281. /* GLint attribs [64];
  233282. int n = 0;
  233283. attribs[n++] = AGL_RGBA;
  233284. attribs[n++] = AGL_DOUBLEBUFFER;
  233285. attribs[n++] = AGL_ACCELERATED;
  233286. attribs[n++] = AGL_NO_RECOVERY;
  233287. attribs[n++] = AGL_NONE;
  233288. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  233289. while (p != 0)
  233290. {
  233291. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  233292. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  233293. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  233294. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  233295. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  233296. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  233297. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  233298. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  233299. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  233300. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  233301. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  233302. results.add (pf);
  233303. p = aglNextPixelFormat (p);
  233304. }*/
  233305. //jassertfalse // can't see how you do this in cocoa!
  233306. }
  233307. #else
  233308. END_JUCE_NAMESPACE
  233309. @interface JuceGLView : UIView
  233310. {
  233311. }
  233312. + (Class) layerClass;
  233313. @end
  233314. @implementation JuceGLView
  233315. + (Class) layerClass
  233316. {
  233317. return [CAEAGLLayer class];
  233318. }
  233319. @end
  233320. BEGIN_JUCE_NAMESPACE
  233321. class GLESContext : public OpenGLContext
  233322. {
  233323. public:
  233324. GLESContext (UIViewComponentPeer* peer,
  233325. Component* const component_,
  233326. const OpenGLPixelFormat& pixelFormat_,
  233327. const GLESContext* const sharedContext,
  233328. NSUInteger apiType)
  233329. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  233330. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  233331. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  233332. {
  233333. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  233334. view.opaque = YES;
  233335. view.hidden = NO;
  233336. view.backgroundColor = [UIColor blackColor];
  233337. view.userInteractionEnabled = NO;
  233338. glLayer = (CAEAGLLayer*) [view layer];
  233339. [peer->view addSubview: view];
  233340. if (sharedContext != 0)
  233341. context = [[EAGLContext alloc] initWithAPI: apiType
  233342. sharegroup: [sharedContext->context sharegroup]];
  233343. else
  233344. context = [[EAGLContext alloc] initWithAPI: apiType];
  233345. createGLBuffers();
  233346. }
  233347. ~GLESContext()
  233348. {
  233349. deleteContext();
  233350. [view removeFromSuperview];
  233351. [view release];
  233352. freeGLBuffers();
  233353. }
  233354. void deleteContext()
  233355. {
  233356. makeInactive();
  233357. [context release];
  233358. context = nil;
  233359. }
  233360. bool makeActive() const throw()
  233361. {
  233362. jassert (context != 0);
  233363. [EAGLContext setCurrentContext: context];
  233364. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233365. return true;
  233366. }
  233367. void swapBuffers()
  233368. {
  233369. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233370. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233371. }
  233372. bool makeInactive() const throw()
  233373. {
  233374. return [EAGLContext setCurrentContext: nil];
  233375. }
  233376. bool isActive() const throw()
  233377. {
  233378. return [EAGLContext currentContext] == context;
  233379. }
  233380. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233381. void* getRawContext() const throw() { return glLayer; }
  233382. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233383. {
  233384. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233385. if (lastWidth != w || lastHeight != h)
  233386. {
  233387. lastWidth = w;
  233388. lastHeight = h;
  233389. freeGLBuffers();
  233390. createGLBuffers();
  233391. }
  233392. }
  233393. bool setSwapInterval (const int numFramesPerSwap)
  233394. {
  233395. numFrames = numFramesPerSwap;
  233396. return true;
  233397. }
  233398. int getSwapInterval() const
  233399. {
  233400. return numFrames;
  233401. }
  233402. void repaint()
  233403. {
  233404. }
  233405. void createGLBuffers()
  233406. {
  233407. makeActive();
  233408. glGenFramebuffersOES (1, &frameBufferHandle);
  233409. glGenRenderbuffersOES (1, &colorBufferHandle);
  233410. glGenRenderbuffersOES (1, &depthBufferHandle);
  233411. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233412. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233413. GLint width, height;
  233414. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233415. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233416. if (useDepthBuffer)
  233417. {
  233418. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233419. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233420. }
  233421. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233422. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233423. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233424. if (useDepthBuffer)
  233425. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233426. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233427. }
  233428. void freeGLBuffers()
  233429. {
  233430. if (frameBufferHandle != 0)
  233431. {
  233432. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233433. frameBufferHandle = 0;
  233434. }
  233435. if (colorBufferHandle != 0)
  233436. {
  233437. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233438. colorBufferHandle = 0;
  233439. }
  233440. if (depthBufferHandle != 0)
  233441. {
  233442. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233443. depthBufferHandle = 0;
  233444. }
  233445. }
  233446. juce_UseDebuggingNewOperator
  233447. private:
  233448. Component::SafePointer<Component> component;
  233449. OpenGLPixelFormat pixelFormat;
  233450. JuceGLView* view;
  233451. CAEAGLLayer* glLayer;
  233452. EAGLContext* context;
  233453. bool useDepthBuffer;
  233454. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233455. int numFrames;
  233456. int lastWidth, lastHeight;
  233457. GLESContext (const GLESContext&);
  233458. GLESContext& operator= (const GLESContext&);
  233459. };
  233460. OpenGLContext* OpenGLComponent::createContext()
  233461. {
  233462. ScopedAutoReleasePool pool;
  233463. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233464. if (peer != 0)
  233465. return new GLESContext (peer, this, preferredPixelFormat,
  233466. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233467. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233468. return 0;
  233469. }
  233470. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233471. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233472. {
  233473. }
  233474. void juce_glViewport (const int w, const int h)
  233475. {
  233476. glViewport (0, 0, w, h);
  233477. }
  233478. #endif
  233479. #endif
  233480. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233481. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233482. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233483. // compiled on its own).
  233484. #if JUCE_INCLUDED_FILE
  233485. class JuceMainMenuHandler;
  233486. END_JUCE_NAMESPACE
  233487. using namespace JUCE_NAMESPACE;
  233488. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233489. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233490. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233491. #else
  233492. @interface JuceMenuCallback : NSObject
  233493. #endif
  233494. {
  233495. JuceMainMenuHandler* owner;
  233496. }
  233497. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233498. - (void) dealloc;
  233499. - (void) menuItemInvoked: (id) menu;
  233500. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233501. @end
  233502. BEGIN_JUCE_NAMESPACE
  233503. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233504. private DeletedAtShutdown
  233505. {
  233506. public:
  233507. static JuceMainMenuHandler* instance;
  233508. JuceMainMenuHandler()
  233509. : currentModel (0),
  233510. lastUpdateTime (0)
  233511. {
  233512. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233513. }
  233514. ~JuceMainMenuHandler()
  233515. {
  233516. setMenu (0);
  233517. jassert (instance == this);
  233518. instance = 0;
  233519. [callback release];
  233520. }
  233521. void setMenu (MenuBarModel* const newMenuBarModel)
  233522. {
  233523. if (currentModel != newMenuBarModel)
  233524. {
  233525. if (currentModel != 0)
  233526. currentModel->removeListener (this);
  233527. currentModel = newMenuBarModel;
  233528. if (currentModel != 0)
  233529. currentModel->addListener (this);
  233530. menuBarItemsChanged (0);
  233531. }
  233532. }
  233533. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233534. const String& name, const int menuId, const int tag)
  233535. {
  233536. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233537. action: nil
  233538. keyEquivalent: @""];
  233539. [item setTag: tag];
  233540. NSMenu* sub = createMenu (child, name, menuId, tag);
  233541. [parent setSubmenu: sub forItem: item];
  233542. [sub setAutoenablesItems: false];
  233543. [sub release];
  233544. }
  233545. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233546. const String& name, const int menuId, const int tag)
  233547. {
  233548. [parentItem setTag: tag];
  233549. NSMenu* menu = [parentItem submenu];
  233550. [menu setTitle: juceStringToNS (name)];
  233551. while ([menu numberOfItems] > 0)
  233552. [menu removeItemAtIndex: 0];
  233553. PopupMenu::MenuItemIterator iter (menuToCopy);
  233554. while (iter.next())
  233555. addMenuItem (iter, menu, menuId, tag);
  233556. [menu setAutoenablesItems: false];
  233557. [menu update];
  233558. }
  233559. void menuBarItemsChanged (MenuBarModel*)
  233560. {
  233561. lastUpdateTime = Time::getMillisecondCounter();
  233562. StringArray menuNames;
  233563. if (currentModel != 0)
  233564. menuNames = currentModel->getMenuBarNames();
  233565. NSMenu* menuBar = [NSApp mainMenu];
  233566. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233567. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233568. int menuId = 1;
  233569. for (int i = 0; i < menuNames.size(); ++i)
  233570. {
  233571. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233572. if (i >= [menuBar numberOfItems] - 1)
  233573. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233574. else
  233575. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233576. }
  233577. }
  233578. static void flashMenuBar (NSMenu* menu)
  233579. {
  233580. if ([[menu title] isEqualToString: @"Apple"])
  233581. return;
  233582. [menu retain];
  233583. const unichar f35Key = NSF35FunctionKey;
  233584. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233585. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233586. action: nil
  233587. keyEquivalent: f35String];
  233588. [item setTarget: nil];
  233589. [menu insertItem: item atIndex: [menu numberOfItems]];
  233590. [item release];
  233591. if ([menu indexOfItem: item] >= 0)
  233592. {
  233593. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233594. location: NSZeroPoint
  233595. modifierFlags: NSCommandKeyMask
  233596. timestamp: 0
  233597. windowNumber: 0
  233598. context: [NSGraphicsContext currentContext]
  233599. characters: f35String
  233600. charactersIgnoringModifiers: f35String
  233601. isARepeat: NO
  233602. keyCode: 0];
  233603. [menu performKeyEquivalent: f35Event];
  233604. if ([menu indexOfItem: item] >= 0)
  233605. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233606. }
  233607. [menu release];
  233608. }
  233609. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233610. {
  233611. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233612. {
  233613. NSMenuItem* m = [menu itemAtIndex: i];
  233614. if ([m tag] == info.commandID)
  233615. return m;
  233616. if ([m submenu] != 0)
  233617. {
  233618. NSMenuItem* found = findMenuItem ([m submenu], info);
  233619. if (found != 0)
  233620. return found;
  233621. }
  233622. }
  233623. return 0;
  233624. }
  233625. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233626. {
  233627. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233628. if (item != 0)
  233629. flashMenuBar ([item menu]);
  233630. }
  233631. void updateMenus()
  233632. {
  233633. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233634. menuBarItemsChanged (0);
  233635. }
  233636. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233637. {
  233638. if (currentModel != 0)
  233639. {
  233640. if (commandManager != 0)
  233641. {
  233642. ApplicationCommandTarget::InvocationInfo info (commandId);
  233643. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233644. commandManager->invoke (info, true);
  233645. }
  233646. currentModel->menuItemSelected (commandId, topLevelIndex);
  233647. }
  233648. }
  233649. MenuBarModel* currentModel;
  233650. uint32 lastUpdateTime;
  233651. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233652. const int topLevelMenuId, const int topLevelIndex)
  233653. {
  233654. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233655. if (text == 0)
  233656. text = @"";
  233657. if (iter.isSeparator)
  233658. {
  233659. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233660. }
  233661. else if (iter.isSectionHeader)
  233662. {
  233663. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233664. action: nil
  233665. keyEquivalent: @""];
  233666. [item setEnabled: false];
  233667. }
  233668. else if (iter.subMenu != 0)
  233669. {
  233670. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233671. action: nil
  233672. keyEquivalent: @""];
  233673. [item setTag: iter.itemId];
  233674. [item setEnabled: iter.isEnabled];
  233675. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233676. [sub setDelegate: nil];
  233677. [menuToAddTo setSubmenu: sub forItem: item];
  233678. [sub release];
  233679. }
  233680. else
  233681. {
  233682. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233683. action: @selector (menuItemInvoked:)
  233684. keyEquivalent: @""];
  233685. [item setTag: iter.itemId];
  233686. [item setEnabled: iter.isEnabled];
  233687. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233688. [item setTarget: (id) callback];
  233689. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233690. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233691. [item setRepresentedObject: info];
  233692. if (iter.commandManager != 0)
  233693. {
  233694. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233695. ->getKeyPressesAssignedToCommand (iter.itemId));
  233696. if (keyPresses.size() > 0)
  233697. {
  233698. const KeyPress& kp = keyPresses.getReference(0);
  233699. if (kp.getKeyCode() != KeyPress::backspaceKey
  233700. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233701. // every time you press the key while editing text)
  233702. {
  233703. juce_wchar key = kp.getTextCharacter();
  233704. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233705. key = NSBackspaceCharacter;
  233706. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233707. key = NSDeleteCharacter;
  233708. else if (key == 0)
  233709. key = (juce_wchar) kp.getKeyCode();
  233710. unsigned int mods = 0;
  233711. if (kp.getModifiers().isShiftDown())
  233712. mods |= NSShiftKeyMask;
  233713. if (kp.getModifiers().isCtrlDown())
  233714. mods |= NSControlKeyMask;
  233715. if (kp.getModifiers().isAltDown())
  233716. mods |= NSAlternateKeyMask;
  233717. if (kp.getModifiers().isCommandDown())
  233718. mods |= NSCommandKeyMask;
  233719. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233720. [item setKeyEquivalentModifierMask: mods];
  233721. }
  233722. }
  233723. }
  233724. }
  233725. }
  233726. JuceMenuCallback* callback;
  233727. private:
  233728. NSMenu* createMenu (const PopupMenu menu,
  233729. const String& menuName,
  233730. const int topLevelMenuId,
  233731. const int topLevelIndex)
  233732. {
  233733. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233734. [m setAutoenablesItems: false];
  233735. [m setDelegate: callback];
  233736. PopupMenu::MenuItemIterator iter (menu);
  233737. while (iter.next())
  233738. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233739. [m update];
  233740. return m;
  233741. }
  233742. };
  233743. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233744. END_JUCE_NAMESPACE
  233745. @implementation JuceMenuCallback
  233746. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233747. {
  233748. [super init];
  233749. owner = owner_;
  233750. return self;
  233751. }
  233752. - (void) dealloc
  233753. {
  233754. [super dealloc];
  233755. }
  233756. - (void) menuItemInvoked: (id) menu
  233757. {
  233758. NSMenuItem* item = (NSMenuItem*) menu;
  233759. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233760. {
  233761. // 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
  233762. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233763. // into the focused component and let it trigger the menu item indirectly.
  233764. NSEvent* e = [NSApp currentEvent];
  233765. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233766. {
  233767. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233768. {
  233769. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233770. if (peer != 0)
  233771. {
  233772. if ([e type] == NSKeyDown)
  233773. peer->redirectKeyDown (e);
  233774. else
  233775. peer->redirectKeyUp (e);
  233776. return;
  233777. }
  233778. }
  233779. }
  233780. NSArray* info = (NSArray*) [item representedObject];
  233781. owner->invoke ((int) [item tag],
  233782. (ApplicationCommandManager*) (pointer_sized_int)
  233783. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233784. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233785. }
  233786. }
  233787. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233788. {
  233789. (void) menu;
  233790. if (JuceMainMenuHandler::instance != 0)
  233791. JuceMainMenuHandler::instance->updateMenus();
  233792. }
  233793. @end
  233794. BEGIN_JUCE_NAMESPACE
  233795. namespace MainMenuHelpers
  233796. {
  233797. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  233798. {
  233799. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233800. {
  233801. PopupMenu::MenuItemIterator iter (*extraItems);
  233802. while (iter.next())
  233803. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233804. [menu addItem: [NSMenuItem separatorItem]];
  233805. }
  233806. NSMenuItem* item;
  233807. // Services...
  233808. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233809. action: nil keyEquivalent: @""];
  233810. [menu addItem: item];
  233811. [item release];
  233812. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233813. [menu setSubmenu: servicesMenu forItem: item];
  233814. [NSApp setServicesMenu: servicesMenu];
  233815. [servicesMenu release];
  233816. [menu addItem: [NSMenuItem separatorItem]];
  233817. // Hide + Show stuff...
  233818. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233819. action: @selector (hide:) keyEquivalent: @"h"];
  233820. [item setTarget: NSApp];
  233821. [menu addItem: item];
  233822. [item release];
  233823. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233824. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233825. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233826. [item setTarget: NSApp];
  233827. [menu addItem: item];
  233828. [item release];
  233829. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233830. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233831. [item setTarget: NSApp];
  233832. [menu addItem: item];
  233833. [item release];
  233834. [menu addItem: [NSMenuItem separatorItem]];
  233835. // Quit item....
  233836. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233837. action: @selector (terminate:) keyEquivalent: @"q"];
  233838. [item setTarget: NSApp];
  233839. [menu addItem: item];
  233840. [item release];
  233841. return menu;
  233842. }
  233843. // Since our app has no NIB, this initialises a standard app menu...
  233844. void rebuildMainMenu (const PopupMenu* extraItems)
  233845. {
  233846. // this can't be used in a plugin!
  233847. jassert (JUCEApplication::isStandaloneApp());
  233848. if (JUCEApplication::getInstance() != 0)
  233849. {
  233850. const ScopedAutoReleasePool pool;
  233851. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233852. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233853. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233854. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233855. [mainMenu setSubmenu: appMenu forItem: item];
  233856. [NSApp setMainMenu: mainMenu];
  233857. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233858. [appMenu release];
  233859. [mainMenu release];
  233860. }
  233861. }
  233862. }
  233863. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233864. const PopupMenu* extraAppleMenuItems)
  233865. {
  233866. if (getMacMainMenu() != newMenuBarModel)
  233867. {
  233868. const ScopedAutoReleasePool pool;
  233869. if (newMenuBarModel == 0)
  233870. {
  233871. delete JuceMainMenuHandler::instance;
  233872. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233873. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233874. extraAppleMenuItems = 0;
  233875. }
  233876. else
  233877. {
  233878. if (JuceMainMenuHandler::instance == 0)
  233879. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233880. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233881. }
  233882. }
  233883. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  233884. if (newMenuBarModel != 0)
  233885. newMenuBarModel->menuItemsChanged();
  233886. }
  233887. MenuBarModel* MenuBarModel::getMacMainMenu()
  233888. {
  233889. return JuceMainMenuHandler::instance != 0
  233890. ? JuceMainMenuHandler::instance->currentModel : 0;
  233891. }
  233892. void juce_initialiseMacMainMenu()
  233893. {
  233894. if (JuceMainMenuHandler::instance == 0)
  233895. MainMenuHelpers::rebuildMainMenu (0);
  233896. }
  233897. #endif
  233898. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233899. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233900. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233901. // compiled on its own).
  233902. #if JUCE_INCLUDED_FILE
  233903. #if JUCE_MAC
  233904. END_JUCE_NAMESPACE
  233905. using namespace JUCE_NAMESPACE;
  233906. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233907. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233908. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233909. #else
  233910. @interface JuceFileChooserDelegate : NSObject
  233911. #endif
  233912. {
  233913. StringArray* filters;
  233914. }
  233915. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233916. - (void) dealloc;
  233917. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233918. @end
  233919. @implementation JuceFileChooserDelegate
  233920. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233921. {
  233922. [super init];
  233923. filters = filters_;
  233924. return self;
  233925. }
  233926. - (void) dealloc
  233927. {
  233928. delete filters;
  233929. [super dealloc];
  233930. }
  233931. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233932. {
  233933. (void) sender;
  233934. const File f (nsStringToJuce (filename));
  233935. for (int i = filters->size(); --i >= 0;)
  233936. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233937. return true;
  233938. return f.isDirectory();
  233939. }
  233940. @end
  233941. BEGIN_JUCE_NAMESPACE
  233942. void FileChooser::showPlatformDialog (Array<File>& results,
  233943. const String& title,
  233944. const File& currentFileOrDirectory,
  233945. const String& filter,
  233946. bool selectsDirectory,
  233947. bool selectsFiles,
  233948. bool isSaveDialogue,
  233949. bool warnAboutOverwritingExistingFiles,
  233950. bool selectMultipleFiles,
  233951. FilePreviewComponent* extraInfoComponent)
  233952. {
  233953. const ScopedAutoReleasePool pool;
  233954. StringArray* filters = new StringArray();
  233955. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233956. filters->trim();
  233957. filters->removeEmptyStrings();
  233958. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233959. [delegate autorelease];
  233960. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233961. : [NSOpenPanel openPanel];
  233962. [panel setTitle: juceStringToNS (title)];
  233963. if (! isSaveDialogue)
  233964. {
  233965. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233966. [openPanel setCanChooseDirectories: selectsDirectory];
  233967. [openPanel setCanChooseFiles: selectsFiles];
  233968. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233969. }
  233970. [panel setDelegate: delegate];
  233971. if (isSaveDialogue || selectsDirectory)
  233972. [panel setCanCreateDirectories: YES];
  233973. String directory, filename;
  233974. if (currentFileOrDirectory.isDirectory())
  233975. {
  233976. directory = currentFileOrDirectory.getFullPathName();
  233977. }
  233978. else
  233979. {
  233980. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233981. filename = currentFileOrDirectory.getFileName();
  233982. }
  233983. if ([panel runModalForDirectory: juceStringToNS (directory)
  233984. file: juceStringToNS (filename)]
  233985. == NSOKButton)
  233986. {
  233987. if (isSaveDialogue)
  233988. {
  233989. results.add (File (nsStringToJuce ([panel filename])));
  233990. }
  233991. else
  233992. {
  233993. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233994. NSArray* urls = [openPanel filenames];
  233995. for (unsigned int i = 0; i < [urls count]; ++i)
  233996. {
  233997. NSString* f = [urls objectAtIndex: i];
  233998. results.add (File (nsStringToJuce (f)));
  233999. }
  234000. }
  234001. }
  234002. [panel setDelegate: nil];
  234003. }
  234004. #else
  234005. void FileChooser::showPlatformDialog (Array<File>& results,
  234006. const String& title,
  234007. const File& currentFileOrDirectory,
  234008. const String& filter,
  234009. bool selectsDirectory,
  234010. bool selectsFiles,
  234011. bool isSaveDialogue,
  234012. bool warnAboutOverwritingExistingFiles,
  234013. bool selectMultipleFiles,
  234014. FilePreviewComponent* extraInfoComponent)
  234015. {
  234016. const ScopedAutoReleasePool pool;
  234017. jassertfalse; //xxx to do
  234018. }
  234019. #endif
  234020. #endif
  234021. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  234022. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234023. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234024. // compiled on its own).
  234025. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  234026. END_JUCE_NAMESPACE
  234027. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  234028. @interface NonInterceptingQTMovieView : QTMovieView
  234029. {
  234030. }
  234031. - (id) initWithFrame: (NSRect) frame;
  234032. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  234033. - (NSView*) hitTest: (NSPoint) p;
  234034. @end
  234035. @implementation NonInterceptingQTMovieView
  234036. - (id) initWithFrame: (NSRect) frame
  234037. {
  234038. self = [super initWithFrame: frame];
  234039. [self setNextResponder: [self superview]];
  234040. return self;
  234041. }
  234042. - (void) dealloc
  234043. {
  234044. [super dealloc];
  234045. }
  234046. - (NSView*) hitTest: (NSPoint) point
  234047. {
  234048. return [self isControllerVisible] ? [super hitTest: point] : nil;
  234049. }
  234050. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  234051. {
  234052. return YES;
  234053. }
  234054. @end
  234055. BEGIN_JUCE_NAMESPACE
  234056. #define theMovie (static_cast <QTMovie*> (movie))
  234057. QuickTimeMovieComponent::QuickTimeMovieComponent()
  234058. : movie (0)
  234059. {
  234060. setOpaque (true);
  234061. setVisible (true);
  234062. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  234063. setView (view);
  234064. [view release];
  234065. }
  234066. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  234067. {
  234068. closeMovie();
  234069. setView (0);
  234070. }
  234071. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  234072. {
  234073. return true;
  234074. }
  234075. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  234076. {
  234077. // unfortunately, QTMovie objects can only be created on the main thread..
  234078. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234079. QTMovie* movie = 0;
  234080. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  234081. if (fin != 0)
  234082. {
  234083. movieFile = fin->getFile();
  234084. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  234085. error: nil];
  234086. }
  234087. else
  234088. {
  234089. MemoryBlock temp;
  234090. movieStream->readIntoMemoryBlock (temp);
  234091. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  234092. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  234093. {
  234094. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  234095. length: temp.getSize()]
  234096. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  234097. MIMEType: @""]
  234098. error: nil];
  234099. if (movie != 0)
  234100. break;
  234101. }
  234102. }
  234103. return movie;
  234104. }
  234105. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  234106. const bool isControllerVisible_)
  234107. {
  234108. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  234109. }
  234110. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  234111. const bool controllerVisible_)
  234112. {
  234113. closeMovie();
  234114. if (getPeer() == 0)
  234115. {
  234116. // To open a movie, this component must be visible inside a functioning window, so that
  234117. // the QT control can be assigned to the window.
  234118. jassertfalse;
  234119. return false;
  234120. }
  234121. movie = openMovieFromStream (movieStream, movieFile);
  234122. [theMovie retain];
  234123. QTMovieView* view = (QTMovieView*) getView();
  234124. [view setMovie: theMovie];
  234125. [view setControllerVisible: controllerVisible_];
  234126. setLooping (looping);
  234127. return movie != nil;
  234128. }
  234129. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  234130. const bool isControllerVisible_)
  234131. {
  234132. // unfortunately, QTMovie objects can only be created on the main thread..
  234133. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234134. closeMovie();
  234135. if (getPeer() == 0)
  234136. {
  234137. // To open a movie, this component must be visible inside a functioning window, so that
  234138. // the QT control can be assigned to the window.
  234139. jassertfalse;
  234140. return false;
  234141. }
  234142. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  234143. NSError* err;
  234144. if ([QTMovie canInitWithURL: url])
  234145. movie = [QTMovie movieWithURL: url error: &err];
  234146. [theMovie retain];
  234147. QTMovieView* view = (QTMovieView*) getView();
  234148. [view setMovie: theMovie];
  234149. [view setControllerVisible: controllerVisible];
  234150. setLooping (looping);
  234151. return movie != nil;
  234152. }
  234153. void QuickTimeMovieComponent::closeMovie()
  234154. {
  234155. stop();
  234156. QTMovieView* view = (QTMovieView*) getView();
  234157. [view setMovie: nil];
  234158. [theMovie release];
  234159. movie = 0;
  234160. movieFile = File::nonexistent;
  234161. }
  234162. bool QuickTimeMovieComponent::isMovieOpen() const
  234163. {
  234164. return movie != nil;
  234165. }
  234166. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  234167. {
  234168. return movieFile;
  234169. }
  234170. void QuickTimeMovieComponent::play()
  234171. {
  234172. [theMovie play];
  234173. }
  234174. void QuickTimeMovieComponent::stop()
  234175. {
  234176. [theMovie stop];
  234177. }
  234178. bool QuickTimeMovieComponent::isPlaying() const
  234179. {
  234180. return movie != 0 && [theMovie rate] != 0;
  234181. }
  234182. void QuickTimeMovieComponent::setPosition (const double seconds)
  234183. {
  234184. if (movie != 0)
  234185. {
  234186. QTTime t;
  234187. t.timeValue = (uint64) (100000.0 * seconds);
  234188. t.timeScale = 100000;
  234189. t.flags = 0;
  234190. [theMovie setCurrentTime: t];
  234191. }
  234192. }
  234193. double QuickTimeMovieComponent::getPosition() const
  234194. {
  234195. if (movie == 0)
  234196. return 0.0;
  234197. QTTime t = [theMovie currentTime];
  234198. return t.timeValue / (double) t.timeScale;
  234199. }
  234200. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  234201. {
  234202. [theMovie setRate: newSpeed];
  234203. }
  234204. double QuickTimeMovieComponent::getMovieDuration() const
  234205. {
  234206. if (movie == 0)
  234207. return 0.0;
  234208. QTTime t = [theMovie duration];
  234209. return t.timeValue / (double) t.timeScale;
  234210. }
  234211. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  234212. {
  234213. looping = shouldLoop;
  234214. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  234215. forKey: QTMovieLoopsAttribute];
  234216. }
  234217. bool QuickTimeMovieComponent::isLooping() const
  234218. {
  234219. return looping;
  234220. }
  234221. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  234222. {
  234223. [theMovie setVolume: newVolume];
  234224. }
  234225. float QuickTimeMovieComponent::getMovieVolume() const
  234226. {
  234227. return movie != 0 ? [theMovie volume] : 0.0f;
  234228. }
  234229. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  234230. {
  234231. width = 0;
  234232. height = 0;
  234233. if (movie != 0)
  234234. {
  234235. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  234236. width = (int) s.width;
  234237. height = (int) s.height;
  234238. }
  234239. }
  234240. void QuickTimeMovieComponent::paint (Graphics& g)
  234241. {
  234242. if (movie == 0)
  234243. g.fillAll (Colours::black);
  234244. }
  234245. bool QuickTimeMovieComponent::isControllerVisible() const
  234246. {
  234247. return controllerVisible;
  234248. }
  234249. void QuickTimeMovieComponent::goToStart()
  234250. {
  234251. setPosition (0.0);
  234252. }
  234253. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  234254. const RectanglePlacement& placement)
  234255. {
  234256. int normalWidth, normalHeight;
  234257. getMovieNormalSize (normalWidth, normalHeight);
  234258. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  234259. {
  234260. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  234261. placement.applyTo (x, y, w, h,
  234262. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  234263. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  234264. if (w > 0 && h > 0)
  234265. {
  234266. setBounds (roundToInt (x), roundToInt (y),
  234267. roundToInt (w), roundToInt (h));
  234268. }
  234269. }
  234270. else
  234271. {
  234272. setBounds (spaceToFitWithin);
  234273. }
  234274. }
  234275. #if ! (JUCE_MAC && JUCE_64BIT)
  234276. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  234277. {
  234278. if (movieStream == 0)
  234279. return false;
  234280. File file;
  234281. QTMovie* movie = openMovieFromStream (movieStream, file);
  234282. if (movie != nil)
  234283. result = [movie quickTimeMovie];
  234284. return movie != nil;
  234285. }
  234286. #endif
  234287. #endif
  234288. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234289. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  234290. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234291. // compiled on its own).
  234292. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  234293. const int kilobytesPerSecond1x = 176;
  234294. END_JUCE_NAMESPACE
  234295. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  234296. @interface OpenDiskDevice : NSObject
  234297. {
  234298. @public
  234299. DRDevice* device;
  234300. NSMutableArray* tracks;
  234301. bool underrunProtection;
  234302. }
  234303. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  234304. - (void) dealloc;
  234305. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  234306. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234307. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  234308. @end
  234309. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  234310. @interface AudioTrackProducer : NSObject
  234311. {
  234312. JUCE_NAMESPACE::AudioSource* source;
  234313. int readPosition, lengthInFrames;
  234314. }
  234315. - (AudioTrackProducer*) init: (int) lengthInFrames;
  234316. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  234317. - (void) dealloc;
  234318. - (void) setupTrackProperties: (DRTrack*) track;
  234319. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  234320. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  234321. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  234322. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  234323. toMedia:(NSDictionary*)mediaInfo;
  234324. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  234325. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  234326. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234327. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234328. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234329. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234330. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234331. ioFlags:(uint32_t*)flags;
  234332. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  234333. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234334. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234335. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234336. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234337. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234338. ioFlags:(uint32_t*)flags;
  234339. @end
  234340. @implementation OpenDiskDevice
  234341. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  234342. {
  234343. [super init];
  234344. device = device_;
  234345. tracks = [[NSMutableArray alloc] init];
  234346. underrunProtection = true;
  234347. return self;
  234348. }
  234349. - (void) dealloc
  234350. {
  234351. [tracks release];
  234352. [super dealloc];
  234353. }
  234354. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  234355. {
  234356. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  234357. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  234358. [p setupTrackProperties: t];
  234359. [tracks addObject: t];
  234360. [t release];
  234361. [p release];
  234362. }
  234363. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234364. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234365. {
  234366. DRBurn* burn = [DRBurn burnForDevice: device];
  234367. if (! [device acquireExclusiveAccess])
  234368. {
  234369. *error = "Couldn't open or write to the CD device";
  234370. return;
  234371. }
  234372. [device acquireMediaReservation];
  234373. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234374. [d autorelease];
  234375. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234376. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234377. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234378. if (burnSpeed > 0)
  234379. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234380. if (! underrunProtection)
  234381. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234382. [burn setProperties: d];
  234383. [burn writeLayout: tracks];
  234384. for (;;)
  234385. {
  234386. JUCE_NAMESPACE::Thread::sleep (300);
  234387. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234388. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234389. {
  234390. [burn abort];
  234391. *error = "User cancelled the write operation";
  234392. break;
  234393. }
  234394. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234395. {
  234396. *error = "Write operation failed";
  234397. break;
  234398. }
  234399. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234400. {
  234401. break;
  234402. }
  234403. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234404. objectForKey: DRErrorStatusErrorStringKey];
  234405. if ([err length] > 0)
  234406. {
  234407. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234408. break;
  234409. }
  234410. }
  234411. [device releaseMediaReservation];
  234412. [device releaseExclusiveAccess];
  234413. }
  234414. @end
  234415. @implementation AudioTrackProducer
  234416. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234417. {
  234418. lengthInFrames = lengthInFrames_;
  234419. readPosition = 0;
  234420. return self;
  234421. }
  234422. - (void) setupTrackProperties: (DRTrack*) track
  234423. {
  234424. NSMutableDictionary* p = [[track properties] mutableCopy];
  234425. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234426. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234427. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234428. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234429. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234430. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234431. [track setProperties: p];
  234432. [p release];
  234433. }
  234434. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234435. {
  234436. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234437. if (s != nil)
  234438. s->source = source_;
  234439. return s;
  234440. }
  234441. - (void) dealloc
  234442. {
  234443. if (source != 0)
  234444. {
  234445. source->releaseResources();
  234446. delete source;
  234447. }
  234448. [super dealloc];
  234449. }
  234450. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234451. {
  234452. }
  234453. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234454. {
  234455. return true;
  234456. }
  234457. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234458. {
  234459. return lengthInFrames;
  234460. }
  234461. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234462. toMedia: (NSDictionary*) mediaInfo
  234463. {
  234464. if (source != 0)
  234465. source->prepareToPlay (44100 / 75, 44100);
  234466. readPosition = 0;
  234467. return true;
  234468. }
  234469. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234470. {
  234471. if (source != 0)
  234472. source->prepareToPlay (44100 / 75, 44100);
  234473. return true;
  234474. }
  234475. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234476. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234477. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234478. {
  234479. if (source != 0)
  234480. {
  234481. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234482. if (numSamples > 0)
  234483. {
  234484. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234485. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234486. info.buffer = &tempBuffer;
  234487. info.startSample = 0;
  234488. info.numSamples = numSamples;
  234489. source->getNextAudioBlock (info);
  234490. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  234491. JUCE_NAMESPACE::AudioData::LittleEndian,
  234492. JUCE_NAMESPACE::AudioData::Interleaved,
  234493. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  234494. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  234495. JUCE_NAMESPACE::AudioData::NativeEndian,
  234496. JUCE_NAMESPACE::AudioData::NonInterleaved,
  234497. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  234498. CDSampleFormat left (buffer, 2);
  234499. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  234500. CDSampleFormat right (buffer + 2, 2);
  234501. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  234502. readPosition += numSamples;
  234503. }
  234504. return numSamples * 4;
  234505. }
  234506. return 0;
  234507. }
  234508. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234509. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234510. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234511. ioFlags: (uint32_t*) flags
  234512. {
  234513. zeromem (buffer, bufferLength);
  234514. return bufferLength;
  234515. }
  234516. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234517. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234518. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234519. {
  234520. return true;
  234521. }
  234522. @end
  234523. BEGIN_JUCE_NAMESPACE
  234524. class AudioCDBurner::Pimpl : public Timer
  234525. {
  234526. public:
  234527. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234528. : device (0), owner (owner_)
  234529. {
  234530. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234531. if (dev != 0)
  234532. {
  234533. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234534. lastState = getDiskState();
  234535. startTimer (1000);
  234536. }
  234537. }
  234538. ~Pimpl()
  234539. {
  234540. stopTimer();
  234541. [device release];
  234542. }
  234543. void timerCallback()
  234544. {
  234545. const DiskState state = getDiskState();
  234546. if (state != lastState)
  234547. {
  234548. lastState = state;
  234549. owner.sendChangeMessage();
  234550. }
  234551. }
  234552. DiskState getDiskState() const
  234553. {
  234554. if ([device->device isValid])
  234555. {
  234556. NSDictionary* status = [device->device status];
  234557. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234558. if ([state isEqualTo: DRDeviceMediaStateNone])
  234559. {
  234560. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234561. return trayOpen;
  234562. return noDisc;
  234563. }
  234564. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234565. {
  234566. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234567. return writableDiskPresent;
  234568. else
  234569. return readOnlyDiskPresent;
  234570. }
  234571. }
  234572. return unknown;
  234573. }
  234574. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234575. const Array<int> getAvailableWriteSpeeds() const
  234576. {
  234577. Array<int> results;
  234578. if ([device->device isValid])
  234579. {
  234580. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234581. for (unsigned int i = 0; i < [speeds count]; ++i)
  234582. {
  234583. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234584. results.add (kbPerSec / kilobytesPerSecond1x);
  234585. }
  234586. }
  234587. return results;
  234588. }
  234589. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234590. {
  234591. if ([device->device isValid])
  234592. {
  234593. device->underrunProtection = shouldBeEnabled;
  234594. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234595. }
  234596. return false;
  234597. }
  234598. int getNumAvailableAudioBlocks() const
  234599. {
  234600. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234601. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234602. }
  234603. OpenDiskDevice* device;
  234604. private:
  234605. DiskState lastState;
  234606. AudioCDBurner& owner;
  234607. };
  234608. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234609. {
  234610. pimpl = new Pimpl (*this, deviceIndex);
  234611. }
  234612. AudioCDBurner::~AudioCDBurner()
  234613. {
  234614. }
  234615. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234616. {
  234617. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234618. if (b->pimpl->device == 0)
  234619. b = 0;
  234620. return b.release();
  234621. }
  234622. namespace
  234623. {
  234624. NSArray* findDiskBurnerDevices()
  234625. {
  234626. NSMutableArray* results = [NSMutableArray array];
  234627. NSArray* devs = [DRDevice devices];
  234628. for (int i = 0; i < [devs count]; ++i)
  234629. {
  234630. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234631. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234632. if (name != nil)
  234633. [results addObject: name];
  234634. }
  234635. return results;
  234636. }
  234637. }
  234638. const StringArray AudioCDBurner::findAvailableDevices()
  234639. {
  234640. NSArray* names = findDiskBurnerDevices();
  234641. StringArray s;
  234642. for (unsigned int i = 0; i < [names count]; ++i)
  234643. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234644. return s;
  234645. }
  234646. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234647. {
  234648. return pimpl->getDiskState();
  234649. }
  234650. bool AudioCDBurner::isDiskPresent() const
  234651. {
  234652. return getDiskState() == writableDiskPresent;
  234653. }
  234654. bool AudioCDBurner::openTray()
  234655. {
  234656. return pimpl->openTray();
  234657. }
  234658. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234659. {
  234660. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234661. DiskState oldState = getDiskState();
  234662. DiskState newState = oldState;
  234663. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234664. {
  234665. newState = getDiskState();
  234666. Thread::sleep (100);
  234667. }
  234668. return newState;
  234669. }
  234670. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234671. {
  234672. return pimpl->getAvailableWriteSpeeds();
  234673. }
  234674. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234675. {
  234676. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234677. }
  234678. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234679. {
  234680. return pimpl->getNumAvailableAudioBlocks();
  234681. }
  234682. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234683. {
  234684. if ([pimpl->device->device isValid])
  234685. {
  234686. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234687. return true;
  234688. }
  234689. return false;
  234690. }
  234691. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234692. bool ejectDiscAfterwards,
  234693. bool performFakeBurnForTesting,
  234694. int writeSpeed)
  234695. {
  234696. String error ("Couldn't open or write to the CD device");
  234697. if ([pimpl->device->device isValid])
  234698. {
  234699. error = String::empty;
  234700. [pimpl->device burn: listener
  234701. errorString: &error
  234702. ejectAfterwards: ejectDiscAfterwards
  234703. isFake: performFakeBurnForTesting
  234704. speed: writeSpeed];
  234705. }
  234706. return error;
  234707. }
  234708. #endif
  234709. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234710. void AudioCDReader::ejectDisk()
  234711. {
  234712. const ScopedAutoReleasePool p;
  234713. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234714. }
  234715. #endif
  234716. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234717. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234718. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234719. // compiled on its own).
  234720. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234721. namespace CDReaderHelpers
  234722. {
  234723. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234724. {
  234725. forEachXmlChildElementWithTagName (xml, child, "key")
  234726. if (child->getAllSubText().trim() == key)
  234727. return child->getNextElement();
  234728. return 0;
  234729. }
  234730. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234731. {
  234732. const XmlElement* const block = getElementForKey (xml, key);
  234733. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234734. }
  234735. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234736. // Returns NULL on success, otherwise a const char* representing an error.
  234737. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234738. {
  234739. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234740. if (xml == 0)
  234741. return "Couldn't parse XML in file";
  234742. const XmlElement* const dict = xml->getChildByName ("dict");
  234743. if (dict == 0)
  234744. return "Couldn't get top level dictionary";
  234745. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234746. if (sessions == 0)
  234747. return "Couldn't find sessions key";
  234748. const XmlElement* const session = sessions->getFirstChildElement();
  234749. if (session == 0)
  234750. return "Couldn't find first session";
  234751. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234752. if (leadOut < 0)
  234753. return "Couldn't find Leadout Block";
  234754. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234755. if (trackArray == 0)
  234756. return "Couldn't find Track Array";
  234757. forEachXmlChildElement (*trackArray, track)
  234758. {
  234759. const int trackValue = getIntValueForKey (*track, "Start Block");
  234760. if (trackValue < 0)
  234761. return "Couldn't find Start Block in the track";
  234762. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234763. }
  234764. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234765. return 0;
  234766. }
  234767. static void findDevices (Array<File>& cds)
  234768. {
  234769. File volumes ("/Volumes");
  234770. volumes.findChildFiles (cds, File::findDirectories, false);
  234771. for (int i = cds.size(); --i >= 0;)
  234772. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234773. cds.remove (i);
  234774. }
  234775. struct TrackSorter
  234776. {
  234777. static int getCDTrackNumber (const File& file)
  234778. {
  234779. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234780. }
  234781. static int compareElements (const File& first, const File& second)
  234782. {
  234783. const int firstTrack = getCDTrackNumber (first);
  234784. const int secondTrack = getCDTrackNumber (second);
  234785. jassert (firstTrack > 0 && secondTrack > 0);
  234786. return firstTrack - secondTrack;
  234787. }
  234788. };
  234789. }
  234790. const StringArray AudioCDReader::getAvailableCDNames()
  234791. {
  234792. Array<File> cds;
  234793. CDReaderHelpers::findDevices (cds);
  234794. StringArray names;
  234795. for (int i = 0; i < cds.size(); ++i)
  234796. names.add (cds.getReference(i).getFileName());
  234797. return names;
  234798. }
  234799. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234800. {
  234801. Array<File> cds;
  234802. CDReaderHelpers::findDevices (cds);
  234803. if (cds[index].exists())
  234804. return new AudioCDReader (cds[index]);
  234805. return 0;
  234806. }
  234807. AudioCDReader::AudioCDReader (const File& volume)
  234808. : AudioFormatReader (0, "CD Audio"),
  234809. volumeDir (volume),
  234810. currentReaderTrack (-1),
  234811. reader (0)
  234812. {
  234813. sampleRate = 44100.0;
  234814. bitsPerSample = 16;
  234815. numChannels = 2;
  234816. usesFloatingPointData = false;
  234817. refreshTrackLengths();
  234818. }
  234819. AudioCDReader::~AudioCDReader()
  234820. {
  234821. }
  234822. void AudioCDReader::refreshTrackLengths()
  234823. {
  234824. tracks.clear();
  234825. trackStartSamples.clear();
  234826. lengthInSamples = 0;
  234827. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234828. CDReaderHelpers::TrackSorter sorter;
  234829. tracks.sort (sorter);
  234830. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234831. if (toc.exists())
  234832. {
  234833. XmlDocument doc (toc);
  234834. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234835. (void) error; // could be logged..
  234836. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234837. }
  234838. }
  234839. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234840. int64 startSampleInFile, int numSamples)
  234841. {
  234842. while (numSamples > 0)
  234843. {
  234844. int track = -1;
  234845. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234846. {
  234847. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234848. {
  234849. track = i;
  234850. break;
  234851. }
  234852. }
  234853. if (track < 0)
  234854. return false;
  234855. if (track != currentReaderTrack)
  234856. {
  234857. reader = 0;
  234858. FileInputStream* const in = tracks [track].createInputStream();
  234859. if (in != 0)
  234860. {
  234861. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234862. AiffAudioFormat format;
  234863. reader = format.createReaderFor (bin, true);
  234864. if (reader == 0)
  234865. currentReaderTrack = -1;
  234866. else
  234867. currentReaderTrack = track;
  234868. }
  234869. }
  234870. if (reader == 0)
  234871. return false;
  234872. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234873. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234874. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234875. numSamples -= numAvailable;
  234876. startSampleInFile += numAvailable;
  234877. }
  234878. return true;
  234879. }
  234880. bool AudioCDReader::isCDStillPresent() const
  234881. {
  234882. return volumeDir.exists();
  234883. }
  234884. bool AudioCDReader::isTrackAudio (int trackNum) const
  234885. {
  234886. return tracks [trackNum].hasFileExtension (".aiff");
  234887. }
  234888. void AudioCDReader::enableIndexScanning (bool b)
  234889. {
  234890. // any way to do this on a Mac??
  234891. }
  234892. int AudioCDReader::getLastIndex() const
  234893. {
  234894. return 0;
  234895. }
  234896. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234897. {
  234898. return Array <int>();
  234899. }
  234900. #endif
  234901. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234902. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234903. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234904. // compiled on its own).
  234905. #if JUCE_INCLUDED_FILE
  234906. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234907. for example having more than one juce plugin loaded into a host, then when a
  234908. method is called, the actual code that runs might actually be in a different module
  234909. than the one you expect... So any calls to library functions or statics that are
  234910. made inside obj-c methods will probably end up getting executed in a different DLL's
  234911. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234912. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234913. virtual methods of an object that's known to live inside the right module's space.
  234914. */
  234915. class AppDelegateRedirector
  234916. {
  234917. public:
  234918. AppDelegateRedirector()
  234919. {
  234920. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234921. runLoop = CFRunLoopGetMain();
  234922. #else
  234923. runLoop = CFRunLoopGetCurrent();
  234924. #endif
  234925. CFRunLoopSourceContext sourceContext;
  234926. zerostruct (sourceContext);
  234927. sourceContext.info = this;
  234928. sourceContext.perform = runLoopSourceCallback;
  234929. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234930. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234931. }
  234932. virtual ~AppDelegateRedirector()
  234933. {
  234934. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234935. CFRunLoopSourceInvalidate (runLoopSource);
  234936. CFRelease (runLoopSource);
  234937. }
  234938. virtual NSApplicationTerminateReply shouldTerminate()
  234939. {
  234940. if (JUCEApplication::getInstance() != 0)
  234941. {
  234942. JUCEApplication::getInstance()->systemRequestedQuit();
  234943. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234944. return NSTerminateCancel;
  234945. }
  234946. return NSTerminateNow;
  234947. }
  234948. virtual void willTerminate()
  234949. {
  234950. JUCEApplication::appWillTerminateByForce();
  234951. }
  234952. virtual BOOL openFile (NSString* filename)
  234953. {
  234954. if (JUCEApplication::getInstance() != 0)
  234955. {
  234956. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234957. return YES;
  234958. }
  234959. return NO;
  234960. }
  234961. virtual void openFiles (NSArray* filenames)
  234962. {
  234963. StringArray files;
  234964. for (unsigned int i = 0; i < [filenames count]; ++i)
  234965. {
  234966. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234967. if (filename.containsChar (' '))
  234968. filename = filename.quoted('"');
  234969. files.add (filename);
  234970. }
  234971. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234972. {
  234973. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234974. }
  234975. }
  234976. virtual void focusChanged()
  234977. {
  234978. juce_HandleProcessFocusChange();
  234979. }
  234980. struct CallbackMessagePayload
  234981. {
  234982. MessageCallbackFunction* function;
  234983. void* parameter;
  234984. void* volatile result;
  234985. bool volatile hasBeenExecuted;
  234986. };
  234987. virtual void performCallback (CallbackMessagePayload* pl)
  234988. {
  234989. pl->result = (*pl->function) (pl->parameter);
  234990. pl->hasBeenExecuted = true;
  234991. }
  234992. virtual void deleteSelf()
  234993. {
  234994. delete this;
  234995. }
  234996. void postMessage (Message* const m)
  234997. {
  234998. messages.add (m);
  234999. CFRunLoopSourceSignal (runLoopSource);
  235000. CFRunLoopWakeUp (runLoop);
  235001. }
  235002. private:
  235003. CFRunLoopRef runLoop;
  235004. CFRunLoopSourceRef runLoopSource;
  235005. OwnedArray <Message, CriticalSection> messages;
  235006. void runLoopCallback()
  235007. {
  235008. int numDispatched = 0;
  235009. do
  235010. {
  235011. Message* const nextMessage = messages.removeAndReturn (0);
  235012. if (nextMessage == 0)
  235013. return;
  235014. const ScopedAutoReleasePool pool;
  235015. MessageManager::getInstance()->deliverMessage (nextMessage);
  235016. } while (++numDispatched <= 4);
  235017. CFRunLoopSourceSignal (runLoopSource);
  235018. CFRunLoopWakeUp (runLoop);
  235019. }
  235020. static void runLoopSourceCallback (void* info)
  235021. {
  235022. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  235023. }
  235024. };
  235025. END_JUCE_NAMESPACE
  235026. using namespace JUCE_NAMESPACE;
  235027. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  235028. @interface JuceAppDelegate : NSObject
  235029. {
  235030. @private
  235031. id oldDelegate;
  235032. @public
  235033. AppDelegateRedirector* redirector;
  235034. }
  235035. - (JuceAppDelegate*) init;
  235036. - (void) dealloc;
  235037. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  235038. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  235039. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  235040. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  235041. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  235042. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  235043. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  235044. - (void) performCallback: (id) info;
  235045. - (void) dummyMethod;
  235046. @end
  235047. @implementation JuceAppDelegate
  235048. - (JuceAppDelegate*) init
  235049. {
  235050. [super init];
  235051. redirector = new AppDelegateRedirector();
  235052. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  235053. if (JUCEApplication::isStandaloneApp())
  235054. {
  235055. oldDelegate = [NSApp delegate];
  235056. [NSApp setDelegate: self];
  235057. }
  235058. else
  235059. {
  235060. oldDelegate = 0;
  235061. [center addObserver: self selector: @selector (applicationDidResignActive:)
  235062. name: NSApplicationDidResignActiveNotification object: NSApp];
  235063. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  235064. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  235065. [center addObserver: self selector: @selector (applicationWillUnhide:)
  235066. name: NSApplicationWillUnhideNotification object: NSApp];
  235067. }
  235068. return self;
  235069. }
  235070. - (void) dealloc
  235071. {
  235072. if (oldDelegate != 0)
  235073. [NSApp setDelegate: oldDelegate];
  235074. redirector->deleteSelf();
  235075. [super dealloc];
  235076. }
  235077. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  235078. {
  235079. (void) app;
  235080. return redirector->shouldTerminate();
  235081. }
  235082. - (void) applicationWillTerminate: (NSNotification*) aNotification
  235083. {
  235084. (void) aNotification;
  235085. redirector->willTerminate();
  235086. }
  235087. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  235088. {
  235089. (void) app;
  235090. return redirector->openFile (filename);
  235091. }
  235092. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  235093. {
  235094. (void) sender;
  235095. return redirector->openFiles (filenames);
  235096. }
  235097. - (void) applicationDidBecomeActive: (NSNotification*) notification
  235098. {
  235099. (void) notification;
  235100. redirector->focusChanged();
  235101. }
  235102. - (void) applicationDidResignActive: (NSNotification*) notification
  235103. {
  235104. (void) notification;
  235105. redirector->focusChanged();
  235106. }
  235107. - (void) applicationWillUnhide: (NSNotification*) notification
  235108. {
  235109. (void) notification;
  235110. redirector->focusChanged();
  235111. }
  235112. - (void) performCallback: (id) info
  235113. {
  235114. if ([info isKindOfClass: [NSData class]])
  235115. {
  235116. AppDelegateRedirector::CallbackMessagePayload* pl
  235117. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  235118. if (pl != 0)
  235119. redirector->performCallback (pl);
  235120. }
  235121. else
  235122. {
  235123. jassertfalse; // should never get here!
  235124. }
  235125. }
  235126. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  235127. @end
  235128. BEGIN_JUCE_NAMESPACE
  235129. static JuceAppDelegate* juceAppDelegate = 0;
  235130. void MessageManager::runDispatchLoop()
  235131. {
  235132. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  235133. {
  235134. const ScopedAutoReleasePool pool;
  235135. // must only be called by the message thread!
  235136. jassert (isThisTheMessageThread());
  235137. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  235138. @try
  235139. {
  235140. [NSApp run];
  235141. }
  235142. @catch (NSException* e)
  235143. {
  235144. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  235145. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  235146. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  235147. }
  235148. @finally
  235149. {
  235150. }
  235151. #else
  235152. [NSApp run];
  235153. #endif
  235154. }
  235155. }
  235156. void MessageManager::stopDispatchLoop()
  235157. {
  235158. quitMessagePosted = true;
  235159. [NSApp stop: nil];
  235160. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  235161. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  235162. }
  235163. namespace
  235164. {
  235165. bool isEventBlockedByModalComps (NSEvent* e)
  235166. {
  235167. if (Component::getNumCurrentlyModalComponents() == 0)
  235168. return false;
  235169. NSWindow* const w = [e window];
  235170. if (w == 0 || [w worksWhenModal])
  235171. return false;
  235172. bool isKey = false, isInputAttempt = false;
  235173. switch ([e type])
  235174. {
  235175. case NSKeyDown:
  235176. case NSKeyUp:
  235177. isKey = isInputAttempt = true;
  235178. break;
  235179. case NSLeftMouseDown:
  235180. case NSRightMouseDown:
  235181. case NSOtherMouseDown:
  235182. isInputAttempt = true;
  235183. break;
  235184. case NSLeftMouseDragged:
  235185. case NSRightMouseDragged:
  235186. case NSLeftMouseUp:
  235187. case NSRightMouseUp:
  235188. case NSOtherMouseUp:
  235189. case NSOtherMouseDragged:
  235190. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  235191. return false;
  235192. break;
  235193. case NSMouseMoved:
  235194. case NSMouseEntered:
  235195. case NSMouseExited:
  235196. case NSCursorUpdate:
  235197. case NSScrollWheel:
  235198. case NSTabletPoint:
  235199. case NSTabletProximity:
  235200. break;
  235201. default:
  235202. return false;
  235203. }
  235204. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  235205. {
  235206. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  235207. NSView* const compView = (NSView*) peer->getNativeHandle();
  235208. if ([compView window] == w)
  235209. {
  235210. if (isKey)
  235211. {
  235212. if (compView == [w firstResponder])
  235213. return false;
  235214. }
  235215. else
  235216. {
  235217. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  235218. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  235219. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  235220. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  235221. return false;
  235222. }
  235223. }
  235224. }
  235225. if (isInputAttempt)
  235226. {
  235227. if (! [NSApp isActive])
  235228. [NSApp activateIgnoringOtherApps: YES];
  235229. Component* const modal = Component::getCurrentlyModalComponent (0);
  235230. if (modal != 0)
  235231. modal->inputAttemptWhenModal();
  235232. }
  235233. return true;
  235234. }
  235235. }
  235236. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  235237. {
  235238. jassert (isThisTheMessageThread()); // must only be called by the message thread
  235239. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  235240. while (! quitMessagePosted)
  235241. {
  235242. const ScopedAutoReleasePool pool;
  235243. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  235244. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  235245. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  235246. inMode: NSDefaultRunLoopMode
  235247. dequeue: YES];
  235248. if (e != 0 && ! isEventBlockedByModalComps (e))
  235249. [NSApp sendEvent: e];
  235250. if (Time::getMillisecondCounter() >= endTime)
  235251. break;
  235252. }
  235253. return ! quitMessagePosted;
  235254. }
  235255. void MessageManager::doPlatformSpecificInitialisation()
  235256. {
  235257. if (juceAppDelegate == 0)
  235258. juceAppDelegate = [[JuceAppDelegate alloc] init];
  235259. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  235260. // correctly (needed prior to 10.5)
  235261. if (! [NSThread isMultiThreaded])
  235262. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  235263. toTarget: juceAppDelegate
  235264. withObject: nil];
  235265. }
  235266. void MessageManager::doPlatformSpecificShutdown()
  235267. {
  235268. if (juceAppDelegate != 0)
  235269. {
  235270. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  235271. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  235272. [juceAppDelegate release];
  235273. juceAppDelegate = 0;
  235274. }
  235275. }
  235276. bool juce_postMessageToSystemQueue (Message* message)
  235277. {
  235278. juceAppDelegate->redirector->postMessage (message);
  235279. return true;
  235280. }
  235281. void MessageManager::broadcastMessage (const String& value)
  235282. {
  235283. }
  235284. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  235285. {
  235286. if (isThisTheMessageThread())
  235287. {
  235288. return (*callback) (data);
  235289. }
  235290. else
  235291. {
  235292. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  235293. // deadlock because the message manager is blocked from running, so can never
  235294. // call your function..
  235295. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  235296. const ScopedAutoReleasePool pool;
  235297. AppDelegateRedirector::CallbackMessagePayload cmp;
  235298. cmp.function = callback;
  235299. cmp.parameter = data;
  235300. cmp.result = 0;
  235301. cmp.hasBeenExecuted = false;
  235302. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  235303. withObject: [NSData dataWithBytesNoCopy: &cmp
  235304. length: sizeof (cmp)
  235305. freeWhenDone: NO]
  235306. waitUntilDone: YES];
  235307. return cmp.result;
  235308. }
  235309. }
  235310. #endif
  235311. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  235312. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235313. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235314. // compiled on its own).
  235315. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  235316. #if JUCE_MAC
  235317. END_JUCE_NAMESPACE
  235318. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  235319. @interface DownloadClickDetector : NSObject
  235320. {
  235321. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  235322. }
  235323. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  235324. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235325. request: (NSURLRequest*) request
  235326. frame: (WebFrame*) frame
  235327. decisionListener: (id<WebPolicyDecisionListener>) listener;
  235328. @end
  235329. @implementation DownloadClickDetector
  235330. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  235331. {
  235332. [super init];
  235333. ownerComponent = ownerComponent_;
  235334. return self;
  235335. }
  235336. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235337. request: (NSURLRequest*) request
  235338. frame: (WebFrame*) frame
  235339. decisionListener: (id <WebPolicyDecisionListener>) listener
  235340. {
  235341. (void) sender;
  235342. (void) request;
  235343. (void) frame;
  235344. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  235345. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  235346. [listener use];
  235347. else
  235348. [listener ignore];
  235349. }
  235350. @end
  235351. BEGIN_JUCE_NAMESPACE
  235352. class WebBrowserComponentInternal : public NSViewComponent
  235353. {
  235354. public:
  235355. WebBrowserComponentInternal (WebBrowserComponent* owner)
  235356. {
  235357. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  235358. frameName: @""
  235359. groupName: @""];
  235360. setView (webView);
  235361. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  235362. [webView setPolicyDelegate: clickListener];
  235363. }
  235364. ~WebBrowserComponentInternal()
  235365. {
  235366. [webView setPolicyDelegate: nil];
  235367. [clickListener release];
  235368. setView (0);
  235369. }
  235370. void goToURL (const String& url,
  235371. const StringArray* headers,
  235372. const MemoryBlock* postData)
  235373. {
  235374. NSMutableURLRequest* r
  235375. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235376. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235377. timeoutInterval: 30.0];
  235378. if (postData != 0 && postData->getSize() > 0)
  235379. {
  235380. [r setHTTPMethod: @"POST"];
  235381. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235382. length: postData->getSize()]];
  235383. }
  235384. if (headers != 0)
  235385. {
  235386. for (int i = 0; i < headers->size(); ++i)
  235387. {
  235388. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235389. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235390. [r setValue: juceStringToNS (headerValue)
  235391. forHTTPHeaderField: juceStringToNS (headerName)];
  235392. }
  235393. }
  235394. stop();
  235395. [[webView mainFrame] loadRequest: r];
  235396. }
  235397. void goBack()
  235398. {
  235399. [webView goBack];
  235400. }
  235401. void goForward()
  235402. {
  235403. [webView goForward];
  235404. }
  235405. void stop()
  235406. {
  235407. [webView stopLoading: nil];
  235408. }
  235409. void refresh()
  235410. {
  235411. [webView reload: nil];
  235412. }
  235413. void mouseMove (const MouseEvent&)
  235414. {
  235415. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  235416. // them work is to push them via this non-public method..
  235417. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  235418. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  235419. }
  235420. private:
  235421. WebView* webView;
  235422. DownloadClickDetector* clickListener;
  235423. };
  235424. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235425. : browser (0),
  235426. blankPageShown (false),
  235427. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235428. {
  235429. setOpaque (true);
  235430. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235431. }
  235432. WebBrowserComponent::~WebBrowserComponent()
  235433. {
  235434. deleteAndZero (browser);
  235435. }
  235436. void WebBrowserComponent::goToURL (const String& url,
  235437. const StringArray* headers,
  235438. const MemoryBlock* postData)
  235439. {
  235440. lastURL = url;
  235441. lastHeaders.clear();
  235442. if (headers != 0)
  235443. lastHeaders = *headers;
  235444. lastPostData.setSize (0);
  235445. if (postData != 0)
  235446. lastPostData = *postData;
  235447. blankPageShown = false;
  235448. browser->goToURL (url, headers, postData);
  235449. }
  235450. void WebBrowserComponent::stop()
  235451. {
  235452. browser->stop();
  235453. }
  235454. void WebBrowserComponent::goBack()
  235455. {
  235456. lastURL = String::empty;
  235457. blankPageShown = false;
  235458. browser->goBack();
  235459. }
  235460. void WebBrowserComponent::goForward()
  235461. {
  235462. lastURL = String::empty;
  235463. browser->goForward();
  235464. }
  235465. void WebBrowserComponent::refresh()
  235466. {
  235467. browser->refresh();
  235468. }
  235469. void WebBrowserComponent::paint (Graphics&)
  235470. {
  235471. }
  235472. void WebBrowserComponent::checkWindowAssociation()
  235473. {
  235474. if (isShowing())
  235475. {
  235476. if (blankPageShown)
  235477. goBack();
  235478. }
  235479. else
  235480. {
  235481. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235482. {
  235483. // when the component becomes invisible, some stuff like flash
  235484. // carries on playing audio, so we need to force it onto a blank
  235485. // page to avoid this, (and send it back when it's made visible again).
  235486. blankPageShown = true;
  235487. browser->goToURL ("about:blank", 0, 0);
  235488. }
  235489. }
  235490. }
  235491. void WebBrowserComponent::reloadLastURL()
  235492. {
  235493. if (lastURL.isNotEmpty())
  235494. {
  235495. goToURL (lastURL, &lastHeaders, &lastPostData);
  235496. lastURL = String::empty;
  235497. }
  235498. }
  235499. void WebBrowserComponent::parentHierarchyChanged()
  235500. {
  235501. checkWindowAssociation();
  235502. }
  235503. void WebBrowserComponent::resized()
  235504. {
  235505. browser->setSize (getWidth(), getHeight());
  235506. }
  235507. void WebBrowserComponent::visibilityChanged()
  235508. {
  235509. checkWindowAssociation();
  235510. }
  235511. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235512. {
  235513. return true;
  235514. }
  235515. #else
  235516. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235517. {
  235518. }
  235519. WebBrowserComponent::~WebBrowserComponent()
  235520. {
  235521. }
  235522. void WebBrowserComponent::goToURL (const String& url,
  235523. const StringArray* headers,
  235524. const MemoryBlock* postData)
  235525. {
  235526. }
  235527. void WebBrowserComponent::stop()
  235528. {
  235529. }
  235530. void WebBrowserComponent::goBack()
  235531. {
  235532. }
  235533. void WebBrowserComponent::goForward()
  235534. {
  235535. }
  235536. void WebBrowserComponent::refresh()
  235537. {
  235538. }
  235539. void WebBrowserComponent::paint (Graphics& g)
  235540. {
  235541. }
  235542. void WebBrowserComponent::checkWindowAssociation()
  235543. {
  235544. }
  235545. void WebBrowserComponent::reloadLastURL()
  235546. {
  235547. }
  235548. void WebBrowserComponent::parentHierarchyChanged()
  235549. {
  235550. }
  235551. void WebBrowserComponent::resized()
  235552. {
  235553. }
  235554. void WebBrowserComponent::visibilityChanged()
  235555. {
  235556. }
  235557. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235558. {
  235559. return true;
  235560. }
  235561. #endif
  235562. #endif
  235563. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235564. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235565. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235566. // compiled on its own).
  235567. #if JUCE_INCLUDED_FILE
  235568. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235569. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235570. #endif
  235571. #undef log
  235572. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235573. #define log(a) Logger::writeToLog (a)
  235574. #else
  235575. #define log(a)
  235576. #endif
  235577. #undef OK
  235578. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235579. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235580. {
  235581. if (err == noErr)
  235582. return true;
  235583. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235584. jassertfalse;
  235585. return false;
  235586. }
  235587. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235588. #else
  235589. #define OK(a) (a == noErr)
  235590. #endif
  235591. class CoreAudioInternal : public Timer
  235592. {
  235593. public:
  235594. CoreAudioInternal (AudioDeviceID id)
  235595. : inputLatency (0),
  235596. outputLatency (0),
  235597. callback (0),
  235598. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235599. audioProcID (0),
  235600. #endif
  235601. isSlaveDevice (false),
  235602. deviceID (id),
  235603. started (false),
  235604. sampleRate (0),
  235605. bufferSize (512),
  235606. numInputChans (0),
  235607. numOutputChans (0),
  235608. callbacksAllowed (true),
  235609. numInputChannelInfos (0),
  235610. numOutputChannelInfos (0)
  235611. {
  235612. jassert (deviceID != 0);
  235613. updateDetailsFromDevice();
  235614. AudioObjectPropertyAddress pa;
  235615. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235616. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235617. pa.mElement = kAudioObjectPropertyElementWildcard;
  235618. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235619. }
  235620. ~CoreAudioInternal()
  235621. {
  235622. AudioObjectPropertyAddress pa;
  235623. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235624. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235625. pa.mElement = kAudioObjectPropertyElementWildcard;
  235626. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235627. stop (false);
  235628. }
  235629. void allocateTempBuffers()
  235630. {
  235631. const int tempBufSize = bufferSize + 4;
  235632. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235633. tempInputBuffers.calloc (numInputChans + 2);
  235634. tempOutputBuffers.calloc (numOutputChans + 2);
  235635. int i, count = 0;
  235636. for (i = 0; i < numInputChans; ++i)
  235637. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235638. for (i = 0; i < numOutputChans; ++i)
  235639. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235640. }
  235641. // returns the number of actual available channels
  235642. void fillInChannelInfo (const bool input)
  235643. {
  235644. int chanNum = 0;
  235645. UInt32 size;
  235646. AudioObjectPropertyAddress pa;
  235647. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235648. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235649. pa.mElement = kAudioObjectPropertyElementMaster;
  235650. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235651. {
  235652. HeapBlock <AudioBufferList> bufList;
  235653. bufList.calloc (size, 1);
  235654. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235655. {
  235656. const int numStreams = bufList->mNumberBuffers;
  235657. for (int i = 0; i < numStreams; ++i)
  235658. {
  235659. const AudioBuffer& b = bufList->mBuffers[i];
  235660. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235661. {
  235662. String name;
  235663. {
  235664. char channelName [256];
  235665. zerostruct (channelName);
  235666. UInt32 nameSize = sizeof (channelName);
  235667. UInt32 channelNum = chanNum + 1;
  235668. pa.mSelector = kAudioDevicePropertyChannelName;
  235669. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235670. name = String::fromUTF8 (channelName, nameSize);
  235671. }
  235672. if (input)
  235673. {
  235674. if (activeInputChans[chanNum])
  235675. {
  235676. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235677. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235678. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235679. ++numInputChannelInfos;
  235680. }
  235681. if (name.isEmpty())
  235682. name << "Input " << (chanNum + 1);
  235683. inChanNames.add (name);
  235684. }
  235685. else
  235686. {
  235687. if (activeOutputChans[chanNum])
  235688. {
  235689. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235690. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235691. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235692. ++numOutputChannelInfos;
  235693. }
  235694. if (name.isEmpty())
  235695. name << "Output " << (chanNum + 1);
  235696. outChanNames.add (name);
  235697. }
  235698. ++chanNum;
  235699. }
  235700. }
  235701. }
  235702. }
  235703. }
  235704. void updateDetailsFromDevice()
  235705. {
  235706. stopTimer();
  235707. if (deviceID == 0)
  235708. return;
  235709. const ScopedLock sl (callbackLock);
  235710. Float64 sr;
  235711. UInt32 size = sizeof (Float64);
  235712. AudioObjectPropertyAddress pa;
  235713. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235714. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235715. pa.mElement = kAudioObjectPropertyElementMaster;
  235716. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235717. sampleRate = sr;
  235718. UInt32 framesPerBuf;
  235719. size = sizeof (framesPerBuf);
  235720. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235721. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235722. {
  235723. bufferSize = framesPerBuf;
  235724. allocateTempBuffers();
  235725. }
  235726. bufferSizes.clear();
  235727. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235728. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235729. {
  235730. HeapBlock <AudioValueRange> ranges;
  235731. ranges.calloc (size, 1);
  235732. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235733. {
  235734. bufferSizes.add ((int) ranges[0].mMinimum);
  235735. for (int i = 32; i < 2048; i += 32)
  235736. {
  235737. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235738. {
  235739. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235740. {
  235741. bufferSizes.addIfNotAlreadyThere (i);
  235742. break;
  235743. }
  235744. }
  235745. }
  235746. if (bufferSize > 0)
  235747. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235748. }
  235749. }
  235750. if (bufferSizes.size() == 0 && bufferSize > 0)
  235751. bufferSizes.add (bufferSize);
  235752. sampleRates.clear();
  235753. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235754. String rates;
  235755. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235756. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235757. {
  235758. HeapBlock <AudioValueRange> ranges;
  235759. ranges.calloc (size, 1);
  235760. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235761. {
  235762. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235763. {
  235764. bool ok = false;
  235765. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235766. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235767. ok = true;
  235768. if (ok)
  235769. {
  235770. sampleRates.add (possibleRates[i]);
  235771. rates << possibleRates[i] << ' ';
  235772. }
  235773. }
  235774. }
  235775. }
  235776. if (sampleRates.size() == 0 && sampleRate > 0)
  235777. {
  235778. sampleRates.add (sampleRate);
  235779. rates << sampleRate;
  235780. }
  235781. log ("sr: " + rates);
  235782. inputLatency = 0;
  235783. outputLatency = 0;
  235784. UInt32 lat;
  235785. size = sizeof (lat);
  235786. pa.mSelector = kAudioDevicePropertyLatency;
  235787. pa.mScope = kAudioDevicePropertyScopeInput;
  235788. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235789. inputLatency = (int) lat;
  235790. pa.mScope = kAudioDevicePropertyScopeOutput;
  235791. size = sizeof (lat);
  235792. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235793. outputLatency = (int) lat;
  235794. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235795. inChanNames.clear();
  235796. outChanNames.clear();
  235797. inputChannelInfo.calloc (numInputChans + 2);
  235798. numInputChannelInfos = 0;
  235799. outputChannelInfo.calloc (numOutputChans + 2);
  235800. numOutputChannelInfos = 0;
  235801. fillInChannelInfo (true);
  235802. fillInChannelInfo (false);
  235803. }
  235804. const StringArray getSources (bool input)
  235805. {
  235806. StringArray s;
  235807. HeapBlock <OSType> types;
  235808. const int num = getAllDataSourcesForDevice (deviceID, types);
  235809. for (int i = 0; i < num; ++i)
  235810. {
  235811. AudioValueTranslation avt;
  235812. char buffer[256];
  235813. avt.mInputData = &(types[i]);
  235814. avt.mInputDataSize = sizeof (UInt32);
  235815. avt.mOutputData = buffer;
  235816. avt.mOutputDataSize = 256;
  235817. UInt32 transSize = sizeof (avt);
  235818. AudioObjectPropertyAddress pa;
  235819. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235820. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235821. pa.mElement = kAudioObjectPropertyElementMaster;
  235822. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235823. {
  235824. DBG (buffer);
  235825. s.add (buffer);
  235826. }
  235827. }
  235828. return s;
  235829. }
  235830. int getCurrentSourceIndex (bool input) const
  235831. {
  235832. OSType currentSourceID = 0;
  235833. UInt32 size = sizeof (currentSourceID);
  235834. int result = -1;
  235835. AudioObjectPropertyAddress pa;
  235836. pa.mSelector = kAudioDevicePropertyDataSource;
  235837. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235838. pa.mElement = kAudioObjectPropertyElementMaster;
  235839. if (deviceID != 0)
  235840. {
  235841. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235842. {
  235843. HeapBlock <OSType> types;
  235844. const int num = getAllDataSourcesForDevice (deviceID, types);
  235845. for (int i = 0; i < num; ++i)
  235846. {
  235847. if (types[num] == currentSourceID)
  235848. {
  235849. result = i;
  235850. break;
  235851. }
  235852. }
  235853. }
  235854. }
  235855. return result;
  235856. }
  235857. void setCurrentSourceIndex (int index, bool input)
  235858. {
  235859. if (deviceID != 0)
  235860. {
  235861. HeapBlock <OSType> types;
  235862. const int num = getAllDataSourcesForDevice (deviceID, types);
  235863. if (((unsigned int) index) < (unsigned int) num)
  235864. {
  235865. AudioObjectPropertyAddress pa;
  235866. pa.mSelector = kAudioDevicePropertyDataSource;
  235867. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235868. pa.mElement = kAudioObjectPropertyElementMaster;
  235869. OSType typeId = types[index];
  235870. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235871. }
  235872. }
  235873. }
  235874. const String reopen (const BigInteger& inputChannels,
  235875. const BigInteger& outputChannels,
  235876. double newSampleRate,
  235877. int bufferSizeSamples)
  235878. {
  235879. String error;
  235880. log ("CoreAudio reopen");
  235881. callbacksAllowed = false;
  235882. stopTimer();
  235883. stop (false);
  235884. activeInputChans = inputChannels;
  235885. activeInputChans.setRange (inChanNames.size(),
  235886. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235887. false);
  235888. activeOutputChans = outputChannels;
  235889. activeOutputChans.setRange (outChanNames.size(),
  235890. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235891. false);
  235892. numInputChans = activeInputChans.countNumberOfSetBits();
  235893. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235894. // set sample rate
  235895. AudioObjectPropertyAddress pa;
  235896. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235897. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235898. pa.mElement = kAudioObjectPropertyElementMaster;
  235899. Float64 sr = newSampleRate;
  235900. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235901. {
  235902. error = "Couldn't change sample rate";
  235903. }
  235904. else
  235905. {
  235906. // change buffer size
  235907. UInt32 framesPerBuf = bufferSizeSamples;
  235908. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235909. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235910. {
  235911. error = "Couldn't change buffer size";
  235912. }
  235913. else
  235914. {
  235915. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235916. // correctly report their new settings until some random time in the future, so
  235917. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235918. // to make sure we're using the correct numbers..
  235919. updateDetailsFromDevice();
  235920. sampleRate = newSampleRate;
  235921. bufferSize = bufferSizeSamples;
  235922. if (sampleRates.size() == 0)
  235923. error = "Device has no available sample-rates";
  235924. else if (bufferSizes.size() == 0)
  235925. error = "Device has no available buffer-sizes";
  235926. else if (inputDevice != 0)
  235927. error = inputDevice->reopen (inputChannels,
  235928. outputChannels,
  235929. newSampleRate,
  235930. bufferSizeSamples);
  235931. }
  235932. }
  235933. callbacksAllowed = true;
  235934. return error;
  235935. }
  235936. bool start (AudioIODeviceCallback* cb)
  235937. {
  235938. if (! started)
  235939. {
  235940. callback = 0;
  235941. if (deviceID != 0)
  235942. {
  235943. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235944. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235945. #else
  235946. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235947. #endif
  235948. {
  235949. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235950. {
  235951. started = true;
  235952. }
  235953. else
  235954. {
  235955. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235956. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235957. #else
  235958. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235959. audioProcID = 0;
  235960. #endif
  235961. }
  235962. }
  235963. }
  235964. }
  235965. if (started)
  235966. {
  235967. const ScopedLock sl (callbackLock);
  235968. callback = cb;
  235969. }
  235970. if (inputDevice != 0)
  235971. return started && inputDevice->start (cb);
  235972. else
  235973. return started;
  235974. }
  235975. void stop (bool leaveInterruptRunning)
  235976. {
  235977. {
  235978. const ScopedLock sl (callbackLock);
  235979. callback = 0;
  235980. }
  235981. if (started
  235982. && (deviceID != 0)
  235983. && ! leaveInterruptRunning)
  235984. {
  235985. OK (AudioDeviceStop (deviceID, audioIOProc));
  235986. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235987. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235988. #else
  235989. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235990. audioProcID = 0;
  235991. #endif
  235992. started = false;
  235993. { const ScopedLock sl (callbackLock); }
  235994. // wait until it's definately stopped calling back..
  235995. for (int i = 40; --i >= 0;)
  235996. {
  235997. Thread::sleep (50);
  235998. UInt32 running = 0;
  235999. UInt32 size = sizeof (running);
  236000. AudioObjectPropertyAddress pa;
  236001. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  236002. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236003. pa.mElement = kAudioObjectPropertyElementMaster;
  236004. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  236005. if (running == 0)
  236006. break;
  236007. }
  236008. const ScopedLock sl (callbackLock);
  236009. }
  236010. if (inputDevice != 0)
  236011. inputDevice->stop (leaveInterruptRunning);
  236012. }
  236013. double getSampleRate() const
  236014. {
  236015. return sampleRate;
  236016. }
  236017. int getBufferSize() const
  236018. {
  236019. return bufferSize;
  236020. }
  236021. void audioCallback (const AudioBufferList* inInputData,
  236022. AudioBufferList* outOutputData)
  236023. {
  236024. int i;
  236025. const ScopedLock sl (callbackLock);
  236026. if (callback != 0)
  236027. {
  236028. if (inputDevice == 0)
  236029. {
  236030. for (i = numInputChans; --i >= 0;)
  236031. {
  236032. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  236033. float* dest = tempInputBuffers [i];
  236034. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  236035. + info.dataOffsetSamples;
  236036. const int stride = info.dataStrideSamples;
  236037. if (stride != 0) // if this is zero, info is invalid
  236038. {
  236039. for (int j = bufferSize; --j >= 0;)
  236040. {
  236041. *dest++ = *src;
  236042. src += stride;
  236043. }
  236044. }
  236045. }
  236046. }
  236047. if (! isSlaveDevice)
  236048. {
  236049. if (inputDevice == 0)
  236050. {
  236051. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  236052. numInputChans,
  236053. tempOutputBuffers,
  236054. numOutputChans,
  236055. bufferSize);
  236056. }
  236057. else
  236058. {
  236059. jassert (inputDevice->bufferSize == bufferSize);
  236060. // Sometimes the two linked devices seem to get their callbacks in
  236061. // parallel, so we need to lock both devices to stop the input data being
  236062. // changed while inside our callback..
  236063. const ScopedLock sl2 (inputDevice->callbackLock);
  236064. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  236065. inputDevice->numInputChans,
  236066. tempOutputBuffers,
  236067. numOutputChans,
  236068. bufferSize);
  236069. }
  236070. for (i = numOutputChans; --i >= 0;)
  236071. {
  236072. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  236073. const float* src = tempOutputBuffers [i];
  236074. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  236075. + info.dataOffsetSamples;
  236076. const int stride = info.dataStrideSamples;
  236077. if (stride != 0) // if this is zero, info is invalid
  236078. {
  236079. for (int j = bufferSize; --j >= 0;)
  236080. {
  236081. *dest = *src++;
  236082. dest += stride;
  236083. }
  236084. }
  236085. }
  236086. }
  236087. }
  236088. else
  236089. {
  236090. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  236091. {
  236092. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  236093. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  236094. + info.dataOffsetSamples;
  236095. const int stride = info.dataStrideSamples;
  236096. if (stride != 0) // if this is zero, info is invalid
  236097. {
  236098. for (int j = bufferSize; --j >= 0;)
  236099. {
  236100. *dest = 0.0f;
  236101. dest += stride;
  236102. }
  236103. }
  236104. }
  236105. }
  236106. }
  236107. // called by callbacks
  236108. void deviceDetailsChanged()
  236109. {
  236110. if (callbacksAllowed)
  236111. startTimer (100);
  236112. }
  236113. void timerCallback()
  236114. {
  236115. stopTimer();
  236116. log ("CoreAudio device changed callback");
  236117. const double oldSampleRate = sampleRate;
  236118. const int oldBufferSize = bufferSize;
  236119. updateDetailsFromDevice();
  236120. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  236121. {
  236122. callbacksAllowed = false;
  236123. stop (false);
  236124. updateDetailsFromDevice();
  236125. callbacksAllowed = true;
  236126. }
  236127. }
  236128. CoreAudioInternal* getRelatedDevice() const
  236129. {
  236130. UInt32 size = 0;
  236131. ScopedPointer <CoreAudioInternal> result;
  236132. AudioObjectPropertyAddress pa;
  236133. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  236134. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236135. pa.mElement = kAudioObjectPropertyElementMaster;
  236136. if (deviceID != 0
  236137. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  236138. && size > 0)
  236139. {
  236140. HeapBlock <AudioDeviceID> devs;
  236141. devs.calloc (size, 1);
  236142. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  236143. {
  236144. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  236145. {
  236146. if (devs[i] != deviceID && devs[i] != 0)
  236147. {
  236148. result = new CoreAudioInternal (devs[i]);
  236149. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  236150. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  236151. if (thisIsInput != otherIsInput
  236152. || (inChanNames.size() + outChanNames.size() == 0)
  236153. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  236154. break;
  236155. result = 0;
  236156. }
  236157. }
  236158. }
  236159. }
  236160. return result.release();
  236161. }
  236162. juce_UseDebuggingNewOperator
  236163. int inputLatency, outputLatency;
  236164. BigInteger activeInputChans, activeOutputChans;
  236165. StringArray inChanNames, outChanNames;
  236166. Array <double> sampleRates;
  236167. Array <int> bufferSizes;
  236168. AudioIODeviceCallback* callback;
  236169. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  236170. AudioDeviceIOProcID audioProcID;
  236171. #endif
  236172. ScopedPointer<CoreAudioInternal> inputDevice;
  236173. bool isSlaveDevice;
  236174. private:
  236175. CriticalSection callbackLock;
  236176. AudioDeviceID deviceID;
  236177. bool started;
  236178. double sampleRate;
  236179. int bufferSize;
  236180. HeapBlock <float> audioBuffer;
  236181. int numInputChans, numOutputChans;
  236182. bool callbacksAllowed;
  236183. struct CallbackDetailsForChannel
  236184. {
  236185. int streamNum;
  236186. int dataOffsetSamples;
  236187. int dataStrideSamples;
  236188. };
  236189. int numInputChannelInfos, numOutputChannelInfos;
  236190. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  236191. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  236192. CoreAudioInternal (const CoreAudioInternal&);
  236193. CoreAudioInternal& operator= (const CoreAudioInternal&);
  236194. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  236195. const AudioTimeStamp* /*inNow*/,
  236196. const AudioBufferList* inInputData,
  236197. const AudioTimeStamp* /*inInputTime*/,
  236198. AudioBufferList* outOutputData,
  236199. const AudioTimeStamp* /*inOutputTime*/,
  236200. void* device)
  236201. {
  236202. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  236203. return noErr;
  236204. }
  236205. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236206. {
  236207. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236208. switch (pa->mSelector)
  236209. {
  236210. case kAudioDevicePropertyBufferSize:
  236211. case kAudioDevicePropertyBufferFrameSize:
  236212. case kAudioDevicePropertyNominalSampleRate:
  236213. case kAudioDevicePropertyStreamFormat:
  236214. case kAudioDevicePropertyDeviceIsAlive:
  236215. intern->deviceDetailsChanged();
  236216. break;
  236217. case kAudioDevicePropertyBufferSizeRange:
  236218. case kAudioDevicePropertyVolumeScalar:
  236219. case kAudioDevicePropertyMute:
  236220. case kAudioDevicePropertyPlayThru:
  236221. case kAudioDevicePropertyDataSource:
  236222. case kAudioDevicePropertyDeviceIsRunning:
  236223. break;
  236224. }
  236225. return noErr;
  236226. }
  236227. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  236228. {
  236229. AudioObjectPropertyAddress pa;
  236230. pa.mSelector = kAudioDevicePropertyDataSources;
  236231. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236232. pa.mElement = kAudioObjectPropertyElementMaster;
  236233. UInt32 size = 0;
  236234. if (deviceID != 0
  236235. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236236. {
  236237. types.calloc (size, 1);
  236238. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  236239. return size / (int) sizeof (OSType);
  236240. }
  236241. return 0;
  236242. }
  236243. };
  236244. class CoreAudioIODevice : public AudioIODevice
  236245. {
  236246. public:
  236247. CoreAudioIODevice (const String& deviceName,
  236248. AudioDeviceID inputDeviceId,
  236249. const int inputIndex_,
  236250. AudioDeviceID outputDeviceId,
  236251. const int outputIndex_)
  236252. : AudioIODevice (deviceName, "CoreAudio"),
  236253. inputIndex (inputIndex_),
  236254. outputIndex (outputIndex_),
  236255. isOpen_ (false),
  236256. isStarted (false)
  236257. {
  236258. CoreAudioInternal* device = 0;
  236259. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  236260. {
  236261. jassert (inputDeviceId != 0);
  236262. device = new CoreAudioInternal (inputDeviceId);
  236263. }
  236264. else
  236265. {
  236266. device = new CoreAudioInternal (outputDeviceId);
  236267. if (inputDeviceId != 0)
  236268. {
  236269. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  236270. device->inputDevice = secondDevice;
  236271. secondDevice->isSlaveDevice = true;
  236272. }
  236273. }
  236274. internal = device;
  236275. AudioObjectPropertyAddress pa;
  236276. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236277. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236278. pa.mElement = kAudioObjectPropertyElementWildcard;
  236279. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236280. }
  236281. ~CoreAudioIODevice()
  236282. {
  236283. AudioObjectPropertyAddress pa;
  236284. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236285. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236286. pa.mElement = kAudioObjectPropertyElementWildcard;
  236287. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236288. }
  236289. const StringArray getOutputChannelNames()
  236290. {
  236291. return internal->outChanNames;
  236292. }
  236293. const StringArray getInputChannelNames()
  236294. {
  236295. if (internal->inputDevice != 0)
  236296. return internal->inputDevice->inChanNames;
  236297. else
  236298. return internal->inChanNames;
  236299. }
  236300. int getNumSampleRates()
  236301. {
  236302. return internal->sampleRates.size();
  236303. }
  236304. double getSampleRate (int index)
  236305. {
  236306. return internal->sampleRates [index];
  236307. }
  236308. int getNumBufferSizesAvailable()
  236309. {
  236310. return internal->bufferSizes.size();
  236311. }
  236312. int getBufferSizeSamples (int index)
  236313. {
  236314. return internal->bufferSizes [index];
  236315. }
  236316. int getDefaultBufferSize()
  236317. {
  236318. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  236319. if (getBufferSizeSamples(i) >= 512)
  236320. return getBufferSizeSamples(i);
  236321. return 512;
  236322. }
  236323. const String open (const BigInteger& inputChannels,
  236324. const BigInteger& outputChannels,
  236325. double sampleRate,
  236326. int bufferSizeSamples)
  236327. {
  236328. isOpen_ = true;
  236329. if (bufferSizeSamples <= 0)
  236330. bufferSizeSamples = getDefaultBufferSize();
  236331. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  236332. isOpen_ = lastError.isEmpty();
  236333. return lastError;
  236334. }
  236335. void close()
  236336. {
  236337. isOpen_ = false;
  236338. internal->stop (false);
  236339. }
  236340. bool isOpen()
  236341. {
  236342. return isOpen_;
  236343. }
  236344. int getCurrentBufferSizeSamples()
  236345. {
  236346. return internal != 0 ? internal->getBufferSize() : 512;
  236347. }
  236348. double getCurrentSampleRate()
  236349. {
  236350. return internal != 0 ? internal->getSampleRate() : 0;
  236351. }
  236352. int getCurrentBitDepth()
  236353. {
  236354. return 32; // no way to find out, so just assume it's high..
  236355. }
  236356. const BigInteger getActiveOutputChannels() const
  236357. {
  236358. return internal != 0 ? internal->activeOutputChans : BigInteger();
  236359. }
  236360. const BigInteger getActiveInputChannels() const
  236361. {
  236362. BigInteger chans;
  236363. if (internal != 0)
  236364. {
  236365. chans = internal->activeInputChans;
  236366. if (internal->inputDevice != 0)
  236367. chans |= internal->inputDevice->activeInputChans;
  236368. }
  236369. return chans;
  236370. }
  236371. int getOutputLatencyInSamples()
  236372. {
  236373. if (internal == 0)
  236374. return 0;
  236375. // this seems like a good guess at getting the latency right - comparing
  236376. // this with a round-trip measurement, it gets it to within a few millisecs
  236377. // for the built-in mac soundcard
  236378. return internal->outputLatency + internal->getBufferSize() * 2;
  236379. }
  236380. int getInputLatencyInSamples()
  236381. {
  236382. if (internal == 0)
  236383. return 0;
  236384. return internal->inputLatency + internal->getBufferSize() * 2;
  236385. }
  236386. void start (AudioIODeviceCallback* callback)
  236387. {
  236388. if (internal != 0 && ! isStarted)
  236389. {
  236390. if (callback != 0)
  236391. callback->audioDeviceAboutToStart (this);
  236392. isStarted = true;
  236393. internal->start (callback);
  236394. }
  236395. }
  236396. void stop()
  236397. {
  236398. if (isStarted && internal != 0)
  236399. {
  236400. AudioIODeviceCallback* const lastCallback = internal->callback;
  236401. isStarted = false;
  236402. internal->stop (true);
  236403. if (lastCallback != 0)
  236404. lastCallback->audioDeviceStopped();
  236405. }
  236406. }
  236407. bool isPlaying()
  236408. {
  236409. if (internal->callback == 0)
  236410. isStarted = false;
  236411. return isStarted;
  236412. }
  236413. const String getLastError()
  236414. {
  236415. return lastError;
  236416. }
  236417. int inputIndex, outputIndex;
  236418. juce_UseDebuggingNewOperator
  236419. private:
  236420. ScopedPointer<CoreAudioInternal> internal;
  236421. bool isOpen_, isStarted;
  236422. String lastError;
  236423. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236424. {
  236425. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236426. switch (pa->mSelector)
  236427. {
  236428. case kAudioHardwarePropertyDevices:
  236429. intern->deviceDetailsChanged();
  236430. break;
  236431. case kAudioHardwarePropertyDefaultOutputDevice:
  236432. case kAudioHardwarePropertyDefaultInputDevice:
  236433. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236434. break;
  236435. }
  236436. return noErr;
  236437. }
  236438. CoreAudioIODevice (const CoreAudioIODevice&);
  236439. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  236440. };
  236441. class CoreAudioIODeviceType : public AudioIODeviceType
  236442. {
  236443. public:
  236444. CoreAudioIODeviceType()
  236445. : AudioIODeviceType ("CoreAudio"),
  236446. hasScanned (false)
  236447. {
  236448. }
  236449. ~CoreAudioIODeviceType()
  236450. {
  236451. }
  236452. void scanForDevices()
  236453. {
  236454. hasScanned = true;
  236455. inputDeviceNames.clear();
  236456. outputDeviceNames.clear();
  236457. inputIds.clear();
  236458. outputIds.clear();
  236459. UInt32 size;
  236460. AudioObjectPropertyAddress pa;
  236461. pa.mSelector = kAudioHardwarePropertyDevices;
  236462. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236463. pa.mElement = kAudioObjectPropertyElementMaster;
  236464. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236465. {
  236466. HeapBlock <AudioDeviceID> devs;
  236467. devs.calloc (size, 1);
  236468. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236469. {
  236470. const int num = size / (int) sizeof (AudioDeviceID);
  236471. for (int i = 0; i < num; ++i)
  236472. {
  236473. char name [1024];
  236474. size = sizeof (name);
  236475. pa.mSelector = kAudioDevicePropertyDeviceName;
  236476. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236477. {
  236478. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236479. const int numIns = getNumChannels (devs[i], true);
  236480. const int numOuts = getNumChannels (devs[i], false);
  236481. if (numIns > 0)
  236482. {
  236483. inputDeviceNames.add (nameString);
  236484. inputIds.add (devs[i]);
  236485. }
  236486. if (numOuts > 0)
  236487. {
  236488. outputDeviceNames.add (nameString);
  236489. outputIds.add (devs[i]);
  236490. }
  236491. }
  236492. }
  236493. }
  236494. }
  236495. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236496. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236497. }
  236498. const StringArray getDeviceNames (bool wantInputNames) const
  236499. {
  236500. jassert (hasScanned); // need to call scanForDevices() before doing this
  236501. if (wantInputNames)
  236502. return inputDeviceNames;
  236503. else
  236504. return outputDeviceNames;
  236505. }
  236506. int getDefaultDeviceIndex (bool forInput) const
  236507. {
  236508. jassert (hasScanned); // need to call scanForDevices() before doing this
  236509. AudioDeviceID deviceID;
  236510. UInt32 size = sizeof (deviceID);
  236511. // if they're asking for any input channels at all, use the default input, so we
  236512. // get the built-in mic rather than the built-in output with no inputs..
  236513. AudioObjectPropertyAddress pa;
  236514. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236515. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236516. pa.mElement = kAudioObjectPropertyElementMaster;
  236517. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236518. {
  236519. if (forInput)
  236520. {
  236521. for (int i = inputIds.size(); --i >= 0;)
  236522. if (inputIds[i] == deviceID)
  236523. return i;
  236524. }
  236525. else
  236526. {
  236527. for (int i = outputIds.size(); --i >= 0;)
  236528. if (outputIds[i] == deviceID)
  236529. return i;
  236530. }
  236531. }
  236532. return 0;
  236533. }
  236534. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236535. {
  236536. jassert (hasScanned); // need to call scanForDevices() before doing this
  236537. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236538. if (d == 0)
  236539. return -1;
  236540. return asInput ? d->inputIndex
  236541. : d->outputIndex;
  236542. }
  236543. bool hasSeparateInputsAndOutputs() const { return true; }
  236544. AudioIODevice* createDevice (const String& outputDeviceName,
  236545. const String& inputDeviceName)
  236546. {
  236547. jassert (hasScanned); // need to call scanForDevices() before doing this
  236548. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236549. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236550. String deviceName (outputDeviceName);
  236551. if (deviceName.isEmpty())
  236552. deviceName = inputDeviceName;
  236553. if (index >= 0)
  236554. return new CoreAudioIODevice (deviceName,
  236555. inputIds [inputIndex],
  236556. inputIndex,
  236557. outputIds [outputIndex],
  236558. outputIndex);
  236559. return 0;
  236560. }
  236561. juce_UseDebuggingNewOperator
  236562. private:
  236563. StringArray inputDeviceNames, outputDeviceNames;
  236564. Array <AudioDeviceID> inputIds, outputIds;
  236565. bool hasScanned;
  236566. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236567. {
  236568. int total = 0;
  236569. UInt32 size;
  236570. AudioObjectPropertyAddress pa;
  236571. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236572. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236573. pa.mElement = kAudioObjectPropertyElementMaster;
  236574. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236575. {
  236576. HeapBlock <AudioBufferList> bufList;
  236577. bufList.calloc (size, 1);
  236578. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236579. {
  236580. const int numStreams = bufList->mNumberBuffers;
  236581. for (int i = 0; i < numStreams; ++i)
  236582. {
  236583. const AudioBuffer& b = bufList->mBuffers[i];
  236584. total += b.mNumberChannels;
  236585. }
  236586. }
  236587. }
  236588. return total;
  236589. }
  236590. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236591. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236592. };
  236593. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236594. {
  236595. return new CoreAudioIODeviceType();
  236596. }
  236597. #undef log
  236598. #endif
  236599. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236600. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236601. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236602. // compiled on its own).
  236603. #if JUCE_INCLUDED_FILE
  236604. #if JUCE_MAC
  236605. namespace CoreMidiHelpers
  236606. {
  236607. static bool logError (const OSStatus err, const int lineNum)
  236608. {
  236609. if (err == noErr)
  236610. return true;
  236611. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236612. jassertfalse;
  236613. return false;
  236614. }
  236615. #undef CHECK_ERROR
  236616. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236617. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236618. {
  236619. String result;
  236620. CFStringRef str = 0;
  236621. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236622. if (str != 0)
  236623. {
  236624. result = PlatformUtilities::cfStringToJuceString (str);
  236625. CFRelease (str);
  236626. str = 0;
  236627. }
  236628. MIDIEntityRef entity = 0;
  236629. MIDIEndpointGetEntity (endpoint, &entity);
  236630. if (entity == 0)
  236631. return result; // probably virtual
  236632. if (result.isEmpty())
  236633. {
  236634. // endpoint name has zero length - try the entity
  236635. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236636. if (str != 0)
  236637. {
  236638. result += PlatformUtilities::cfStringToJuceString (str);
  236639. CFRelease (str);
  236640. str = 0;
  236641. }
  236642. }
  236643. // now consider the device's name
  236644. MIDIDeviceRef device = 0;
  236645. MIDIEntityGetDevice (entity, &device);
  236646. if (device == 0)
  236647. return result;
  236648. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236649. if (str != 0)
  236650. {
  236651. const String s (PlatformUtilities::cfStringToJuceString (str));
  236652. CFRelease (str);
  236653. // if an external device has only one entity, throw away
  236654. // the endpoint name and just use the device name
  236655. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236656. {
  236657. result = s;
  236658. }
  236659. else if (! result.startsWithIgnoreCase (s))
  236660. {
  236661. // prepend the device name to the entity name
  236662. result = (s + " " + result).trimEnd();
  236663. }
  236664. }
  236665. return result;
  236666. }
  236667. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236668. {
  236669. String result;
  236670. // Does the endpoint have connections?
  236671. CFDataRef connections = 0;
  236672. int numConnections = 0;
  236673. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236674. if (connections != 0)
  236675. {
  236676. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236677. if (numConnections > 0)
  236678. {
  236679. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236680. for (int i = 0; i < numConnections; ++i, ++pid)
  236681. {
  236682. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236683. MIDIObjectRef connObject;
  236684. MIDIObjectType connObjectType;
  236685. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236686. if (err == noErr)
  236687. {
  236688. String s;
  236689. if (connObjectType == kMIDIObjectType_ExternalSource
  236690. || connObjectType == kMIDIObjectType_ExternalDestination)
  236691. {
  236692. // Connected to an external device's endpoint (10.3 and later).
  236693. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236694. }
  236695. else
  236696. {
  236697. // Connected to an external device (10.2) (or something else, catch-all)
  236698. CFStringRef str = 0;
  236699. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236700. if (str != 0)
  236701. {
  236702. s = PlatformUtilities::cfStringToJuceString (str);
  236703. CFRelease (str);
  236704. }
  236705. }
  236706. if (s.isNotEmpty())
  236707. {
  236708. if (result.isNotEmpty())
  236709. result += ", ";
  236710. result += s;
  236711. }
  236712. }
  236713. }
  236714. }
  236715. CFRelease (connections);
  236716. }
  236717. if (result.isNotEmpty())
  236718. return result;
  236719. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236720. return getEndpointName (endpoint, false);
  236721. }
  236722. static MIDIClientRef getGlobalMidiClient()
  236723. {
  236724. static MIDIClientRef globalMidiClient = 0;
  236725. if (globalMidiClient == 0)
  236726. {
  236727. String name ("JUCE");
  236728. if (JUCEApplication::getInstance() != 0)
  236729. name = JUCEApplication::getInstance()->getApplicationName();
  236730. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236731. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236732. CFRelease (appName);
  236733. }
  236734. return globalMidiClient;
  236735. }
  236736. class MidiPortAndEndpoint
  236737. {
  236738. public:
  236739. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236740. : port (port_), endPoint (endPoint_)
  236741. {
  236742. }
  236743. ~MidiPortAndEndpoint()
  236744. {
  236745. if (port != 0)
  236746. MIDIPortDispose (port);
  236747. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236748. MIDIEndpointDispose (endPoint);
  236749. }
  236750. void send (const MIDIPacketList* const packets)
  236751. {
  236752. if (port != 0)
  236753. MIDISend (port, endPoint, packets);
  236754. else
  236755. MIDIReceived (endPoint, packets);
  236756. }
  236757. MIDIPortRef port;
  236758. MIDIEndpointRef endPoint;
  236759. };
  236760. class MidiPortAndCallback;
  236761. static CriticalSection callbackLock;
  236762. static Array<MidiPortAndCallback*> activeCallbacks;
  236763. class MidiPortAndCallback
  236764. {
  236765. public:
  236766. MidiPortAndCallback (MidiInputCallback& callback_)
  236767. : input (0), active (false), callback (callback_), concatenator (2048)
  236768. {
  236769. }
  236770. ~MidiPortAndCallback()
  236771. {
  236772. active = false;
  236773. {
  236774. const ScopedLock sl (callbackLock);
  236775. activeCallbacks.removeValue (this);
  236776. }
  236777. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236778. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236779. }
  236780. void handlePackets (const MIDIPacketList* const pktlist)
  236781. {
  236782. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236783. const ScopedLock sl (callbackLock);
  236784. if (activeCallbacks.contains (this) && active)
  236785. {
  236786. const MIDIPacket* packet = &pktlist->packet[0];
  236787. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236788. {
  236789. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236790. input, callback);
  236791. packet = MIDIPacketNext (packet);
  236792. }
  236793. }
  236794. }
  236795. MidiInput* input;
  236796. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236797. volatile bool active;
  236798. private:
  236799. MidiInputCallback& callback;
  236800. MidiDataConcatenator concatenator;
  236801. };
  236802. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236803. {
  236804. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236805. }
  236806. }
  236807. const StringArray MidiOutput::getDevices()
  236808. {
  236809. StringArray s;
  236810. const ItemCount num = MIDIGetNumberOfDestinations();
  236811. for (ItemCount i = 0; i < num; ++i)
  236812. {
  236813. MIDIEndpointRef dest = MIDIGetDestination (i);
  236814. if (dest != 0)
  236815. {
  236816. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236817. if (name.isEmpty())
  236818. name = "<error>";
  236819. s.add (name);
  236820. }
  236821. else
  236822. {
  236823. s.add ("<error>");
  236824. }
  236825. }
  236826. return s;
  236827. }
  236828. int MidiOutput::getDefaultDeviceIndex()
  236829. {
  236830. return 0;
  236831. }
  236832. MidiOutput* MidiOutput::openDevice (int index)
  236833. {
  236834. MidiOutput* mo = 0;
  236835. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236836. {
  236837. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236838. CFStringRef pname;
  236839. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236840. {
  236841. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236842. MIDIPortRef port;
  236843. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236844. {
  236845. mo = new MidiOutput();
  236846. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236847. }
  236848. CFRelease (pname);
  236849. }
  236850. }
  236851. return mo;
  236852. }
  236853. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236854. {
  236855. MidiOutput* mo = 0;
  236856. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236857. MIDIEndpointRef endPoint;
  236858. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236859. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236860. {
  236861. mo = new MidiOutput();
  236862. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236863. }
  236864. CFRelease (name);
  236865. return mo;
  236866. }
  236867. MidiOutput::~MidiOutput()
  236868. {
  236869. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236870. }
  236871. void MidiOutput::reset()
  236872. {
  236873. }
  236874. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236875. {
  236876. return false;
  236877. }
  236878. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236879. {
  236880. }
  236881. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236882. {
  236883. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236884. if (message.isSysEx())
  236885. {
  236886. const int maxPacketSize = 256;
  236887. int pos = 0, bytesLeft = message.getRawDataSize();
  236888. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236889. HeapBlock <MIDIPacketList> packets;
  236890. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236891. packets->numPackets = numPackets;
  236892. MIDIPacket* p = packets->packet;
  236893. for (int i = 0; i < numPackets; ++i)
  236894. {
  236895. p->timeStamp = 0;
  236896. p->length = jmin (maxPacketSize, bytesLeft);
  236897. memcpy (p->data, message.getRawData() + pos, p->length);
  236898. pos += p->length;
  236899. bytesLeft -= p->length;
  236900. p = MIDIPacketNext (p);
  236901. }
  236902. mpe->send (packets);
  236903. }
  236904. else
  236905. {
  236906. MIDIPacketList packets;
  236907. packets.numPackets = 1;
  236908. packets.packet[0].timeStamp = 0;
  236909. packets.packet[0].length = message.getRawDataSize();
  236910. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236911. mpe->send (&packets);
  236912. }
  236913. }
  236914. const StringArray MidiInput::getDevices()
  236915. {
  236916. StringArray s;
  236917. const ItemCount num = MIDIGetNumberOfSources();
  236918. for (ItemCount i = 0; i < num; ++i)
  236919. {
  236920. MIDIEndpointRef source = MIDIGetSource (i);
  236921. if (source != 0)
  236922. {
  236923. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236924. if (name.isEmpty())
  236925. name = "<error>";
  236926. s.add (name);
  236927. }
  236928. else
  236929. {
  236930. s.add ("<error>");
  236931. }
  236932. }
  236933. return s;
  236934. }
  236935. int MidiInput::getDefaultDeviceIndex()
  236936. {
  236937. return 0;
  236938. }
  236939. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236940. {
  236941. jassert (callback != 0);
  236942. using namespace CoreMidiHelpers;
  236943. MidiInput* newInput = 0;
  236944. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236945. {
  236946. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236947. if (endPoint != 0)
  236948. {
  236949. CFStringRef name;
  236950. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236951. {
  236952. MIDIClientRef client = getGlobalMidiClient();
  236953. if (client != 0)
  236954. {
  236955. MIDIPortRef port;
  236956. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236957. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236958. {
  236959. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236960. {
  236961. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236962. newInput = new MidiInput (getDevices() [index]);
  236963. mpc->input = newInput;
  236964. newInput->internal = mpc;
  236965. const ScopedLock sl (callbackLock);
  236966. activeCallbacks.add (mpc.release());
  236967. }
  236968. else
  236969. {
  236970. CHECK_ERROR (MIDIPortDispose (port));
  236971. }
  236972. }
  236973. }
  236974. }
  236975. CFRelease (name);
  236976. }
  236977. }
  236978. return newInput;
  236979. }
  236980. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236981. {
  236982. jassert (callback != 0);
  236983. using namespace CoreMidiHelpers;
  236984. MidiInput* mi = 0;
  236985. MIDIClientRef client = getGlobalMidiClient();
  236986. if (client != 0)
  236987. {
  236988. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236989. mpc->active = false;
  236990. MIDIEndpointRef endPoint;
  236991. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236992. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236993. {
  236994. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236995. mi = new MidiInput (deviceName);
  236996. mpc->input = mi;
  236997. mi->internal = mpc;
  236998. const ScopedLock sl (callbackLock);
  236999. activeCallbacks.add (mpc.release());
  237000. }
  237001. CFRelease (name);
  237002. }
  237003. return mi;
  237004. }
  237005. MidiInput::MidiInput (const String& name_)
  237006. : name (name_)
  237007. {
  237008. }
  237009. MidiInput::~MidiInput()
  237010. {
  237011. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  237012. }
  237013. void MidiInput::start()
  237014. {
  237015. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  237016. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  237017. }
  237018. void MidiInput::stop()
  237019. {
  237020. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  237021. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  237022. }
  237023. #undef CHECK_ERROR
  237024. #else // Stubs for iOS...
  237025. MidiOutput::~MidiOutput() {}
  237026. void MidiOutput::reset() {}
  237027. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  237028. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  237029. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  237030. const StringArray MidiOutput::getDevices() { return StringArray(); }
  237031. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  237032. const StringArray MidiInput::getDevices() { return StringArray(); }
  237033. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  237034. #endif
  237035. #endif
  237036. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  237037. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  237038. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  237039. // compiled on its own).
  237040. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  237041. #if ! JUCE_QUICKTIME
  237042. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  237043. #endif
  237044. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  237045. class QTCameraDeviceInteral;
  237046. END_JUCE_NAMESPACE
  237047. @interface QTCaptureCallbackDelegate : NSObject
  237048. {
  237049. @public
  237050. CameraDevice* owner;
  237051. QTCameraDeviceInteral* internal;
  237052. int64 firstPresentationTime;
  237053. int64 averageTimeOffset;
  237054. }
  237055. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  237056. - (void) dealloc;
  237057. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237058. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237059. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237060. fromConnection: (QTCaptureConnection*) connection;
  237061. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237062. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237063. fromConnection: (QTCaptureConnection*) connection;
  237064. @end
  237065. BEGIN_JUCE_NAMESPACE
  237066. class QTCameraDeviceInteral
  237067. {
  237068. public:
  237069. QTCameraDeviceInteral (CameraDevice* owner, int index)
  237070. {
  237071. const ScopedAutoReleasePool pool;
  237072. session = [[QTCaptureSession alloc] init];
  237073. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237074. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  237075. input = 0;
  237076. audioInput = 0;
  237077. audioDevice = 0;
  237078. fileOutput = 0;
  237079. imageOutput = 0;
  237080. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  237081. internalDev: this];
  237082. NSError* err = 0;
  237083. [device retain];
  237084. [device open: &err];
  237085. if (err == 0)
  237086. {
  237087. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237088. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237089. [session addInput: input error: &err];
  237090. if (err == 0)
  237091. {
  237092. resetFile();
  237093. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  237094. [imageOutput setDelegate: callbackDelegate];
  237095. if (err == 0)
  237096. {
  237097. [session startRunning];
  237098. return;
  237099. }
  237100. }
  237101. }
  237102. openingError = nsStringToJuce ([err description]);
  237103. DBG (openingError);
  237104. }
  237105. ~QTCameraDeviceInteral()
  237106. {
  237107. [session stopRunning];
  237108. [session removeOutput: imageOutput];
  237109. [session release];
  237110. [input release];
  237111. [device release];
  237112. [audioDevice release];
  237113. [audioInput release];
  237114. [fileOutput release];
  237115. [imageOutput release];
  237116. [callbackDelegate release];
  237117. }
  237118. void resetFile()
  237119. {
  237120. [fileOutput recordToOutputFileURL: nil];
  237121. [session removeOutput: fileOutput];
  237122. [fileOutput release];
  237123. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  237124. [session removeInput: audioInput];
  237125. [audioInput release];
  237126. audioInput = 0;
  237127. [audioDevice release];
  237128. audioDevice = 0;
  237129. [fileOutput setDelegate: callbackDelegate];
  237130. }
  237131. void addDefaultAudioInput()
  237132. {
  237133. NSError* err = nil;
  237134. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  237135. if ([audioDevice open: &err])
  237136. [audioDevice retain];
  237137. else
  237138. audioDevice = nil;
  237139. if (audioDevice != 0)
  237140. {
  237141. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  237142. [session addInput: audioInput error: &err];
  237143. }
  237144. }
  237145. void addListener (CameraDevice::Listener* listenerToAdd)
  237146. {
  237147. const ScopedLock sl (listenerLock);
  237148. if (listeners.size() == 0)
  237149. [session addOutput: imageOutput error: nil];
  237150. listeners.addIfNotAlreadyThere (listenerToAdd);
  237151. }
  237152. void removeListener (CameraDevice::Listener* listenerToRemove)
  237153. {
  237154. const ScopedLock sl (listenerLock);
  237155. listeners.removeValue (listenerToRemove);
  237156. if (listeners.size() == 0)
  237157. [session removeOutput: imageOutput];
  237158. }
  237159. void callListeners (CIImage* frame, int w, int h)
  237160. {
  237161. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  237162. Image image (cgImage);
  237163. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  237164. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  237165. CGContextFlush (cgImage->context);
  237166. const ScopedLock sl (listenerLock);
  237167. for (int i = listeners.size(); --i >= 0;)
  237168. {
  237169. CameraDevice::Listener* const l = listeners[i];
  237170. if (l != 0)
  237171. l->imageReceived (image);
  237172. }
  237173. }
  237174. QTCaptureDevice* device;
  237175. QTCaptureDeviceInput* input;
  237176. QTCaptureDevice* audioDevice;
  237177. QTCaptureDeviceInput* audioInput;
  237178. QTCaptureSession* session;
  237179. QTCaptureMovieFileOutput* fileOutput;
  237180. QTCaptureDecompressedVideoOutput* imageOutput;
  237181. QTCaptureCallbackDelegate* callbackDelegate;
  237182. String openingError;
  237183. Array<CameraDevice::Listener*> listeners;
  237184. CriticalSection listenerLock;
  237185. };
  237186. END_JUCE_NAMESPACE
  237187. @implementation QTCaptureCallbackDelegate
  237188. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  237189. internalDev: (QTCameraDeviceInteral*) d
  237190. {
  237191. [super init];
  237192. owner = owner_;
  237193. internal = d;
  237194. firstPresentationTime = 0;
  237195. averageTimeOffset = 0;
  237196. return self;
  237197. }
  237198. - (void) dealloc
  237199. {
  237200. [super dealloc];
  237201. }
  237202. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237203. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237204. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237205. fromConnection: (QTCaptureConnection*) connection
  237206. {
  237207. if (internal->listeners.size() > 0)
  237208. {
  237209. const ScopedAutoReleasePool pool;
  237210. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  237211. CVPixelBufferGetWidth (videoFrame),
  237212. CVPixelBufferGetHeight (videoFrame));
  237213. }
  237214. }
  237215. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237216. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237217. fromConnection: (QTCaptureConnection*) connection
  237218. {
  237219. const Time now (Time::getCurrentTime());
  237220. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  237221. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  237222. #else
  237223. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  237224. #endif
  237225. int64 presentationTime = (hosttime != nil)
  237226. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  237227. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  237228. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  237229. if (firstPresentationTime == 0)
  237230. {
  237231. firstPresentationTime = presentationTime;
  237232. averageTimeOffset = timeDiff;
  237233. }
  237234. else
  237235. {
  237236. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  237237. }
  237238. }
  237239. @end
  237240. BEGIN_JUCE_NAMESPACE
  237241. class QTCaptureViewerComp : public NSViewComponent
  237242. {
  237243. public:
  237244. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  237245. {
  237246. const ScopedAutoReleasePool pool;
  237247. captureView = [[QTCaptureView alloc] init];
  237248. [captureView setCaptureSession: internal->session];
  237249. setSize (640, 480); // xxx need to somehow get the movie size - how?
  237250. setView (captureView);
  237251. }
  237252. ~QTCaptureViewerComp()
  237253. {
  237254. setView (0);
  237255. [captureView setCaptureSession: nil];
  237256. [captureView release];
  237257. }
  237258. QTCaptureView* captureView;
  237259. };
  237260. CameraDevice::CameraDevice (const String& name_, int index)
  237261. : name (name_)
  237262. {
  237263. isRecording = false;
  237264. internal = new QTCameraDeviceInteral (this, index);
  237265. }
  237266. CameraDevice::~CameraDevice()
  237267. {
  237268. stopRecording();
  237269. delete static_cast <QTCameraDeviceInteral*> (internal);
  237270. internal = 0;
  237271. }
  237272. Component* CameraDevice::createViewerComponent()
  237273. {
  237274. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  237275. }
  237276. const String CameraDevice::getFileExtension()
  237277. {
  237278. return ".mov";
  237279. }
  237280. void CameraDevice::startRecordingToFile (const File& file, int quality)
  237281. {
  237282. stopRecording();
  237283. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237284. d->callbackDelegate->firstPresentationTime = 0;
  237285. file.deleteFile();
  237286. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  237287. // out wrong, so we'll put some audio in there too..,
  237288. d->addDefaultAudioInput();
  237289. [d->session addOutput: d->fileOutput error: nil];
  237290. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  237291. for (;;)
  237292. {
  237293. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  237294. if (connection == 0)
  237295. break;
  237296. QTCompressionOptions* options = 0;
  237297. NSString* mediaType = [connection mediaType];
  237298. if ([mediaType isEqualToString: QTMediaTypeVideo])
  237299. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  237300. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  237301. : @"QTCompressionOptions240SizeH264Video"];
  237302. else if ([mediaType isEqualToString: QTMediaTypeSound])
  237303. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  237304. [d->fileOutput setCompressionOptions: options forConnection: connection];
  237305. }
  237306. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  237307. isRecording = true;
  237308. }
  237309. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  237310. {
  237311. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237312. if (d->callbackDelegate->firstPresentationTime != 0)
  237313. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  237314. return Time();
  237315. }
  237316. void CameraDevice::stopRecording()
  237317. {
  237318. if (isRecording)
  237319. {
  237320. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  237321. isRecording = false;
  237322. }
  237323. }
  237324. void CameraDevice::addListener (Listener* listenerToAdd)
  237325. {
  237326. if (listenerToAdd != 0)
  237327. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  237328. }
  237329. void CameraDevice::removeListener (Listener* listenerToRemove)
  237330. {
  237331. if (listenerToRemove != 0)
  237332. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  237333. }
  237334. const StringArray CameraDevice::getAvailableDevices()
  237335. {
  237336. const ScopedAutoReleasePool pool;
  237337. StringArray results;
  237338. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237339. for (int i = 0; i < (int) [devs count]; ++i)
  237340. {
  237341. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  237342. results.add (nsStringToJuce ([dev localizedDisplayName]));
  237343. }
  237344. return results;
  237345. }
  237346. CameraDevice* CameraDevice::openDevice (int index,
  237347. int minWidth, int minHeight,
  237348. int maxWidth, int maxHeight)
  237349. {
  237350. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  237351. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  237352. return d.release();
  237353. return 0;
  237354. }
  237355. #endif
  237356. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  237357. #endif
  237358. #endif
  237359. END_JUCE_NAMESPACE
  237360. #endif
  237361. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  237362. #endif
  237363. #endif